diff --git a/.clang-format b/.clang-format index 82ee19c725..f6abc90133 100644 --- a/.clang-format +++ b/.clang-format @@ -13,7 +13,7 @@ AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: Always AllowShortLambdasOnASingleLine: All AllowShortLoopsOnASingleLine: true -AlwaysBreakAfterReturnType: All +AlwaysBreakAfterReturnType: None AlwaysBreakTemplateDeclarations: MultiLine BreakBeforeBraces: Custom BraceWrapping: diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 0000000000..cc81d474a7 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,488 @@ +--- +Checks: 'clang-diagnostic-*,clang-analyzer-*,boost-*,bugprone-*,performance-*,readability-*,portability-*,modernize-*,cppcoreguidelines-*,concurrency-*,-modernize-use-trailing-return-type' +WarningsAsErrors: '' +HeaderFilterRegex: '' +AnalyzeTemporaryDtors: false +FormatStyle: file +User: florians +CheckOptions: + - key: readability-suspicious-call-argument.PrefixSimilarAbove + value: '30' + - key: cppcoreguidelines-no-malloc.Reallocations + value: '::realloc' + - key: cppcoreguidelines-owning-memory.LegacyResourceConsumers + value: '::free;::realloc;::freopen;::fclose' + - key: bugprone-reserved-identifier.Invert + value: 'false' + - key: bugprone-narrowing-conversions.PedanticMode + value: 'false' + - key: bugprone-unused-return-value.CheckedFunctions + value: '::std::async;::std::launder;::std::remove;::std::remove_if;::std::unique;::std::unique_ptr::release;::std::basic_string::empty;::std::vector::empty;::std::back_inserter;::std::distance;::std::find;::std::find_if;::std::inserter;::std::lower_bound;::std::make_pair;::std::map::count;::std::map::find;::std::map::lower_bound;::std::multimap::equal_range;::std::multimap::upper_bound;::std::set::count;::std::set::find;::std::setfill;::std::setprecision;::std::setw;::std::upper_bound;::std::vector::at;::bsearch;::ferror;::feof;::isalnum;::isalpha;::isblank;::iscntrl;::isdigit;::isgraph;::islower;::isprint;::ispunct;::isspace;::isupper;::iswalnum;::iswprint;::iswspace;::isxdigit;::memchr;::memcmp;::strcmp;::strcoll;::strncmp;::strpbrk;::strrchr;::strspn;::strstr;::wcscmp;::access;::bind;::connect;::difftime;::dlsym;::fnmatch;::getaddrinfo;::getopt;::htonl;::htons;::iconv_open;::inet_addr;::isascii;::isatty;::mmap;::newlocale;::openat;::pathconf;::pthread_equal;::pthread_getspecific;::pthread_mutex_trylock;::readdir;::readlink;::recvmsg;::regexec;::scandir;::semget;::setjmp;::shm_open;::shmget;::sigismember;::strcasecmp;::strsignal;::ttyname' + - key: modernize-use-auto.MinTypeNameLength + value: '5' + - key: cppcoreguidelines-macro-usage.CheckCapsOnly + value: 'false' + - key: readability-inconsistent-declaration-parameter-name.Strict + value: 'false' + - key: readability-suspicious-call-argument.DiceDissimilarBelow + value: '60' + - key: bugprone-assert-side-effect.IgnoredFunctions + value: __builtin_expect + - key: readability-suspicious-call-argument.Equality + value: 'true' + - key: bugprone-easily-swappable-parameters.QualifiersMix + value: 'false' + - key: bugprone-suspicious-string-compare.WarnOnImplicitComparison + value: 'true' + - key: bugprone-argument-comment.CommentNullPtrs + value: '0' + - key: cppcoreguidelines-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: 'true' + - key: cppcoreguidelines-init-variables.IncludeStyle + value: llvm + - key: modernize-use-nodiscard.ReplacementString + value: '[[nodiscard]]' + - key: modernize-loop-convert.MakeReverseRangeHeader + value: '' + - key: readability-suspicious-call-argument.SuffixSimilarAbove + value: '30' + - key: cppcoreguidelines-narrowing-conversions.WarnOnIntegerNarrowingConversion + value: 'true' + - key: bugprone-easily-swappable-parameters.IgnoredParameterNames + value: '"";iterator;Iterator;begin;Begin;end;End;first;First;last;Last;lhs;LHS;rhs;RHS' + - key: modernize-loop-convert.UseCxx20ReverseRanges + value: 'true' + - key: cppcoreguidelines-prefer-member-initializer.UseAssignment + value: 'false' + - key: performance-type-promotion-in-math-fn.IncludeStyle + value: llvm + - key: readability-function-cognitive-complexity.DescribeBasicIncrements + value: 'true' + - key: bugprone-suspicious-include.ImplementationFileExtensions + value: 'c;cc;cpp;cxx' + - key: modernize-loop-convert.MakeReverseRangeFunction + value: '' + - key: readability-inconsistent-declaration-parameter-name.IgnoreMacros + value: 'true' + - key: bugprone-suspicious-missing-comma.SizeThreshold + value: '5' + - key: readability-identifier-naming.IgnoreFailedSplit + value: 'false' + - key: readability-qualified-auto.AddConstToQualified + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfThis + value: 'true' + - key: bugprone-string-constructor.WarnOnLargeLength + value: 'true' + - key: cppcoreguidelines-explicit-virtual-functions.OverrideSpelling + value: override + - key: readability-uppercase-literal-suffix.IgnoreMacros + value: 'true' + - key: modernize-make-shared.IgnoreMacros + value: 'true' + - key: bugprone-dynamic-static-initializers.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: bugprone-suspicious-enum-usage.StrictMode + value: 'false' + - key: performance-unnecessary-copy-initialization.AllowedTypes + value: '' + - key: bugprone-suspicious-missing-comma.MaxConcatenatedTokens + value: '5' + - key: modernize-use-transparent-functors.SafeMode + value: 'false' + - key: readability-suspicious-call-argument.Levenshtein + value: 'true' + - key: bugprone-not-null-terminated-result.WantToUseSafeFunctions + value: 'true' + - key: bugprone-string-constructor.LargeLengthThreshold + value: '8388608' + - key: readability-simplify-boolean-expr.ChainedConditionalAssignment + value: 'false' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField + value: 'false' + - key: bugprone-exception-escape.FunctionsThatShouldNotThrow + value: '' + - key: performance-inefficient-vector-operation.EnableProto + value: 'false' + - key: modernize-make-shared.MakeSmartPtrFunction + value: 'std::make_shared' + - key: modernize-loop-convert.MaxCopySize + value: '16' + - key: readability-suspicious-call-argument.PrefixDissimilarBelow + value: '25' + - key: readability-function-size.LineThreshold + value: '4294967295' + - key: bugprone-easily-swappable-parameters.MinimumLength + value: '2' + - key: portability-simd-intrinsics.Suggest + value: 'false' + - key: cppcoreguidelines-pro-bounds-constant-array-index.GslHeader + value: '' + - key: modernize-use-override.IgnoreDestructors + value: 'false' + - key: modernize-make-shared.MakeSmartPtrFunctionHeader + value: '' + - key: bugprone-sizeof-expression.WarnOnSizeOfConstant + value: 'true' + - key: readability-redundant-string-init.StringNames + value: '::std::basic_string_view;::std::basic_string' + - key: modernize-make-unique.IgnoreDefaultInitialization + value: 'true' + - key: modernize-use-emplace.ContainersWithPushBack + value: '::std::vector;::std::list;::std::deque' + - key: readability-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: modernize-make-unique.IncludeStyle + value: llvm + - key: modernize-use-override.OverrideSpelling + value: override + - key: readability-suspicious-call-argument.LevenshteinDissimilarBelow + value: '50' + - key: bugprone-argument-comment.CommentStringLiterals + value: '0' + - key: concurrency-mt-unsafe.FunctionSet + value: any + - key: readability-identifier-length.IgnoredExceptionVariableNames + value: '^[e]$' + - key: google-readability-braces-around-statements.ShortStatementLines + value: '1' + - key: bugprone-reserved-identifier.AllowedIdentifiers + value: '' + - key: cppcoreguidelines-pro-type-member-init.IgnoreArrays + value: 'false' + - key: readability-else-after-return.WarnOnUnfixable + value: 'true' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: modernize-use-emplace.IgnoreImplicitConstructors + value: 'false' + - key: cppcoreguidelines-macro-usage.IgnoreCommandLineMacros + value: 'true' + - key: readability-suspicious-call-argument.Substring + value: 'true' + - key: modernize-use-equals-delete.IgnoreMacros + value: 'true' + - key: readability-identifier-length.IgnoredVariableNames + value: '' + - key: readability-magic-numbers.IgnoreAllFloatingPointValues + value: 'false' + - key: cppcoreguidelines-pro-bounds-constant-array-index.IncludeStyle + value: llvm + - key: readability-suspicious-call-argument.Abbreviations + value: 'arr=array;cnt=count;idx=index;src=source;stmt=statement;cpy=copy;dest=destination;dist=distancedst=distance;ptr=pointer;wdth=width;str=string;ln=line;srv=server;attr=attribute;ref=reference;buf=buffer;col=column;nr=number;vec=vector;len=length;elem=element;val=value;i=index;var=variable;hght=height;cl=client;num=number;pos=position;lst=list;addr=address' + - key: bugprone-misplaced-widening-cast.CheckImplicitCasts + value: 'false' + - key: readability-uppercase-literal-suffix.NewSuffixes + value: '' + - key: modernize-loop-convert.MinConfidence + value: reasonable + - key: performance-unnecessary-value-param.AllowedTypes + value: '' + - key: readability-uniqueptr-delete-release.PreferResetCall + value: 'false' + - key: readability-identifier-length.MinimumExceptionNameLength + value: '2' + - key: cppcoreguidelines-avoid-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: google-readability-namespace-comments.SpacesBeforeComments + value: '2' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoreBitFieldsWidths + value: 'true' + - key: cppcoreguidelines-avoid-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: cppcoreguidelines-no-malloc.Allocations + value: '::malloc;::calloc' + - key: bugprone-narrowing-conversions.IgnoreConversionFromTypes + value: '' + - key: readability-function-size.BranchThreshold + value: '4294967295' + - key: bugprone-suspicious-missing-comma.RatioThreshold + value: '0.200000' + - key: readability-implicit-bool-conversion.AllowIntegerConditions + value: 'false' + - key: readability-identifier-length.IgnoredParameterNames + value: '^[n]$' + - key: readability-function-size.StatementThreshold + value: '800' + - key: readability-identifier-naming.IgnoreMainLikeFunctions + value: 'false' + - key: cppcoreguidelines-init-variables.MathHeader + value: '' + - key: google-readability-function-size.StatementThreshold + value: '800' + - key: bugprone-reserved-identifier.AggressiveDependentMemberLookup + value: 'false' + - key: readability-suspicious-call-argument.DiceSimilarAbove + value: '70' + - key: modernize-use-equals-default.IgnoreMacros + value: 'true' + - key: readability-suspicious-call-argument.Abbreviation + value: 'true' + - key: cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor + value: 'false' + - key: readability-identifier-length.MinimumLoopCounterNameLength + value: '2' + - key: modernize-use-emplace.SmartPointers + value: '::std::shared_ptr;::std::unique_ptr;::std::auto_ptr;::std::weak_ptr' + - key: cppcoreguidelines-no-malloc.Deallocations + value: '::free' + - key: bugprone-dangling-handle.HandleClasses + value: 'std::basic_string_view;std::experimental::basic_string_view' + - key: readability-magic-numbers.IgnorePowersOf2IntegerValues + value: 'false' + - key: readability-suspicious-call-argument.JaroWinklerSimilarAbove + value: '85' + - key: readability-simplify-subscript-expr.Types + value: '::std::basic_string;::std::basic_string_view;::std::vector;::std::array' + - key: performance-unnecessary-copy-initialization.ExcludedContainerTypes + value: '' + - key: modernize-replace-auto-ptr.IncludeStyle + value: llvm + - key: performance-move-const-arg.CheckTriviallyCopyableMove + value: 'true' + - key: readability-static-accessed-through-instance.NameSpecifierNestingThreshold + value: '3' + - key: readability-function-size.VariableThreshold + value: '4294967295' + - key: cert-dcl16-c.NewSuffixes + value: 'L;LL;LU;LLU' + - key: bugprone-narrowing-conversions.WarnOnFloatingPointNarrowingConversion + value: 'true' + - key: readability-identifier-naming.GetConfigPerFile + value: 'true' + - key: modernize-use-default-member-init.UseAssignment + value: 'false' + - key: readability-function-size.NestingThreshold + value: '4294967295' + - key: modernize-use-override.AllowOverrideAndFinal + value: 'false' + - key: cppcoreguidelines-narrowing-conversions.IgnoreConversionFromTypes + value: '' + - key: readability-function-size.ParameterThreshold + value: '4294967295' + - key: modernize-pass-by-value.ValuesOnly + value: 'false' + - key: readability-function-cognitive-complexity.IgnoreMacros + value: 'false' + - key: modernize-loop-convert.IncludeStyle + value: llvm + - key: cert-str34-c.DiagnoseSignedUnsignedCharComparisons + value: 'false' + - key: bugprone-narrowing-conversions.WarnWithinTemplateInstantiation + value: 'false' + - key: cert-err33-c.CheckedFunctions + value: '::aligned_alloc;::asctime_s;::at_quick_exit;::atexit;::bsearch;::bsearch_s;::btowc;::c16rtomb;::c32rtomb;::calloc;::clock;::cnd_broadcast;::cnd_init;::cnd_signal;::cnd_timedwait;::cnd_wait;::ctime_s;::fclose;::fflush;::fgetc;::fgetpos;::fgets;::fgetwc;::fopen;::fopen_s;::fprintf;::fprintf_s;::fputc;::fputs;::fputwc;::fputws;::fread;::freopen;::freopen_s;::fscanf;::fscanf_s;::fseek;::fsetpos;::ftell;::fwprintf;::fwprintf_s;::fwrite;::fwscanf;::fwscanf_s;::getc;::getchar;::getenv;::getenv_s;::gets_s;::getwc;::getwchar;::gmtime;::gmtime_s;::localtime;::localtime_s;::malloc;::mbrtoc16;::mbrtoc32;::mbsrtowcs;::mbsrtowcs_s;::mbstowcs;::mbstowcs_s;::memchr;::mktime;::mtx_init;::mtx_lock;::mtx_timedlock;::mtx_trylock;::mtx_unlock;::printf_s;::putc;::putwc;::raise;::realloc;::remove;::rename;::scanf;::scanf_s;::setlocale;::setvbuf;::signal;::snprintf;::snprintf_s;::sprintf;::sprintf_s;::sscanf;::sscanf_s;::strchr;::strerror_s;::strftime;::strpbrk;::strrchr;::strstr;::strtod;::strtof;::strtoimax;::strtok;::strtok_s;::strtol;::strtold;::strtoll;::strtoul;::strtoull;::strtoumax;::strxfrm;::swprintf;::swprintf_s;::swscanf;::swscanf_s;::thrd_create;::thrd_detach;::thrd_join;::thrd_sleep;::time;::timespec_get;::tmpfile;::tmpfile_s;::tmpnam;::tmpnam_s;::tss_create;::tss_get;::tss_set;::ungetc;::ungetwc;::vfprintf;::vfprintf_s;::vfscanf;::vfscanf_s;::vfwprintf;::vfwprintf_s;::vfwscanf;::vfwscanf_s;::vprintf_s;::vscanf;::vscanf_s;::vsnprintf;::vsnprintf_s;::vsprintf;::vsprintf_s;::vsscanf;::vsscanf_s;::vswprintf;::vswprintf_s;::vswscanf;::vswscanf_s;::vwprintf_s;::vwscanf;::vwscanf_s;::wcrtomb;::wcschr;::wcsftime;::wcspbrk;::wcsrchr;::wcsrtombs;::wcsrtombs_s;::wcsstr;::wcstod;::wcstof;::wcstoimax;::wcstok;::wcstok_s;::wcstol;::wcstold;::wcstoll;::wcstombs;::wcstombs_s;::wcstoul;::wcstoull;::wcstoumax;::wcsxfrm;::wctob;::wctrans;::wctype;::wmemchr;::wprintf_s;::wscanf;::wscanf_s;' + - key: bugprone-suspicious-string-compare.WarnOnLogicalNotComparison + value: 'false' + - key: readability-redundant-smartptr-get.IgnoreMacros + value: 'true' + - key: cppcoreguidelines-explicit-virtual-functions.AllowOverrideAndFinal + value: 'false' + - key: readability-identifier-naming.AggressiveDependentMemberLookup + value: 'false' + - key: readability-identifier-length.MinimumParameterNameLength + value: '3' + - key: modernize-use-emplace.TupleTypes + value: '::std::pair;::std::tuple' + - key: modernize-use-emplace.TupleMakeFunctions + value: '::std::make_pair;::std::make_tuple' + - key: bugprone-narrowing-conversions.WarnOnIntegerToFloatingPointNarrowingConversion + value: 'true' + - key: cppcoreguidelines-owning-memory.LegacyResourceProducers + value: '::malloc;::aligned_alloc;::realloc;::calloc;::fopen;::freopen;::tmpfile' + - key: bugprone-easily-swappable-parameters.SuppressParametersUsedTogether + value: 'true' + - key: bugprone-argument-comment.StrictMode + value: '0' + - key: modernize-replace-random-shuffle.IncludeStyle + value: llvm + - key: modernize-use-bool-literals.IgnoreMacros + value: 'true' + - key: bugprone-unhandled-self-assignment.WarnOnlyIfThisHasSuspiciousField + value: 'true' + - key: google-readability-namespace-comments.ShortNamespaceLines + value: '10' + - key: bugprone-suspicious-string-compare.StringCompareLikeFunctions + value: '' + - key: modernize-avoid-bind.PermissiveParameterList + value: 'false' + - key: bugprone-easily-swappable-parameters.NamePrefixSuffixSilenceDissimilarityTreshold + value: '1' + - key: readability-suspicious-call-argument.Suffix + value: 'true' + - key: readability-suspicious-call-argument.JaroWinklerDissimilarBelow + value: '75' + - key: modernize-use-noexcept.ReplacementString + value: '' + - key: modernize-use-override.FinalSpelling + value: final + - key: modernize-use-using.IgnoreMacros + value: 'true' + - key: cppcoreguidelines-explicit-virtual-functions.FinalSpelling + value: final + - key: readability-suspicious-call-argument.MinimumIdentifierNameLength + value: '3' + - key: bugprone-narrowing-conversions.WarnOnIntegerNarrowingConversion + value: 'true' + - key: modernize-loop-convert.NamingStyle + value: CamelCase + - key: cppcoreguidelines-pro-type-member-init.UseAssignment + value: 'false' + - key: bugprone-suspicious-include.HeaderFileExtensions + value: ';h;hh;hpp;hxx' + - key: performance-no-automatic-move.AllowedTypes + value: '' + - key: readability-suspicious-call-argument.SubstringDissimilarBelow + value: '40' + - key: bugprone-argument-comment.CommentIntegerLiterals + value: '0' + - key: bugprone-stringview-nullptr.IncludeStyle + value: llvm + - key: performance-for-range-copy.WarnOnAllAutoCopies + value: 'false' + - key: modernize-pass-by-value.IncludeStyle + value: llvm + - key: bugprone-argument-comment.CommentFloatLiterals + value: '0' + - key: bugprone-too-small-loop-variable.MagnitudeBitsUpperLimit + value: '16' + - key: readability-simplify-boolean-expr.ChainedConditionalReturn + value: 'false' + - key: readability-else-after-return.WarnOnConditionVariables + value: 'true' + - key: modernize-use-nullptr.NullMacros + value: 'NULL' + - key: readability-suspicious-call-argument.SuffixDissimilarBelow + value: '25' + - key: bugprone-argument-comment.CommentCharacterLiterals + value: '0' + - key: cppcoreguidelines-macro-usage.AllowedRegexp + value: '^DEBUG_*' + - key: readability-suspicious-call-argument.LevenshteinSimilarAbove + value: '66' + - key: cppcoreguidelines-narrowing-conversions.PedanticMode + value: 'false' + - key: modernize-make-shared.IgnoreDefaultInitialization + value: 'true' + - key: readability-suspicious-call-argument.JaroWinkler + value: 'true' + - key: bugprone-implicit-widening-of-multiplication-result.UseCXXHeadersInCppSources + value: 'true' + - key: modernize-make-shared.IncludeStyle + value: llvm + - key: readability-suspicious-call-argument.Prefix + value: 'true' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctions + value: 'false' + - key: bugprone-implicit-widening-of-multiplication-result.UseCXXStaticCastsInCppSources + value: 'true' + - key: bugprone-signed-char-misuse.CharTypdefsToIgnore + value: '' + - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors + value: 'false' + - key: modernize-make-unique.IgnoreMacros + value: 'true' + - key: performance-for-range-copy.AllowedTypes + value: '' + - key: bugprone-argument-comment.CommentBoolLiterals + value: '0' + - key: readability-braces-around-statements.ShortStatementLines + value: '0' + - key: bugprone-argument-comment.CommentUserDefinedLiterals + value: '0' + - key: readability-magic-numbers.IgnoredFloatingPointValues + value: '1.0;100.0;' + - key: performance-inefficient-string-concatenation.StrictMode + value: 'false' + - key: readability-redundant-declaration.IgnoreMacros + value: 'true' + - key: bugprone-easily-swappable-parameters.IgnoredParameterTypeSuffixes + value: 'bool;Bool;_Bool;it;It;iterator;Iterator;inputit;InputIt;forwardit;ForwardIt;bidirit;BidirIt;constiterator;const_iterator;Const_Iterator;Constiterator;ConstIterator;RandomIt;randomit;random_iterator;ReverseIt;reverse_iterator;reverse_const_iterator;ConstReverseIterator;Const_Reverse_Iterator;const_reverse_iterator;Constreverseiterator;constreverseiterator' + - key: modernize-make-unique.MakeSmartPtrFunction + value: 'std::make_unique' + - key: portability-restrict-system-includes.Includes + value: '*' + - key: readability-implicit-bool-conversion.AllowPointerConditions + value: 'true' + - key: modernize-make-unique.MakeSmartPtrFunctionHeader + value: '' + - key: bugprone-signal-handler.AsyncSafeFunctionSet + value: POSIX + - key: bugprone-easily-swappable-parameters.ModelImplicitConversions + value: 'true' + - key: readability-suspicious-call-argument.SubstringSimilarAbove + value: '50' + - key: cppcoreguidelines-narrowing-conversions.WarnWithinTemplateInstantiation + value: 'false' + - key: readability-identifier-length.MinimumVariableNameLength + value: '3' + - key: cppcoreguidelines-narrowing-conversions.WarnOnEquivalentBitWidth + value: 'true' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnorePublicMemberVariables + value: 'false' + - key: cppcoreguidelines-special-member-functions.AllowMissingMoveFunctionsWhenCopyIsDeleted + value: 'false' + - key: modernize-use-noexcept.UseNoexceptFalse + value: 'true' + - key: readability-function-cognitive-complexity.Threshold + value: '25' + - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic + value: 'true' + - key: bugprone-argument-comment.IgnoreSingleArgument + value: '0' + - key: bugprone-narrowing-conversions.WarnOnEquivalentBitWidth + value: 'true' + - key: bugprone-sizeof-expression.WarnOnSizeOfIntegerExpression + value: 'false' + - key: performance-faster-string-find.StringLikeClasses + value: '::std::basic_string;::std::basic_string_view' + - key: cppcoreguidelines-narrowing-conversions.WarnOnIntegerToFloatingPointNarrowingConversion + value: 'true' + - key: bugprone-assert-side-effect.CheckFunctionCalls + value: 'false' + - key: bugprone-string-constructor.StringNames + value: '::std::basic_string;::std::basic_string_view' + - key: bugprone-assert-side-effect.AssertMacros + value: assert,NSAssert,NSCAssert + - key: bugprone-exception-escape.IgnoredExceptions + value: '' + - key: bugprone-signed-char-misuse.DiagnoseSignedUnsignedCharComparisons + value: 'true' + - key: modernize-use-default-member-init.IgnoreMacros + value: 'true' + - key: llvm-qualified-auto.AddConstToQualified + value: 'false' + - key: llvm-else-after-return.WarnOnConditionVariables + value: 'false' + - key: bugprone-sizeof-expression.WarnOnSizeOfCompareToConstant + value: 'true' + - key: modernize-raw-string-literal.DelimiterStem + value: lit + - key: readability-suspicious-call-argument.Dice + value: 'true' + - key: readability-identifier-length.IgnoredLoopCounterNames + value: '^[ijk_]$' + - key: modernize-raw-string-literal.ReplaceShorterLiterals + value: 'false' + - key: readability-magic-numbers.IgnoredIntegerValues + value: '1;2;3;4;' + - key: performance-inefficient-vector-operation.VectorLikeClasses + value: '::std::vector' + - key: modernize-use-auto.RemoveStars + value: 'false' + - key: bugprone-implicit-widening-of-multiplication-result.IncludeStyle + value: llvm + - key: portability-simd-intrinsics.Std + value: '' + - key: performance-unnecessary-value-param.IncludeStyle + value: llvm + - key: readability-redundant-member-init.IgnoreBaseInCopyConstructors + value: 'false' + - key: modernize-replace-disallow-copy-and-assign-macro.MacroName + value: DISALLOW_COPY_AND_ASSIGN + - key: llvm-else-after-return.WarnOnUnfixable + value: 'false' +... + diff --git a/.github/problemMatcher/blackWarning.json b/.github/problemMatcher/blackWarning.json new file mode 100644 index 0000000000..2d48de1576 --- /dev/null +++ b/.github/problemMatcher/blackWarning.json @@ -0,0 +1,15 @@ +{ + "problemMatcher": [ + { + "owner": "black-warning", + "severity": "warning", + "pattern": [ + { + "regexp": "^(would reformat (.*))$", + "file": 2, + "message": 1 + } + ] + } + ] +} diff --git a/.github/problemMatcher/clang.json b/.github/problemMatcher/clang.json new file mode 100644 index 0000000000..b8a1185427 --- /dev/null +++ b/.github/problemMatcher/clang.json @@ -0,0 +1,17 @@ +{ + "problemMatcher": [ + { + "owner": "clang", + "pattern": [ + { + "regexp": "^(.+):([0-9]+):([0-9]+): (error|warning|note): (.+)$", + "file": 1, + "line": 2, + "column": 3, + "severity": 4, + "message": 5 + } + ] + } + ] +} diff --git a/.github/problemMatcher/codespell.json b/.github/problemMatcher/codespell.json new file mode 100644 index 0000000000..e8f4f8381f --- /dev/null +++ b/.github/problemMatcher/codespell.json @@ -0,0 +1,16 @@ +{ + "problemMatcher": [ + { + "owner": "codespell-matcher", + "severity": "warning", + "pattern": [ + { + "regexp": "^(.+):(\\d+):\\s+(.+)$", + "file": 1, + "line": 2, + "message": 3 + } + ] + } + ] +} diff --git a/.github/problemMatcher/cpplint.json b/.github/problemMatcher/cpplint.json new file mode 100644 index 0000000000..79efedb0f1 --- /dev/null +++ b/.github/problemMatcher/cpplint.json @@ -0,0 +1,16 @@ +{ + "problemMatcher": [ + { + "owner": "cpplint", + "severity": "warning", + "pattern": [ + { + "regexp": "^(.+):([0-9]+): (.+)$", + "file": 1, + "line": 2, + "message": 3 + } + ] + } + ] +} diff --git a/.github/problemMatcher/grepMatcherWarning.json b/.github/problemMatcher/grepMatcherWarning.json new file mode 100644 index 0000000000..49671d4253 --- /dev/null +++ b/.github/problemMatcher/grepMatcherWarning.json @@ -0,0 +1,16 @@ +{ + "problemMatcher": [ + { + "owner": "grepMatcher-warning", + "severity": "warning", + "pattern": [ + { + "regexp": "^(.+):([0-9]+):(.+)$", + "file": 1, + "line": 2, + "message": 3 + } + ] + } + ] +} diff --git a/.github/problemMatcher/pylintError.json b/.github/problemMatcher/pylintError.json new file mode 100644 index 0000000000..8c5f73fbf5 --- /dev/null +++ b/.github/problemMatcher/pylintError.json @@ -0,0 +1,18 @@ +{ + "problemMatcher": [ + { + "owner": "pylint-error", + "severity": "error", + "pattern": [ + { + "regexp": "^(.+?):([0-9]+):([0-9]+): ([([E|F][0-9]+): (.*)$", + "file": 1, + "line": 2, + "column": 3, + "code": 4, + "message": 5 + } + ] + } + ] +} diff --git a/.github/problemMatcher/pylintWarning.json b/.github/problemMatcher/pylintWarning.json new file mode 100644 index 0000000000..6a453f1d43 --- /dev/null +++ b/.github/problemMatcher/pylintWarning.json @@ -0,0 +1,18 @@ +{ + "problemMatcher": [ + { + "owner": "pylint-warning", + "severity": "warning", + "pattern": [ + { + "regexp": "^(.+?):([0-9]+):([0-9]+): ([^E|F][0-9]+): (.*)$", + "file": 1, + "line": 2, + "column": 3, + "code": 4, + "message": 5 + } + ] + } + ] +} diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000000..8c03475ed9 --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,1128 @@ +name: CI +on: + push: + branches: ['master', 'development/toponaming', 'releases/FreeCAD-0-20'] + pull_request: + +permissions: + pull-requests: write + contents: write + +env: + logdir: logs/ + fixesdir: fixes/ + + # Build and Test + buildFailSilent: false + test: true # run Unit tests + testFailSilent: false # don't fail CI if Unittests fail + + testInstall: true # run CMake install and Unit tests on install + installFailSilent: false # don't fail if CMake install fails + testInstallFailSilent: false # don't fail CI if Unittests fail + + # Linting + checkWhitespace: true + whitespaceFailSilent: true + + checkTabs: true + tabsFailSilent: true + + checkQtconnections: true + qtconnectionSyntaxFailSilent: true + + checkCpplint: true + # This option allows you to specify a comma-separated list of rule-filters to apply. For example, the rule names look like whitespace/indent. In that case, the category is whitespace. + # To turn off, specify - as prefix like -whitespace or -whitespace/indent. On the other hand, to turn on, specify + like +whitespace or +whitespace/indent. + # The recommended filters are taken from https://github.com/sider/runners/blob/HEAD/images/cpplint/sider_recommended_CPPLINT.cfg + cpplintFilters: -build/c++11,-build/header_guard,-build/include,-build/include_alpha,-build/include_order,-build/include_subdir,-build/include_what_you_use,-build/namespaces,-legal/copyright,-readability/braces,-readability/casting,-readability/namespace,-readability/todo,-runtime/int,-runtime/references,-whitespace/blank_line,-whitespace/braces,-whitespace/comments,-whitespace/end_of_line,-whitespace/indent,-whitespace/line_length,-whitespace/newline,-whitespace/operators,-whitespace/parens,-whitespace/tab,-whitespace/todo + cpplintLineLength: 120 + cpplintFailSilent: true + + checkPylint: true + # additional disables to the .pylintrc file + # for the Message codes see: https://pylint.pycqa.org/en/latest/user_guide/messages/index.html + pylintDisable: disable=C0302 # too-many-lines + + checkBlack: true + blackFailSilent: true + + checkClangFormat: false + clangStyle: file #for .clang-format file + clangFormatFailSilent: true + + checkSpelling: true + listIgnoredMisspelling: .github/codespellignore + skip: ./.git,*.po,*.ts,*.svg,./ChangeLog.txt,./src/3rdParty,./src/Mod/Assembly/App/opendcm,./src/CXX,./src/zipios++,./src/Base/swig*,./src/Mod/Robot/App/kdl_cp,./src/Mod/Import/App/SCL,./src/WindowsInstaller,./src/Doc/FreeCAD.uml,./build/ + codespellFailSilent: false + + # Static Analysis + checkClangTidy: true + # for the Message codes see: https://clang-tidy.llvm.org/checks/index.html + clangTidyChecks: # empty to use the .clang-tidy file + clangTidyFailSilent: true # if false, the CI will fail if clang-tidy finds errors. Warnings or notes will not fail the CI + + checkClazy: true + # for the Message codes see: https://invent.kde.org/sdk/clazy#list-of-checks + clazyChecks: level1 + clazyFailSilent: true # if false, the CI will fail if clazy finds errors. Warnings or notes will not fail the CI + + checkClazyQT6: true + clazyQT6Checks: qt6-deprecated-api-fixes,qt6-header-fixes,qt6-qhash-signature,qt6-fwd-fixes,missing-qobject-macro # for QT6 Porting https://invent.kde.org/sdk/clazy#list-of-checks + QT6Branch: master # branch to check for QT6 Porting + clazyQT6FailSilent: true # if false, the CI will fail if clazy finds errors. Warnings or notes will not fail the CI + + # Reporting + reportStepSummary: true + reportPRComment: false # disabled because of permission hell (and the comments are to big for Github) + reportPushComment: false # disabled because of permission hell (and the comments are to big for Github) + +jobs: + checks: + name: Checks + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 2 + + - name: Install FreeCAD dependencies + id: install-dependencies + run: | + sudo apt-get update -qq + + # apt-get install all the dependencies + # TODO: script to install all the dependencies (tools/build/ubuntu.sh) not working + # chmod +x tools/build/ubuntu.sh + # sudo ./tools/build/ubuntu.sh + + sudo apt-get install -y --no-install-recommends \ + python3-dev \ + python3-matplotlib \ + python3-pivy \ + python3-ply \ + python3-pyside2.qtcore \ + python3-pyside2.qtgui \ + python3-pyside2.qtsvg \ + python3-pyside2.qtwidgets \ + python3-pyside2.qtnetwork \ + python3-markdown \ + python3-git \ + libboost-date-time-dev \ + libboost-dev \ + libboost-filesystem-dev \ + libboost-graph-dev \ + libboost-iostreams-dev \ + libboost-program-options-dev \ + libboost-python-dev \ + libboost-regex-dev \ + libboost-serialization-dev \ + libboost-thread-dev \ + libxerces-c-dev \ + libocct-data-exchange-dev \ + libocct-ocaf-dev \ + libocct-visualization-dev \ + occt-draw \ + libvtk7-dev \ + swig \ + libcoin-dev \ + libeigen3-dev \ + libgts-bin \ + libgts-dev \ + libkdtree++-dev \ + libmedc-dev \ + libopencv-dev \ + libproj-dev \ + libpyside2-dev \ + pyside2-tools \ + pyqt5-dev-tools \ + libqt5opengl5-dev \ + libqt5svg5-dev \ + libqt5webkit5-dev \ + libqt5x11extras5-dev \ + libqt5xmlpatterns5-dev \ + qtbase5-dev \ + qttools5-dev \ + libx11-dev \ + libzipios++-dev \ + doxygen \ + graphviz \ + libnglib-dev \ + netgen \ + netgen-headers \ + libmetis-dev \ + libspnav-dev \ + libshiboken2-dev \ + shiboken2 \ + imagemagick + + - name: Get Date + if: always() + id: get-date + run: | + echo "::set-output name=date::$(/bin/date -u "+%Y%m%d%H%M")" + shell: bash + + - name: Install ccache + if: always() + run: | + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends ccache + + - name: make directories + if: always() + run: | + mkdir -p ${{ env.logdir }} + mkdir -p ${{ env.fixesdir }} + + mkdir -p ~/.ccache + + - name: Restore Compiler Cache + if: always() + uses: pat-s/always-upload-cache@v3 + with: + path: | + ~/.ccache + key: CI-cache-${{ steps.get-date.outputs.date }}-${{ github.run_number }} + restore-keys: | + CI-cache-${{ steps.get-date.outputs.date }}- + CI-cache- + + - name: Configure Cache + if: always() + run: | + ccache -z -M 1G + ccache --show-config + ccache -s + + - name: Job summary Header + if: always() + id: header + run: | + echo '# Check Results: :rocket:' >> ${{ env.logdir }}checkReport.md + + - name: Get changed files + if: always() + id: changed-files + uses: tj-actions/changed-files@v24 + + - name: Report all changed Files + id: list-changed-files + run: | + echo "
:clipboard: Changed Files:" >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '``` shell' >> ${{ env.logdir }}checkReport.md + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + echo "$file" >> ${{ env.logdir }}checkReport.md + done + echo '```' >> ${{ env.logdir }}checkReport.md + echo '
' >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + - name: Harmonize Line endings + id: harmonize-line-endings + shell: bash + run: | + # harmonize line endings in all changed files (Windows -> Unix) + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + if [ -f "$file" ]; then + echo "Harmonizing line endings in $file" + sed -i 's/\r//g' $file + fi + done + + - name: filter files by extensions + if: always() + id: files-by-extensions + shell: bash + run: | + changed_files=$( echo ${{ steps.changed-files.outputs.all_changed_files }} ) + + py=$(grep -oE '\S+\.(py|py3)' <<< $changed_files | tr '\n' ' ') || true # grep returns non-zero exit code if no match is found + cpp=$(grep -oE '\S+\.(c|c\+\+|cc|cpp|cu|cuh|cxx|h|h\+\+|hh|hpp|hxx)' <<< $changed_files | tr '\n' ' ') || true + echo "::set-output name=python_files::$py" + echo "::set-output name=cpp_files::$cpp" + echo "Python Files: $py" + echo "C++ Files: $cpp" + + - name: CMake Configure + id: configure + if: always() + run: | + set +e + + cmake \ + -D CMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE \ + -B build/ > ${{ env.logdir }}Cmake.log 2> ${{ env.logdir }}CmakeErrors.log + + exitCode=$? + + # Build Header in Report + echo '### Build:' >> ${{ env.logdir }}checkReport.md + + # Write the configure report + if [ $exitCode -eq 0 ] ; then + echo "
:heavy_check_mark: CMake configure succeeded" >> ${{ env.logdir }}checkReport.md + else + echo "
:fire: CMake configure failed" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + echo "Configure Error Log (stderr output):" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}CmakeErrors.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "Configure Log (stdout output):" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + tail -n 60 ${{ env.logdir }}Cmake.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + cat ${{ env.logdir }}CmakeErrors.log + echo "::group::Configure Log" + cat ${{ env.logdir }}Cmake.log + echo "::endgroup::" + + exit $exitCode + + - name: Print ccache statistics before Build + if: always() + run: ccache -s + + - name: CMake Build + id: build + if: always() + run: | + set +e + + cmake --build build/ > ${{ env.logdir }}Build.log 2> ${{ env.logdir }}BuildErrors.log + + exitCode=$? + + # Write the build report + if [ $exitCode -eq 0 ] ; then + echo "
:heavy_check_mark: CMake build succeeded" >> ${{ env.logdir }}checkReport.md + else + echo "
:fire: CMake build failed" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + echo "Build Error Log (stderr output):" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}BuildErrors.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "Build Log (stdout output trimmed to the last 100 Lines):" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + tail -n 50 ${{ env.logdir }}Build.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Print the Log to the console + cat ${{ env.logdir }}BuildErrors.log + echo "::group::Build Log" + cat ${{ env.logdir }}Build.log + echo "::endgroup::" + + # Exit the step with the exit code of the build + if [ ${{ env.buildFailSilent }} != true ]; then + exit $exitCode + else + echo "Build exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: Print ccache statistics after Build + if: always() + run: ccache -s + + - name: FreeCAD UnitTests + id: test + if: env.test == 'true' && always() + run: | + set +e + + build/bin/FreeCADCmd -t 0 &> ${{ env.logdir }}Test.log + + exitCode=$? + + # Trim the Log file + # remove "(xx %)" + sed -E '/\t+\([[:digit:]]{1,3} %\)\t/d' ${{ env.logdir }}Test.log > ${{ env.logdir }}TestTrimmed.log + + # Write the test report + if [ $exitCode -eq 0 ] ; then + echo "
:heavy_check_mark: Unittests succeeded" >> ${{ env.logdir }}checkReport.md + else + echo "
:fire: CMake test failed" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + tail -n 100 ${{ env.logdir }}TestTrimmed.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Print the Log to the console + cat ${{ env.logdir }}Test.log + + # Exit the step with the exit code of the UnitTests + if [ ${{ env.testFailSilent }} != true ]; then + exit $exitCode + else + echo "Test exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: CMake Install + id: install + if: env.testInstall == 'true' && always() + run: | + set +e + + # Run the CMake Configure step again to update the install path + cmake \ + -D CMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE \ + -D CMAKE_INSTALL_PREFIX='/usr/lib/freecad' \ + -D CMAKE_INSTALL_BINDIR='/usr/lib/freecad/bin' \ + -D CMAKE_INSTALL_LIBDIR='/usr/lib/freecad/lib' \ + -D CMAKE_INSTALL_DATADIR='/usr/share/freecad' \ + -D CMAKE_INSTALL_DATAROOTDIR='/usr/share' \ + -D CMAKE_INSTALL_DOCDIR='/usr/share/doc/freecad' \ + -B build/ >> ${{ env.logdir }}Install.log 2>> ${{ env.logdir }}InstallErrors.log + + # Build again to copy the files to the install path + cmake --build build/ >> ${{ env.logdir }}Install.log 2>> ${{ env.logdir }}InstallErrors.log + + # Run CMake Install + sudo cmake --install build/ >> ${{ env.logdir }}Install.log 2>> ${{ env.logdir }}InstallErrors.log + + exitCode=$? + + # links for bin + FILES=/usr/lib/freecad/bin/* + for f in $FILES + do + sudo ln -vs /usr/lib/freecad/bin/$(basename $f) /usr/bin/$(basename $f) + done + + # Write the install report + if [ $exitCode -eq 0 ] ; then + echo "
:heavy_check_mark: CMake install succeeded" >> ${{ env.logdir }}checkReport.md + else + echo "
:fire: CMake install failed" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + echo "Install Error Log (stderr output):" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}InstallErrors.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "Install Error Log (stdout output trimmed to the last 100 Lines):" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + tail -n 100 ${{ env.logdir }}Install.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Print the Log to the console + cat ${{ env.logdir }}InstallErrors.log + echo "::group::Install Log" + cat ${{ env.logdir }}Install.log + echo "::endgroup::" + + # Exit the step with the exit code of the Install + if [ ${{ env.cmakeInstallFailSilent }} != true ]; then + exit $exitCode + else + echo "CMake install exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: FreeCAD UnitTests on Install + id: testInstall + if: env.testInstall == 'true' && always() + run: | + set +e + + LD_LIBRARY_PATH=/usr/lib/freecad/lib FreeCADCmd -t 0 &> ${{ env.logdir }}TestInstall.log + + exitCode=$? + + # Trim the Log file + # remove "(xx %)" + sed -E '/\t+\([[:digit:]]{1,3} %\)\t/d' ${{ env.logdir }}TestInstall.log > ${{ env.logdir }}TestInstallTrimmed.log + + # Write the testInstall report + if [ $exitCode -eq 0 ] ; then + echo "
:heavy_check_mark: Unittests on install succeeded" >> ${{ env.logdir }}checkReport.md + else + echo "
:fire: CMake test on install failed" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + tail -n 100 ${{ env.logdir }}TestInstallTrimmed.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Print the Log to the console + cat ${{ env.logdir }}TestInstall.log + + # Exit the step with the exit code of the UnitTests + if [ ${{ env.testInstallFailSilent }} != true ]; then + exit $exitCode + else + echo "Test on install exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: Report Tests header + if: always() + id: tests-header + run: | + echo '### Tests:' >> ${{ env.logdir }}checkReport.md + + - name: Trailing whitespaces + shell: bash + if: env.checkWhitespace == 'true' && always() + run: | + whitespaceErrors="0" + exclude="*[.md]" + + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + # check for whitespaces + grep -rnIHE --exclude="$exclude" " $" $file | sed 's/$/<-- trailing whitespace/' >> ${{ env.logdir }}whitespace.log || true + done + + # Write the Log to the console with the Problem Matchers + if [ -f ${{ env.logdir }}whitespace.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/grepMatcherWarning.json" + cat ${{ env.logdir }}whitespace.log + echo "::remove-matcher owner=grepMatcher-warning::" + + whitespaceErrors=$(wc -l < ${{ env.logdir }}whitespace.log) + fi + + echo "Found $whitespaceErrors whitespace errors" + + echo "whitespaceErrors=$whitespaceErrors" >> $GITHUB_ENV + + # Write the report + if [ $whitespaceErrors -gt 0 ]; then + echo "
:information_source: Found $whitespaceErrors trailing whitespace" >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}whitespace.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + else + echo ":heavy_check_mark: No trailing whitespace found " >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + + # Exit the step with the exit code + if [ $whitespaceErrors -gt 0 ] && [ ${{ env.whitespaceFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Tabs + shell: bash + if: env.checkTabs == 'true' && always() + run: | + tabErrors="0" + exclude="*[.md]" + + # check for tabs + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + grep -rnIHE --exclude="$exclude" $'\t' $file | sed 's/$/ <-- contains tab/' >> ${{ env.logdir }}tab.log || true + done + + # Write the Log to the console with the Problem Matchers + if [ -f ${{ env.logdir }}tab.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/grepMatcherWarning.json" + cat ${{ env.logdir }}tab.log + echo "::remove-matcher owner=grepMatcher-warning::" + + tabErrors=$(wc -l < ${{ env.logdir }}tab.log) + fi + + echo "Found $tabErrors tab errors" + + echo "tabErrors=$tabErrors" >> $GITHUB_ENV + + # Write the report + if [ $tabErrors -gt 0 ]; then + echo "
:information_source: Found $tabErrors tabs, better to use spaces" >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}tab.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + else + echo ":heavy_check_mark: No tabs found" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + + # Exit the step with the exit code + if [ $tabErrors -gt 0 ] && [ ${{ env.tabsFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: QT - old string-based connections (https://wiki.qt.io/New_Signal_Slot_Syntax) + shell: bash + if: env.checkQtconnections == 'true' && steps.files-by-extensions.outputs.cpp_files != '' && always() + run: | + qtconnectionSyntax="0" + exclude="*[.md,.log,.ts,.git]" + + # check all files for QT string-based connections + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + grep -rnIHE --exclude="$exclude" $' SIGNAL| SLOT' $file | sed 's,$, <--Consider using Functor-Based Connections,' >> ${{ env.logdir }}stringSyntax.log || true + done + + # Parse the log file + if [ -f ${{ env.logdir }}stringSyntax.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/grepMatcherWarning.json" + cat ${{ env.logdir }}stringSyntax.log + echo "::remove-matcher owner=grepMatcher-warning::" + + qtconnectionSyntax=$(wc -l < ${{ env.logdir }}stringSyntax.log) + fi + + # Pass Variables to GitHub Env + echo "qtconnectionSyntax=$qtconnectionSyntax" >> $GITHUB_ENV + + echo "Found $qtconnectionSyntax QT string-based connections" + + # Step-Report + if [ $qtconnectionSyntax -gt 0 ]; then + echo "
:information_source: Found $qtconnectionSyntax QT string-based connections :arrow_right: consider using QT functor-Based Connections" >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + # documentation link + echo "For more information see: https://wiki.qt.io/New_Signal_Slot_Syntax or https://github.com/FreeCAD/FreeCAD/issues/6166" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}stringSyntax.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + else + echo ":heavy_check_mark: No string-based connections found " >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + + # Exit the step with the exit code + if [ $qtconnectionSyntax -gt 0 ] && [ ${{ env.qtconnectionSyntaxFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Cpplint + shell: bash + if: env.checkCpplint == 'true' && steps.files-by-extensions.outputs.cpp_files != '' && always() + run: | + cpplintErrors="0" + + pip install cpplint + + # run cpplint + for file in ${{ steps.files-by-extensions.outputs.cpp_files }}; do + cpplint --filter=${{ env.cpplintFilters }} --linelength=${{ env.cpplintLineLength }} $file &>> ${{ env.logdir }}cpplint.log || true + done + + # if cpplint has run successfully parse the output + if [ -f ${{ env.logdir }}cpplint.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/cpplint.json" + cat ${{ env.logdir }}cpplint.log + echo "::remove-matcher owner=cpplint::" + + cpplintErrors=$(grep -rnIHE "\[[0-9]\]$" ${{ env.logdir }}cpplint.log | wc -l ) || true + fi + + # Pass Variables to GitHub Env + echo "cpplintErrors=$cpplintErrors" >> $GITHUB_ENV + + echo "Found $cpplintErrors cpplint errors" + + # Step-Report + if [ $cpplintErrors -gt 0 ]; then + echo "
:warning: CppLint found $cpplintErrors errors / warnings" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: No cpplint errors found " >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}cpplint.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Exit the step with the exit code + if [ $cpplintErrors -gt 0 ] && [ ${{ env.cpplintFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Pylint + shell: bash + if: env.checkPylint == 'true' && steps.files-by-extensions.outputs.python_files != '' && always() + run: | + set +e + + pylintErrors="0" + + pip install pylint + + pylintErrors="0" + pylintWarnings="0" + pylintRefactorings="0" + pylintConventions="0" + + # List enabled pylint checks + pylint --list-msgs-enabled > ${{ env.logdir }}pylint-enabled-checks.log + + # Run pylint on all python files + pylint --disable=${{ env.pylintDisable }} ${{ steps.files-by-extensions.outputs.python_files }} > ${{ env.logdir }}pylint.log + + exitCode=$? + + # if pylint has run successfully, then parse the output + if [ -f ${{ env.logdir }}pylint.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/pylintError.json" + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/pylintWarning.json" + cat ${{ env.logdir }}pylint.log + echo "::remove-matcher owner=pylint-error::" + echo "::remove-matcher owner=pylint-warning::" + + pylintErrors=$( grep -oP '(?<=error \|)\d+' ${{ env.logdir }}pylint.log) || true # grep returns 0 if no match is found + pylintWarnings=$( grep -oP '(?<=warning \|)\d+' ${{ env.logdir }}pylint.log) || true + pylintRefactorings=$( grep -oP '(?<=refactor \|)\d+' ${{ env.logdir }}pylint.log) || true + pylintConventions=$( grep -oP '(?<=convention \|)\d+' ${{ env.logdir }}pylint.log) || true + fi + + # Pass Variables to GitHub Env + echo "pylintErrors=$pylintErrors" >> $GITHUB_ENV + echo "pylintWarnings=$pylintWarnings" >> $GITHUB_ENV + echo "pylintRefactorings=$pylintRefactorings" >> $GITHUB_ENV + echo "pylintConventions=$pylintConventions" >> $GITHUB_ENV + + echo "Found $pylintErrors errors, $pylintWarnings warnings, $pylintRefactorings refactorings, $pylintConventions conventions" + + #Step-summary + if [ $pylintErrors -gt 0 ]; then + echo "
:fire: Pylint found :fire: $pylintErrors errors, :warning: $pylintWarnings warnings, :construction: $pylintRefactorings refactorings and :pencil2: $pylintConventions conventions" >> ${{ env.logdir }}checkReport.md + elif [ $pylintWarnings -gt 0 ]; then + echo "
:warning: Pylint found :warning: $pylintWarnings warnings, :construction: $pylintRefactorings refactorings and :pencil2: $pylintConventions conventions" >> ${{ env.logdir }}checkReport.md + elif [ $pylintRefactorings -gt 0 ]; then + echo "
:construction: Pylint found :construction: $pylintRefactorings refactorings and :pencil2: $pylintConventions conventions" >> ${{ env.logdir }}checkReport.md + elif [ $pylintConventions -gt 0 ]; then + echo "
:pencil2: Pylint found :pencil2: $pylintConventions conventions" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: No pylint errors found " >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + # list enabled checks + echo "
:information_source: Enabled checks" >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}pylint-enabled-checks.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}pylint.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Error the step if pylint has found errors + if [ $pylintErrors -gt 0 ] && [ ${{ env.pylintFailSilent }} != true ]; then + exit $exitCode + else + echo "Pylint exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: Black (Python) + shell: bash + if: env.checkBlack == 'true' && steps.files-by-extensions.outputs.python_files != '' && always() + run: | + set +e + + pip install black + + blackReformats="0" + blackFails="0" + + black --check ${{ steps.files-by-extensions.outputs.python_files }} &> ${{ env.logdir }}black.log + + exitCode=$? + + # if black has run successfully, then parse the output + if [ -f ${{ env.logdir }}black.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/blackWarning.json" + cat ${{ env.logdir }}black.log + echo "::remove-matcher owner=black-warning::" + + blackReformats=$( grep -oP '\d+(?= fil.+ would be reformatted)' ${{ env.logdir }}black.log) || true # grep returns 0 if no match is found + blackFails=$( grep -oP '\d+(?= fil.+ would fail to reformat)' ${{ env.logdir }}black.log) || true + fi + + # Pass Variables to GitHub Env + echo "blackReformats=$blackReformats" >> $GITHUB_ENV + echo "blackFails=$blackFails" >> $GITHUB_ENV + + echo "Found $blackReformats files would be reformatted and $blackFails files would fail to reformat" + + #Step-summary + if [ $blackReformats -gt 0 ] || [ $blackFails -gt 0 ] ; then + echo "
:pencil2: Black would reformat $blackReformats files" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: Black would reformat no file" >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}black.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + if [ $exitCode -gt 0 ] && [ ${{ env.blackFailSilent }} != true ]; then + exit $exitCode + else + echo "Black exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: Clang-format + shell: bash + if: env.checkClangFormat == 'true' && steps.files-by-extensions.outputs.cpp_files != '' && always() + run: | + clangFormatErrors="0" + + # run clang-format on all cpp files + clang-format --dry-run --ferror-limit=1 --verbose --style=${{ env.clangStyle }} ${{ steps.files-by-extensions.outputs.cpp_files }} &>> ${{ env.logdir }}clang-format.log || true + + # if cpplint has run successfully parse the output + if [ -f ${{ env.logdir }}clang-format.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/clang.json" + cat ${{ env.logdir }}clang-format.log + echo "::remove-matcher owner=clang::" + + clangFormatErrors=$(grep -rnIHE "\[-Wclang-format-violations]$" ${{ env.logdir }}clang-format.log | wc -l ) || true + fi + + # Pass Variables to GitHub Env + echo "clangFormatErrors=$clangFormatErrors" >> $GITHUB_ENV + + echo "Found $clangFormatErrors clang-format errors" + + # Report + + if [ $clangFormatErrors -gt 0 ]; then + echo "
:pencil2: Clang-format would reformat $clangFormatErrors files" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: Clang-format would reformat no file " >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}clang-format.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + if [ $clangFormatErrors -gt 0 ] && [ ${{ env.clangFormatFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Codespell + shell: bash + if: env.checkSpelling == 'true' && always() + run: | + pip install codespell + + wget https://raw.githubusercontent.com/codespell-project/codespell/master/codespell_lib/data/dictionary.txt + #wget https://raw.githubusercontent.com/codespell-project/codespell/master/codespell_lib/data/dictionary_rare.txt + + #misspellings=$( codespell --quiet-level 3 --summary --count --ignore-words ${{ env.listIgnoredMisspelling }} --skip ${{ env.skip }} -D dictionary.txt -D dictionary_rare.txt ${{ steps.changed-files.outputs.all_changed_files }} 2>&1 > ${{ env.logdir }}codespell.log ) || true + misspellings=$( codespell --quiet-level 3 --summary --count --ignore-words ${{ env.listIgnoredMisspelling }} --skip ${{ env.skip }} -D dictionary.txt ${{ steps.changed-files.outputs.all_changed_files }} 2>&1 > ${{ env.logdir }}codespell.log ) || true + + # if codespell has run successfully, then parse the output + if [ -f ${{ env.logdir }}codespell.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/codespell.json" + cat ${{ env.logdir }}codespell.log + echo "::remove-matcher owner=codespell::" + fi + + # Pass Variables to GitHub Env + echo "CodespellMisspellings=$misspellings" >> $GITHUB_ENV + + echo "Found $misspellings misspellings" + + #Step-summary + if [ $misspellings -gt 0 ]; then + echo "
:pencil2: Codespell found $misspellings misspellings" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: Codespell found no misspellings" >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + # documentation link + echo "To ignore false positives, append the word to the [.github/codespellignore](https://github.com/FreeCAD/FreeCAD/blob/c38e88c61b8926f725215da88940025c94be1daa/.github/codespellignore) file (lowercase)" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}codespell.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Error the step if pylint has found errors + if [ $misspellings -gt 0 ] && [ ${{ env.codespellFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Clang-tidy + shell: bash + if: env.checkClangTidy == 'true' && steps.files-by-extensions.outputs.cpp_files != '' && always() + run: | + set +e + + clangTidyErrors="0" + clangTidyWarnings="0" + clangTidyNotes="0" + + sudo apt-get install -y --no-install-recommends clang-tidy + + clang-tidy --quiet --format-style=${{ env.clangStyle }} --export-fixes=${{ env.fixesdir }}clang-tidy.yaml -checks=${{ env.clangTidyChecks }} -p build/ --explain-config &>> ${{ env.logdir }}clang-tidy-enabled-checks.log + + clang-tidy --quiet --format-style=${{ env.clangStyle }} --export-fixes=${{ env.fixesdir }}clang-tidy.yaml -checks=${{ env.clangTidyChecks }} -p build/ ${{ steps.files-by-extensions.outputs.cpp_files }} &>> ${{ env.logdir }}clang-tidy.log + + exitCode=$? + + # if clang-tidy has run successfully parse the output + if [ -f ${{ env.logdir }}clang-tidy.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/clang.json" + cat ${{ env.logdir }}clang-tidy.log + echo "::remove-matcher owner=clang::" + + clangTidyErrors=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): error: .+$" ${{ env.logdir }}clang-tidy.log | wc -l ) || true + clangTidyWarnings=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): warning: .+$" ${{ env.logdir }}clang-tidy.log | wc -l ) || true + clangTidyNotes=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): note: .+$" ${{ env.logdir }}clang-tidy.log | wc -l ) || true + fi + + # Pass Variables to GitHub Env + echo "clangTidyErrors=$clangTidyErrors" >> $GITHUB_ENV + echo "clangTidyWarnings=$clangTidyWarnings" >> $GITHUB_ENV + echo "clangTidyNotes=$clangTidyNotes" >> $GITHUB_ENV + + echo "Found $clangTidyErrors errors, $clangTidyWarnings warnings, $clangTidyNotes notes" + + # Step-Report + if [ $clangTidyErrors -gt 0 ]; then + echo "
:fire: Clang-Tidy found :fire: $clangTidyErrors errors, :warning: $clangTidyWarnings warnings and :pencil2: $clangTidyNotes notes" >> ${{ env.logdir }}checkReport.md + elif [ $clangTidyWarnings -gt 0 ]; then + echo "
:warning: Clang-Tidy found :warning: $clangTidyWarnings warnings and :pencil2: $clangTidyNotes notes" >> ${{ env.logdir }}checkReport.md + elif [ $clangTidyNotes -gt 0 ]; then + echo "
:pencil2: Clang-Tidy found :pencil2: $clangTidyNotes notes" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: Clang-Tidy found no errors, warnings or notes" >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + # enabled checks + echo "
:information_source: Enabled checks" >> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}clang-tidy-enabled-checks.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}clang-tidy.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Error the step if pylint has found errors + if [ $clangTidyErrors -gt 0 ] && [ ${{ env.clangTidyFailSilent }} != true ]; then + exit 1 + else + echo "Clang-tidy exited with code $exitCode, but we are ignoring it" + exit 0 + fi + + - name: Clazy + shell: bash + if: env.checkClazy == 'true' && steps.files-by-extensions.outputs.cpp_files != '' && always() + run: | + clazyErrors="0" + clazyWarnings="0" + clazyNotes="0" + + sudo apt-get install -y --no-install-recommends clazy + + clazy-standalone --export-fixes=${{ env.fixesdir }}clazy.yaml -checks=${{ env.clazyChecks }} -p build/ ${{ steps.files-by-extensions.outputs.cpp_files }} &>> ${{ env.logdir }}clazy.log || true + + # if Clazy has run successfully parse the output + if [ -f ${{ env.logdir }}clazy.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/clang.json" + cat ${{ env.logdir }}clazy.log + echo "::remove-matcher owner=clang::" + + clazyErrors=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): error: .+$" ${{ env.logdir }}clazy.log | wc -l ) || true + clazyWarnings=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): warning: .+$" ${{ env.logdir }}clazy.log | wc -l ) || true + clazyNotes=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): note: .+$" ${{ env.logdir }}clazy.log | wc -l ) || true + fi + + # Pass Variables to GitHub Env + echo "clazyErrors=$clazyErrors" >> $GITHUB_ENV + echo "clazyWarnings=$clazyWarnings" >> $GITHUB_ENV + echo "clazyNotes=$clazyNotes" >> $GITHUB_ENV + + echo "Found $clazyErrors errors, $clazyWarnings warnings, $clazyNotes notes" + + # Step-Report + if [ "$clazyErrors" -gt 0 ]; then + echo "
:fire: Clazy found :fire: $clazyErrors errors, :warning: $clazyWarnings warnings and :pencil2: $clazyNotes notes" >> ${{ env.logdir }}checkReport.md + elif [ "$clazyWarnings" -gt 0 ]; then + echo "
:warning: Clazy found :warning: $clazyWarnings warnings and :pencil2: $clazyNotes notes" >> ${{ env.logdir }}checkReport.md + elif [ "$clazyNotes" -gt 0 ]; then + echo "
:pencil2: Clazy found :pencil2: $clazyNotes notes" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: Clazy found no errors, warnings or notes" >> ${{ env.logdir }}checkReport.md + fi + echo "" >> ${{ env.logdir }}checkReport.md + # documentation link + echo "[List of checks](https://github.com/KDE/clazy#list-of-checks), [This explains some of the clazy warnings](https://www.kdab.com/uncovering-32-qt-best-practices-compile-time-clazy/) " >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}clazy.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Error the step if pylint has found errors + if [ "$clazyErrors" -gt 0 ] && [ ${{ env.clazyFailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Clazy-QT6 + shell: bash + if: env.checkClazyQT6 == 'true' && steps.files-by-extensions.outputs.cpp_files != '' && github.ref == env.QT6Branch && always() + run: | + clazyQT6Errors="0" + clazyQT6Warnings="0" + clazyQT6Notes="0" + + sudo apt-get install clazy + + # clazy checks for qt6 porting + clazy-standalone --export-fixes=${{ env.fixesdir }}clazyQT6.yaml -checks=${{ env.clazyQT6Checks }} -p build/ ${{ steps.files-by-extensions.outputs.cpp_files }} &>> ${{ env.logdir }}clazyQT6.log || true + + + # if Clazy has run successfully parse the output + if [ -f ${{ env.logdir }}clazyQT6.log ]; then + echo "::add-matcher::${{ runner.workspace }}/FreeCAD/.github/problemMatcher/clang.json" + cat ${{ env.logdir }}clazyQT6.log + echo "::remove-matcher owner=clang::" + + clazyQT6Errors=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): error: .+$" ${{ env.logdir }}clazyQT6.log | wc -l ) || true + clazyQT6Warnings=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): warning: .+$" ${{ env.logdir }}clazyQT6.log | wc -l ) || true + clazyQT6Notes=$(grep -rnIHE "^(.+):([0-9]+):([0-9]+): note: .+$" ${{ env.logdir }}clazyQT6.log | wc -l ) || true + fi + + # Pass Variables to GitHub Env + echo "clazyQT6Errors=$clazyQT6Errors" >> $GITHUB_ENV + echo "clazyQT6Warnings=$clazyQT6Warnings" >> $GITHUB_ENV + echo "clazyQT6Notes=$clazyQT6Notes" >> $GITHUB_ENV + + echo "Found $clazyQT6Errors errors, $clazyQT6Warnings warnings, $clazyQT6Notes notes" + + # Step-Report + if [ "$clazyQT6Errors" -gt 0 ]; then + echo "
:fire: Clazy found :fire: $clazyQT6Errors errors, :warning: $clazyQT6Warnings warnings and :pencil2: $clazyQT6Notes notes for porting to QT6" >> ${{ env.logdir }}checkReport.md + elif [ "$clazyQT6Warnings" -gt 0 ]; then + echo "
:warning: Clazy found :warning: $clazyQT6Warnings warnings and :pencil2: $clazyQT6Notes notes for porting to QT6" >> ${{ env.logdir }}checkReport.md + elif [ "$clazyNotes" -gt 0 ]; then + echo "
:pencil2: Clazy found :pencil2: $clazyQT6Notes notes for porting to QT6" >> ${{ env.logdir }}checkReport.md + else + echo "
:heavy_check_mark: Clazy found no errors, warnings or notes for porting to QT6" >> ${{ env.logdir }}checkReport.md + fi + + echo "" >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + cat ${{ env.logdir }}clazyQT6.log >> ${{ env.logdir }}checkReport.md + echo '```' >> ${{ env.logdir }}checkReport.md + echo "
">> ${{ env.logdir }}checkReport.md + echo "" >> ${{ env.logdir }}checkReport.md + + # Error the step if pylint has found errors + if [ "$clazyQT6Errors" -gt 0 ] && [ ${{ env.clazyQT6FailSilent }} != true ]; then + exit 1 + else + exit 0 + fi + + - name: Zip Logs + if: always() + run: | + zip -r ${{ env.logdir }}logs.zip ${{ env.logdir }} + + - name: Upload Logs + if: always() + uses: actions/upload-artifact@v3 + with: + name: Logs + path: ${{ env.logdir }}logs.zip + + - name: Zip Fixes + if: always() + run: | + zip -r ${{ env.fixesdir }}fixes.zip ${{ env.fixesdir }} + + - name: Upload Fixes + if: always() + uses: actions/upload-artifact@v3 + with: + name: Fixes + path: ${{ env.fixesdir }}fixes.zip + + - name: Post Report to GITHUB_STEP_SUMMARY + if: env.reportStepSummary == 'true' && always() + id: post-report-to-github-step-summary + run: | + cat ${{ env.logdir }}checkReport.md > $GITHUB_STEP_SUMMARY + + - name: Create Pull request comment + if: env.reportPRComment == 'true' && github.event_name == 'pull_request' && always() + uses: marocchino/sticky-pull-request-comment@v2 + with: + header: Check results + path: ${{ env.logdir }}checkReport.md + + - name: get comment body + id: get-comment-body + if: env.reportPushComment == 'true' && github.event_name == 'push' && always() + run: | + body=$(cat ${{ env.logdir }}checkReport.md) + body="${body//'%'/'%25'}" + body="${body//$'\n'/'%0A'}" + body="${body//$'\r'/'%0D'}" + echo ::set-output name=body::$body + + - name: Create commit comment + if: env.reportPushComment == 'true' && github.event_name == 'push' && always() + uses: peter-evans/commit-comment@v2 + with: + body: ${{ steps.get-comment-body.outputs.body }} diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml deleted file mode 100644 index f6f3b112af..0000000000 --- a/.github/workflows/codespell.yml +++ /dev/null @@ -1,31 +0,0 @@ -# GitHub Action to automate the identification of common misspellings in text files. -# https://github.com/codespell-project/actions-codespell -# https://github.com/codespell-project/codespell - -name: Codespell -on: - pull_request: - -jobs: - codespell: - name: Check for spelling errors - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - - name: Get changed files - id: changed-files - uses: tj-actions/changed-files@v12.2 - - - name: List all changed files - run: | - for file in ${{ steps.changed-files.outputs.all_changed_files }}; do - echo "$file was changed" - done - - - uses: codespell-project/actions-codespell@master - with: - check_filenames: true - ignore_words_file: .github/codespellignore - skip: ./.git,*.po,*.ts,*.svg,./ChangeLog.txt,./src/3rdParty,./src/Mod/Assembly/App/opendcm,./src/CXX,./src/zipios++,./src/Base/swig*,./src/Mod/Robot/App/kdl_cp,./src/Mod/Import/App/SCL,./src/WindowsInstaller,./src/Doc/FreeCAD.uml,./build/ - path: ${{ steps.changed-files.outputs.all_changed_files }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 83c653a823..5a5018c2db 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,9 @@ # file types to ignore - +.* +!/.gitignore +!/.clang-format +!/.git-blame-ignore-revs +!/.gitattributes *.DS_Store *.pyc *.obj @@ -34,10 +38,7 @@ install_manifest.txt /src/Tools/offlinedoc/localwiki/ /src/Tools/offlinedoc/*.txt OpenSCAD_rc.py -/\.idea/ -.tags tags -/\.vscode/ # crowdin file src/Tools/freecad.zip diff --git a/.log_errors b/.log_errors deleted file mode 100644 index 7977e46ea4..0000000000 --- a/.log_errors +++ /dev/null @@ -1,3 +0,0 @@ -Wrn: -Err: -Cannot find icon: diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000000..e1669ef067 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,614 @@ +[MAIN] + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Load and enable all available extensions. Use --list-extensions to see a list +# all available extensions. +#enable-all-extensions= + +# In error mode, messages with a category besides ERROR or FATAL are +# suppressed, and no reports are done by default. Error mode is compatible with +# disabling specific errors. +#errors-only= + +# Always return a 0 (non-error) status code, even if lint errors are found. +# This is primarily useful in continuous integration scripts. +#exit-zero= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-allow-list= + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. (This is an alternative name to extension-pkg-allow-list +# for backward compatibility.) +extension-pkg-whitelist= + +# Return non-zero exit code if any of these messages/categories are detected, +# even if score is above --fail-under value. Syntax same as enable. Messages +# specified are enabled, while categories only check already-enabled messages. +fail-on= + +# Specify a score threshold to be exceeded before program exits with error. +fail-under=10 + +# Interpret the stdin as a python script, whose filename needs to be passed as +# the module_or_package argument. +#from-stdin= + +# Files or directories to be skipped. They should be base names, not paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against paths and can be in Posix or Windows format. +ignore-paths= + +# Files or directories matching the regex patterns are skipped. The regex +# matches against base names, not paths. The default value ignores Emacs file +# locks +ignore-patterns=^\.# + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use, and will cap the count on Windows to +# avoid hangs. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Minimum Python version to use for version dependent checks. Will default to +# the version used to run pylint. +py-version=3.10 + +# Discover python modules and packages in the file system subtree. +recursive=no + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# In verbose mode, extra non-checker-related info will be displayed. +#verbose= + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'fatal', 'error', 'warning', 'refactor', +# 'convention', and 'info' which contain the number of messages in each +# category, as well as 'statement' which is the total number of statements +# analyzed. This score is used by the global evaluation report (RP0004). +evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +#output-format= + +# Tells whether to display a full report or only the messages. +reports=yes + +# Activate the evaluation score. +score=yes + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE, +# UNDEFINED. +confidence=HIGH, + CONTROL_FLOW, + INFERENCE, + INFERENCE_FAILURE, + UNDEFINED + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then re-enable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + invalid-name, + wrong-import-order, + import-error, + undefined-variable + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. If left empty, argument names will be checked with the set +# naming style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. If left empty, attribute names will be checked with the set naming +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Bad variable names regexes, separated by a comma. If names match any regex, +# they will always be refused +bad-names-rgxs= + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. If left empty, class attribute names will be checked +# with the set naming style. +#class-attribute-rgx= + +# Naming style matching correct class constant names. +class-const-naming-style=UPPER_CASE + +# Regular expression matching correct class constant names. Overrides class- +# const-naming-style. If left empty, class constant names will be checked with +# the set naming style. +#class-const-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. If left empty, class names will be checked with the set naming style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. If left empty, constant names will be checked with the set naming +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. If left empty, function names will be checked with the set +# naming style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + ex, + Run, + _ + +# Good variable names regexes, separated by a comma. If names match any regex, +# they will always be accepted +good-names-rgxs= + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. If left empty, inline iteration names will be checked +# with the set naming style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. If left empty, method names will be checked with the set naming style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. If left empty, module names will be checked with the set naming style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Regular expression matching correct type variable names. If left empty, type +# variable names will be checked with the set naming style. +#typevar-rgx= + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. If left empty, variable names will be checked with the set +# naming style. +#variable-rgx= + + +[CLASSES] + +# Warn about protected attribute access inside special methods +check-protected-access-in-special-methods=no + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit,argparse.parse_error + + +[DESIGN] + +# List of regular expressions of class ancestor names to ignore when counting +# public methods (see R0903) +exclude-too-few-public-methods= + +# List of qualified class names to ignore when counting class parents (see +# R0901) +ignored-parents= + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when caught. +overgeneral-exceptions=BaseException, + Exception + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules= + +# Output a graph (.gv or any supported image format) of external dependencies +# to the given file (report RP0402 must not be disabled). +ext-import-graph= + +# Output a graph (.gv or any supported image format) of all (i.e. internal and +# external) dependencies to the given file (report RP0402 must not be +# disabled). +import-graph= + +# Output a graph (.gv or any supported image format) of internal dependencies +# to the given file (report RP0402 must not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[LOGGING] + +# The type of string formatting that logging methods do. `old` means using % +# formatting, `new` is for `{}` formatting. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + +# Regular expression of note tags to take in consideration. +notes-rgx= + + +[SIMILARITIES] + +# Comments are removed from the similarity computation +ignore-comments=yes + +# Docstrings are removed from the similarity computation +ignore-docstrings=yes + +# Imports are removed from the similarity computation +ignore-imports=yes + +# Signatures are removed from the similarity computation +ignore-signatures=yes + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the 'python-enchant' package. +spelling-dict= + +# List of comma separated words that should be considered directives if they +# appear at the beginning of a comment and should not be checked. +spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy: + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[STRING] + +# This flag controls whether inconsistent-quotes generates a warning when the +# character used as a quote delimiter is used inconsistently within a module. +check-quote-consistency=no + +# This flag controls whether the implicit-str-concat should generate a warning +# on implicit string concatenation in sequences defined over several lines. +check-str-concat-over-line-jumps=no + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of symbolic message names to ignore for Mixin members. +ignored-checks-for-mixins=no-member, + not-async-context-manager, + not-context-manager, + attribute-defined-outside-init + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# Regex pattern to define which classes are considered mixins. +mixin-class-rgx=.*[Mm]ixin + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of names allowed to shadow builtins +allowed-redefined-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of dummy variables (i.e. expected to +# not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io diff --git a/.travis.yml b/.travis.yml deleted file mode 100755 index 00c1d08bf6..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,357 +0,0 @@ -###### -# -# Travis-CI configuration file for FreeCAD. -# -# This build configuration will build and test FreeCAD on both Linux -# and Mac OS X. For Mac OS X, this configuration will also package -# and deploy the build to GitHub provided the following prerequisites -# are satisfied: -# -# GH_TOKEN is defined as a secure environment variable and contains a -# a valid GitHub OAUTH token with repo_deployment scope. -# NOTE: Define this env using the Travis-CI Repo Settings UI -# -# FREECAD_RELEASE: A GitHub Release with this identifier exists in the -# repo. The Travis job will deploy the OS X build to this -# GitHub release name as a release asset. -# -# DEPLOY: Repo setting to deploy (defaults to no deploy to reduce -# Travis build times. Set DEPLOY=1 to enable in repo settings. -###### -env: - global: - - GENERATOR="Unix Makefiles" - - CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE:-Release} -# - FREECAD_RELEASE="0.18" -# - DEPLOY_RELEASE=${DEPLOY_RELEASE:-$FREECAD_RELEASE} -# - OSX_PORTS_CACHE=${OSX_PORTS_CACHE:-FreeCAD/FreeCAD-ports-cache} -# - DEPLOY=${DEPLOY:-0} - -# jobs: - # chunk.io key (if needed, obtain it with Yorik, PrzemoF, Kunda1) - # secure: MJu0ZU/9Yqut6bUkHoSrXTV/c/WhCLR0KnHKCsnEU081PYoukzH6ngzgKk7/trAH2In080d/ra4B2OmTNl/LAgV6DXKFY9dO1aG8QwcrHgaMPf0pHYUy/OfwQSFYFByQDV2OEMAHcIWc/dtNkzK2QUi44Kn7d0GtSEiN4s816lriWtjg0vmEGAU8MjvcAGss4gKyn05Xm1NUCYPKgpgIHsywLbpE76lv0eOYoosEuKv5Q9Pb4FMQts02+JUlqE8eY4ZZ3nV8iQbgIDdseOSA7Ixn05zWjU/ZRZ74TrYxMnzfUAwQcJe9OcqoESq+pPWQt5HYG66VmeVxQim1gmsiDASH51U/nswKt0Q4bISj3tVk0YZMFV8Ax+SzPvLEmFZJQGfgO1mg7HdNcz9N9G5JHPawrV19DwYIEFbAw8MCSAoIXFOcPQZUWXCbtjm7NO9vCjMrqyVJMDD9L8omvQajHoajuHbOT8KB250gFokeLj3z8yu++Tz+IrZX5inUMrXsARVt/ALXpi8rJPXmoFMpMUjyWmDPqPWlnqUhLtTtEtKpuOWP8ZnWVwkg4QYOUhCy95C1okJSGkG+ylHWncWfY4mS+UBT525laoh+GOhH+sRW+p2xkI21xGFRqg1oHjjgY1yIYF6nnSHPzxMBRYmZwagyXsjkFG5FPMWR2oYk0Yg - -git: - depth: 5000 - -notifications: - email: false - webhooks: - urls: - - https://webhooks.gitter.im/e/479456663cdf5c84e4d8 - on_success: always - on_failure: always - on_start: change - -# Inject osx build into matrix - needed to specify image/dist -jobs: -# allow_failures: -# - python: 3.7 - fast_finish: true # https://blog.travis-ci.com/2013-11-27-fast-finishing-builds - include: - - if: type != pull_request - os: linux - dist: bionic - language: cpp - compiler: clang - cache: ccache - addons: - apt: - sources: - - sourceline: 'ppa:ubuntu-toolchain-r/test' - - sourceline: 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-10 main' - key_url: 'https://apt.llvm.org/llvm-snapshot.gpg.key' - packages: - - clang-10 - env: - - CC=clang-10 - - CXX=clang++-10 - - CMAKE_ARGS="-DPYTHON_EXECUTABLE=/usr/bin/python3 -DBUILD_FEM_NETGEN=ON" - - CACHE_NAME=JOB1 - - - os: linux - dist: bionic - language: cpp - compiler: gcc-10 - cache: ccache - addons: - apt: - sources: - - sourceline: 'ppa:ubuntu-toolchain-r/test' - packages: - - gcc-10 - - g++-10 - env: - - CC=gcc-10 - - CXX=g++-10 - - CC_FOR_BUILD=gcc-10 - - CXX_FOR_BUILD=g++-10 - - CMAKE_ARGS="-DCMAKE_CXX_COMPILER=/usr/bin/c++ -DCMAKE_C_COMPILER=/usr/bin/cc -DPYTHON_EXECUTABLE=/usr/bin/python3 -DBUILD_FEM_NETGEN=ON" - - CACHE_NAME=JOB2 - - # - os: osx - # osx_image: xcode11.6 - # language: cpp - # cache: - # - ccache: true - # - directories: - # - $HOME/.ccache - # - $HOME/Library/Caches/Homebrew - # - /usr/local/Homebrew - # env: - # - CMAKE_OPTS="-DBUILD_QT5=ON -DBUILD_ENABLE_CXX_STD='C++17' -DUSE_PYTHON3=1 -DCMAKE_CXX_FLAGS='-Wno-deprecated-declarations' -DBUILD_FEM_NETGEN=1 -DBUILD_FEM=1 -DBUILD_TECHDRAW=0 -DCMAKE_PREFIX_PATH='/usr/local/opt/qt/lib/cmake;/usr/local/opt/nglib/Contents/Resources' -DBUILD_FEM_NETGEN:BOOL=ON -DFREECAD_USE_EXTERNAL_KDL=ON -DCMAKE_BUILD_TYPE=Release" - # - PATH=/usr/local/bin:$PATH - # - CACHE_NAME=OSX1 - - - os: windows - language: cpp - env: - - CMAKE_OPTS="-DBUILD_FEM_NETGEN=OFF -DFREECAD_RELEASE_PDB=OFF -DFREECAD_RELEASE_SEH=OFF" - - GENERATOR="Visual Studio 15 2017 Win64" - - PYTHON_MAJOR_VERSION=3 - - MSBUILD_PATH="c:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin" - - TEST_PATH="C:\Users\travis\build\FreeCAD\FreeCAD\build\bin" - - CLCACHE_PATH="C:\Users\travis\build\FreeCAD\FreeCAD" - - VS15=true - - CCACHE_TEMPDIR=/tmp/.ccache-temp - - CCACHE_COMPRESS=1 - - CCACHE_DIR=$HOME/.ccache - - CACHE_NAME=JOB5 - # enable this if clcache extended log is needed - #- CLCACHE_LOG=1 - cache: - directories: - - $HOME/clcache - -# - language: python -# python: 3.7 -# dist: xenial # required for Python >= 3.7 (travis-ci/travis-ci#9069) -# before_install: true -# install: python3 -m pip install flake8 -# # fail the build if there are Python syntax errors or undefined names -# script: flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics - -before_cache: - - if [ "${TRAVIS_OS_NAME}" = "osx" ]; then brew cleanup; fi - - if [ "${TRAVIS_OS_NAME}" = "osx" ]; then find /usr/local/Homebrew \! -regex ".+\.git.+" -delete; fi - -before_install: -# - eval "$(curl -fsSL "https://raw.githubusercontent.com/${OSX_PORTS_CACHE}/v${FREECAD_RELEASE}/travis-helpers.sh")" -- | - case "${TRAVIS_OS_NAME}" in - - "linux") - # Daily PPA for OCCT, Pivy, Netgen, PySide ... packages - sudo apt-add-repository -y ppa:freecad-maintainers/freecad-daily - sudo apt-get update -qq - # Build deps - sudo apt-get install -y --no-install-recommends \ - python-dev \ - python-pyside \ - python-matplotlib \ - python3-dev \ - python3-pyside \ - python3-matplotlib \ - libboost1.65-dev \ - libboost-filesystem1.65-dev \ - libboost-program-options1.65-dev \ - libboost-python1.65-dev \ - libboost-regex1.65-dev \ - libboost-signals1.65-dev \ - libboost-system1.65-dev \ - libboost-thread1.65-dev \ - libxerces-c-dev \ - libocct-data-exchange-dev \ - libocct-ocaf-dev \ - libocct-visualization-dev \ - libvtk7-dev \ - libmedc-dev \ - pybind11-dev \ - swig \ - qt4-qmake \ - libqt4-opengl-dev \ - libqtwebkit-dev \ - qtbase5-dev \ - libqt5xmlpatterns5-dev \ - libqt5svg5-dev \ - libqt5opengl5-dev \ - qttools5-dev \ - qtwebengine5-dev \ - libcoin80-dev \ - libpyside-dev \ - libpyside2-dev \ - libshiboken-dev \ - libshiboken2-dev \ - pyside-tools \ - pyside2-tools \ - doxygen \ - graphviz \ - libnglib-dev \ - netgen \ - netgen-headers \ - libmetis-dev \ - libspnav-dev - # Runtime deps - sudo apt-get install -y --no-install-recommends freecad-daily-python3 python-pivy python3-pivy python-ply python3-ply - - # Use newer Eigen to suppress warnings - # https://github.com/FreeCAD/FreeCAD/pull/3485 - wget http://mirrors.kernel.org/ubuntu/pool/universe/e/eigen3/libeigen3-dev_3.3.7-2_all.deb - sudo dpkg -i libeigen3-dev_3.3.7-2_all.deb - - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start - - export INSTALLED_APP_PATH="/usr/local/bin/FreeCAD" - export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/netgen/:$LD_LIRBARY_PATH - ;; - - "osx") - xcodebuild -version -sdk - brew --config - brew install ccache - brew install coreutils - brew update >/dev/null - brew --config - brew update - brew upgrade - brew install python@3.9 - brew unlink python@3.8 - brew link --overwrite --force python@3.9 - rm /usr/local/bin/python - ln -s /usr/local/bin/python3 /usr/local/bin/python - pip3 install six - pip3 install pyyaml - pip3 install ply - export PATH=/usr/local/bin:$PATH - brew reinstall vtk@8.2 - brew link --force vtk@8.2 - which python - python --version - brew install boost - brew install boost-python3 - brew tap FreeCAD/freecad - brew install freecad/freecad/coin - brew install freecad/freecad/nglib - brew install freecad/freecad/med-file - brew install freecad/freecad/opencamlib - brew install freecad/freecad/shiboken2 - brew install freecad/freecad/pyside2 - brew install freecad/freecad/pyside2-tools - brew install freecad/freecad/pivy - brew install freecad/freecad/matplotlib - - ##Install the 3DConnexion frameworks - if [ ! -d /Library/Frameworks/3DconnexionClient.framework ]; then - curl -o /tmp/3dFW.dmg -L 'https://download.3dconnexion.com/drivers/mac/10-6-6_360DF97D-ED08-4ccf-A55E-0BF905E58476/3DxWareMac_v10-6-6_r3234.dmg' - hdiutil attach -readonly /tmp/3dFW.dmg - sudo installer -package /Volumes/3Dconnexion\ Software/Install\ 3Dconnexion\ software.pkg -target / - diskutil eject /Volumes/3Dconnexion\ Software - fi - export CMAKE_OPTS="${CMAKE_OPTS} -DFREECAD_CREATE_MAC_APP=OFF" - export INSTALLED_APP_PATH="/usr/local/MacOS/FreeCAD" - - export CMAKE_ARGS="${CMAKE_OPTS} -DFREECAD_USE_EXTERNAL_KDL=ON" - brew link --overwrite matplotlib - if [ -f "/usr/local/Cellar/opencascade/7.4.0_1/include/opencascade/Standard_Macro.hxx" ]; then - sed '1,$s/\[\[nodiscard\]\]//' /usr/local/Cellar/opencascade/7.4.0_1/include/opencascade/Standard_Macro.hxx > /tmp/Standard_Macro.hxx && cp /tmp/Standard_Macro.hxx /usr/local/Cellar/opencascade/7.4.0_1/include/opencascade/Standard_Macro.hxx ; - fi - ;; - - "windows") - #choco install -y python - #py -m pip install --quiet --upgrade pip - #py -m pip install git+https://github.com/frerich/clcache.git@v4.2.0 - curl -L https://github.com/frerich/clcache/releases/download/v4.2.0/clcache-4.2.0.zip --output clcache-4.2.0.zip - 7z x clcache-4.2.0.zip > /dev/null - export PATH=$CLCACHE_PATH:$PATH - export PATH=$TEST_PATH:$PATH - #reset clcache hit stats - cmd.exe //C 'C:\Users\travis\build\FreeCAD\FreeCAD\clcache.exe -z' - # clcache stats before compilation - cmd.exe //C 'C:\Users\travis\build\FreeCAD\FreeCAD\clcache.exe -s' - - curl -L https://github.com/FreeCAD/FreeCAD/releases/download/0.19.1/FreeCADLibs_12.5.3_x64_VC17.7z --output FreeCADLibs.7z - 7z x FreeCADLibs.7z -oFreeCADLibs > /dev/null - rm -f FreeCADLibs.7z - export FREECAD_LIBPACK_DIR="$TRAVIS_BUILD_DIR\FreeCADLibs\FreeCADLibs_12.5.3_x64_VC17" - - export CMAKE_ARGS="${CMAKE_OPTS} -DFREECAD_LIBPACK_DIR=$TRAVIS_BUILD_DIR\FreeCADLibs\FreeCADLibs_12.5.3_x64_VC17 -DPYTHON_EXECUTABLE=$TRAVIS_BUILD_DIR\FreeCADLibs\FreeCADLibs_12.5.3_x64_VC17\bin\python.exe \ - -DBUILD_QT5=TRUE" - export PATH=$MSBUILD_PATH:$PATH - ;; - - *) - echo "Invalid or unsupported operating system ${TRAVIS_OS_NAME}" - exit 1 - ;; - esac - -install: -#### -# Build FreeCAD with cmake options set above for each platform -## - - if [ "$TRAVIS_OS_NAME" = "osx" ]; then export PATH="/usr/local/bin:/usr/local/opt/ccache/libexec:$PATH"; fi - - echo ${CMAKE_ARGS} - - mkdir build && cd build && cmake -Wno-dev -G"${GENERATOR}" ${CMAKE_ARGS} -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} ../ - -script: -#### -# Install FreeCAD and run unit tests. Test failures will fail the build -## -# MSBuild.exe /m FreeCAD.sln - - | - if [ "${TRAVIS_OS_NAME}" == "windows" ]; then - # https://travis-ci.community/t/vcvarsall-bat-freezes-on-new-1809-based-windows-images/7098/6 - # call msbuild using clcache - #cmd.exe //C '"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" amd64 && MSBuild.exe FreeCAD.sln /p:CLToolExe=clcache.exe /p:TrackFileAccess=false /p:CLToolPath=C:\Users\travis\build\FreeCAD\FreeCAD /m:2 /nologo /verbosity:minimal /p:Configuration=Release /p:Platform=x64' - cmd.exe //C 'C:\Users\travis\build\FreeCAD\FreeCAD\.travis\build.bat' - # ls -lahR - mkdir bin/ - mv ../FreeCADLibs/FreeCADLibs_12.5.3_x64_VC17/bin/* bin/ - du -hs bin/ - # show clcache hit stats - cmd.exe //C 'C:\Users\travis\build\FreeCAD\FreeCAD\clcache.exe -s' - # run the tests - #cmd.exe //C 'cd C:\Users\travis\build\FreeCAD\FreeCAD\build\bin && FreeCADCmd.exe --run-test 0' - # Make build fail if ANY of the following fails - #set -ev - winpty.exe -Xallow-non-tty -Xplain /C/Users/travis/build/FreeCAD/FreeCAD/build/bin/FreeCADCmd.exe --run-test 0 | tee runlog.txt - grep -q FAILED runlog.txt ; [ $? == 1 ] && echo "Build succeeded and tests passed!" || ( echo "Tests failed!" && false ) - else - # Stop compiling (GCC) after 2 hrs 50 min (3 hrs limit). - # Preserves created ccache for the next build job. - # if [ "${TRAVIS_OS_NAME}" == "linux" ]; then sudo timeout -k 175m 170m make -j2 install || true; fi - # if [ "${TRAVIS_OS_NAME}" == "osx" ]; then sudo gtimeout -s KILL make -j2 install; fi - cat $HOME/.ccache/ccache.conf - ccache -z -s - df -h - if [ "${TRAVIS_OS_NAME}" == "osx" ]; then export PATH="/usr/local/opt/ccacche/libexec:$PATH"; sudo gtimeout -s KILL 7200 make -j2; [ $? == 124 ] && { ccache -s; return 0; } fi - if [ "${TRAVIS_OS_NAME}" == "linux" ]; then sudo timeout -k 175m 170m make -j2 install || true; fi - sudo make -j2 install - ccache -s - ${INSTALLED_APP_PATH} --console --run-test 0 || travis_terminate 1 - ${INSTALLED_APP_PATH} --log-file /tmp/FreeCAD_installed.log & - sleep 10 && pkill FreeCAD - cat /tmp/FreeCAD_installed.log - grep --file=../.log_errors /tmp/FreeCAD_installed.log ; [ $? == 1 ] && echo "No errors from .log_errors file found in the log after start from /usr/local/bin" || ( echo "Error from .log_errors found!" && false ) - fi - -#after_success: -# Package and deploy the build to GitHub. This will only run for builds on -# master (i.e. pull requests are only built and tested but not deployed). -# -# GH_TOKEN must be set in order to deploy releases to GitHub -# -#- | -# if [ "${TRAVIS_OS_NAME}" == "osx" -a "${TRAVIS_PULL_REQUEST}" == "false" -a "${DEPLOY}" == "1" ]; then -# brew ls --versions jq || brew install jq -# npm install -g appdmg -# export VSN=$(python ${TRAVIS_BUILD_DIR}/src/Tools/ArchiveNameFromVersionHeader.py ${TRAVIS_BUILD_DIR}/build/src/Build/Version.h) -# export DEPLOYMENT_ARCHIVE=${VSN}-${QT}.dmg -# appdmg ${TRAVIS_BUILD_DIR}/src/MacAppBundle/DiskImage/layout.json "${DEPLOYMENT_ARCHIVE}" -# deployContext=$(create_helper_context repo=${TRAVIS_REPO_SLUG} auth_token=${GH_TOKEN} release=${DEPLOY_RELEASE}) -# gitHub_deploy_asset_to_release_named $deployContext ${DEPLOYMENT_ARCHIVE} -# gitHub_prune_assets_for_release_named $deployContext "-${QT}" 1 -# fi - diff --git a/.travis/build.bat b/.travis/build.bat deleted file mode 100644 index ada67ab56f..0000000000 --- a/.travis/build.bat +++ /dev/null @@ -1,6 +0,0 @@ -echo on - -call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvarsall.bat" amd64 - -MSBuild.exe FreeCAD.sln /p:CLToolExe=clcache.exe /p:TrackFileAccess=false /p:CLToolPath=C:\Users\travis\build\FreeCAD\FreeCAD /m:2 /nologo /verbosity:minimal /p:Configuration=Release /p:Platform=x64 - diff --git a/build_unix_dev_conda.sh b/build_unix_dev_conda.sh deleted file mode 100755 index 01be6d7046..0000000000 --- a/build_unix_dev_conda.sh +++ /dev/null @@ -1,91 +0,0 @@ -##!/usr/bin/env bash -# -# MacOS Build Script for FreeCAD using Conda. -# This is intended for developer use. -# -# Copyright (c) 2020 by Jeffrey Zampieron. All rights reserved. -# -# License: LGPLv2.1 -# -# References: -# - Conda: https://conda.io/projects/conda/en/latest/user-guide/install/index.html -# - Conda Build: https://docs.conda.io/projects/conda-build/en/latest/install-conda-build.html - -########################################################################### -# Script wide setup. -########################################################################### -# The Conda environment name -FCENV=freecad_dev -# The cmake build directory -HOST=$(uname) - -########################################################################### -# Env Checks -########################################################################### -if [[ ${HOST} =~ "Linux" ]]; then - # Linux specific checks here - echo "Linux specific checks..." -elif [[ ${HOST} =~ "Darwin" ]]; then - # OSX specific checks here. - echo "OS X specific checks..." - which xcrun - if [ $? != 0 ]; then - echo "xcrun not found... install XCode command line tools..." - echo "using: xcode-select --install" - exit 1 - fi -else - echo "unknown host env... probably won't work. Aborting build." - exit 1 -fi - -########################################################################### -# Conda Setup -########################################################################### -which conda -if [ $? != 0 ]; then - echo "Failed to find conda executable. Please install." - exit 1 -fi - -if [[ "${CONDA_DEFAULT_ENV}" =~ "${FCENV}" ]]; then - echo "Already in env" -elif [[ -z "${CONDA_DEFAULT_ENV}" ]]; then - echo "Not in conda env... activating" - eval "$(conda shell.bash hook)" - conda activate ${FCENV} -else - # Assume we are in some other env. - echo "In ${CONDA_DEFAULT_ENV}, attempting switch to ${FCENV}" - eval "$(conda shell.bash hook)" - conda deactivate - conda activate ${FCENV} -fi - -if [ $? != 0 ]; then - echo "Failed to activate conda env: ${FCENV} ... creating" - - if [[ ${HOST} =~ "Linux" ]]; then - echo "Linux" - conda env create -f environment-linux.yml - elif [[ ${HOST} =~ "Darwin" ]]; then - echo "OS X" - conda env create -f environment-osx.yml - else - echo "Unknown Host: ${HOST}" - exit 1 - fi - - conda activate ${FCENV} - if [ $? != 0 ]; then - echo "Failed to create conda environment and activate it." - exit 1 - fi -fi - -if [ -z "${CONDA_PREFIX}" ]; then - echo "Failed to find CONDA_PREFIX variable." - exit 1 -fi - -PREFIX="${CONDA_PREFIX}" ./conda/build.sh diff --git a/cMake/FindCoin3D.cmake b/cMake/FindCoin3D.cmake deleted file mode 100644 index 8e14ef41f8..0000000000 --- a/cMake/FindCoin3D.cmake +++ /dev/null @@ -1,125 +0,0 @@ -# Try to find Coin3D -# Once done this will define -# -# COIN3D_FOUND - system has Coin3D - Open Inventor -# COIN3D_INCLUDE_DIRS - where the Inventor include directory can be found -# COIN3D_LIBRARIES - Link this to use Coin3D -# - -SET( COIN3D_FOUND "NO" ) - -IF (WIN32) - IF (CYGWIN OR MINGW) - - FIND_PATH(COIN3D_INCLUDE_DIRS Inventor/So.h - ${CMAKE_INCLUDE_PATH} - /usr/include - /usr/local/include - /usr/include/coin - ) - - FIND_LIBRARY(COIN3D_LIBRARIES Coin - ${CMAKE_LIBRARY_PATH} - /usr/lib - /usr/local/lib - ) - - ELSE (CYGWIN OR MINGW) - - FIND_PATH(COIN3D_INCLUDE_DIRS Inventor/So.h - "[HKEY_LOCAL_MACHINE\\SOFTWARE\\SIM\\Coin3D\\2;Installation Path]/include" - ) - - FIND_LIBRARY(COIN3D_LIBRARY_DEBUG coin2d - "[HKEY_LOCAL_MACHINE\\SOFTWARE\\SIM\\Coin3D\\2;Installation Path]/lib" - ) - - FIND_LIBRARY(COIN3D_LIBRARY_RELEASE - NAMES - coin2 - Coin4 - PATHS - ${CMAKE_LIBRARY_PATH} - "[HKEY_LOCAL_MACHINE\\SOFTWARE\\SIM\\Coin3D\\2;Installation Path]/lib" - ) - - IF (COIN3D_LIBRARY_DEBUG AND COIN3D_LIBRARY_RELEASE) - SET(COIN3D_LIBRARIES optimized ${COIN3D_LIBRARY_RELEASE} - debug ${COIN3D_LIBRARY_DEBUG}) - ELSE (COIN3D_LIBRARY_DEBUG AND COIN3D_LIBRARY_RELEASE) - IF (COIN3D_LIBRARY_DEBUG) - SET (COIN3D_LIBRARIES ${COIN3D_LIBRARY_DEBUG}) - ENDIF (COIN3D_LIBRARY_DEBUG) - IF (COIN3D_LIBRARY_RELEASE) - SET (COIN3D_LIBRARIES ${COIN3D_LIBRARY_RELEASE}) - ENDIF (COIN3D_LIBRARY_RELEASE) - ENDIF (COIN3D_LIBRARY_DEBUG AND COIN3D_LIBRARY_RELEASE) - - IF (COIN3D_LIBRARIES) - # ADD_DEFINITIONS ( -DCOIN_NOT_DLL ) - #ELSE (COIN3D_LIBRARIES) - # SET (COIN3D_LIBRARIES coin2d CACHE STRING "Coin3D Library (Debug) - Open Inventor API") - ENDIF (COIN3D_LIBRARIES) - - ENDIF (CYGWIN OR MINGW) - -ELSE (WIN32) - IF(APPLE) - FIND_PATH(COIN3D_INCLUDE_DIRS Inventor/So.h - /Library/Frameworks/Inventor.framework/Headers - /usr/local/include - /usr/include - ) - FIND_LIBRARY(COIN3D_LIBRARIES Coin - /Library/Frameworks/Inventor.framework/Libraries - /usr/lib - /usr/local/lib - ) - SET(COIN3D_LIBRARIES "-framework Coin3d" CACHE STRING "Coin3D library for OSX") - ELSE(APPLE) - # Try to use pkg-config first... - find_package(PkgConfig) - pkg_check_modules(COIN3D Coin) - # ... then fall back to manual lookup - IF(NOT COIN3D_FOUND) - FIND_PATH(COIN3D_INCLUDE_DIRS Inventor/So.h - ${CMAKE_INCLUDE_PATH} - /usr/include/Coin3 - /usr/include - /usr/include/coin - /usr/local/include - ) - - FIND_LIBRARY(COIN3D_LIBRARIES Coin - ${CMAKE_LIBRARY_PATH} - /usr/lib - /usr/local/lib - PATH_SUFFIXES Coin2 Coin3 - ) - ENDIF(NOT COIN3D_FOUND) - ENDIF(APPLE) - -ENDIF (WIN32) - - -IF(COIN3D_LIBRARIES) - SET( COIN3D_FOUND "YES" ) - message(STATUS "Coin3D libraries found") - - IF(NOT COIN3D_VERSION) - file(READ "${COIN3D_INCLUDE_DIRS}/Inventor/C/basic.h" _coin3d_basic_h) - string(REGEX MATCH "define[ \t]+COIN_MAJOR_VERSION[ \t]+([0-9?])" _coin3d_major_version_match "${_coin3d_basic_h}") - set(COIN3D_MAJOR_VERSION "${CMAKE_MATCH_1}") - string(REGEX MATCH "define[ \t]+COIN_MINOR_VERSION[ \t]+([0-9?])" _coin3d_minor_version_match "${_coin3d_basic_h}") - set(COIN3D_MINOR_VERSION "${CMAKE_MATCH_1}") - string(REGEX MATCH "define[ \t]+COIN_MICRO_VERSION[ \t]+([0-9?])" _coin3d_micro_version_match "${_coin3d_basic_h}") - set(COIN3D_MICRO_VERSION "${CMAKE_MATCH_1}") - set(COIN3D_VERSION "${COIN3D_MAJOR_VERSION}.${COIN3D_MINOR_VERSION}.${COIN3D_MICRO_VERSION}") - ENDIF() - - IF(NOT PIVY_VERSION) - execute_process (COMMAND ${Python3_EXECUTABLE} -c "import pivy as p; print(p.__version__,end='')" OUTPUT_VARIABLE PIVY_VERSION) - ENDIF() - -ENDIF(COIN3D_LIBRARIES) - diff --git a/cMake/FindPyCXX.cmake b/cMake/FindPyCXX.cmake index 8de77eebf7..1b703e967a 100644 --- a/cMake/FindPyCXX.cmake +++ b/cMake/FindPyCXX.cmake @@ -117,7 +117,7 @@ if(PYCXX_FOUND) ${PYCXX_SOURCE_DIR}/cxxsupport.cxx ${PYCXX_SOURCE_DIR}/IndirectPythonInterface.cxx ) - if(NOT ${PYCXX_VERSION} VERSION_LESS 7.0.0) + if(NOT ${PYCXX_VERSION} VERSION_LESS 6.3.0) list(APPEND PYCXX_SOURCES ${PYCXX_SOURCE_DIR}/cxx_exceptions.cxx) add_definitions(-DPYCXX_6_2_COMPATIBILITY) diff --git a/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake b/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake index d0641b2284..313165fe52 100644 --- a/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake +++ b/cMake/FreeCAD_Helpers/CompilerChecksAndSetups.cmake @@ -17,9 +17,9 @@ macro(CompilerChecksAndSetups) add_definitions(-DHAVE_SNPRINTF) endif() - # Allow developers to use Boost < 1.55 + # Allow developers to use Boost < 1.65 if (NOT BOOST_MIN_VERSION) - set(BOOST_MIN_VERSION 1.55) + set(BOOST_MIN_VERSION 1.65) endif() # For older cmake versions the variable 'CMAKE_CXX_COMPILER_VERSION' is missing @@ -48,8 +48,6 @@ macro(CompilerChecksAndSetups) set(CMAKE_CXX_STANDARD 17) elseif(${BUILD_ENABLE_CXX_STD} MATCHES "C\\+\\+14") set(CMAKE_CXX_STANDARD 14) - elseif (${BUILD_ENABLE_CXX_STD} MATCHES "C\\+\\+11") - set(CMAKE_CXX_STANDARD 11) endif() # Log the compiler and version diff --git a/cMake/FreeCAD_Helpers/SetupCoin3D.cmake b/cMake/FreeCAD_Helpers/SetupCoin3D.cmake index b50db9a93d..2f4c5c99a8 100644 --- a/cMake/FreeCAD_Helpers/SetupCoin3D.cmake +++ b/cMake/FreeCAD_Helpers/SetupCoin3D.cmake @@ -1,11 +1,39 @@ macro(SetupCoin3D) # -------------------------------- Coin3D -------------------------------- - find_package(Coin3D REQUIRED) + if (WIN32 AND MINGW) + find_path(COIN3D_INCLUDE_DIRS Inventor/So.h) + find_library(COIN3D_LIBRARIES Coin) + endif () + + # Try MODULE mode + find_package(Coin3D) if(NOT COIN3D_FOUND) - message(FATAL_ERROR "=================\n" - "Coin3D not found.\n" - "=================\n") + # Try CONFIG mode + find_package(Coin CONFIG REQUIRED) + if (Coin_FOUND) + set (COIN3D_INCLUDE_DIRS ${Coin_INCLUDE_DIR}) + set (COIN3D_LIBRARIES ${Coin_LIBRARIES}) + else() + message(FATAL_ERROR "=================\n" + "Coin3D not found.\n" + "=================\n") + endif() endif(NOT COIN3D_FOUND) + IF(NOT COIN3D_VERSION) + file(READ "${COIN3D_INCLUDE_DIRS}/Inventor/C/basic.h" _coin3d_basic_h) + string(REGEX MATCH "define[ \t]+COIN_MAJOR_VERSION[ \t]+([0-9?])" _coin3d_major_version_match "${_coin3d_basic_h}") + set(COIN3D_MAJOR_VERSION "${CMAKE_MATCH_1}") + string(REGEX MATCH "define[ \t]+COIN_MINOR_VERSION[ \t]+([0-9?])" _coin3d_minor_version_match "${_coin3d_basic_h}") + set(COIN3D_MINOR_VERSION "${CMAKE_MATCH_1}") + string(REGEX MATCH "define[ \t]+COIN_MICRO_VERSION[ \t]+([0-9?])" _coin3d_micro_version_match "${_coin3d_basic_h}") + set(COIN3D_MICRO_VERSION "${CMAKE_MATCH_1}") + set(COIN3D_VERSION "${COIN3D_MAJOR_VERSION}.${COIN3D_MINOR_VERSION}.${COIN3D_MICRO_VERSION}") + ENDIF() + + IF(NOT PIVY_VERSION) + execute_process (COMMAND ${Python3_EXECUTABLE} -c "import pivy as p; print(p.__version__,end='')" OUTPUT_VARIABLE PIVY_VERSION) + ENDIF() + endmacro(SetupCoin3D) diff --git a/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake b/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake index 2824af9c81..7b9628387f 100644 --- a/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake +++ b/cMake/FreeCAD_Helpers/SetupShibokenAndPyside.cmake @@ -125,9 +125,7 @@ macro(SetupShibokenAndPyside) "PySide2 Python module not found.\n" "================================\n") else() - message(STATUS "===============================================\n" - "PySide2 Python module found at ${PRINT_OUTPUT}.\n" - "===============================================\n") + message(STATUS "PySide2 Python module found at ${PRINT_OUTPUT}.\n") endif() endmacro(SetupShibokenAndPyside) diff --git a/conda/bld.bat b/conda/bld.bat deleted file mode 100644 index 11967adf35..0000000000 --- a/conda/bld.bat +++ /dev/null @@ -1,53 +0,0 @@ -mkdir build -cd build - -if "%FEATURE_DEBUG%"=="1" ( - set BUILD_TYPE="Debug" - echo "#! building debug package !#") else ( - set BUILD_TYPE="Release") - - -set "CFLAGS= " -set "CXXFLAGS= " -set "LDFLAGS_SHARED= ucrt.lib" - -cmake -G "Ninja" ^ - -D BUID_WITH_CONDA:BOOL=ON ^ - -D CMAKE_BUILD_TYPE=%BUILD_TYPE% ^ - -D FREECAD_LIBPACK_USE:BOOL=OFF ^ - -D CMAKE_INSTALL_PREFIX:FILEPATH=%LIBRARY_PREFIX% ^ - -D CMAKE_PREFIX_PATH:FILEPATH=%LIBRARY_PREFIX% ^ - -D CMAKE_INCLUDE_PATH:FILEPATH=%LIBRARY_PREFIX%/include ^ - -D CMAKE_LIBRARY_PATH:FILEPATH=%LIBRARY_PREFIX%/lib ^ - -D CMAKE_INSTALL_LIBDIR:FILEPATH=%LIBRARY_PREFIX%/lib ^ - -D BUILD_QT5:BOOL=ON ^ - -D NETGENDATA:FILEPATH=%LIBRARY_PREFIX%/include/netgen ^ - -D NGLIB_INCLUDE_DIR:FILEPATH=%LIBRARY_PREFIX%/include/netgen ^ - -D BUILD_FEM_NETGEN:BOOL=ON ^ - -D OCC_INCLUDE_DIR:FILEPATH=%LIBRARY_PREFIX%/include/opencascade ^ - -D OCC_LIBRARY_DIR:FILEPATH=%LIBRARY_PREFIX%/lib ^ - -D OCC_LIBRARIES:FILEPATH=%LIBRARY_PREFIX%/lib ^ - -D FREECAD_USE_OCC_VARIANT="Official Version" ^ - -D OCC_OCAF_LIBRARIES:FILEPATH=%LIBRARY_PREFIX%/lib ^ - -D BUILD_REVERSEENGINEERING:BOOL=ON ^ - -D USE_BOOST_PYTHON:BOOL=OFF ^ - -D FREECAD_USE_PYBIND11:BOOL=ON ^ - -D SMESH_INCLUDE_DIR:FILEPATH=%LIBRARY_PREFIX%/include/smesh ^ - -D FREECAD_USE_EXTERNAL_SMESH:BOOL=ON ^ - -D BUILD_FLAT_MESH:BOOL=ON ^ - -D OCCT_CMAKE_FALLBACK:BOOL=ON ^ - -D PYTHON_EXECUTABLE:FILEPATH=%PREFIX%/python ^ - -D BUILD_DYNAMIC_LINK_PYTHON:BOOL=ON ^ - -D Boost_NO_BOOST_CMAKE:BOOL=ON ^ - -D FREECAD_USE_PCH:BOOL=OFF ^ - -D FREECAD_USE_PCL:BOOL=ON ^ - -D INSTALL_TO_SITEPACKAGES:BOOL=ON ^ - .. - -if errorlevel 1 exit 1 -ninja install -if errorlevel 1 exit 1 - -rmdir /s /q "%LIBRARY_PREFIX%\doc" -ren %LIBRARY_PREFIX%\bin\FreeCAD.exe freecad.exe -ren %LIBRARY_PREFIX%\bin\FreeCADCmd.exe freecadcmd.exe diff --git a/conda/build.sh b/conda/build.sh deleted file mode 100755 index f8e271f76d..0000000000 --- a/conda/build.sh +++ /dev/null @@ -1,84 +0,0 @@ - -HOST=$(uname) - -mkdir -p build -cd build - -if [[ ${FEATURE_DEBUG} = 1 ]]; then - BUILD_TYPE="Debug" -else - BUILD_TYPE="Release" -fi - -declare -a CMAKE_PLATFORM_FLAGS - -if [[ ${HOST} =~ "Linux" ]]; then - echo "adding hacks for linux" - # temporary workaround for vtk-cmake setup - # should be applied @vtk-feedstock - sed -i 's#/home/conda/feedstock_root/build_artifacts/vtk_.*_build_env/x86_64-conda_cos6-linux-gnu/sysroot/usr/lib.*;##g' ${PREFIX}/lib/cmake/vtk-8.2/Modules/vtkhdf5.cmake - # temporary workaround for qt-cmake: - sed -i 's|_qt5gui_find_extra_libs(EGL.*)|_qt5gui_find_extra_libs(EGL "EGL" "" "")|g' $PREFIX/lib/cmake/Qt5Gui/Qt5GuiConfigExtras.cmake - sed -i 's|_qt5gui_find_extra_libs(OPENGL.*)|_qt5gui_find_extra_libs(OPENGL "GL" "" "")|g' $PREFIX/lib/cmake/Qt5Gui/Qt5GuiConfigExtras.cmake - CMAKE_PLATFORM_FLAGS+=(-DCMAKE_TOOLCHAIN_FILE="${RECIPE_DIR}/cross-linux.cmake") -fi - - -if [[ ${HOST} =~ "Darwin" ]]; then - # add hacks for osx here! - echo "adding hacks for osx" - #ln -s /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk - - # install space-mouse - if [ ! -d "/Library/Frameworks/3DconnexionClient.framework" ]; then - echo "Installing 3D connexion spacemouse drivers." - curl -o /tmp/3dFW.dmg -L 'https://download.3dconnexion.com/drivers/mac/10-6-6_360DF97D-ED08-4ccf-A55E-0BF905E58476/3DxWareMac_v10-6-6_r3234.dmg' - hdiutil attach -readonly /tmp/3dFW.dmg - sudo installer -package /Volumes/3Dconnexion\ Software/Install\ 3Dconnexion\ software.pkg -target / - diskutil eject /Volumes/3Dconnexion\ Software - fi - CMAKE_PLATFORM_FLAGS+=(-DFREECAD_USE_3DCONNEXION:BOOL=ON) - CMAKE_PLATFORM_FLAGS+=(-D3DCONNEXIONCLIENT_FRAMEWORK:FILEPATH="/Library/Frameworks/3DconnexionClient.framework") -fi - -cmake \ - -G "Ninja" \ - -D BUID_WITH_CONDA:BOOL=ON \ - -D CMAKE_BUILD_TYPE=${BUILD_TYPE} \ - -D CMAKE_INSTALL_PREFIX:FILEPATH=$PREFIX \ - -D CMAKE_PREFIX_PATH:FILEPATH=$PREFIX \ - -D CMAKE_LIBRARY_PATH:FILEPATH=$PREFIX/lib \ - -D CMAKE_INSTALL_LIBDIR:FILEPATH=$PREFIX/lib \ - -D CMAKE_INCLUDE_PATH:FILEPATH=$PREFIX/include \ - -D BUILD_QT5:BOOL=ON \ - -D FREECAD_USE_OCC_VARIANT="Official Version" \ - -D OCC_INCLUDE_DIR:FILEPATH=$PREFIX/include \ - -D USE_BOOST_PYTHON:BOOL=OFF \ - -D FREECAD_USE_PYBIND11:BOOL=ON \ - -D BUILD_ENABLE_CXX11:BOOL=ON \ - -D SMESH_INCLUDE_DIR:FILEPATH=$PREFIX/include/smesh \ - -D FREECAD_USE_EXTERNAL_SMESH=ON \ - -D BUILD_FLAT_MESH:BOOL=ON \ - -D BUILD_WITH_CONDA:BOOL=ON \ - -D PYTHON_EXECUTABLE:FILEPATH=$PREFIX/bin/python \ - -D BUILD_FEM_NETGEN:BOOL=ON \ - -D OCCT_CMAKE_FALLBACK:BOOL=OFF \ - -D FREECAD_USE_QT_DIALOG:BOOL=ON \ - -D BUILD_DYNAMIC_LINK_PYTHON:BOOL=OFF \ - -D Boost_NO_BOOST_CMAKE:BOOL=ON \ - -D FREECAD_USE_PCL:BOOL=ON \ - -D INSTALL_TO_SITEPACKAGES:BOOL=ON \ - ${CMAKE_PLATFORM_FLAGS[@]} \ - .. - -if [ $? != 0 ]; then - echo "CMake failed to configure." - exit 1 -fi - -echo "FREECAD_USE_3DCONNEXION=${FREECAD_USE_3DCONNEXION}" - -ninja install -rm -r ${PREFIX}/share/doc/FreeCAD # smaller size of package! -mv ${PREFIX}/bin/FreeCAD ${PREFIX}/bin/freecad -mv ${PREFIX}/bin/FreeCADCmd ${PREFIX}/bin/freecadcmd diff --git a/conda/conda_build_config.yaml b/conda/conda_build_config.yaml deleted file mode 100644 index e8bec02772..0000000000 --- a/conda/conda_build_config.yaml +++ /dev/null @@ -1,6 +0,0 @@ -channel_sources: -- conda-forge,defaults -channel_targets: -- freecad dev -MACOSX_DEPLOYMENT_TARGET: # [osx] -- '10.12' # [osx] \ No newline at end of file diff --git a/conda/cross-linux.cmake b/conda/cross-linux.cmake deleted file mode 100644 index 1693e03275..0000000000 --- a/conda/cross-linux.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# this one is important -set(CMAKE_SYSTEM_NAME Linux) -set(CMAKE_PLATFORM Linux) - -# specify the cross compiler -set(CMAKE_C_COMPILER $ENV{CC}) -set(CMAKE_CXX_COMPILER $ENV{CXX}) - -# where is the target environment -set(CMAKE_FIND_ROOT_PATH $ENV{PREFIX} $ENV{BUILD_PREFIX}/$ENV{HOST}/sysroot) - -# search for programs in the build host directories -set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) -# for libraries and headers in the target directories -set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) -set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) diff --git a/conda/meta.yaml b/conda/meta.yaml deleted file mode 100644 index ee7356f5c8..0000000000 --- a/conda/meta.yaml +++ /dev/null @@ -1,118 +0,0 @@ -{% set name = "freecad" %} -{% set version = "0.19.pre" %} -{% set build_number = 142 %} -{% set build_number = build_number + 500 %} # [FEATURE_DEBUG] - -package: - name: {{ name }} - version: {{ version }} - -source: - # JZ - For local building this is the setup. - path: ../ - #git_url: https://github.com/FreeCAD/FreeCAD - #git_tag: master - patches: - - windows_python_interface.patch - - -build: - number: {{ build_number }} - skip: true # [py < 38] - -requirements: - build: - - {{ compiler("cxx") }} - - {{ cdt('mesa-libgl-devel') }} # [linux] - - {{ cdt('mesa-dri-drivers') }} # [linux] - - {{ cdt('mesa-libegl-devel') }} # [linux] - - {{ cdt('libselinux') }} # [linux] - - {{ cdt('libxdamage') }} # [linux] - - {{ cdt('libxfixes') }} # [linux] - - {{ cdt('libxxf86vm') }} # [linux] - - {{ cdt('libxcb') }} # [linux] - - {{ cdt('libxext') }} # [linux] - - {{ cdt('xorg-x11-server-xvfb') }} # [linux] - - {{ cdt('libxau') }} # [linux] - - {{ cdt('libxi-devel') }} # [linux] - - cmake - - ninja - - git - host: - - boost-cpp - - python - - qt - - occt - - xerces-c - - zlib - - vtk - - swig - - eigen - - pybind11 - - coin3d - - pivy - - pyside2 - - smesh - - netgen 6.2.1808* - - doxygen - - hdf5 - - xorg-libxt # [linux] - - freetype - - libspnav # [linux] - - pcl - - six - - ply - - tbb-devel - run: - - {{ pin_compatible("pyside2") }} - - vtk - - occt - - qt - - xerces-c - - zlib - - boost-cpp - - hdf5 - - python - - coin3d - - pivy - - smesh - - netgen 6.2.1808* - - xorg-libxt # [linux] - - freetype - - numpy - - six - - pyyaml - - libspnav # [linux] - - pcl - - ply - run_constrained: - - __osx >={{ MACOSX_DEPLOYMENT_TARGET|default("10.9") }} # [osx] - -#test: -# commands: -# - FreeCADCmd -t 0 - -about: - home: https://www.freecadweb.org/ - license: LGPL2.1 - license_family: LGPL - license_file: LICENSE - summary: 'FreeCAD is a parametric 3D modeler made primarily to design real-life objects of any size. ' - description: | - FreeCAD is a general purpose feature-based, parametric 3D modeler for - CAD, MCAD, CAx, CAE and PLM, aimed directly at mechanical engineering - and product design but also fits a wider range of uses in engineering, - such as architecture or other engineering specialities. It is 100% Open - Source (LGPL2+ license) and extremely modular, allowing for very - advanced extension and customization. - FreeCAD is based on OpenCASCADE, a powerful geometry kernel, features an - Open Inventor-compliant 3D scene representation model provided by the - Coin 3D library, and a broad Python API. The interface is built with Qt. - FreeCAD runs exactly the same way on Windows, Mac OSX, BSD and Linux - platforms. - doc_url: https://www.freecadweb.org/wiki/Main_Page - dev_url: https://github.com/FreeCAD/FreeCAD - -extra: - recipe-maintainers: - - looooo diff --git a/conda/windows_python_interface.patch b/conda/windows_python_interface.patch deleted file mode 100644 index 5749162dbe..0000000000 --- a/conda/windows_python_interface.patch +++ /dev/null @@ -1,31 +0,0 @@ -diff --git a/src/Ext/freecad/CMakeLists.txt b/src/Ext/freecad/CMakeLists.txt -index e03b5527e..d9004275b 100644 ---- a/src/Ext/freecad/CMakeLists.txt -+++ b/src/Ext/freecad/CMakeLists.txt -@@ -5,7 +5,9 @@ SET(PYTHON_MAIN_DIR ${python_libs}) - - set(NAMESPACE_INIT "${CMAKE_BINARY_DIR}/Ext/freecad/__init__.py") - if (WIN32) -- set(FREECAD_LIBRARY_INSTALL_DIR ${CMAKE_INSTALL_BINDIR}) -+ get_filename_component(FREECAD_LIBRARY_INSTALL_DIR "${CMAKE_INSTALL_BINDIR}" -+ REALPATH BASE_DIR "${CMAKE_INSTALL_PREFIX}") -+ set( ${CMAKE_INSTALL_BINDIR}) - else() - set(FREECAD_LIBRARY_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR}) - endif() -diff --git a/src/Ext/freecad/__init__.py.template b/src/Ext/freecad/__init__.py.template -index 68ca151a5..d5360b252 100644 ---- a/src/Ext/freecad/__init__.py.template -+++ b/src/Ext/freecad/__init__.py.template -@@ -12,9 +12,9 @@ except ModuleNotFoundError: - except KeyError: - - # 2. we use the default freecad defined for this package -- _path_to_freecad_libdir = "${CMAKE_INSTALL_LIBDIR}" -+ _path_to_freecad_libdir = "${FREECAD_LIBRARY_INSTALL_DIR}" - print("PATH_TO_FREECAD_LIBDIR not specified, using default \ --FreeCAD version in {}".format( "${FREECAD_LIBRARY_INSTALL_DIR}")) -+FreeCAD version in {}".format("${FREECAD_LIBRARY_INSTALL_DIR}")) - - _sys.path.append(_path_to_freecad_libdir) # this is the default version - import FreeCAD as app diff --git a/conda/yum_requirements.txt b/conda/yum_requirements.txt deleted file mode 100644 index 22fa304d99..0000000000 --- a/conda/yum_requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -mesa-libGL -mesa-dri-drivers -libselinux -libXdamage -libXxf86vm -libXext-devel \ No newline at end of file diff --git a/environment-linux.yml b/environment-linux.yml deleted file mode 100644 index cbf2ff2181..0000000000 --- a/environment-linux.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: freecad_dev -channels: - - conda-forge - - defaults -dependencies: - - cxx-compiler - - cmake - - ninja - - git - - doxygen - - python - - qt - - boost-cpp - - xerces-c - - zlib - - vtk - - swig - - eigen - - occt - - pybind11 - - coin3d - - pivy - - smesh - - netgen=6.2.1808* - - hdf5 - - freetype - - pcl - - six - - ply - - tbb-devel - - pyside2 - - numpy - - six - - pyyaml - - libspnav - - libxcb - - xorg-libxt -# Linux ONLY items - - mesa-libgl-devel # [linux] - - mesa-dri-drivers # [linux] - - mesa-libegl-devel # [linux] - - libselinux # [linux] - - libxdamage # [linux] - - libxfixes # [linux] - - libxxf86vm # [linux] - - libxext # [linux] - - xorg-x11-server-xvfb # [linux] - - libxau # [linux] - - libxi-devel # [linux] diff --git a/environment-osx.yml b/environment-osx.yml deleted file mode 100644 index ff1846f00c..0000000000 --- a/environment-osx.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: freecad_dev -channels: - - conda-forge - - defaults -dependencies: - - cxx-compiler - - cmake - - ninja - - git - - doxygen - - python - - qt - - boost-cpp - - xerces-c - - zlib - - vtk - - swig - - eigen - - occt - - pybind11 - - coin3d - - pivy - - smesh - - netgen=6.2.1808* - - hdf5 - - freetype - - pcl - - six - - ply - - tbb-devel - - pyside2 - - numpy - - six - - pyyaml - - libspnav - - libxcb - - xorg-libxt -# Linux ONLY items - # - mesa-libgl-devel # [linux] - # - mesa-dri-drivers # [linux] - # - mesa-libegl-devel # [linux] - # - libselinux # [linux] - # - libxdamage # [linux] - # - libxfixes # [linux] - # - libxxf86vm # [linux] - # - libxext # [linux] - # - xorg-x11-server-xvfb # [linux] - # - libxau # [linux] - # - libxi-devel # [linux] diff --git a/package/conda/build.sh b/package/conda/build.sh deleted file mode 100644 index 7e5eb862c8..0000000000 --- a/package/conda/build.sh +++ /dev/null @@ -1,31 +0,0 @@ -mkdir -p build -cd build - -cmake -D CMAKE_BUILD_TYPE=Release \ - -D CMAKE_INSTALL_PREFIX=$PREFIX \ - -D CMAKE_PREFIX_PATH=$PREFIX \ - -D CMAKE_LIBRARY_PATH=$PREFIX/lib \ - -D BUILD_QT5=ON \ - -D NETGENDATA=$PREFIX/include/netgen \ - -D NETGEN_INCLUDEDIR=$PREFIX/include/netgen \ - -D NGLIB_INCLUDE_DIR=$PREFIX/include/nglib \ - -D OCC_INCLUDE_DIR=$PREFIX/include/opencascade \ - -D OCC_LIBRARY_DIR=$PREFIX/lib \ - -D OCC_LIBRARIES=$PREFIX/lib CACHE PATH \ - -D FREECAD_USE_OCC_VARIANT="Official Version" \ - -D OCC_OCAF_LIBRARIES=$PREFIX/lib CACHE PATH \ - -D SWIG_DIR=$PREFIX/share/swig/3.0.8 \ - -D SWIG_EXECUTABLE=$PREFIX/bin/swig \ - -D PYTHON_EXECUTABLE=$PYTHON \ - -D BUILD_FEM_NETGEN=YES \ - -D USE_BOOST_PYTHON=NO \ - -D FREECAD_USE_PYBIND11=YES \ - -D BUILD_ENABLE_CXX11=ON \ - -D SMESH_INCLUDE_DIR=$PREFIX/include/smesh \ - -D FREECAD_USE_EXTERNAL_SMESH=ON \ - /source - -make -j${CPU_COUNT} 2>&1 | tee output.txt -make -j${CPU_COUNT} install - -rm ${PREFIX}/doc -r # smaller size of package! \ No newline at end of file diff --git a/package/conda/meta.yaml b/package/conda/meta.yaml deleted file mode 100644 index 410d1e045b..0000000000 --- a/package/conda/meta.yaml +++ /dev/null @@ -1,60 +0,0 @@ -package: - name: freecad_daily - version: 0.18 - -build: - number: 0 - -requirements: - build: - - toolchain - - gcc # [unix] - - vc 14 # [win and py>=35] - - ninja - - cmake - - nomkl # [unix] - - swig - - eigen - - boost-cpp 1.66.0 - - boost 1.66.0 # [win] - - pybind11 # [unix] - - python - - matplotlib - - coin3d - - pivy - - qt 5.6.* - - pyside2 5.6.* - - occt 7.2.0 - - smesh - - netgen # [not win32] - - vtk 8.1.* - - hdf5 - - xerces-c 3.2.* - - zlib 1.2.* - - doxygen - - git - - libglu # [linux] - run: - - libgcc # [unix] - - vc 14 # [win and py>=35] - - boost-cpp 1.66.0 - - boost 1.66.0 # [win] - - python - - numpy - - matplotlib - - coin3d - - pivy - - qt 5.6.* - - pyside2 5.6.* - - occt 7.2.0 - - vtk 8.1.* - - smesh - - netgen # [not win32] - - xerces-c 3.2.* - - zlib 1.2* - - git - - calculix # [unix] - - libglu # [linux] -about: - summary: freecad - diff --git a/package/conda/run_docker_build.sh b/package/conda/run_docker_build.sh deleted file mode 100755 index bd54e3dc5e..0000000000 --- a/package/conda/run_docker_build.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/env bash - -FEEDSTOCK_ROOT=$(cd "$(dirname "$0")"; pwd;) -SOURCE_DIR=${FEEDSTOCK_ROOT}/../.. -echo ${SOURCE_DIR} - -docker info - -config=$(cat < /dev/null && docker-machine active > /dev/null; then - HOST_USER_ID=$(docker-machine ssh $(docker-machine active) id -u) -fi - -rm -f "$FEEDSTOCK_ROOT/build_artefacts/conda-forge-build-done" - -cat << EOF | docker run -i \ - -v "${SOURCE_DIR}":/source \ - -e HOST_USER_ID="${HOST_USER_ID}" \ - -a stdin -a stdout -a stderr \ - condaforge/linux-anvil \ - bash || exit 1 - -set -x -export PYTHONUNBUFFERED=1 - -echo "$config" > ~/.condarc - -conda clean --lock - -conda install --yes --quiet conda-build - -/usr/bin/sudo -n yum install -y libXt-devel libXmu-devel libXi-devel mesa-libGLU-devel -conda build /source/package/conda -EOF \ No newline at end of file diff --git a/package/makepkg b/package/makepkg deleted file mode 100644 index 66defab726..0000000000 --- a/package/makepkg +++ /dev/null @@ -1,49 +0,0 @@ -# Contributor: Joaquim Coimbra -# Thanks to Werner Mayer for his support - -pkgname=freecad-svn -pkgver=2152 -pkgrel=2 -pkgdesc="A general purpose 3D CAD modeler, aimed directly at mechanical engineering and product design but also architecture or other engineering specialities" -arch=('x86_64') -url="https://sourceforge.net/apps/mediawiki/free-cad/" -license=('GPL') -groups=() -depends=('xerces-c' 'gts' 'opencascade' 'coin' 'soqt' 'soqt-doc' 'zlib' 'ode' 'qt' 'opencv' 'boost' 'python') -makedepends=('subversion') -provides=('freecad') -conflicts=('freecad') -replaces=() -backup=() -options=('!makeflags') -install= -source=() -noextract=() -md5sums=() - -_svntrunk=https://free-cad.svn.sourceforge.net/svnroot/free-cad/trunk -_svnmod=freecad - -build() { -cd "$srcdir" - -if [ -d $_svnmod/.svn ]; then - (cd $_svnmod && svn up -r $pkgver) -else - svn co $_svntrunk --config-dir ./ -r $pkgver $_svnmod -fi - -msg "SVN checkout done or server timeout" -msg "Starting make..." - -cd $_svnmod - -# -# BUILD -# -./autogen.sh || return 1 -./configure CXXFLAGS="-D_OCC64" --prefix=/usr/ --with-qt4-dir=/usr/lib/qt/ --with-qt4-bin=/usr/bin/ --with-qt4-include=/usr/include/ --with-qt4-lib=/usr/lib/qt/ --with-xercesc-include=/usr/include/xercesc/ --with-xercesc-lib=/usr/lib/ - -make || return 1 -make DESTDIR="$pkgdir/" install || return 1 -} \ No newline at end of file diff --git a/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp b/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp index 7fe268f1ed..e3187310d6 100644 --- a/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/BlobNodeImpl.cpp @@ -184,7 +184,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/CheckedFile.cpp b/src/3rdParty/libE57Format/src/CheckedFile.cpp index 2dc4143ccf..17f646d0a9 100644 --- a/src/3rdParty/libE57Format/src/CheckedFile.cpp +++ b/src/3rdParty/libE57Format/src/CheckedFile.cpp @@ -455,7 +455,7 @@ void CheckedFile::seek( uint64_t offset, OffsetMode omode ) uint64_t CheckedFile::lseek64( int64_t offset, int whence ) { - if ( ( fd_ < 0 ) && ( bufView_ != nullptr ) ) + if ( ( fd_ < 0 ) && bufView_ ) { const auto uoffset = static_cast( offset ); @@ -652,7 +652,7 @@ void CheckedFile::close() fd_ = -1; } - if ( bufView_ != nullptr ) + if ( bufView_ ) { delete bufView_; bufView_ = nullptr; @@ -746,7 +746,7 @@ void CheckedFile::readPhysicalPage( char *page_buffer, uint64_t page ) /// Seek to start of physical page seek( page * physicalPageSize, Physical ); - if ( ( fd_ < 0 ) && ( bufView_ != nullptr ) ) + if ( ( fd_ < 0 ) && bufView_ ) { bufView_->read( page_buffer, physicalPageSize ); return; diff --git a/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp b/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp index 1dbcb98d37..d6bbd53bcb 100644 --- a/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/CompressedVectorNodeImpl.cpp @@ -202,7 +202,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/Decoder.cpp b/src/3rdParty/libE57Format/src/Decoder.cpp index 9eb872ad1a..8b4f468a12 100644 --- a/src/3rdParty/libE57Format/src/Decoder.cpp +++ b/src/3rdParty/libE57Format/src/Decoder.cpp @@ -220,7 +220,7 @@ size_t BitpackDecoder::inputProcess( const char *source, const size_t availableB size_t byteCount = std::min( bytesUnsaved, inBuffer_.size() - static_cast( inBufferEndByte_ ) ); /// Copy input bytes from caller, if any - if ( ( byteCount > 0 ) && ( source != nullptr ) ) + if ( ( byteCount > 0 ) && source ) { memcpy( &inBuffer_[inBufferEndByte_], source, byteCount ); diff --git a/src/3rdParty/libE57Format/src/E57Exception.cpp b/src/3rdParty/libE57Format/src/E57Exception.cpp index ee16efa663..e95afe7724 100644 --- a/src/3rdParty/libE57Format/src/E57Exception.cpp +++ b/src/3rdParty/libE57Format/src/E57Exception.cpp @@ -143,14 +143,14 @@ namespace e57 os << " Debug info: " << std::endl; os << " context: " << context_ << std::endl; os << " sourceFunctionName: " << sourceFunctionName_ << std::endl; - if ( reportingFunctionName != nullptr ) + if ( reportingFunctionName ) os << " reportingFunctionName: " << reportingFunctionName << std::endl; /*** Add a line in error message that a smart editor (gnu emacs) can * interpret as a link to the source code: */ os << sourceFileName_ << "(" << sourceLineNumber_ << ") : error C" << errorCode_ << ": <--- occurred on" << std::endl; - if ( reportingFileName != nullptr ) + if ( reportingFileName ) os << reportingFileName << "(" << reportingLineNumber << ") : error C0: <--- reported on" << std::endl; #endif } diff --git a/src/3rdParty/libE57Format/src/E57XmlParser.cpp b/src/3rdParty/libE57Format/src/E57XmlParser.cpp index ef60ab848a..eecc2ea289 100644 --- a/src/3rdParty/libE57Format/src/E57XmlParser.cpp +++ b/src/3rdParty/libE57Format/src/E57XmlParser.cpp @@ -252,7 +252,7 @@ void E57XmlParser::init() xmlReader = XMLReaderFactory::createXMLReader(); //??? auto_ptr? - if ( xmlReader == nullptr ) + if ( !xmlReader ) { throw E57_EXCEPTION2( E57_ERROR_XML_PARSER_INIT, "could not create the xml reader" ); } diff --git a/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp b/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp index 865b8638ec..7bdb15fa45 100644 --- a/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/FloatNodeImpl.cpp @@ -149,7 +149,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/ImageFileImpl.cpp b/src/3rdParty/libE57Format/src/ImageFileImpl.cpp index 8d05d26af2..fbc9c5924e 100644 --- a/src/3rdParty/libE57Format/src/ImageFileImpl.cpp +++ b/src/3rdParty/libE57Format/src/ImageFileImpl.cpp @@ -290,7 +290,7 @@ namespace e57 void ImageFileImpl::close() { /// If file already closed, have nothing to do - if ( file_ == nullptr ) + if ( !file_ ) { return; } @@ -349,7 +349,7 @@ namespace e57 void ImageFileImpl::cancel() { /// If file already closed, have nothing to do - if ( file_ == nullptr ) + if ( !file_ ) { return; } diff --git a/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp b/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp index de9e73081e..492baab0ae 100644 --- a/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/IntegerNodeImpl.cpp @@ -120,7 +120,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/ReaderImpl.cpp b/src/3rdParty/libE57Format/src/ReaderImpl.cpp index 89f7f762d1..40814e8125 100644 --- a/src/3rdParty/libE57Format/src/ReaderImpl.cpp +++ b/src/3rdParty/libE57Format/src/ReaderImpl.cpp @@ -1254,19 +1254,19 @@ namespace e57 ustring name = lineGroupRecord.get( protoIndex ).elementName(); if ( ( name.compare( "idElementValue" ) == 0 ) && lineGroupRecord.isDefined( "idElementValue" ) && - ( idElementValue != nullptr ) ) + idElementValue ) { groupSDBuffers.emplace_back( imf_, "idElementValue", idElementValue, groupCount, true ); } if ( ( name.compare( "startPointIndex" ) == 0 ) && lineGroupRecord.isDefined( "startPointIndex" ) && - ( startPointIndex != nullptr ) ) + startPointIndex ) { groupSDBuffers.emplace_back( imf_, "startPointIndex", startPointIndex, groupCount, true ); } if ( ( name.compare( "pointCount" ) == 0 ) && lineGroupRecord.isDefined( "pointCount" ) && - ( pointCount != nullptr ) ) + pointCount ) { groupSDBuffers.emplace_back( imf_, "pointCount", pointCount, groupCount, true ); } @@ -1303,117 +1303,117 @@ namespace e57 bool haveNormalsExt = imf_.extensionsLookupPrefix( "nor", norExtUri ); if ( ( name.compare( "cartesianX" ) == 0 ) && proto.isDefined( "cartesianX" ) && - ( buffers.cartesianX != nullptr ) ) + buffers.cartesianX ) { destBuffers.emplace_back( imf_, "cartesianX", buffers.cartesianX, count, true, scaled ); } else if ( ( name.compare( "cartesianY" ) == 0 ) && proto.isDefined( "cartesianY" ) && - ( buffers.cartesianY != nullptr ) ) + buffers.cartesianY ) { destBuffers.emplace_back( imf_, "cartesianY", buffers.cartesianY, count, true, scaled ); } else if ( ( name.compare( "cartesianZ" ) == 0 ) && proto.isDefined( "cartesianZ" ) && - ( buffers.cartesianZ != nullptr ) ) + buffers.cartesianZ ) { destBuffers.emplace_back( imf_, "cartesianZ", buffers.cartesianZ, count, true, scaled ); } else if ( ( name.compare( "cartesianInvalidState" ) == 0 ) && proto.isDefined( "cartesianInvalidState" ) && - ( buffers.cartesianInvalidState != nullptr ) ) + buffers.cartesianInvalidState ) { destBuffers.emplace_back( imf_, "cartesianInvalidState", buffers.cartesianInvalidState, count, true ); } else if ( ( name.compare( "sphericalRange" ) == 0 ) && proto.isDefined( "sphericalRange" ) && - ( buffers.sphericalRange != nullptr ) ) + buffers.sphericalRange ) { destBuffers.emplace_back( imf_, "sphericalRange", buffers.sphericalRange, count, true, scaled ); } else if ( ( name.compare( "sphericalAzimuth" ) == 0 ) && proto.isDefined( "sphericalAzimuth" ) && - ( buffers.sphericalAzimuth != nullptr ) ) + buffers.sphericalAzimuth ) { destBuffers.emplace_back( imf_, "sphericalAzimuth", buffers.sphericalAzimuth, count, true, scaled ); } else if ( ( name.compare( "sphericalElevation" ) == 0 ) && proto.isDefined( "sphericalElevation" ) && - ( buffers.sphericalElevation != nullptr ) ) + buffers.sphericalElevation ) { destBuffers.emplace_back( imf_, "sphericalElevation", buffers.sphericalElevation, count, true, scaled ); } else if ( ( name.compare( "sphericalInvalidState" ) == 0 ) && proto.isDefined( "sphericalInvalidState" ) && - ( buffers.sphericalInvalidState != nullptr ) ) + buffers.sphericalInvalidState ) { destBuffers.emplace_back( imf_, "sphericalInvalidState", buffers.sphericalInvalidState, count, true ); } else if ( ( name.compare( "rowIndex" ) == 0 ) && proto.isDefined( "rowIndex" ) && - ( buffers.rowIndex != nullptr ) ) + buffers.rowIndex ) { destBuffers.emplace_back( imf_, "rowIndex", buffers.rowIndex, count, true ); } else if ( ( name.compare( "columnIndex" ) == 0 ) && proto.isDefined( "columnIndex" ) && - ( buffers.columnIndex != nullptr ) ) + buffers.columnIndex ) { destBuffers.emplace_back( imf_, "columnIndex", buffers.columnIndex, count, true ); } else if ( ( name.compare( "returnIndex" ) == 0 ) && proto.isDefined( "returnIndex" ) && - ( buffers.returnIndex != nullptr ) ) + buffers.returnIndex ) { destBuffers.emplace_back( imf_, "returnIndex", buffers.returnIndex, count, true ); } else if ( ( name.compare( "returnCount" ) == 0 ) && proto.isDefined( "returnCount" ) && - ( buffers.returnCount != nullptr ) ) + buffers.returnCount ) { destBuffers.emplace_back( imf_, "returnCount", buffers.returnCount, count, true ); } else if ( ( name.compare( "timeStamp" ) == 0 ) && proto.isDefined( "timeStamp" ) && - ( buffers.timeStamp != nullptr ) ) + buffers.timeStamp ) { destBuffers.emplace_back( imf_, "timeStamp", buffers.timeStamp, count, true, scaled ); } else if ( ( name.compare( "isTimeStampInvalid" ) == 0 ) && proto.isDefined( "isTimeStampInvalid" ) && - ( buffers.isTimeStampInvalid != nullptr ) ) + buffers.isTimeStampInvalid ) { destBuffers.emplace_back( imf_, "isTimeStampInvalid", buffers.isTimeStampInvalid, count, true ); } else if ( ( name.compare( "intensity" ) == 0 ) && proto.isDefined( "intensity" ) && - ( buffers.intensity != nullptr ) ) + buffers.intensity ) { destBuffers.emplace_back( imf_, "intensity", buffers.intensity, count, true, scaled ); } else if ( ( name.compare( "isIntensityInvalid" ) == 0 ) && proto.isDefined( "isIntensityInvalid" ) && - ( buffers.isIntensityInvalid != nullptr ) ) + buffers.isIntensityInvalid ) { destBuffers.emplace_back( imf_, "isIntensityInvalid", buffers.isIntensityInvalid, count, true ); } else if ( ( name.compare( "colorRed" ) == 0 ) && proto.isDefined( "colorRed" ) && - ( buffers.colorRed != nullptr ) ) + buffers.colorRed ) { destBuffers.emplace_back( imf_, "colorRed", buffers.colorRed, count, true, scaled ); } else if ( ( name.compare( "colorGreen" ) == 0 ) && proto.isDefined( "colorGreen" ) && - ( buffers.colorGreen != nullptr ) ) + buffers.colorGreen ) { destBuffers.emplace_back( imf_, "colorGreen", buffers.colorGreen, count, true, scaled ); } else if ( ( name.compare( "colorBlue" ) == 0 ) && proto.isDefined( "colorBlue" ) && - ( buffers.colorBlue != nullptr ) ) + buffers.colorBlue ) { destBuffers.emplace_back( imf_, "colorBlue", buffers.colorBlue, count, true, scaled ); } else if ( ( name.compare( "isColorInvalid" ) == 0 ) && proto.isDefined( "isColorInvalid" ) && - ( buffers.isColorInvalid != nullptr ) ) + buffers.isColorInvalid ) { destBuffers.emplace_back( imf_, "isColorInvalid", buffers.isColorInvalid, count, true ); } else if ( haveNormalsExt && ( name.compare( "nor:normalX" ) == 0 ) && proto.isDefined( "nor:normalX" ) && - ( buffers.normalX != nullptr ) ) + buffers.normalX ) { destBuffers.emplace_back( imf_, "nor:normalX", buffers.normalX, count, true, scaled ); } else if ( haveNormalsExt && ( name.compare( "nor:normalY" ) == 0 ) && proto.isDefined( "nor:normalY" ) && - ( buffers.normalY != nullptr ) ) + buffers.normalY ) { destBuffers.emplace_back( imf_, "nor:normalY", buffers.normalY, count, true, scaled ); } else if ( haveNormalsExt && ( name.compare( "nor:normalZ" ) == 0 ) && proto.isDefined( "nor:normalZ" ) && - ( buffers.normalZ != nullptr ) ) + buffers.normalZ ) { destBuffers.emplace_back( imf_, "nor:normalZ", buffers.normalZ, count, true, scaled ); } diff --git a/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp b/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp index c6fc94b13d..90c40c6873 100644 --- a/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/ScaledIntegerNodeImpl.cpp @@ -183,7 +183,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp b/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp index c3563730e2..010a27296c 100644 --- a/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp +++ b/src/3rdParty/libE57Format/src/SourceDestBufferImpl.cpp @@ -112,7 +112,7 @@ SourceDestBufferImpl::SourceDestBufferImpl( ImageFileImplWeakPtr destImageFile, /// don't checkImageFileOpen, checkState_ will do it /// Set capacity_ after testing that b is OK - if ( b == nullptr ) + if ( !b ) { throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "sdbuf.pathName=" + pathName ); } @@ -291,7 +291,7 @@ void SourceDestBufferImpl::checkState_() const if ( memoryRepresentation_ != E57_USTRING ) { - if ( base_ == nullptr ) + if ( !base_ ) { throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "pathName=" + pathName_ ); } @@ -304,7 +304,7 @@ void SourceDestBufferImpl::checkState_() const } else { - if ( ustrings_ == nullptr ) + if ( !ustrings_ ) { throw E57_EXCEPTION2( E57_ERROR_BAD_BUFFER, "pathName=" + pathName_ ); } diff --git a/src/3rdParty/libE57Format/src/StringNodeImpl.cpp b/src/3rdParty/libE57Format/src/StringNodeImpl.cpp index 91d1faf317..8d03d58138 100644 --- a/src/3rdParty/libE57Format/src/StringNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/StringNodeImpl.cpp @@ -83,7 +83,7 @@ namespace e57 // don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp b/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp index af9bd168ea..e4aacb6ca0 100644 --- a/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/StructureNodeImpl.cpp @@ -387,7 +387,7 @@ void StructureNodeImpl::writeXml( ImageFileImplSharedPtr imf, CheckedFile &cf, i /// don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp b/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp index 707858e83a..9534375a23 100644 --- a/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp +++ b/src/3rdParty/libE57Format/src/VectorNodeImpl.cpp @@ -103,7 +103,7 @@ namespace e57 /// don't checkImageFileOpen ustring fieldName; - if ( forcedFieldName != nullptr ) + if ( forcedFieldName ) { fieldName = forcedFieldName; } diff --git a/src/3rdParty/libE57Format/src/WriterImpl.cpp b/src/3rdParty/libE57Format/src/WriterImpl.cpp index c1d3afc110..f8942038b3 100644 --- a/src/3rdParty/libE57Format/src/WriterImpl.cpp +++ b/src/3rdParty/libE57Format/src/WriterImpl.cpp @@ -950,90 +950,90 @@ namespace e57 StructureNode proto( points.prototype() ); std::vector sourceBuffers; - if ( proto.isDefined( "cartesianX" ) && ( buffers.cartesianX != nullptr ) ) + if ( proto.isDefined( "cartesianX" ) && buffers.cartesianX ) { sourceBuffers.emplace_back( imf_, "cartesianX", buffers.cartesianX, count, true, true ); } - if ( proto.isDefined( "cartesianY" ) && ( buffers.cartesianY != nullptr ) ) + if ( proto.isDefined( "cartesianY" ) && buffers.cartesianY ) { sourceBuffers.emplace_back( imf_, "cartesianY", buffers.cartesianY, count, true, true ); } - if ( proto.isDefined( "cartesianZ" ) && ( buffers.cartesianZ != nullptr ) ) + if ( proto.isDefined( "cartesianZ" ) && buffers.cartesianZ ) { sourceBuffers.emplace_back( imf_, "cartesianZ", buffers.cartesianZ, count, true, true ); } - if ( proto.isDefined( "sphericalRange" ) && ( buffers.sphericalRange != nullptr ) ) + if ( proto.isDefined( "sphericalRange" ) && buffers.sphericalRange ) { sourceBuffers.emplace_back( imf_, "sphericalRange", buffers.sphericalRange, count, true, true ); } - if ( proto.isDefined( "sphericalAzimuth" ) && ( buffers.sphericalAzimuth != nullptr ) ) + if ( proto.isDefined( "sphericalAzimuth" ) && buffers.sphericalAzimuth ) { sourceBuffers.emplace_back( imf_, "sphericalAzimuth", buffers.sphericalAzimuth, count, true, true ); } - if ( proto.isDefined( "sphericalElevation" ) && ( buffers.sphericalElevation != nullptr ) ) + if ( proto.isDefined( "sphericalElevation" ) && buffers.sphericalElevation ) { sourceBuffers.emplace_back( imf_, "sphericalElevation", buffers.sphericalElevation, count, true, true ); } - if ( proto.isDefined( "intensity" ) && ( buffers.intensity != nullptr ) ) + if ( proto.isDefined( "intensity" ) && buffers.intensity ) { sourceBuffers.emplace_back( imf_, "intensity", buffers.intensity, count, true, true ); } - if ( proto.isDefined( "colorRed" ) && ( buffers.colorRed != nullptr ) ) + if ( proto.isDefined( "colorRed" ) && buffers.colorRed ) { sourceBuffers.emplace_back( imf_, "colorRed", buffers.colorRed, count, true ); } - if ( proto.isDefined( "colorGreen" ) && ( buffers.colorGreen != nullptr ) ) + if ( proto.isDefined( "colorGreen" ) && buffers.colorGreen ) { sourceBuffers.emplace_back( imf_, "colorGreen", buffers.colorGreen, count, true ); } - if ( proto.isDefined( "colorBlue" ) && ( buffers.colorBlue != nullptr ) ) + if ( proto.isDefined( "colorBlue" ) && buffers.colorBlue ) { sourceBuffers.emplace_back( imf_, "colorBlue", buffers.colorBlue, count, true ); } - if ( proto.isDefined( "returnIndex" ) && ( buffers.returnIndex != nullptr ) ) + if ( proto.isDefined( "returnIndex" ) && buffers.returnIndex ) { sourceBuffers.emplace_back( imf_, "returnIndex", buffers.returnIndex, count, true ); } - if ( proto.isDefined( "returnCount" ) && ( buffers.returnCount != nullptr ) ) + if ( proto.isDefined( "returnCount" ) && buffers.returnCount ) { sourceBuffers.emplace_back( imf_, "returnCount", buffers.returnCount, count, true ); } - if ( proto.isDefined( "rowIndex" ) && ( buffers.rowIndex != nullptr ) ) + if ( proto.isDefined( "rowIndex" ) && buffers.rowIndex ) { sourceBuffers.emplace_back( imf_, "rowIndex", buffers.rowIndex, count, true ); } - if ( proto.isDefined( "columnIndex" ) && ( buffers.columnIndex != nullptr ) ) + if ( proto.isDefined( "columnIndex" ) && buffers.columnIndex ) { sourceBuffers.emplace_back( imf_, "columnIndex", buffers.columnIndex, count, true ); } - if ( proto.isDefined( "timeStamp" ) && ( buffers.timeStamp != nullptr ) ) + if ( proto.isDefined( "timeStamp" ) && buffers.timeStamp ) { sourceBuffers.emplace_back( imf_, "timeStamp", buffers.timeStamp, count, true, true ); } - if ( proto.isDefined( "cartesianInvalidState" ) && ( buffers.cartesianInvalidState != nullptr ) ) + if ( proto.isDefined( "cartesianInvalidState" ) && buffers.cartesianInvalidState ) { sourceBuffers.emplace_back( imf_, "cartesianInvalidState", buffers.cartesianInvalidState, count, true ); } - if ( proto.isDefined( "sphericalInvalidState" ) && ( buffers.sphericalInvalidState != nullptr ) ) + if ( proto.isDefined( "sphericalInvalidState" ) && buffers.sphericalInvalidState ) { sourceBuffers.emplace_back( imf_, "sphericalInvalidState", buffers.sphericalInvalidState, count, true ); } - if ( proto.isDefined( "isIntensityInvalid" ) && ( buffers.isIntensityInvalid != nullptr ) ) + if ( proto.isDefined( "isIntensityInvalid" ) && buffers.isIntensityInvalid ) { sourceBuffers.emplace_back( imf_, "isIntensityInvalid", buffers.isIntensityInvalid, count, true ); } - if ( proto.isDefined( "isColorInvalid" ) && ( buffers.isColorInvalid != nullptr ) ) + if ( proto.isDefined( "isColorInvalid" ) && buffers.isColorInvalid ) { sourceBuffers.emplace_back( imf_, "isColorInvalid", buffers.isColorInvalid, count, true ); } - if ( proto.isDefined( "isTimeStampInvalid" ) && ( buffers.isTimeStampInvalid != nullptr ) ) + if ( proto.isDefined( "isTimeStampInvalid" ) && buffers.isTimeStampInvalid ) { sourceBuffers.emplace_back( imf_, "isTimeStampInvalid", buffers.isTimeStampInvalid, count, true ); } @@ -1042,15 +1042,15 @@ namespace e57 ustring norExtUri; if ( imf_.extensionsLookupPrefix( "nor", norExtUri ) ) { - if ( proto.isDefined( "nor:normalX" ) && ( buffers.normalX != nullptr ) ) + if ( proto.isDefined( "nor:normalX" ) && buffers.normalX ) { sourceBuffers.emplace_back( imf_, "nor:normalX", buffers.normalX, count, true, true ); } - if ( proto.isDefined( "nor:normalY" ) && ( buffers.normalY != nullptr ) ) + if ( proto.isDefined( "nor:normalY" ) && buffers.normalY ) { sourceBuffers.emplace_back( imf_, "nor:normalY", buffers.normalY, count, true, true ); } - if ( proto.isDefined( "nor:normalZ" ) && ( buffers.normalZ != nullptr ) ) + if ( proto.isDefined( "nor:normalZ" ) && buffers.normalZ ) { sourceBuffers.emplace_back( imf_, "nor:normalZ", buffers.normalZ, count, true, true ); } diff --git a/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_Mesher.cpp b/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_Mesher.cpp index 4dd8ed274e..0e0f662b92 100644 --- a/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_Mesher.cpp +++ b/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_Mesher.cpp @@ -50,7 +50,9 @@ #include +#include #include +#include #include #include #include @@ -66,6 +68,7 @@ #include #include #include +#include #ifdef _MSC_VER #pragma warning(disable : 4067) @@ -180,7 +183,7 @@ NETGENPlugin_Mesher::NETGENPlugin_Mesher (SMESH_Mesh* mesh, //================================================================================ /*! - * Destuctor + * Destructor */ //================================================================================ @@ -1326,7 +1329,7 @@ namespace struct TIntVData { gp_XY uv; //!< UV in face parametric space - int ngId; //!< ng id of corrsponding node + int ngId; //!< ng id of corresponding node gp_XY uvClose; //!< UV of closest boundary node int ngIdClose; //!< ng id of closest boundary node }; @@ -1982,7 +1985,7 @@ NETGENPlugin_Mesher::AddSegmentsToMesh(netgen::Mesh& ngMesh, netgen::Segment& prevSeg = ngMesh.LineSegment( i-1 ); if ( seg[0] == prevSeg[1] && seg[1] == prevSeg[0] ) { - cout << "Segment: " << seg.edgenr << std::endl << "\tis REVRESE of the previous one" << std::endl; + cout << "Segment: " << seg.edgenr << std::endl << "\tis REVERSE of the previous one" << std::endl; continue; } } @@ -2043,7 +2046,7 @@ int NETGENPlugin_Mesher::FillSMesh(const netgen::OCCGeometry& occgeo, // quadHelper is used for either // 1) making quadratic elements when a lower dimension mesh is loaded - // to SMESH before convertion to quadratic by NETGEN + // to SMESH before conversion to quadratic by NETGEN // 2) sewing of quadratic elements with quadratic elements of sub-meshes if ( quadHelper && !quadHelper->GetIsQuadratic() && quadHelper->GetTLinkNodeMap().empty() ) quadHelper = 0; @@ -2508,7 +2511,7 @@ bool NETGENPlugin_Mesher::Compute() { // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE mparams.uselocalh = false; - mparams.grading = 0.8; // not limitited size growth + mparams.grading = 0.8; // not limited size growth if ( _simpleHyp->GetNumberOfSegments() ) // nb of segments @@ -2974,18 +2977,18 @@ bool NETGENPlugin_Mesher::Compute() if(netgen::multithread.terminate) return false; - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(err); } catch (Standard_Failure& ex) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(ex); err = 1; } catch (netgen::NgException exc) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(exc); err = 1; } @@ -3012,22 +3015,22 @@ bool NETGENPlugin_Mesher::Compute() if(netgen::multithread.terminate) return false; - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(err); } catch (Standard_Failure& ex) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(ex); } catch (netgen::NgException exc) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << text(exc); } } } - if (!err && mparams.secondorder > 0) + if (!err && mparams.secondorder) { try { @@ -3055,12 +3058,12 @@ bool NETGENPlugin_Mesher::Compute() } catch (Standard_Failure& ex) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << "Exception in netgen at passing to 2nd order "; } catch (netgen::NgException exc) { - if ( comment.empty() ) // do not overwrite a previos error + if ( comment.empty() ) // do not overwrite a previous error comment << exc.What(); } } @@ -3199,7 +3202,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) { // not to RestrictLocalH() according to curvature during MESHCONST_ANALYSE mparams.uselocalh = false; - mparams.grading = 0.8; // not limitited size growth + mparams.grading = 0.8; // not limited size growth if ( _simpleHyp->GetNumberOfSegments() ) // nb of segments @@ -3302,7 +3305,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) // calculate total nb of segments and length of edges double fullLen = 0.0; int fullNbSeg = 0; - int entity = mparams.secondorder > 0 ? SMDSEntity_Quad_Edge : SMDSEntity_Edge; + int entity = mparams.secondorder ? SMDSEntity_Quad_Edge : SMDSEntity_Edge; TopTools_DataMapOfShapeInteger Edge2NbSeg; for (TopExp_Explorer exp(_shape, TopAbs_EDGE); exp.More(); exp.Next()) { @@ -3340,7 +3343,7 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) { vector& aVec = aResMap[_mesh->GetSubMesh(Edge2NbSegIt.Key())]; if ( aVec[ entity ] > 1 && aVec[ SMDSEntity_Node ] == 0 ) - aVec[SMDSEntity_Node] = mparams.secondorder > 0 ? 2*aVec[ entity ]-1 : aVec[ entity ]-1; + aVec[SMDSEntity_Node] = mparams.secondorder ? 2*aVec[ entity ]-1 : aVec[ entity ]-1; fullNbSeg += aVec[ entity ]; Edge2NbSeg( Edge2NbSegIt.Key() ) = aVec[ entity ]; @@ -3377,16 +3380,16 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) int nb1d = 0; if ( !tooManyElems ) { - TopTools_MapOfShape egdes; + TopTools_MapOfShape edges; for (TopExp_Explorer exp1(F,TopAbs_EDGE); exp1.More(); exp1.Next()) - if ( egdes.Add( exp1.Current() )) + if (edges.Add(exp1.Current())) nb1d += Edge2NbSeg.Find(exp1.Current()); } int nbFaces = tooManyElems ? hugeNb : int( 4*anArea / (mparams.maxh*mparams.maxh*sqrt(3.))); int nbNodes = tooManyElems ? hugeNb : (( nbFaces*3 - (nb1d-1)*2 ) / 6 + 1 ); vector aVec(SMDSEntity_Last, 0); - if( mparams.secondorder > 0 ) { + if (mparams.secondorder) { int nb1d_in = (nbFaces*3 - nb1d) / 2; aVec[SMDSEntity_Node] = nbNodes + nb1d_in; aVec[SMDSEntity_Quad_Triangle] = nbFaces; @@ -3428,11 +3431,11 @@ bool NETGENPlugin_Mesher::Evaluate(MapShapeNbElems& aResMap) if ( tooManyElems ) // avoid FPE { aVec[SMDSEntity_Node] = hugeNb; - aVec[ mparams.secondorder > 0 ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb; + aVec[ mparams.secondorder ? SMDSEntity_Quad_Tetra : SMDSEntity_Tetra] = hugeNb; } else { - if( mparams.secondorder > 0 ) { + if (mparams.secondorder) { aVec[SMDSEntity_Node] = nb1d_in/3 + 1 + nb1d_in; aVec[SMDSEntity_Quad_Tetra] = nbVols; } @@ -3787,7 +3790,7 @@ NETGENPlugin_Internals::NETGENPlugin_Internals( SMESH_Mesh& mesh, { _intShapes.insert( meshDS->ShapeToIndex( f.Current() )); - // egdes + // edges list< TopoDS_Shape > edges; for ( e.Init( f.Current(), TopAbs_EDGE ); e.More(); e.Next()) if ( SMESH_MesherHelper::NbAncestors( e.Current(), mesh, TopAbs_FACE ) > 1 ) diff --git a/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cpp b/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cpp index 2ebe4f87ac..72269e84db 100644 --- a/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cpp +++ b/src/3rdParty/salomesmesh/src/NETGENPlugin/NETGENPlugin_NETGEN_2D_ONLY.cpp @@ -39,6 +39,8 @@ #include #include #include +#include +#include #include #include diff --git a/src/App/Annotation.cpp b/src/App/Annotation.cpp index d3101d5f5d..ad5ac9134a 100644 --- a/src/App/Annotation.cpp +++ b/src/App/Annotation.cpp @@ -30,28 +30,24 @@ using namespace App; PROPERTY_SOURCE(App::Annotation, App::DocumentObject) -Annotation::Annotation() +Annotation::Annotation() { - ADD_PROPERTY(LabelText ,("")); - ADD_PROPERTY(Position,(Base::Vector3d())); + ADD_PROPERTY(LabelText, ("")); + ADD_PROPERTY(Position, (Base::Vector3d())); } -Annotation::~Annotation() -{ -} +Annotation::~Annotation() = default; // -------------------------------------------------- PROPERTY_SOURCE(App::AnnotationLabel, App::DocumentObject) -AnnotationLabel::AnnotationLabel() +AnnotationLabel::AnnotationLabel() { - ADD_PROPERTY_TYPE(LabelText,(""),"Label",Prop_Output,"Text label of the annotation"); - ADD_PROPERTY_TYPE(BasePosition,(Base::Vector3d()),"Label",Prop_Output,"Base position"); - ADD_PROPERTY_TYPE(TextPosition,(Base::Vector3d()),"Label",Prop_Output,"Text position"); + ADD_PROPERTY_TYPE(LabelText, (""), "Label",Prop_Output, "Text label of the annotation"); + ADD_PROPERTY_TYPE(BasePosition, (Base::Vector3d()), "Label", Prop_Output, "Base position"); + ADD_PROPERTY_TYPE(TextPosition, (Base::Vector3d()), "Label", Prop_Output, "Text position"); } -AnnotationLabel::~AnnotationLabel() -{ -} +AnnotationLabel::~AnnotationLabel() = default; diff --git a/src/App/Annotation.h b/src/App/Annotation.h index 873f4a37c1..4595ae0b58 100644 --- a/src/App/Annotation.h +++ b/src/App/Annotation.h @@ -34,37 +34,37 @@ namespace App class AppExport Annotation : public DocumentObject { - PROPERTY_HEADER(App::Annotation); + PROPERTY_HEADER_WITH_OVERRIDE(App::Annotation); public: /// Constructor - Annotation(void); - virtual ~Annotation(); + Annotation(); + ~Annotation() override; App::PropertyStringList LabelText; App::PropertyVector Position; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderAnnotation"; } }; class AppExport AnnotationLabel : public DocumentObject { - PROPERTY_HEADER(App::AnnotationLabel); + PROPERTY_HEADER_WITH_OVERRIDE(App::AnnotationLabel); public: /// Constructor - AnnotationLabel(void); - virtual ~AnnotationLabel(); + AnnotationLabel(); + ~AnnotationLabel() override; App::PropertyStringList LabelText; App::PropertyVector BasePosition; App::PropertyVector TextPosition; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderAnnotationLabel"; } }; diff --git a/src/App/Application.cpp b/src/App/Application.cpp index 30816239d5..8aaa1fd782 100644 --- a/src/App/Application.cpp +++ b/src/App/Application.cpp @@ -70,6 +70,7 @@ #include #include #include +#include #include #include #include @@ -122,13 +123,6 @@ #include "Branding.h" -using namespace App; -using namespace std; -using namespace boost; -using namespace boost::program_options; -namespace sp = std::placeholders; - - // scriptings (scripts are built-in but can be overridden by command line option) #include #include @@ -146,12 +140,15 @@ namespace sp = std::placeholders; # include #endif -FC_LOG_LEVEL_INIT("App",true,true) +FC_LOG_LEVEL_INIT("App", true, true) -//using Base::GetConsole; -using namespace Base; using namespace App; +using namespace Base; using namespace std; +using namespace boost; +using namespace boost::program_options; +using Base::FileInfo; +namespace sp = std::placeholders; //========================================================================== // Application @@ -162,7 +159,7 @@ ParameterManager *App::Application::_pcUserParamMngr; Base::ConsoleObserverStd *Application::_pConsoleObserverStd = nullptr; Base::ConsoleObserverFile *Application::_pConsoleObserverFile = nullptr; -AppExport std::map Application::mConfig; +AppExport std::map Application::mConfig; // Custom Python exception types BaseExport extern PyObject* Base::PyExc_FC_GeneralError; @@ -190,7 +187,11 @@ PyDoc_STRVAR(FreeCAD_doc, ); PyDoc_STRVAR(Console_doc, - "FreeCAD Console\n" + "FreeCAD Console module.\n\n" + "The Console module contains functions to manage log entries, messages,\n" + "warnings and errors.\n" + "There are also functions to get/set the status of the observers used as\n" + "logging interfaces." ); PyDoc_STRVAR(Base_doc, @@ -213,7 +214,7 @@ init_freecad_base_module(void) } // Set in inside Application -static PyMethodDef* __AppMethods = nullptr; +static PyMethodDef* ApplicationMethods = nullptr; PyMODINIT_FUNC init_freecad_module(void) @@ -221,7 +222,7 @@ init_freecad_module(void) static struct PyModuleDef FreeCADModuleDef = { PyModuleDef_HEAD_INIT, "FreeCAD", FreeCAD_doc, -1, - __AppMethods, + ApplicationMethods, nullptr, nullptr, nullptr, nullptr }; return PyModule_Create(&FreeCADModuleDef); @@ -239,9 +240,7 @@ Application::Application(std::map &mConfig) setupPythonTypes(); } -Application::~Application() -{ -} +Application::~Application() = default; void Application::setupPythonTypes() { @@ -249,7 +248,7 @@ void Application::setupPythonTypes() Base::PyGILStateLocker lock; PyObject* modules = PyImport_GetModuleDict(); - __AppMethods = Application::Methods; + ApplicationMethods = Application::Methods; PyObject* pAppModule = PyImport_ImportModule ("FreeCAD"); if (!pAppModule) { PyErr_Clear(); @@ -261,7 +260,7 @@ void Application::setupPythonTypes() static struct PyModuleDef ConsoleModuleDef = { PyModuleDef_HEAD_INIT, "__FreeCADConsole__", Console_doc, -1, - ConsoleSingleton::Methods, + Base::ConsoleSingleton::Methods, nullptr, nullptr, nullptr, nullptr }; PyObject* pConsoleModule = PyModule_Create(&ConsoleModuleDef); @@ -301,6 +300,7 @@ void Application::setupPythonTypes() Base::Interpreter().addType(&Base::AxisPy ::Type,pBaseModule,"Axis"); Base::Interpreter().addType(&Base::CoordinateSystemPy::Type,pBaseModule,"CoordinateSystem"); Base::Interpreter().addType(&Base::TypePy ::Type,pBaseModule,"TypeId"); + Base::Interpreter().addType(&Base::PrecisionPy ::Type,pBaseModule,"Precision"); Base::Interpreter().addType(&App::MaterialPy::Type, pAppModule, "Material"); Base::Interpreter().addType(&App::MetadataPy::Type, pAppModule, "Metadata"); @@ -412,25 +412,9 @@ void Application::setupPythonException(PyObject* module) /// get called by the document when the name is changing void Application::renameDocument(const char *OldName, const char *NewName) { -#if 1 (void)OldName; (void)NewName; throw Base::RuntimeError("Renaming document internal name is no longer allowed!"); -#else - std::map::iterator pos; - pos = DocMap.find(OldName); - - if (pos != DocMap.end()) { - Document* temp; - temp = pos->second; - DocMap.erase(pos); - DocMap[NewName] = temp; - signalRenameDocument(*temp); - } - else { - throw Base::RuntimeError("Application::renameDocument(): no document with this name to rename!"); - } -#endif } Document* Application::newDocument(const char * Name, const char * UserName, bool createView, bool tempDoc) @@ -457,7 +441,7 @@ Document* Application::newDocument(const char * Name, const char * UserName, boo names.reserve(DocMap.size()); std::map::const_iterator pos; for (pos = DocMap.begin();pos != DocMap.end();++pos) { - names.push_back(pos->second->Label.getValue()); + names.emplace_back(pos->second->Label.getValue()); } if (!names.empty()) @@ -544,7 +528,7 @@ bool Application::closeDocument(const char* name) return true; } -void Application::closeAllDocuments(void) +void Application::closeAllDocuments() { Base::FlagToggler flag(_isClosingAll); std::map::iterator pos; @@ -617,9 +601,9 @@ int Application::addPendingDocument(const char *FileName, const char *objName, b if(!_docReloadAttempts[FileName].emplace(objName).second) return -1; auto ret = _pendingDocMap.emplace(FileName,std::vector()); - ret.first->second.push_back(objName); + ret.first->second.emplace_back(objName); if(ret.second) { - _pendingDocs.push_back(ret.first->first.c_str()); + _pendingDocs.emplace_back(ret.first->first.c_str()); return 1; } return -1; @@ -668,7 +652,7 @@ public: Document* Application::openDocument(const char * FileName, bool createView) { std::vector filenames(1,FileName); auto docs = openDocuments(filenames, nullptr, nullptr, nullptr, createView); - if(docs.size()) + if(!docs.empty()) return docs.front(); return nullptr; } @@ -679,7 +663,7 @@ Document *Application::getDocumentByPath(const char *path, PathMatchMode checkCa if(DocFileMap.empty()) { for(const auto &v : DocMap) { const auto &file = v.second->FileName.getStrValue(); - if(file.size()) + if(!file.empty()) DocFileMap[FileInfo(file.c_str()).filePath()] = v.second; } } @@ -733,7 +717,7 @@ std::vector Application::openDocuments(const std::vector _allowPartial = !hGrp->GetBool("NoPartialLoading",false); for (auto &name : filenames) - _pendingDocs.push_back(name.c_str()); + _pendingDocs.emplace_back(name.c_str()); std::map timings; @@ -794,7 +778,7 @@ std::vector Application::openDocuments(const std::vector if (errs && isMainDoc) (*errs)[count] = e.what(); else - 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) @@ -802,7 +786,7 @@ std::vector Application::openDocuments(const std::vector if (errs && isMainDoc) (*errs)[count] = e.what(); else - 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) { @@ -869,7 +853,7 @@ std::vector Application::openDocuments(const std::vector FC_TIME_INIT(t1); // Finalize document restoring with the correct order if(doc->afterRestore(true)) { - openedDocs.push_back(doc); + openedDocs.emplace_back(doc); it = docs.erase(it); } else { ++it; @@ -880,7 +864,7 @@ std::vector Application::openDocuments(const std::vector // 'touched' object requires recomputation. And an object may // become touched during restoring if externally linked // document time stamp mismatches with the stamp saved. - _pendingDocs.push_back(doc->FileName.getValue()); + _pendingDocs.emplace_back(doc->FileName.getValue()); _pendingDocMap.erase(doc->FileName.getValue()); } FC_DURATION_PLUS(timing.d2,t1); @@ -953,7 +937,7 @@ Document* Application::openDocumentPrivate(const char * FileName, // close and reopen the document immediately here, but // add it to _pendingDocsReopen to delay reloading. for(auto obj : doc->getObjects()) - objNames.push_back(obj->getNameInDocument()); + objNames.emplace_back(obj->getNameInDocument()); _pendingDocMap[doc->FileName.getValue()] = std::move(objNames); break; } @@ -993,7 +977,7 @@ Document* Application::openDocumentPrivate(const char * FileName, try { // read the document newDoc->restore(File.filePath().c_str(),true,objNames); - if(DocFileMap.size()) + if(!DocFileMap.empty()) DocFileMap[FileInfo(newDoc->FileName.getValue()).filePath()] = newDoc; return newDoc; } @@ -1014,7 +998,7 @@ Document* Application::openDocumentPrivate(const char * FileName, } } -Document* Application::getActiveDocument(void) const +Document* Application::getActiveDocument() const { return _pActiveDoc; } @@ -1213,12 +1197,12 @@ bool Application::hasLinksTo(const DocumentObject *obj) const { return !getLinksTo(obj,0,1).empty(); } -ParameterManager & Application::GetSystemParameter(void) +ParameterManager & Application::GetSystemParameter() { return *_pcSysParamMngr; } -ParameterManager & Application::GetUserParameter(void) +ParameterManager & Application::GetUserParameter() { return *_pcUserParamMngr; } @@ -1232,7 +1216,7 @@ ParameterManager * Application::GetParameterSet(const char* sName) const return nullptr; } -const std::map & Application::GetParameterSetList(void) const +const std::map & Application::GetParameterSetList() const { return mpcPramManager; } @@ -1359,7 +1343,7 @@ std::vector Application::getImportTypes(const char* Module) const return types; } -std::vector Application::getImportTypes(void) const +std::vector Application::getImportTypes() const { std::vector types; for (std::vector::const_iterator it = _mImportTypes.begin(); it != _mImportTypes.end(); ++it) { @@ -1390,7 +1374,7 @@ std::map Application::getImportFilters(const char* Typ return moduleFilter; } -std::map Application::getImportFilters(void) const +std::map Application::getImportFilters() const { std::map filter; for (std::vector::const_iterator it = _mImportTypes.begin(); it != _mImportTypes.end(); ++it) { @@ -1482,7 +1466,7 @@ std::vector Application::getExportTypes(const char* Module) const return types; } -std::vector Application::getExportTypes(void) const +std::vector Application::getExportTypes() const { std::vector types; for (std::vector::const_iterator it = _mExportTypes.begin(); it != _mExportTypes.end(); ++it) { @@ -1513,7 +1497,7 @@ std::map Application::getExportFilters(const char* Typ return moduleFilter; } -std::map Application::getExportFilters(void) const +std::map Application::getExportFilters() const { std::map filter; for (std::vector::const_iterator it = _mExportTypes.begin(); it != _mExportTypes.end(); ++it) { @@ -1649,25 +1633,25 @@ void Application::cleanupUnits() } } -void Application::destruct(void) +void Application::destruct() { // saving system parameter - Console().Log("Saving system parameter...\n"); + Base::Console().Log("Saving system parameter...\n"); _pcSysParamMngr->SaveDocument(); // saving the User parameter - Console().Log("Saving system parameter...done\n"); - Console().Log("Saving user parameter...\n"); + Base::Console().Log("Saving system parameter...done\n"); + Base::Console().Log("Saving user parameter...\n"); _pcUserParamMngr->SaveDocument(); - Console().Log("Saving user parameter...done\n"); + Base::Console().Log("Saving user parameter...done\n"); // now save all other parameter files std::map& paramMgr = _pcSingleton->mpcPramManager; for (std::map::iterator it = paramMgr.begin(); it != paramMgr.end(); ++it) { if ((it->second != _pcSysParamMngr) && (it->second != _pcUserParamMngr)) { if (it->second->HasSerializer()) { - Console().Log("Saving %s...\n", it->first.c_str()); + Base::Console().Log("Saving %s...\n", it->first.c_str()); it->second->SaveDocument(); - Console().Log("Saving %s...done\n", it->first.c_str()); + Base::Console().Log("Saving %s...done\n", it->first.c_str()); } } @@ -1693,21 +1677,21 @@ void Application::destruct(void) Base::Interpreter().finalize(); - ScriptFactorySingleton::Destruct(); - InterpreterSingleton::Destruct(); + Base::ScriptFactorySingleton::Destruct(); + Base::InterpreterSingleton::Destruct(); Base::Type::destruct(); ParameterManager::Terminate(); } -void Application::destructObserver(void) +void Application::destructObserver() { if ( _pConsoleObserverFile ) { - Console().DetachObserver(_pConsoleObserverFile); + Base::Console().DetachObserver(_pConsoleObserverFile); delete _pConsoleObserverFile; _pConsoleObserverFile = nullptr; } if ( _pConsoleObserverStd ) { - Console().DetachObserver(_pConsoleObserverStd); + Base::Console().DetachObserver(_pConsoleObserverStd); delete _pConsoleObserverStd; _pConsoleObserverStd = nullptr; } @@ -1905,185 +1889,193 @@ void Application::initTypes() Data::Segment ::init(); // Properties - App ::Property ::init(); - App ::PropertyContainer ::init(); - App ::PropertyLists ::init(); - App ::PropertyBool ::init(); - App ::PropertyBoolList ::init(); - App ::PropertyFloat ::init(); - App ::PropertyFloatList ::init(); - App ::PropertyFloatConstraint ::init(); - App ::PropertyPrecision ::init(); - App ::PropertyQuantity ::init(); - App ::PropertyQuantityConstraint::init(); - App ::PropertyAngle ::init(); - App ::PropertyDistance ::init(); - App ::PropertyLength ::init(); - App ::PropertyArea ::init(); - App ::PropertyVolume ::init(); - App ::PropertyFrequency ::init(); - App ::PropertySpeed ::init(); - App ::PropertyAcceleration ::init(); - App ::PropertyForce ::init(); - App ::PropertyPressure ::init(); - App ::PropertyElectricPotential ::init(); - App ::PropertyVacuumPermittivity::init(); - App ::PropertyInteger ::init(); - App ::PropertyIntegerConstraint ::init(); - App ::PropertyPercent ::init(); - App ::PropertyEnumeration ::init(); - App ::PropertyIntegerList ::init(); - App ::PropertyIntegerSet ::init(); - App ::PropertyMap ::init(); - App ::PropertyString ::init(); - App ::PropertyPersistentObject ::init(); - App ::PropertyUUID ::init(); - App ::PropertyFont ::init(); - App ::PropertyStringList ::init(); - App ::PropertyLinkBase ::init(); - App ::PropertyLinkListBase ::init(); - App ::PropertyLink ::init(); - App ::PropertyLinkChild ::init(); - App ::PropertyLinkGlobal ::init(); - App ::PropertyLinkHidden ::init(); - App ::PropertyLinkSub ::init(); - App ::PropertyLinkSubChild ::init(); - App ::PropertyLinkSubGlobal ::init(); - App ::PropertyLinkSubHidden ::init(); - App ::PropertyLinkList ::init(); - App ::PropertyLinkListChild ::init(); - App ::PropertyLinkListGlobal ::init(); - App ::PropertyLinkListHidden ::init(); - App ::PropertyLinkSubList ::init(); - App ::PropertyLinkSubListChild ::init(); - App ::PropertyLinkSubListGlobal ::init(); - App ::PropertyLinkSubListHidden ::init(); - App ::PropertyXLink ::init(); - App ::PropertyXLinkSub ::init(); - App ::PropertyXLinkSubList ::init(); - App ::PropertyXLinkList ::init(); - App ::PropertyXLinkContainer ::init(); - App ::PropertyMatrix ::init(); - App ::PropertyVector ::init(); - App ::PropertyVectorDistance ::init(); - App ::PropertyPosition ::init(); - App ::PropertyDirection ::init(); - App ::PropertyVectorList ::init(); - App ::PropertyPlacement ::init(); - App ::PropertyPlacementList ::init(); - App ::PropertyPlacementLink ::init(); - App ::PropertyRotation ::init(); - App ::PropertyGeometry ::init(); - App ::PropertyComplexGeoData ::init(); - App ::PropertyColor ::init(); - App ::PropertyColorList ::init(); - App ::PropertyMaterial ::init(); - App ::PropertyMaterialList ::init(); - App ::PropertyPath ::init(); - App ::PropertyFile ::init(); - App ::PropertyFileIncluded ::init(); - App ::PropertyPythonObject ::init(); - App ::PropertyExpressionContainer ::init(); - App ::PropertyExpressionEngine ::init(); + // Note: the order matters + App::Property ::init(); + App::PropertyContainer ::init(); + App::PropertyLists ::init(); + App::PropertyBool ::init(); + App::PropertyBoolList ::init(); + App::PropertyFloat ::init(); + App::PropertyFloatList ::init(); + App::PropertyFloatConstraint ::init(); + App::PropertyPrecision ::init(); + App::PropertyQuantity ::init(); + App::PropertyQuantityConstraint ::init(); + App::PropertyAngle ::init(); + App::PropertyDistance ::init(); + App::PropertyLength ::init(); + App::PropertyArea ::init(); + App::PropertyVolume ::init(); + App::PropertyFrequency ::init(); + App::PropertySpeed ::init(); + App::PropertyAcceleration ::init(); + App::PropertyForce ::init(); + App::PropertyPressure ::init(); + App::PropertyElectricPotential ::init(); + App::PropertyVacuumPermittivity ::init(); + App::PropertyInteger ::init(); + App::PropertyIntegerConstraint ::init(); + App::PropertyPercent ::init(); + App::PropertyEnumeration ::init(); + App::PropertyIntegerList ::init(); + App::PropertyIntegerSet ::init(); + App::PropertyMap ::init(); + App::PropertyString ::init(); + App::PropertyPersistentObject ::init(); + App::PropertyUUID ::init(); + App::PropertyFont ::init(); + App::PropertyStringList ::init(); + App::PropertyLinkBase ::init(); + App::PropertyLinkListBase ::init(); + App::PropertyLink ::init(); + App::PropertyLinkChild ::init(); + App::PropertyLinkGlobal ::init(); + App::PropertyLinkHidden ::init(); + App::PropertyLinkSub ::init(); + App::PropertyLinkSubChild ::init(); + App::PropertyLinkSubGlobal ::init(); + App::PropertyLinkSubHidden ::init(); + App::PropertyLinkList ::init(); + App::PropertyLinkListChild ::init(); + App::PropertyLinkListGlobal ::init(); + App::PropertyLinkListHidden ::init(); + App::PropertyLinkSubList ::init(); + App::PropertyLinkSubListChild ::init(); + App::PropertyLinkSubListGlobal ::init(); + App::PropertyLinkSubListHidden ::init(); + App::PropertyXLink ::init(); + App::PropertyXLinkSub ::init(); + App::PropertyXLinkSubList ::init(); + App::PropertyXLinkList ::init(); + App::PropertyXLinkContainer ::init(); + App::PropertyMatrix ::init(); + App::PropertyVector ::init(); + App::PropertyVectorDistance ::init(); + App::PropertyPosition ::init(); + App::PropertyDirection ::init(); + App::PropertyVectorList ::init(); + App::PropertyPlacement ::init(); + App::PropertyPlacementList ::init(); + App::PropertyPlacementLink ::init(); + App::PropertyRotation ::init(); + App::PropertyGeometry ::init(); + App::PropertyComplexGeoData ::init(); + App::PropertyColor ::init(); + App::PropertyColorList ::init(); + App::PropertyMaterial ::init(); + App::PropertyMaterialList ::init(); + App::PropertyPath ::init(); + App::PropertyFile ::init(); + App::PropertyFileIncluded ::init(); + App::PropertyPythonObject ::init(); + App::PropertyExpressionContainer::init(); + App::PropertyExpressionEngine ::init(); // Extension classes - App ::Extension ::init(); - App ::ExtensionContainer ::init(); - App ::DocumentObjectExtension ::init(); - App ::GroupExtension ::init(); - App ::GroupExtensionPython ::init(); - App ::GeoFeatureGroupExtension ::init(); - App ::GeoFeatureGroupExtensionPython::init(); - App ::OriginGroupExtension ::init(); - App ::OriginGroupExtensionPython ::init(); - App ::LinkBaseExtension ::init(); - App ::LinkBaseExtensionPython ::init(); - App ::LinkExtension ::init(); - App ::LinkExtensionPython ::init(); + App::Extension ::init(); + App::ExtensionContainer ::init(); + App::DocumentObjectExtension ::init(); + App::GroupExtension ::init(); + App::GroupExtensionPython ::init(); + App::GeoFeatureGroupExtension ::init(); + App::GeoFeatureGroupExtensionPython::init(); + App::OriginGroupExtension ::init(); + App::OriginGroupExtensionPython ::init(); + App::LinkBaseExtension ::init(); + App::LinkBaseExtensionPython ::init(); + App::LinkExtension ::init(); + App::LinkExtensionPython ::init(); // Document classes - App ::TransactionalObject ::init(); - App ::DocumentObject ::init(); - App ::GeoFeature ::init(); - App ::FeatureTest ::init(); - App ::FeatureTestException ::init(); - App ::FeaturePython ::init(); - App ::GeometryPython ::init(); - App ::Document ::init(); - App ::DocumentObjectGroup ::init(); - App ::DocumentObjectGroupPython ::init(); - App ::DocumentObjectFileIncluded::init(); - App ::InventorObject ::init(); - App ::VRMLObject ::init(); - App ::Annotation ::init(); - App ::AnnotationLabel ::init(); - App ::MeasureDistance ::init(); - App ::MaterialObject ::init(); - App ::MaterialObjectPython ::init(); - App ::TextDocument ::init(); - App ::Placement ::init(); - App ::PlacementPython ::init(); - App ::OriginFeature ::init(); - App ::Plane ::init(); - App ::Line ::init(); - App ::Part ::init(); - App ::Origin ::init(); - App ::Link ::init(); - App ::LinkPython ::init(); - App ::LinkElement ::init(); - App ::LinkElementPython ::init(); - App ::LinkGroup ::init(); - App ::LinkGroupPython ::init(); + App::TransactionalObject ::init(); + App::DocumentObject ::init(); + App::GeoFeature ::init(); + + // Test features + App::FeatureTest ::init(); + App::FeatureTestException ::init(); + App::FeatureTestColumn ::init(); + App::FeatureTestPlacement ::init(); + App::FeatureTestAttribute ::init(); + + // Feature class + App::FeaturePython ::init(); + App::GeometryPython ::init(); + App::Document ::init(); + App::DocumentObjectGroup ::init(); + App::DocumentObjectGroupPython ::init(); + App::DocumentObjectFileIncluded::init(); + App::InventorObject ::init(); + App::VRMLObject ::init(); + App::Annotation ::init(); + App::AnnotationLabel ::init(); + App::MeasureDistance ::init(); + App ::MaterialObject ::init(); + App::MaterialObjectPython ::init(); + App::TextDocument ::init(); + App::Placement ::init(); + App::PlacementPython ::init(); + App::OriginFeature ::init(); + App::Plane ::init(); + App::Line ::init(); + App::Part ::init(); + App::Origin ::init(); + App::Link ::init(); + App::LinkPython ::init(); + App::LinkElement ::init(); + App::LinkElementPython ::init(); + App::LinkGroup ::init(); + App::LinkGroupPython ::init(); // Expression classes - App ::Expression ::init(); - App ::UnitExpression ::init(); - App ::NumberExpression ::init(); - App ::ConstantExpression ::init(); - App ::OperatorExpression ::init(); - App ::VariableExpression ::init(); - App ::ConditionalExpression ::init(); - App ::StringExpression ::init(); - App ::FunctionExpression ::init(); - App ::RangeExpression ::init(); - App ::PyObjectExpression ::init(); + App::Expression ::init(); + App::UnitExpression ::init(); + App::NumberExpression ::init(); + App::ConstantExpression ::init(); + App::OperatorExpression ::init(); + App::VariableExpression ::init(); + App::ConditionalExpression ::init(); + App::StringExpression ::init(); + App::FunctionExpression ::init(); + App::RangeExpression ::init(); + App::PyObjectExpression ::init(); // register transaction type new App::TransactionProducer (DocumentObject::getClassTypeId()); // register exception producer types - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; - new ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; + new Base::ExceptionProducer; } namespace { @@ -2219,7 +2211,7 @@ void parseProgramOptions(int ac, char ** av, const string& exe, variables_map& v args.back() += av[i]; } else { - args.push_back(av[i]); + args.emplace_back(av[i]); } if (strcmp(av[i],"-style") == 0) { merge = true; @@ -2261,12 +2253,12 @@ void parseProgramOptions(int ac, char ** av, const string& exe, variables_map& v catch (const std::exception& e) { std::stringstream str; str << e.what() << endl << endl << visible << endl; - throw UnknownProgramOption(str.str()); + throw Base::UnknownProgramOption(str.str()); } catch (...) { std::stringstream str; str << "Wrong or unknown option, bailing out!" << endl << endl << visible << endl; - throw UnknownProgramOption(str.str()); + throw Base::UnknownProgramOption(str.str()); } if (vm.count("help")) { @@ -2489,7 +2481,7 @@ void Application::initConfig(int argc, char ** argv) // init python PyImport_AppendInittab ("FreeCAD", init_freecad_module); PyImport_AppendInittab ("__FreeCADBase__", init_freecad_base_module); - const char* pythonpath = Interpreter().init(argc,argv); + const char* pythonpath = Base::Interpreter().init(argc,argv); if (pythonpath) mConfig["PythonSearchPath"] = pythonpath; else @@ -2500,8 +2492,8 @@ void Application::initConfig(int argc, char ** argv) // Init console =========================================================== Base::PyGILStateLocker lock; - _pConsoleObserverStd = new ConsoleObserverStd(); - Console().AttachObserver(_pConsoleObserverStd); + _pConsoleObserverStd = new Base::ConsoleObserverStd(); + Base::Console().AttachObserver(_pConsoleObserverStd); if (mConfig["LoggingConsole"] != "1") { _pConsoleObserverStd->bMsg = false; _pConsoleObserverStd->bLog = false; @@ -2509,12 +2501,12 @@ void Application::initConfig(int argc, char ** argv) _pConsoleObserverStd->bErr = false; } if (mConfig["Verbose"] == "Strict") - Console().UnsetConsoleMode(ConsoleSingleton::Verbose); + Base::Console().UnsetConsoleMode(Base::ConsoleSingleton::Verbose); // file logging Init =========================================================== if (mConfig["LoggingFile"] == "1") { - _pConsoleObserverFile = new ConsoleObserverFile(mConfig["LoggingFileName"].c_str()); - Console().AttachObserver(_pConsoleObserverFile); + _pConsoleObserverFile = new Base::ConsoleObserverFile(mConfig["LoggingFileName"].c_str()); + Base::Console().AttachObserver(_pConsoleObserverFile); } else _pConsoleObserverFile = nullptr; @@ -2524,14 +2516,14 @@ void Application::initConfig(int argc, char ** argv) // Remove banner if FreeCAD is invoked via the -c command as regular // Python interpreter if (!(mConfig["Verbose"] == "Strict")) - Console().Message("%s %s, Libs: %s.%sR%s\n%s",mConfig["ExeName"].c_str(), + Base::Console().Message("%s %s, Libs: %s.%sR%s\n%s",mConfig["ExeName"].c_str(), mConfig["ExeVersion"].c_str(), mConfig["BuildVersionMajor"].c_str(), mConfig["BuildVersionMinor"].c_str(), mConfig["BuildRevision"].c_str(), mConfig["CopyrightInfo"].c_str()); else - Console().Message("%s %s, Libs: %s.%sB%s\n",mConfig["ExeName"].c_str(), + Base::Console().Message("%s %s, Libs: %s.%sB%s\n",mConfig["ExeName"].c_str(), mConfig["ExeVersion"].c_str(), mConfig["BuildVersionMajor"].c_str(), mConfig["BuildVersionMinor"].c_str(), @@ -2625,23 +2617,24 @@ void Application::SaveEnv(const char* s) mConfig[s] = c; } -void Application::initApplication(void) +void Application::initApplication() { // interpreter and Init script ========================================================== // register scripts - new ScriptProducer( "CMakeVariables", CMakeVariables ); - new ScriptProducer( "FreeCADInit", FreeCADInit ); - new ScriptProducer( "FreeCADTest", FreeCADTest ); + new Base::ScriptProducer( "CMakeVariables", CMakeVariables ); + new Base::ScriptProducer( "FreeCADInit", FreeCADInit ); + new Base::ScriptProducer( "FreeCADTest", FreeCADTest ); // creating the application - if (!(mConfig["Verbose"] == "Strict")) Console().Log("Create Application\n"); + if (!(mConfig["Verbose"] == "Strict")) + Base::Console().Log("Create Application\n"); Application::_pcSingleton = new Application(mConfig); // set up Unit system default ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Units"); - UnitsApi::setSchema((UnitSystem)hGrp->GetInt("UserSchema",0)); - UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals())); + Base::UnitsApi::setSchema((Base::UnitSystem)hGrp->GetInt("UserSchema",0)); + Base::UnitsApi::setDecimals(hGrp->GetInt("Decimals", Base::UnitsApi::getDecimals())); // In case we are using fractional inches, get user setting for min unit int denom = hGrp->GetInt("FracInch", Base::QuantityFormat::getDefaultDenominator()); @@ -2649,14 +2642,14 @@ void Application::initApplication(void) #if defined (_DEBUG) - Console().Log("Application is built with debug information\n"); + Base::Console().Log("Application is built with debug information\n"); #endif // starting the init script - Console().Log("Run App init script\n"); + Base::Console().Log("Run App init script\n"); try { - Interpreter().runString(Base::ScriptFactory().ProduceScript("CMakeVariables")); - Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADInit")); + Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("CMakeVariables")); + Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADInit")); } catch (const Base::Exception& e) { e.ReportException(); @@ -2712,7 +2705,7 @@ std::list Application::processFiles(const std::list& f Base::Interpreter().loadModule(file.fileNamePure().c_str()); processed.push_back(*it); } - catch (const PyException&) { + catch (const Base::PyException&) { // if loading the module does not work, try just running the script (run in __main__) Base::Interpreter().runFile(file.filePath().c_str(),true); processed.push_back(*it); @@ -2733,7 +2726,7 @@ std::list Application::processFiles(const std::list& f Base::Console().Log("Command line open: %s.open(u\"%s\")\n",mods.front().c_str(),escapedstr.c_str()); } else if (file.exists()) { - 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()); } } } @@ -2741,17 +2734,17 @@ std::list Application::processFiles(const std::list& f throw; // re-throw to main() function } catch (const Base::Exception& e) { - 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 (...) { - 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()); } } return processed; // successfully processed files } -void Application::processCmdLineFiles(void) +void Application::processCmdLineFiles() { // process files passed to command line std::list files = getCmdLineFiles(); @@ -2766,7 +2759,7 @@ void Application::processCmdLineFiles(void) // then execute it. This is to behave like the standard Python executable. Base::FileInfo file(files.front()); if (!file.exists()) { - Interpreter().runString(files.front().c_str()); + Base::Interpreter().runString(files.front().c_str()); mConfig["RunMode"] = "Exit"; } } @@ -2788,14 +2781,14 @@ void Application::processCmdLineFiles(void) ,mods.front().c_str(),output.c_str()); } else { - 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) { - 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 (...) { - 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()); } } } @@ -2807,19 +2800,19 @@ void Application::runApplication() if (mConfig["RunMode"] == "Cmd") { // Run the commandline interface - Interpreter().runCommandLine("FreeCAD Console mode"); + Base::Interpreter().runCommandLine("FreeCAD Console mode"); } else if (mConfig["RunMode"] == "Internal") { // run internal script - Console().Log("Running internal script:\n"); - Interpreter().runString(Base::ScriptFactory().ProduceScript(mConfig["ScriptFileName"].c_str())); + Base::Console().Log("Running internal script:\n"); + Base::Interpreter().runString(Base::ScriptFactory().ProduceScript(mConfig["ScriptFileName"].c_str())); } else if (mConfig["RunMode"] == "Exit") { // getting out - Console().Log("Exiting on purpose\n"); + Base::Console().Log("Exiting on purpose\n"); } else { - 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()); } } @@ -2827,14 +2820,14 @@ void Application::logStatus() { std::string time_str = boost::posix_time::to_simple_string( boost::posix_time::second_clock::local_time()); - Console().Log("Time = %s\n", time_str.c_str()); + Base::Console().Log("Time = %s\n", time_str.c_str()); for (std::map::iterator It = mConfig.begin();It!= mConfig.end();++It) { - 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()); } } -void Application::LoadParameters(void) +void Application::LoadParameters() { // Init parameter sets =========================================================== // @@ -2854,10 +2847,10 @@ void Application::LoadParameters(void) if (_pcSysParamMngr->LoadOrCreateDocument() && !(mConfig["Verbose"] == "Strict")) { // Configuration file optional when using as Python module if (!Py_IsInitialized()) { - Console().Warning(" Parameter does not exist, writing initial one\n"); - 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"); + 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"); } } } @@ -2888,10 +2881,10 @@ void Application::LoadParameters(void) // Configuration file optional when using as Python module if (!Py_IsInitialized()) { - Console().Warning(" User settings do not exist, writing initial one\n"); - 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"); + 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"); } } } diff --git a/src/App/Application.h b/src/App/Application.h index 6b86d9b843..0148a064d5 100644 --- a/src/App/Application.h +++ b/src/App/Application.h @@ -119,7 +119,7 @@ public: std::vector *errs=nullptr, bool createView = true); /// Retrieve the active document - App::Document* getActiveDocument(void) const; + App::Document* getActiveDocument() const; /// Retrieve a named document App::Document* getDocument(const char *Name) const; @@ -157,7 +157,7 @@ public: void setActiveDocument(App::Document* pDoc); void setActiveDocument(const char *Name); /// close all documents (without saving) - void closeAllDocuments(void); + void closeAllDocuments(); /// Add pending document to open together with the current opening document int addPendingDocument(const char *FileName, const char *objName, bool allowPartial); /// Indicate whether the application is opening (restoring) some document @@ -311,9 +311,9 @@ public: /** @name methods for parameter handling */ //@{ /// returns the system parameter - ParameterManager & GetSystemParameter(void) ; + ParameterManager & GetSystemParameter(); /// returns the user parameter - ParameterManager & GetUserParameter(void) ; + ParameterManager & GetUserParameter(); /** Gets a parameter group by a full qualified path * It's an easy method to get a group: * \code @@ -326,7 +326,7 @@ public: Base::Reference GetParameterGroupByPath(const char* sName); ParameterManager * GetParameterSet(const char* sName) const; - const std::map & GetParameterSetList(void) const; + const std::map & GetParameterSetList() const; void AddParameterSet(const char* sName); void RemoveParameterSet(const char* sName); //@} @@ -354,11 +354,11 @@ public: /// Return a list of filetypes that are supported by a module. std::vector getImportTypes(const char* Module) const; /// Return a list of all filetypes. - std::vector getImportTypes(void) const; + std::vector getImportTypes() const; /// Return the import filters with modules of a given filetype. std::map getImportFilters(const char* Type) const; /// Return a list of all import filters. - std::map getImportFilters(void) const; + std::map getImportFilters() const; //@} //@{ /// Register an export filetype and a module name @@ -372,27 +372,27 @@ public: /// Return a list of filetypes that are supported by a module. std::vector getExportTypes(const char* Module) const; /// Return a list of all filetypes. - std::vector getExportTypes(void) const; + std::vector getExportTypes() const; /// Return the export filters with modules of a given filetype. std::map getExportFilters(const char* Type) const; /// Return a list of all export filters. - std::map getExportFilters(void) const; + std::map getExportFilters() const; //@} /** @name Init, Destruct an Access methods */ //@{ static void init(int argc, char ** argv); - static void initTypes(void); - static void destruct(void); - static void destructObserver(void); - static void processCmdLineFiles(void); + static void initTypes(); + static void destruct(); + static void destructObserver(); + static void processCmdLineFiles(); static std::list getCmdLineFiles(); static std::list processFiles(const std::list&); - static void runApplication(void); - friend Application &GetApplication(void); - static std::map &Config(void){return mConfig;} - static int GetARGC(void){return _argc;} - static char** GetARGV(void){return _argv;} + static void runApplication(); + friend Application &GetApplication(); + static std::map &Config(){return mConfig;} + static int GetARGC(){return _argc;} + static char** GetARGV(){return _argv;} //@} /** @name Application directories */ @@ -480,7 +480,7 @@ protected: /// Helper class for App::Document to signal on close/abort transaction class AppExport TransactionSignaller { public: - TransactionSignaller(bool abort,bool signal); + TransactionSignaller(bool abort, bool signal); ~TransactionSignaller(); private: bool abort; @@ -488,7 +488,7 @@ protected: private: /// Constructor - Application(std::map &mConfig); + explicit Application(std::map &mConfig); /// Destructor virtual ~Application(); @@ -507,27 +507,27 @@ private: static void setupPythonException(PyObject*); // static python wrapper of the exported functions - static PyObject* sGetParam (PyObject *self,PyObject *args); - static PyObject* sSaveParameter (PyObject *self,PyObject *args); - static PyObject* sGetVersion (PyObject *self,PyObject *args); - static PyObject* sGetConfig (PyObject *self,PyObject *args); - static PyObject* sSetConfig (PyObject *self,PyObject *args); - static PyObject* sDumpConfig (PyObject *self,PyObject *args); - static PyObject* sAddImportType (PyObject *self,PyObject *args); - static PyObject* sChangeImportModule(PyObject *self,PyObject *args); - static PyObject* sGetImportType (PyObject *self,PyObject *args); - static PyObject* sAddExportType (PyObject *self,PyObject *args); - static PyObject* sChangeExportModule(PyObject *self,PyObject *args); - static PyObject* sGetExportType (PyObject *self,PyObject *args); - static PyObject* sGetResourcePath (PyObject *self,PyObject *args); - static PyObject* sGetLibraryPath (PyObject *self,PyObject *args); - static PyObject* sGetTempPath (PyObject *self,PyObject *args); - static PyObject* sGetUserCachePath (PyObject *self,PyObject *args); - static PyObject* sGetUserConfigPath (PyObject *self,PyObject *args); - static PyObject* sGetUserAppDataPath(PyObject *self,PyObject *args); - static PyObject* sGetUserMacroPath (PyObject *self,PyObject *args); - static PyObject* sGetHelpPath (PyObject *self,PyObject *args); - static PyObject* sGetHomePath (PyObject *self,PyObject *args); + static PyObject* sGetParam (PyObject *self, PyObject *args); + static PyObject* sSaveParameter (PyObject *self, PyObject *args); + static PyObject* sGetVersion (PyObject *self, PyObject *args); + static PyObject* sGetConfig (PyObject *self, PyObject *args); + static PyObject* sSetConfig (PyObject *self, PyObject *args); + static PyObject* sDumpConfig (PyObject *self, PyObject *args); + static PyObject* sAddImportType (PyObject *self, PyObject *args); + static PyObject* sChangeImportModule(PyObject *self, PyObject *args); + static PyObject* sGetImportType (PyObject *self, PyObject *args); + static PyObject* sAddExportType (PyObject *self, PyObject *args); + static PyObject* sChangeExportModule(PyObject *self, PyObject *args); + static PyObject* sGetExportType (PyObject *self, PyObject *args); + static PyObject* sGetResourcePath (PyObject *self, PyObject *args); + static PyObject* sGetLibraryPath (PyObject *self, PyObject *args); + static PyObject* sGetTempPath (PyObject *self, PyObject *args); + static PyObject* sGetUserCachePath (PyObject *self, PyObject *args); + static PyObject* sGetUserConfigPath (PyObject *self, PyObject *args); + static PyObject* sGetUserAppDataPath(PyObject *self, PyObject *args); + static PyObject* sGetUserMacroPath (PyObject *self, PyObject *args); + static PyObject* sGetHelpPath (PyObject *self, PyObject *args); + static PyObject* sGetHomePath (PyObject *self, PyObject *args); static PyObject* sLoadFile (PyObject *self,PyObject *args); static PyObject* sOpenDocument (PyObject *self,PyObject *args, PyObject *kwd); @@ -562,8 +562,8 @@ private: /** @name Private Init, Destruct an Access methods */ //@{ static void initConfig(int argc, char ** argv); - static void initApplication(void); - static void logStatus(void); + static void initApplication(); + static void logStatus(); // the one and only pointer to the application object static Application *_pcSingleton; /// checks if the environment is alright @@ -574,11 +574,11 @@ private: */ static std::string FindHomePath(const char* sCall); /// Print the help message - static void PrintInitHelp(void); + static void PrintInitHelp(); /// figure out some things static void ExtractUserPath(); /// load the user and system parameter set - static void LoadParameters(void); + static void LoadParameters(); /// puts the given env variable in the config static void SaveEnv(const char *); /// startup configuration container @@ -629,7 +629,7 @@ private: }; /// Singleton getter of the Application -inline App::Application &GetApplication(void){ +inline App::Application &GetApplication(){ return *App::Application::_pcSingleton; } diff --git a/src/App/ApplicationPy.cpp b/src/App/ApplicationPy.cpp index 83ac48a225..22b46350f9 100644 --- a/src/App/ApplicationPy.cpp +++ b/src/App/ApplicationPy.cpp @@ -45,7 +45,7 @@ using namespace App; //************************************************************************** // Python stuff -// Application Methods // Methods structure +// Application methods structure PyMethodDef Application::Methods[] = { {"ParamGet", (PyCFunction) Application::sGetParam, METH_VARARGS, "Get parameters by path"}, @@ -66,10 +66,6 @@ PyMethodDef Application::Methods[] = { "Change the import module name of a registered filetype"}, {"getImportType", (PyCFunction) Application::sGetImportType, METH_VARARGS, "Get the name of the module that can import the filetype"}, - {"EndingAdd", (PyCFunction) Application::sAddImportType, METH_VARARGS, // deprecated - "deprecated -- use addImportType"}, - {"EndingGet", (PyCFunction) Application::sGetImportType, METH_VARARGS, // deprecated - "deprecated -- use getImportType"}, {"addExportType", (PyCFunction) Application::sAddExportType, METH_VARARGS, "Register filetype for export"}, {"changeExportModule", (PyCFunction) Application::sChangeExportModule, METH_VARARGS, @@ -104,9 +100,9 @@ PyMethodDef Application::Methods[] = { "* If no module is given it will be determined by the file extension.\n" "* If more than one module can load a file the first one will be taken.\n" "* If no module exists to load the file an exception will be raised."}, - {"open", reinterpret_cast(reinterpret_cast( Application::sOpenDocument )), METH_VARARGS|METH_KEYWORDS, + {"open", reinterpret_cast(reinterpret_cast( Application::sOpenDocument )), METH_VARARGS|METH_KEYWORDS, "See openDocument(string)"}, - {"openDocument", reinterpret_cast(reinterpret_cast( Application::sOpenDocument )), METH_VARARGS|METH_KEYWORDS, + {"openDocument", reinterpret_cast(reinterpret_cast( Application::sOpenDocument )), METH_VARARGS|METH_KEYWORDS, "openDocument(filepath,hidden=False) -> object\n" "Create a document and load the project file into the document.\n\n" "filepath: file path to an existing file. If the file doesn't exist\n" @@ -116,7 +112,7 @@ PyMethodDef Application::Methods[] = { // {"saveDocument", (PyCFunction) Application::sSaveDocument, METH_VARARGS, // "saveDocument(string) -- Save the document to a file."}, // {"saveDocumentAs", (PyCFunction) Application::sSaveDocumentAs, METH_VARARGS}, - {"newDocument", reinterpret_cast(reinterpret_cast( Application::sNewDocument )), METH_VARARGS|METH_KEYWORDS, + {"newDocument", reinterpret_cast(reinterpret_cast( Application::sNewDocument )), METH_VARARGS|METH_KEYWORDS, "newDocument(name, label=None, hidden=False, temp=False) -> object\n" "Create a new document with a given name.\n\n" "name: unique document name which is checked automatically.\n" @@ -129,7 +125,7 @@ PyMethodDef Application::Methods[] = { {"activeDocument", (PyCFunction) Application::sActiveDocument, METH_VARARGS, "activeDocument() -> object or None\n\n" "Return the active document or None if there is no one."}, - {"setActiveDocument",(PyCFunction) Application::sSetActiveDocument, METH_VARARGS, + {"setActiveDocument", (PyCFunction) Application::sSetActiveDocument, METH_VARARGS, "setActiveDocement(string) -> None\n\n" "Set the active document by its name."}, {"getDocument", (PyCFunction) Application::sGetDocument, METH_VARARGS, @@ -183,13 +179,15 @@ PyMethodDef Application::Methods[] = { "There is an active sequencer during document restore and recomputation. User may\n" "abort the operation by pressing the ESC key. Once detected, this function will\n" "trigger a Base.FreeCADAbort exception."}, - {nullptr, nullptr, 0, nullptr} /* Sentinel */ + {nullptr, nullptr, 0, nullptr} /* Sentinel */ }; PyObject* Application::sLoadFile(PyObject * /*self*/, PyObject *args) { - char *path, *doc="",*mod=""; + char *path; + char *doc=""; + char *mod=""; if (!PyArg_ParseTuple(args, "s|ss", &path, &doc, &mod)) return nullptr; try { @@ -242,7 +240,7 @@ PyObject* Application::sOpenDocument(PyObject * /*self*/, PyObject *args, PyObje { char* Name; PyObject *hidden = Py_False; - static char *kwlist[] = {"name","hidden",nullptr}; + static char *kwlist[] = {"name", "hidden", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwd, "et|O!", kwlist, "utf-8", &Name, &PyBool_Type, &hidden)) return nullptr; @@ -269,7 +267,7 @@ PyObject* Application::sNewDocument(PyObject * /*self*/, PyObject *args, PyObjec char *usrName = nullptr; PyObject *hidden = Py_False; PyObject *temp = Py_False; - static char *kwlist[] = {"name","label","hidden","temp",nullptr}; + static char *kwlist[] = {"name", "label", "hidden", "temp", nullptr}; if (!PyArg_ParseTupleAndKeywords(args, kwd, "|etetO!O!", kwlist, "utf-8", &docName, "utf-8", &usrName, &PyBool_Type, &hidden, &PyBool_Type, &temp)) return nullptr; @@ -343,25 +341,7 @@ PyObject* Application::sSaveDocument(PyObject * /*self*/, PyObject *args) Py_Return; } -#if 0 -PyObject* Application::sSaveDocumentAs(PyObject * /*self*/, PyObject *args) -{ - char *pDoc, *pFileName; - if (!PyArg_ParseTuple(args, "ss", &pDoc, &pFileName)) - return nullptr; - Document* doc = GetApplication().getDocument(pDoc); - if (doc) { - doc->saveAs( pFileName ); - } - else { - PyErr_Format(PyExc_NameError, "Unknown document '%s'", pDoc); - return NULL; - } - - Py_Return; -} -#endif PyObject* Application::sActiveDocument(PyObject * /*self*/, PyObject *args) { if (!PyArg_ParseTuple(args, "")) @@ -441,7 +421,7 @@ PyObject* Application::sGetConfig(PyObject * /*self*/, PyObject *args) std::map::const_iterator it = Map.find(pstr); if (it != Map.end()) { - return Py_BuildValue("s",it->second.c_str()); + return Py_BuildValue("s", it->second.c_str()); } else { // do not set an error because this may break existing python code @@ -455,8 +435,7 @@ PyObject* Application::sDumpConfig(PyObject * /*self*/, PyObject *args) return nullptr; PyObject *dict = PyDict_New(); - for (std::map::iterator It= GetApplication()._mConfig.begin(); - It!=GetApplication()._mConfig.end();++It) { + for (auto It= GetApplication()._mConfig.begin(); It != GetApplication()._mConfig.end(); ++It) { PyDict_SetItemString(dict,It->first.c_str(), PyUnicode_FromString(It->second.c_str())); } return dict; @@ -464,9 +443,9 @@ PyObject* Application::sDumpConfig(PyObject * /*self*/, PyObject *args) PyObject* Application::sSetConfig(PyObject * /*self*/, PyObject *args) { - char *pstr,*pstr2; + char *pstr, *pstr2; - if (!PyArg_ParseTuple(args, "ss", &pstr,&pstr2)) + if (!PyArg_ParseTuple(args, "ss", &pstr, &pstr2)) return nullptr; GetApplication()._mConfig[pstr] = pstr2; @@ -843,21 +822,6 @@ PyObject *Application::sGetLogLevel(PyObject * /*self*/, PyObject *args) } // For performance reason, we only output integer value return Py_BuildValue("i",Base::Console().LogLevel(l)); - - // switch(l) { - // case FC_LOGLEVEL_LOG: - // return Py_BuildValue("s","Log"); - // case FC_LOGLEVEL_WARN: - // return Py_BuildValue("s","Warning"); - // case FC_LOGLEVEL_ERR: - // return Py_BuildValue("s","Error"); - // case FC_LOGLEVEL_MSG: - // return Py_BuildValue("s","Message"); - // case FC_LOGLEVEL_TRACE: - // return Py_BuildValue("s","Trace"); - // default: - // return Py_BuildValue("i",l); - // } } PY_CATCH; } diff --git a/src/App/ColorModel.cpp b/src/App/ColorModel.cpp index fc6cb5c78c..6af1a42ffd 100644 --- a/src/App/ColorModel.cpp +++ b/src/App/ColorModel.cpp @@ -328,9 +328,9 @@ ColorLegend::ColorLegend () colorFields.emplace_back(0, 1, 0); colorFields.emplace_back(1, 0, 0); - names.push_back("Min"); - names.push_back("Mid"); - names.push_back("Max"); + names.emplace_back("Min"); + names.emplace_back("Mid"); + names.emplace_back("Max"); values.push_back(-1.0f); values.push_back(-0.333f); @@ -451,7 +451,7 @@ bool ColorLegend::remove (std::size_t ulPos) void ColorLegend::removeFirst () { - if (colorFields.size() > 0) { + if (!colorFields.empty()) { colorFields.erase(colorFields.begin()); names.erase(names.begin()); values.erase(values.begin()); @@ -460,7 +460,7 @@ void ColorLegend::removeFirst () void ColorLegend::removeLast () { - if (colorFields.size() > 0) { + if (!colorFields.empty()) { colorFields.erase(colorFields.end()-1); names.erase(names.end()-1); values.erase(values.end()-1); diff --git a/src/App/ColorModel.h b/src/App/ColorModel.h index 98badd2271..b38a79fb4b 100644 --- a/src/App/ColorModel.h +++ b/src/App/ColorModel.h @@ -74,7 +74,7 @@ class AppExport ColorModel { public: ColorModel() = default; - ColorModel (std::size_t usCt) { + explicit ColorModel (std::size_t usCt) { colors.resize(usCt); } ColorModel(const ColorModel&) = default; @@ -442,7 +442,7 @@ class AppExport ColorLegend public: ColorLegend (); ColorLegend (const ColorLegend &rclCL); - virtual ~ColorLegend () {} + virtual ~ColorLegend () = default; ColorLegend& operator = (const ColorLegend &rclCL); bool operator == (const ColorLegend &rclCL) const; diff --git a/src/App/ComplexGeoData.cpp b/src/App/ComplexGeoData.cpp index 115458272b..151216727a 100644 --- a/src/App/ComplexGeoData.cpp +++ b/src/App/ComplexGeoData.cpp @@ -28,7 +28,7 @@ #endif #include -#include +#include #include "ComplexGeoData.h" #include @@ -49,22 +49,20 @@ ComplexGeoData::ComplexGeoData() { } -ComplexGeoData::~ComplexGeoData() -{ -} +ComplexGeoData::~ComplexGeoData() = default; Data::Segment* ComplexGeoData::getSubElementByName(const char* name) const { - int index = 0; - std::string element; - boost::regex ex("^([^0-9]*)([0-9]*)$"); - boost::cmatch what; - - if (boost::regex_match(name, what, ex)) { - element = what[1].str(); - index = std::atoi(what[2].str().c_str()); - } - + int index = 0; + std::string element; + boost::regex ex("^([^0-9]*)([0-9]*)$"); + boost::cmatch what; + + if (boost::regex_match(name, what, ex)) { + element = what[1].str(); + index = std::atoi(what[2].str().c_str()); + } + return getSubElement(element.c_str(), static_cast(index)); } @@ -175,10 +173,10 @@ const char *ComplexGeoData::isMappedElement(const char *name) { } std::string ComplexGeoData::newElementName(const char *name) { - if(!name) + if(!name) return std::string(); const char *dot = strrchr(name,'.'); - if(!dot || dot==name) + if(!dot || dot==name) return name; const char *c = dot-1; for(;c!=name;--c) { @@ -193,10 +191,10 @@ std::string ComplexGeoData::newElementName(const char *name) { } std::string ComplexGeoData::oldElementName(const char *name) { - if(!name) + if(!name) return std::string(); const char *dot = strrchr(name,'.'); - if(!dot || dot==name) + if(!dot || dot==name) return name; const char *c = dot-1; for(;c!=name;--c) { @@ -211,7 +209,7 @@ std::string ComplexGeoData::oldElementName(const char *name) { } std::string ComplexGeoData::noElementName(const char *name) { - if(!name) + if(!name) return std::string(); auto element = findElementName(name); if(element) diff --git a/src/App/ComplexGeoData.h b/src/App/ComplexGeoData.h index 81ae1e347e..6ea8a3af1b 100644 --- a/src/App/ComplexGeoData.h +++ b/src/App/ComplexGeoData.h @@ -24,6 +24,7 @@ #ifndef _AppComplexGeoData_h_ #define _AppComplexGeoData_h_ +#include #include #include #include @@ -50,10 +51,10 @@ namespace Data */ class AppExport Segment: public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~Segment(){} + ~Segment() override = default; virtual std::string getName() const=0; }; @@ -62,7 +63,7 @@ public: */ class AppExport ComplexGeoData: public Base::Persistence, public Base::Handled { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: struct Line {uint32_t I1; uint32_t I2;}; @@ -75,7 +76,7 @@ public: /// Constructor ComplexGeoData(); /// Destructor - virtual ~ComplexGeoData(); + ~ComplexGeoData() override; /** @name Subelement management */ //@{ @@ -199,14 +200,52 @@ public: protected: /// from local to outside - inline Base::Vector3d transformToOutside(const Base::Vector3f& vec) const + inline Base::Vector3d transformPointToOutside(const Base::Vector3f& vec) const { return getTransform() * Base::Vector3d(static_cast(vec.x), static_cast(vec.y), static_cast(vec.z)); } + /// from local to outside + template + inline std::vector transformPointsToOutside(const std::vector& input) const + { + std::vector output; + output.reserve(input.size()); + Base::Matrix4D mat(getTransform()); + std::transform(input.cbegin(), input.cend(), std::back_inserter(output), [&mat](const Vec& vec) { + return mat * Base::Vector3d(static_cast(vec.x), + static_cast(vec.y), + static_cast(vec.z)); + }); + + return output; + } + inline Base::Vector3d transformVectorToOutside(const Base::Vector3f& vec) const + { + Base::Matrix4D mat(getTransform()); + mat.setCol(3, Base::Vector3d()); + return mat * Base::Vector3d(static_cast(vec.x), + static_cast(vec.y), + static_cast(vec.z)); + } + template + std::vector transformVectorsToOutside(const std::vector& input) const + { + std::vector output; + output.reserve(input.size()); + Base::Matrix4D mat(getTransform()); + mat.setCol(3, Base::Vector3d()); + std::transform(input.cbegin(), input.cend(), std::back_inserter(output), [&mat](const Vec& vec) { + return mat * Base::Vector3d(static_cast(vec.x), + static_cast(vec.y), + static_cast(vec.z)); + }); + + return output; + } /// from local to inside - inline Base::Vector3f transformToInside(const Base::Vector3d& vec) const + inline Base::Vector3f transformPointToInside(const Base::Vector3d& vec) const { Base::Matrix4D tmpM(getTransform()); tmpM.inverse(); diff --git a/src/App/Document.cpp b/src/App/Document.cpp index 2f491650ac..817ce571dd 100644 --- a/src/App/Document.cpp +++ b/src/App/Document.cpp @@ -328,7 +328,7 @@ void Document::exportGraphviz(std::ostream& out) const class GraphCreator { public: - GraphCreator(struct DocumentP* _d) : d(_d), vertex_no(0), seed(std::random_device()()), distribution(0,255) { + explicit GraphCreator(struct DocumentP* _d) : d(_d), vertex_no(0), seed(std::random_device()()), distribution(0,255) { build(); } @@ -938,7 +938,7 @@ void Document::exportGraphviz(std::ostream& out) const // return false; //} -bool Document::checkOnCycle(void) +bool Document::checkOnCycle() {/* std::vector < default_color_type > color(num_vertices(_DepList), white_color); graph_traits < DependencyList >::vertex_iterator vi, vi_end; @@ -957,7 +957,7 @@ bool Document::undo(int id) if(it == mUndoMap.end()) return false; if(it->second != d->activeUndoTransaction) { - while(mUndoTransactions.size() && mUndoTransactions.back()!=it->second) + while(!mUndoTransactions.empty() && mUndoTransactions.back()!=it->second) undo(0); } } @@ -1008,7 +1008,7 @@ bool Document::redo(int id) auto it = mRedoMap.find(id); if(it == mRedoMap.end()) return false; - while(mRedoTransactions.size() && mRedoTransactions.back()!=it->second) + while(!mRedoTransactions.empty() && mRedoTransactions.back()!=it->second) redo(0); } @@ -1428,12 +1428,12 @@ void Document::setUndoMode(int iMode) d->iUndoMode = iMode; } -int Document::getUndoMode(void) const +int Document::getUndoMode() const { return d->iUndoMode; } -unsigned int Document::getUndoMemSize (void) const +unsigned int Document::getUndoMemSize () const { return d->UndoMemSize; } @@ -1448,7 +1448,7 @@ void Document::setMaxUndoStackSize(unsigned int UndoMaxStackSize) d->UndoMaxStackSize = UndoMaxStackSize; } -unsigned int Document::getMaxUndoStackSize(void)const +unsigned int Document::getMaxUndoStackSize()const { return d->UndoMaxStackSize; } @@ -1541,94 +1541,90 @@ Document::Document(const char *name) 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::TimeInfo::currentDateTimeString(); - std::string Author = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Document")->GetASCII("prefAuthor",""); - std::string AuthorComp = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Document")->GetASCII("prefCompany",""); - ADD_PROPERTY_TYPE(Label,("Unnamed"),0,Prop_None,"The name of the document"); - ADD_PROPERTY_TYPE(FileName,(""),0,PropertyType(Prop_Transient|Prop_ReadOnly),"The path to the file where the document is saved to"); - ADD_PROPERTY_TYPE(CreatedBy,(Author.c_str()),0,Prop_None,"The creator of the document"); - ADD_PROPERTY_TYPE(CreationDate,(CreationDateString.c_str()),0,Prop_ReadOnly,"Date of creation"); - ADD_PROPERTY_TYPE(LastModifiedBy,(""),0,Prop_None,0); - ADD_PROPERTY_TYPE(LastModifiedDate,("Unknown"),0,Prop_ReadOnly,"Date of last modification"); - ADD_PROPERTY_TYPE(Company,(AuthorComp.c_str()),0,Prop_None,"Additional tag to save the name of the company"); - ADD_PROPERTY_TYPE(Comment,(""),0,Prop_None,"Additional tag to save a comment"); - ADD_PROPERTY_TYPE(Meta,(),0,Prop_None,"Map with additional meta information"); - ADD_PROPERTY_TYPE(Material,(),0,Prop_None,"Map with material properties"); + std::string Author = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")->GetASCII("prefAuthor", ""); + std::string AuthorComp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")->GetASCII("prefCompany", ""); + ADD_PROPERTY_TYPE(Label, ("Unnamed"), 0, Prop_None, "The name of the document"); + ADD_PROPERTY_TYPE(FileName, (""), 0, PropertyType(Prop_Transient | Prop_ReadOnly), "The path to the file where the document is saved to"); + ADD_PROPERTY_TYPE(CreatedBy, (Author.c_str()), 0, Prop_None, "The creator of the document"); + ADD_PROPERTY_TYPE(CreationDate, (CreationDateString.c_str()), 0, Prop_ReadOnly, "Date of creation"); + ADD_PROPERTY_TYPE(LastModifiedBy, (""), 0, Prop_None, 0); + ADD_PROPERTY_TYPE(LastModifiedDate, ("Unknown"), 0, Prop_ReadOnly, "Date of last modification"); + ADD_PROPERTY_TYPE(Company, (AuthorComp.c_str()), 0, Prop_None, "Additional tag to save the name of the company"); + ADD_PROPERTY_TYPE(Comment, (""), 0, Prop_None, "Additional tag to save a comment"); + ADD_PROPERTY_TYPE(Meta, (), 0, Prop_None, "Map with additional meta information"); + ADD_PROPERTY_TYPE(Material, (), 0, Prop_None, "Map with material properties"); // create the uuid for the document Base::Uuid id; - ADD_PROPERTY_TYPE(Id,(""),0,Prop_None,"ID of the document"); - ADD_PROPERTY_TYPE(Uid,(id),0,Prop_ReadOnly,"UUID of the document"); + ADD_PROPERTY_TYPE(Id, (""), 0, Prop_None, "ID of the document"); + ADD_PROPERTY_TYPE(Uid, (id), 0, Prop_ReadOnly, "UUID of the document"); // license stuff - ADD_PROPERTY_TYPE(License,("CC-BY 3.0"),0,Prop_None,"License string of the Item"); - ADD_PROPERTY_TYPE(LicenseURL,("http://creativecommons.org/licenses/by/3.0/"),0,Prop_None,"URL to the license text/contract"); + ADD_PROPERTY_TYPE(License, ("CC-BY 3.0"), 0, Prop_None, "License string of the Item"); + ADD_PROPERTY_TYPE(LicenseURL, ("https://creativecommons.org/licenses/by/3.0/"), 0, Prop_None, "URL to the license text/contract"); // license stuff - int licenseId = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Document")->GetInt("prefLicenseType",0); + int licenseId = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")->GetInt("prefLicenseType", 0); std::string license; std::string licenseUrl; switch (licenseId) { case 0: license = "All rights reserved"; - licenseUrl = "http://en.wikipedia.org/wiki/All_rights_reserved"; + licenseUrl = "https://en.wikipedia.org/wiki/All_rights_reserved"; break; case 1: license = "Creative Commons Attribution"; - licenseUrl = "http://creativecommons.org/licenses/by/4.0/"; + licenseUrl = "https://creativecommons.org/licenses/by/4.0/"; break; case 2: license = "Creative Commons Attribution-ShareAlike"; - licenseUrl = "http://creativecommons.org/licenses/by-sa/4.0/"; + licenseUrl = "https://creativecommons.org/licenses/by-sa/4.0/"; break; case 3: license = "Creative Commons Attribution-NoDerivatives"; - licenseUrl = "http://creativecommons.org/licenses/by-nd/4.0/"; + licenseUrl = "https://creativecommons.org/licenses/by-nd/4.0/"; break; case 4: license = "Creative Commons Attribution-NonCommercial"; - licenseUrl = "http://creativecommons.org/licenses/by-nc/4.0/"; + licenseUrl = "https://creativecommons.org/licenses/by-nc/4.0/"; break; case 5: license = "Creative Commons Attribution-NonCommercial-ShareAlike"; - licenseUrl = "http://creativecommons.org/licenses/by-nc-sa/4.0/"; + licenseUrl = "https://creativecommons.org/licenses/by-nc-sa/4.0/"; break; case 6: license = "Creative Commons Attribution-NonCommercial-NoDerivatives"; - licenseUrl = "http://creativecommons.org/licenses/by-nc-nd/4.0/"; + licenseUrl = "https://creativecommons.org/licenses/by-nc-nd/4.0/"; break; case 7: license = "Public Domain"; - licenseUrl = "http://en.wikipedia.org/wiki/Public_domain"; + licenseUrl = "https://en.wikipedia.org/wiki/Public_domain"; break; case 8: license = "FreeArt"; - licenseUrl = "http://artlibre.org/licence/lal"; + licenseUrl = "https://artlibre.org/licence/lal"; break; default: license = "Other"; break; } - licenseUrl = App::GetApplication().GetParameterGroupByPath - ("User parameter:BaseApp/Preferences/Document")->GetASCII("prefLicenseUrl", licenseUrl.c_str()); + licenseUrl = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Document")->GetASCII("prefLicenseUrl", licenseUrl.c_str()); - ADD_PROPERTY_TYPE(License,(license.c_str()),0,Prop_None,"License string of the Item"); - ADD_PROPERTY_TYPE(LicenseURL,(licenseUrl.c_str()),0,Prop_None,"URL to the license text/contract"); - ADD_PROPERTY_TYPE(ShowHidden,(false), 0,PropertyType(Prop_None), - "Whether to show hidden object items in the tree view"); + ADD_PROPERTY_TYPE(License, (license.c_str()), 0, Prop_None, "License string of the Item"); + ADD_PROPERTY_TYPE(LicenseURL, (licenseUrl.c_str()), 0, Prop_None, "URL to the license text/contract"); + ADD_PROPERTY_TYPE(ShowHidden, (false), 0, PropertyType(Prop_None), + "Whether to show hidden object items in the tree view"); // this creates and sets 'TransientDir' in onChanged() - ADD_PROPERTY_TYPE(TransientDir,(""),0,PropertyType(Prop_Transient|Prop_ReadOnly), - "Transient directory, where the files live while the document is open"); - ADD_PROPERTY_TYPE(Tip,(nullptr),0,PropertyType(Prop_Transient), - "Link of the tip object of the document"); - ADD_PROPERTY_TYPE(TipName,(""),0,PropertyType(Prop_Hidden|Prop_ReadOnly), - "Link of the tip object of the document"); + ADD_PROPERTY_TYPE(TransientDir, (""), 0, PropertyType(Prop_Transient | Prop_ReadOnly), + "Transient directory, where the files live while the document is open"); + ADD_PROPERTY_TYPE(Tip, (nullptr), 0, PropertyType(Prop_Transient), + "Link of the tip object of the document"); + ADD_PROPERTY_TYPE(TipName, (""), 0, PropertyType(Prop_Hidden | Prop_ReadOnly), + "Link of the tip object of the document"); Uid.touch(); } @@ -1797,7 +1793,7 @@ static DocExportStatus _ExportStatus; // Exception-safe exporting status setter class DocumentExporting { public: - DocumentExporting(const std::vector &objs) { + explicit DocumentExporting(const std::vector &objs) { _ExportStatus.status = Document::Exporting; _ExportStatus.objs.insert(objs.begin(),objs.end()); } @@ -2003,7 +1999,7 @@ Document::readObjects(Base::XMLReader& reader) if(!reader.hasAttribute(FC_ATTR_DEPENDENCIES)) d->partialLoadObjects.clear(); - else if(d->partialLoadObjects.size()) { + else if(!d->partialLoadObjects.empty()) { std::unordered_map deps; for (int i=0 ;i objs; objs.reserve(d->partialLoadObjects.size()); for(auto &v : d->partialLoadObjects) - objs.push_back(v.first.c_str()); + objs.emplace_back(v.first.c_str()); for(auto &name : objs) _loadDeps(name,d->partialLoadObjects,deps); if(Cnt > (int)d->partialLoadObjects.size()) @@ -2049,7 +2045,7 @@ Document::readObjects(Base::XMLReader& reader) std::string viewType = reader.hasAttribute("ViewType")?reader.getAttribute("ViewType"):""; bool partial = false; - if(d->partialLoadObjects.size()) { + if(!d->partialLoadObjects.empty()) { auto it = d->partialLoadObjects.find(name); if(it == d->partialLoadObjects.end()) continue; @@ -2224,7 +2220,7 @@ Document::importObjects(Base::XMLReader& reader) return objs; } -unsigned int Document::getMemSize (void) const +unsigned int Document::getMemSize () const { unsigned int size = 0; @@ -2285,7 +2281,7 @@ bool Document::saveCopy(const char* _file) const } // Save the document under the name it has been opened -bool Document::save (void) +bool Document::save () { if(testStatus(Document::PartialDoc)) { FC_ERR("Partial loaded document '" << Label.getValue() << "' cannot be saved"); @@ -2332,8 +2328,7 @@ public: useFCBakExtension = false; saveBackupDateFormat = "%Y%m%d-%H%M%S"; } - ~BackupPolicy() { - } + ~BackupPolicy() = default; void setPolicy(Policy p) { policy = p; } @@ -2373,7 +2368,7 @@ private: if (file.substr(0,fn.length()) == fn) { // starts with the same file name std::string suf(file.substr(fn.length())); - if (suf.size() > 0) { + if (!suf.empty()) { std::string::size_type nPos = suf.find_first_not_of("0123456789"); if (nPos==std::string::npos) { // store all backup files @@ -2505,7 +2500,7 @@ private: fn = str.str(); bool done = false; - if ((fn == "") || (fn[fn.length()-1] == ' ') || (fn[fn.length()-1] == '-')) { + if ((fn.empty()) || (fn[fn.length()-1] == ' ') || (fn[fn.length()-1] == '-')) { if (fn[fn.length()-1] == ' ') { fn = fn.substr(0,fn.length()-1); } @@ -2614,15 +2609,37 @@ bool Document::saveToFile(const char* filename) const bool policy = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/Document")->GetBool("BackupPolicy",true); - //realpath is canonical filename i.e. without symlink + auto canonical_path = [](const char* filename) { + try { #ifdef FC_OS_WIN32 - QString utf8Name = QString::fromUtf8(filename); - auto realpath = fs::weakly_canonical(fs::absolute(fs::path(utf8Name.toStdWString()))); - std::string nativePath = QString::fromStdWString(realpath.native()).toStdString(); + QString utf8Name = QString::fromUtf8(filename); + auto realpath = fs::weakly_canonical(fs::absolute(fs::path(utf8Name.toStdWString()))); + std::string nativePath = QString::fromStdWString(realpath.native()).toStdString(); #else - auto realpath = fs::weakly_canonical(fs::absolute(fs::path(filename))); - std::string nativePath = realpath.native(); + auto realpath = fs::weakly_canonical(fs::absolute(fs::path(filename))); + std::string nativePath = realpath.native(); #endif + // In case some folders in the path do not exist + auto parentPath = realpath.parent_path(); + fs::create_directories(parentPath); + + return nativePath; + } + catch (const std::exception&) { +#ifdef FC_OS_WIN32 + QString utf8Name = QString::fromUtf8(filename); + auto parentPath = fs::absolute(fs::path(utf8Name.toStdWString())).parent_path(); +#else + auto parentPath = fs::absolute(fs::path(filename)).parent_path(); +#endif + fs::create_directories(parentPath); + + return std::string(filename); + } + }; + + //realpath is canonical filename i.e. without symlink + std::string nativePath = canonical_path(filename); // make a tmp. file where to save the project data first and then rename to // the actual file name. This may be useful if overwriting an existing file @@ -2636,10 +2653,6 @@ bool Document::saveToFile(const char* filename) const Base::FileInfo tmp(fn); - // In case some folders in the path do not exist - auto parentPath = realpath.parent_path(); - fs::create_directories(parentPath); - // open extra scope to close ZipWriter properly { Base::ofstream file(tmp, std::ios::out | std::ios::binary); @@ -2804,7 +2817,7 @@ bool Document::afterRestore(bool checkPartial) { bool Document::afterRestore(const std::vector &objArray, bool checkPartial) { checkPartial = checkPartial && testStatus(Document::PartialDoc); - if(checkPartial && d->touchedObjs.size()) + if(checkPartial && !d->touchedObjs.empty()) return false; // some link type property cannot restore link information until other @@ -2827,7 +2840,7 @@ bool Document::afterRestore(const std::vector &objArray, bool } } - if(checkPartial && d->touchedObjs.size()) { + if(checkPartial && !d->touchedObjs.empty()) { // partial document touched, signal full reload return false; } @@ -2888,7 +2901,7 @@ bool Document::afterRestore(const std::vector &objArray, bool } } - if(checkPartial && d->touchedObjs.size()) { + if(checkPartial && !d->touchedObjs.empty()) { // partial document touched, signal full reload return false; } else if(!d->touchedObjs.count(obj)) @@ -2956,7 +2969,7 @@ bool Document::isTouched() const return false; } -vector Document::getTouched(void) const +vector Document::getTouched() const { vector result; @@ -2977,7 +2990,7 @@ bool Document::isClosable() const return testStatus(Document::Closable); } -int Document::countObjects(void) const +int Document::countObjects() const { return static_cast(d->objectArray.size()); } @@ -2988,7 +3001,7 @@ void Document::getLinksTo(std::set &links, { std::map > linkMap; - for(auto o : objs.size()?objs:d->objectArray) { + for(auto o : !objs.empty()?objs:d->objectArray) { if(o == obj) continue; auto linked = o; if(options & GetLinkArrayElement) @@ -3022,7 +3035,7 @@ void Document::getLinksTo(std::set &links, return; std::vector current(1,obj); - for(int depth=0;current.size();++depth) { + for(int depth=0;!current.empty();++depth) { if(!GetApplication().checkLinkDepth(depth,true)) break; std::vector next; @@ -3092,7 +3105,7 @@ static void _buildDependencyList(const std::vector &object int op = (options & Document::DepNoXLinked)?DocumentObject::OutListNoXLinked:0; for (auto obj : objectArray) { objs.push_back(obj); - while(objs.size()) { + while(!objs.empty()) { auto obj = objs.front(); objs.pop_front(); if(!obj || !obj->getNameInDocument()) @@ -3228,7 +3241,7 @@ std::vector Document::getDependentDocuments( for(auto doc : pending) docMap[doc] = add_vertex(depList); } - while(pending.size()) { + while(!pending.empty()) { auto doc = pending.back(); pending.pop_back(); @@ -3579,7 +3592,7 @@ int Document::recompute(const std::vector &objs, bool forc FC_TIME_LOG(t,"Recompute total"); - if (d->_RecomputeLog.size()) { + if (!d->_RecomputeLog.empty()) { d->pendingRemove.clear(); if (!testStatus(Status::IgnoreErrorOnRecompute)) Base::Console().Error("Recompute failed! Please check report view.\n"); @@ -3891,8 +3904,6 @@ DocumentObject * Document::addObject(const char* sType, const char* pObjectName, pcObject->pcNameInDocument = &(d->objectMap.find(ObjectName)->first); // insert in the vector d->objectArray.push_back(pcObject); - // insert in the adjacence list and reference through the ConectionMap - //_DepConMap[pcObject] = add_vertex(_DepList); // If we are restoring, don't set the Label object now; it will be restored later. This is to avoid potential duplicate // label conflicts later. @@ -4134,27 +4145,6 @@ void Document::removeObject(const char* sName) _checkTransaction(pos->second,nullptr,__LINE__); -#if 0 - if(!d->rollback && d->activeUndoTransaction && pos->second->hasChildElement()) { - // Preserve link group sub object global visibilities. Normally those - // claimed object should be hidden in global coordinate space. However, - // when the group is deleted, the user will naturally try to show the - // children, which may now in the global space. When the parent is - // undeleted, having its children shown in both the local and global - // coordinate space is very confusing. Hence, we preserve the visibility - // here - for(auto &sub : pos->second->getSubObjects()) { - if(sub.empty()) - continue; - if(sub[sub.size()-1]!='.') - sub += '.'; - auto sobj = pos->second->getSubObject(sub.c_str()); - if(sobj && sobj->getDocument()==this && !sobj->Visibility.getValue()) - d->activeUndoTransaction->addObjectChange(sobj,&sobj->Visibility); - } - } -#endif - if (d->activeObject == pos->second) d->activeObject = nullptr; @@ -4225,6 +4215,10 @@ void Document::removeObject(const char* sName) } } + // In case the object gets deleted the pointer must be nullified + if (tobedestroyed) { + tobedestroyed->pcNameInDocument = nullptr; + } d->objectMap.erase(pos); } @@ -4496,7 +4490,7 @@ DocumentObject* Document::moveObject(DocumentObject* obj, bool recursive) return objs.back(); } -DocumentObject * Document::getActiveObject(void) const +DocumentObject * Document::getActiveObject() const { return d->activeObject; } diff --git a/src/App/Document.h b/src/App/Document.h index 5148c53889..1a81d28033 100644 --- a/src/App/Document.h +++ b/src/App/Document.h @@ -183,7 +183,7 @@ public: /// Save the Document under a new Name //void saveAs (const char* Name); /// Save the document to the file in Property Path - bool save (void); + bool save (); bool saveAs(const char* file); bool saveCopy(const char* file) const; /// Restore the document from the file in Property Path @@ -230,11 +230,11 @@ public: const char* getFileName() const; //@} - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; /// returns the complete document memory consumption, including all managed DocObjects and Undo Redo. - unsigned int getMemSize (void) const override; + unsigned int getMemSize () const override; /** @name Object handling */ //@{ @@ -289,7 +289,7 @@ public: */ DocumentObject* moveObject(DocumentObject* obj, bool recursive=false); /// Returns the active Object of this document - DocumentObject *getActiveObject(void) const; + DocumentObject *getActiveObject() const; /// Returns a Object of this document DocumentObject *getObject(const char *Name) const; /// Returns a Object of this document by its id @@ -314,7 +314,7 @@ public: template inline std::vector getObjectsOfType() const; int countObjectsOfType(const Base::Type& typeId) const; /// get the number of objects in the document - int countObjects(void) const; + int countObjects() const; //@} /** @name methods for modification and state handling @@ -323,11 +323,11 @@ public: /// Remove all modifications. After this call The document becomes Valid again. void purgeTouched(); /// check if there is any touched object in this document - bool isTouched(void) const; + bool isTouched() const; /// check if there is any object must execute in this document - bool mustExecute(void) const; + bool mustExecute() const; /// returns all touched objects - std::vector getTouched(void) const; + std::vector getTouched() const; /// set the document to be closable, this is on by default. void setClosable(bool); /// check whether the document can be closed @@ -361,7 +361,7 @@ public: * transactions, meaning that there are other transactions before the given * ID. The Gui component shall ask user if they want to undo multiple steps. * And if the user agrees, call undo(id) to unroll all transaction before - * and including the the one with the give ID. Same applies for redo. + * and including the one with the given ID. Same applies for redo. * * The new transaction ID describe here is fully backward compatible. * Calling the APIs with a default id=0 gives the original behavior. @@ -370,7 +370,7 @@ public: /// switch the level of Undo/Redo void setUndoMode(int iMode); /// switch the level of Undo/Redo - int getUndoMode(void) const; + int getUndoMode() const; /// switch the transaction mode void setTransactionMode(int iMode); /** Open a new command Undo/Redo, an UTF-8 name can be specified @@ -398,11 +398,11 @@ public: /// Set the Undo limit in Byte! void setUndoLimit(unsigned int UndoMemSize=0); /// Returns the actual memory consumption of the Undo redo stuff. - unsigned int getUndoMemSize (void) const; + unsigned int getUndoMemSize () const; /// Set the Undo limit as stack size void setMaxUndoStackSize(unsigned int UndoMaxStackSize=20); /// Set the Undo limit as stack size - unsigned int getMaxUndoStackSize(void)const; + unsigned int getMaxUndoStackSize()const; /// Remove all stored Undos and Redos void clearUndos(); /// Returns the number of stored Undos. If greater than 0 Undo will be effective. @@ -428,7 +428,7 @@ public: /// write GraphViz file void writeDependencyGraphViz(std::ostream &out); /// checks if the graph is directed and has no cycles - bool checkOnCycle(void); + bool checkOnCycle(); /// get a list of all objects linking to the given object std::vector getInList(const DocumentObject* me) const; @@ -491,9 +491,9 @@ public: /// Function called to signal that an object identifier has been renamed void renameObjectIdentifiers(const std::map & paths, const std::function &selector = [](const App::DocumentObject *) { return true; }); - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual std::string getFullName() const override; + std::string getFullName() const override; /// Indicate if there is any document restoring/importing static bool isAnyRestoring(); @@ -506,11 +506,11 @@ public: friend class TransactionDocumentObject; /// Destruction - virtual ~Document(); + ~Document() override; protected: /// Construction - Document(const char *name = ""); + explicit Document(const char *name = ""); void _removeObject(DocumentObject* pcObject); void _addObject(DocumentObject* pcObject, const char* pObjectName); diff --git a/src/App/DocumentObject.cpp b/src/App/DocumentObject.cpp index 0ee1d368ae..88a09972ea 100644 --- a/src/App/DocumentObject.cpp +++ b/src/App/DocumentObject.cpp @@ -62,7 +62,7 @@ DocumentObjectExecReturn *DocumentObject::StdReturn = nullptr; // DocumentObject //=========================================================================== -DocumentObject::DocumentObject(void) +DocumentObject::DocumentObject() : ExpressionEngine(),_pDoc(nullptr),pcNameInDocument(nullptr),_Id(0) { // define Label of type 'Output' to avoid being marked as touched after relabeling @@ -81,7 +81,7 @@ DocumentObject::DocumentObject(void) Visibility.setStatus(Property::NoModify,true); } -DocumentObject::~DocumentObject(void) +DocumentObject::~DocumentObject() { if (!PythonObject.is(Py::_None())){ Base::PyGILStateLocker lock; @@ -96,15 +96,14 @@ DocumentObject::~DocumentObject(void) } } -App::DocumentObjectExecReturn *DocumentObject::recompute(void) +App::DocumentObjectExecReturn *DocumentObject::recompute() { //check if the links are valid before making the recompute if(!GeoFeatureGroupExtension::areLinksValid(this)) { -#if 1 // Get objects that have invalid link scope, and print their names. // Truncate the invalid object list name strings for readability, if they happen to be very long. std::vector invalid_linkobjs; - std::string objnames = "", scopenames = ""; + std::string objnames, scopenames; GeoFeatureGroupExtension::getInvalidLinkObjects(this, invalid_linkobjs); for (auto& obj : invalid_linkobjs) { objnames += obj->getNameInDocument(); @@ -133,9 +132,6 @@ App::DocumentObjectExecReturn *DocumentObject::recompute(void) scopenames.pop_back(); } 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(), getNameInDocument(), scopenames.c_str()); -#else - return new App::DocumentObjectExecReturn("Links go out of the allowed scope", this); -#endif } // set/unset the execution bit @@ -156,7 +152,7 @@ App::DocumentObjectExecReturn *DocumentObject::recompute(void) return ret; } -DocumentObjectExecReturn *DocumentObject::execute(void) +DocumentObjectExecReturn *DocumentObject::execute() { return executeExtensions(); } @@ -213,7 +209,7 @@ bool DocumentObject::isTouched() const * This can be useful to recompute the feature without * having to change one of its input properties. */ -void DocumentObject::enforceRecompute(void) +void DocumentObject::enforceRecompute() { touch(false); } @@ -224,7 +220,7 @@ void DocumentObject::enforceRecompute(void) * returns a value > 0. * @return true if document object must be recomputed, false if not. */ -bool DocumentObject::mustRecompute(void) const +bool DocumentObject::mustRecompute() const { if (StatusBits.test(ObjectStatus::Enforce)) return true; @@ -232,7 +228,7 @@ bool DocumentObject::mustRecompute(void) const return mustExecute() > 0; } -short DocumentObject::mustExecute(void) const +short DocumentObject::mustExecute() const { if (ExpressionEngine.isTouched()) return 1; @@ -247,7 +243,7 @@ short DocumentObject::mustExecute(void) const return 0; } -const char* DocumentObject::getStatusString(void) const +const char* DocumentObject::getStatusString() const { if (isError()) { const char* text = getDocument()->getErrorDescription(this); @@ -379,7 +375,7 @@ std::vector DocumentObject::getInList(void) const #else // ifndef USE_OLD_DAG -const std::vector &DocumentObject::getInList(void) const +const std::vector &DocumentObject::getInList() const { return _inList; } @@ -387,42 +383,6 @@ const std::vector &DocumentObject::getInList(void) const #endif // if USE_OLD_DAG -#if 0 - -void _getInListRecursive(std::set& objSet, - const DocumentObject* obj, - const DocumentObject* checkObj, int depth) -{ - for (const auto objIt : obj->getInList()) { - // if the check object is in the recursive inList we have a cycle! - if (objIt == checkObj || depth <= 0) { - throw Base::BadGraphError("DocumentObject::getInListRecursive(): cyclic dependency detected!"); - } - - // if the element was already in the set then there is no need to process it again - auto pair = objSet.insert(objIt); - if (pair.second) - _getInListRecursive(objSet, objIt, checkObj, depth-1); - } -} - -std::vector DocumentObject::getInListRecursive(void) const -{ - // number of objects in document is a good estimate in result size - // int maxDepth = getDocument()->countObjects() +2; - int maxDepth = GetApplication().checkLinkDepth(0); - std::vector result; - result.reserve(maxDepth); - - // using a rcursie helper to collect all InLists - _getInListRecursive(result, this, this, maxDepth); - - std::vector array; - array.insert(array.begin(), result.begin(), result.end()); - return array; -} - -#else // The original algorithm is highly inefficient in some special case. // Considering an object is linked by every other objects. After excluding this // object, there is another object linked by every other of the remaining @@ -431,14 +391,13 @@ std::vector DocumentObject::getInListRecursive(void) const // of objects. And this may not be the worst case. getInListEx() has no such // problem. -std::vector DocumentObject::getInListRecursive(void) const { +std::vector DocumentObject::getInListRecursive() const { std::set inSet; std::vector res; getInListEx(inSet,true,&res); return res; } -#endif // More efficient algorithm to find the recursive inList of an object, // including possible external parents. One shortcoming of this algorithm is @@ -490,7 +449,7 @@ void DocumentObject::getInListEx(std::set &inSet, std::stack pendings; pendings.push(const_cast(this)); - while(pendings.size()) { + while(!pendings.empty()) { auto obj = pendings.top(); pendings.pop(); for(auto o : obj->getInList()) { @@ -528,7 +487,7 @@ void _getOutListRecursive(std::set& objSet, } } -std::vector DocumentObject::getOutListRecursive(void) const +std::vector DocumentObject::getOutListRecursive() const { // number of objects in document is a good estimate in result size int maxDepth = GetApplication().checkLinkDepth(0); @@ -569,12 +528,7 @@ bool _isInInListRecursive(const DocumentObject* act, bool DocumentObject::isInInListRecursive(DocumentObject *linkTo) const { -#if 0 - int maxDepth = getDocument()->countObjects() + 2; - return _isInInListRecursive(this, linkTo, maxDepth); -#else return this==linkTo || getInListEx(true).count(linkTo); -#endif } bool DocumentObject::isInInList(DocumentObject *linkTo) const @@ -641,24 +595,12 @@ bool DocumentObject::testIfLinkDAGCompatible(DocumentObject *linkTo) const bool DocumentObject::testIfLinkDAGCompatible(const std::vector &linksTo) const { -#if 0 - Document* doc = this->getDocument(); - if (!doc) - throw Base::RuntimeError("DocumentObject::testIfLinkIsDAG: object is not in any document."); - std::vector deplist = doc->getDependencyList(linksTo); - if( std::find(deplist.begin(),deplist.end(),this) != deplist.end() ) - //found this in dependency list - return false; - else - return true; -#else auto inLists = getInListEx(true); inLists.emplace(const_cast(this)); for(auto obj : linksTo) if(inLists.count(obj)) return false; return true; -#endif } bool DocumentObject::testIfLinkDAGCompatible(PropertyLinkSubList &linksTo) const @@ -680,7 +622,7 @@ void DocumentObject::onLostLinkToObject(DocumentObject*) } -App::Document *DocumentObject::getDocument(void) const +App::Document *DocumentObject::getDocument() const { return _pDoc; } @@ -801,7 +743,7 @@ void DocumentObject::clearOutListCache() const { _outListCached = false; } -PyObject *DocumentObject::getPyObject(void) +PyObject *DocumentObject::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 diff --git a/src/App/DocumentObject.h b/src/App/DocumentObject.h index f7f0772566..e863958edc 100644 --- a/src/App/DocumentObject.h +++ b/src/App/DocumentObject.h @@ -74,11 +74,11 @@ enum ObjectStatus { class AppExport DocumentObjectExecReturn { public: - DocumentObjectExecReturn(const std::string& sWhy, DocumentObject* WhichObject=nullptr) + explicit DocumentObjectExecReturn(const std::string& sWhy, DocumentObject* WhichObject=nullptr) : Why(sWhy), Which(WhichObject) { } - DocumentObjectExecReturn(const char* sWhy, DocumentObject* WhichObject=nullptr) + explicit DocumentObjectExecReturn(const char* sWhy, DocumentObject* WhichObject=nullptr) : Which(WhichObject) { if (sWhy) @@ -112,7 +112,7 @@ public: boost::signals2::signal signalChanged; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + virtual const char* getViewProviderName() const { return ""; } /** @@ -129,21 +129,21 @@ public: } /// Constructor - DocumentObject(void); - virtual ~DocumentObject(); + DocumentObject(); + ~DocumentObject() override; /// returns the name which is set in the document for this object (not the name property!) - const char *getNameInDocument(void) const; + const char *getNameInDocument() const; /// Return the object ID that is unique within its owner document long getID() const {return _Id;} /// returns the name that is safe to be exported to other document std::string getExportName(bool forced=false) const; /// Return the object full name of the form DocName#ObjName - virtual std::string getFullName() const override; - virtual bool isAttachedToDocument() const override; - virtual const char* detachFromDocument() override; + std::string getFullName() const override; + bool isAttachedToDocument() const override; + const char* detachFromDocument() override; /// gets the document in which this Object is handled - App::Document *getDocument(void) const; + App::Document *getDocument() const; /** Set the property touched -> changed, cause recomputation in Update() */ @@ -151,22 +151,22 @@ public: /// set this document object touched (cause recomputation on dependent features) void touch(bool noRecompute=false); /// test if this document object is touched - bool isTouched(void) const; + bool isTouched() const; /// Enforce this document object to be recomputed void enforceRecompute(); /// Test if this document object must be recomputed - bool mustRecompute(void) const; + bool mustRecompute() const; /// reset this document object touched - void purgeTouched(void) { + void purgeTouched() { StatusBits.reset(ObjectStatus::Touch); StatusBits.reset(ObjectStatus::Enforce); setPropertyStatus(0,false); } /// set this feature to error - bool isError(void) const {return StatusBits.test(ObjectStatus::Error);} - bool isValid(void) const {return !StatusBits.test(ObjectStatus::Error);} + bool isError() const {return StatusBits.test(ObjectStatus::Error);} + bool isValid() const {return !StatusBits.test(ObjectStatus::Error);} /// remove the error from the object - void purgeError(void){StatusBits.reset(ObjectStatus::Error);} + void purgeError(){StatusBits.reset(ObjectStatus::Error);} /// returns true if this objects is currently recomputing bool isRecomputing() const {return StatusBits.test(ObjectStatus::Recompute);} /// returns true if this objects is currently restoring from file @@ -228,7 +228,7 @@ public: /// returns a list of objects linked by the property std::vector getOutListOfProperty(App::Property*) const; /// returns a list of objects this object is pointing to by Links and all further descended - std::vector getOutListRecursive(void) const; + std::vector getOutListRecursive() const; /// clear internal out list cache void clearOutListCache() const; /// get all possible paths from this to another object following the OutList @@ -237,10 +237,10 @@ public: /// get all objects link to this object std::vector getInList(void) const #else - const std::vector &getInList(void) const; + const std::vector &getInList() const; #endif /// get all objects link directly or indirectly to this object - std::vector getInListRecursive(void) const; + std::vector getInListRecursive() const; /** Get a set of all objects linking to this object, including possible external parent objects * * @param inSet [out]: a set containing all objects linking to this object. @@ -299,7 +299,7 @@ public: * necessarily mean that it will be recomputed. It only means that all * objects that link it (i.e. its InList) will be recomputed. */ - virtual short mustExecute(void) const; + virtual short mustExecute() const; /** Recompute only this feature * @@ -308,7 +308,7 @@ public: bool recomputeFeature(bool recursive=false); /// get the status Message - const char *getStatusString(void) const; + const char *getStatusString() const; /** Called in case of losing a link * Get called by the document when a object got deleted a link property of this @@ -317,7 +317,7 @@ public: * additional or different behavior. */ virtual void onLostLinkToObject(DocumentObject*); - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; /** Get the sub element/object by name * @@ -419,7 +419,7 @@ public: static DocumentObjectExecReturn *StdReturn; - virtual void Save (Base::Writer &writer) const override; + void Save (Base::Writer &writer) const override; /* Expression support */ @@ -437,9 +437,9 @@ public: return _pcViewProviderName.c_str(); } - virtual bool removeDynamicProperty(const char* prop) override; + bool removeDynamicProperty(const char* prop) override; - virtual App::Property* addDynamicProperty( + App::Property* addDynamicProperty( const char* type, const char* name=nullptr, const char* group=nullptr, const char* doc=nullptr, short attr=0, bool ro=false, bool hidden=false) override; @@ -561,7 +561,7 @@ public: protected: /// recompute only this object - virtual App::DocumentObjectExecReturn *recompute(void); + virtual App::DocumentObjectExecReturn *recompute(); /** get called by the document to recompute this feature * Normally this method get called in the processing of * Document::recompute(). @@ -569,7 +569,7 @@ protected: * with the data from linked objects and objects own * properties. */ - virtual App::DocumentObjectExecReturn *execute(void); + virtual App::DocumentObjectExecReturn *execute(); /** * Executes the extensions of a document object. @@ -592,14 +592,14 @@ protected: */ std::bitset<32> StatusBits; - void setError(void){StatusBits.set(ObjectStatus::Error);} - void resetError(void){StatusBits.reset(ObjectStatus::Error);} + void setError(){StatusBits.set(ObjectStatus::Error);} + void resetError(){StatusBits.reset(ObjectStatus::Error);} void setDocument(App::Document* doc); /// get called before the value is changed - virtual void onBeforeChange(const Property* prop) override; + void onBeforeChange(const Property* prop) override; /// get called by the container when a property was changed - virtual void onChanged(const Property* prop) override; + void onChanged(const Property* prop) override; /// get called after a document has been fully restored virtual void onDocumentRestored(); /// get called after an undo/redo transaction is finished @@ -612,7 +612,7 @@ protected: virtual void unsetupObject(); /// get called when a property status has changed - virtual void onPropertyStatusChanged(const Property &prop, unsigned long oldStatus) override; + void onPropertyStatusChanged(const Property &prop, unsigned long oldStatus) override; /// python object of this class and all descendent protected: // attributes diff --git a/src/App/DocumentObjectExtension.cpp b/src/App/DocumentObjectExtension.cpp index fbfd650d9a..7072b6baea 100644 --- a/src/App/DocumentObjectExtension.cpp +++ b/src/App/DocumentObjectExtension.cpp @@ -37,17 +37,14 @@ DocumentObjectExtension::DocumentObjectExtension() initExtensionType(App::DocumentObjectExtension::getExtensionClassTypeId()); } -DocumentObjectExtension::~DocumentObjectExtension() -{ +DocumentObjectExtension::~DocumentObjectExtension() = default; -} - -short int DocumentObjectExtension::extensionMustExecute(void) { +short int DocumentObjectExtension::extensionMustExecute() { return 0; } -App::DocumentObjectExecReturn* DocumentObjectExtension::extensionExecute(void) { +App::DocumentObjectExecReturn* DocumentObjectExtension::extensionExecute() { return App::DocumentObject::StdReturn; } @@ -68,7 +65,7 @@ void DocumentObjectExtension::onExtendedUnsetupObject() { } -PyObject* DocumentObjectExtension::getExtensionPyObject(void) { +PyObject* DocumentObjectExtension::getExtensionPyObject() { if (ExtensionPythonObject.is(Py::_None())){ // ref counter is set to 1 diff --git a/src/App/DocumentObjectExtension.h b/src/App/DocumentObjectExtension.h index 8b7ba82a39..a27b6f680d 100644 --- a/src/App/DocumentObjectExtension.h +++ b/src/App/DocumentObjectExtension.h @@ -47,7 +47,7 @@ class AppExport DocumentObjectExtension : public App::Extension public: DocumentObjectExtension (); - virtual ~DocumentObjectExtension (); + ~DocumentObjectExtension () override; App::DocumentObject* getExtendedObject(); const App::DocumentObject* getExtendedObject() const; @@ -66,7 +66,7 @@ public: /// get called when object is going to be removed from the document virtual void onExtendedUnsetupObject(); - virtual PyObject* getExtensionPyObject() override; + PyObject* getExtensionPyObject() override; /// returns the type name of the ViewProviderExtension which is automatically attached /// to the viewprovider object when it is initiated diff --git a/src/App/DocumentObjectExtensionPyImp.cpp b/src/App/DocumentObjectExtensionPyImp.cpp index c519707e67..deab8c77a4 100644 --- a/src/App/DocumentObjectExtensionPyImp.cpp +++ b/src/App/DocumentObjectExtensionPyImp.cpp @@ -30,7 +30,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string DocumentObjectExtensionPy::representation(void) const +std::string DocumentObjectExtensionPy::representation() const { return std::string(""); } diff --git a/src/App/DocumentObjectFileIncluded.cpp b/src/App/DocumentObjectFileIncluded.cpp index b8bbae91c4..e3bbafe4ae 100644 --- a/src/App/DocumentObjectFileIncluded.cpp +++ b/src/App/DocumentObjectFileIncluded.cpp @@ -35,7 +35,5 @@ DocumentObjectFileIncluded::DocumentObjectFileIncluded() ADD_PROPERTY_TYPE(File,(nullptr),"",(App::PropertyType)(Prop_None),"File to include into Project File"); } -DocumentObjectFileIncluded::~DocumentObjectFileIncluded() -{ -} +DocumentObjectFileIncluded::~DocumentObjectFileIncluded() = default; diff --git a/src/App/DocumentObjectFileIncluded.h b/src/App/DocumentObjectFileIncluded.h index b68c3048d4..eb338fedea 100644 --- a/src/App/DocumentObjectFileIncluded.h +++ b/src/App/DocumentObjectFileIncluded.h @@ -33,16 +33,16 @@ namespace App class AppExport DocumentObjectFileIncluded : public DocumentObject { - PROPERTY_HEADER(App::DocumentObjectFileIncluded); + PROPERTY_HEADER_WITH_OVERRIDE(App::DocumentObjectFileIncluded); public: /// Constructor - DocumentObjectFileIncluded(void); - virtual ~DocumentObjectFileIncluded(); + DocumentObjectFileIncluded(); + ~DocumentObjectFileIncluded() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderDocumentObject"; } diff --git a/src/App/DocumentObjectGroup.cpp b/src/App/DocumentObjectGroup.cpp index 4a09427fd5..c4fdd690f2 100644 --- a/src/App/DocumentObjectGroup.cpp +++ b/src/App/DocumentObjectGroup.cpp @@ -31,15 +31,13 @@ using namespace App; PROPERTY_SOURCE_WITH_EXTENSIONS(App::DocumentObjectGroup, App::DocumentObject) -DocumentObjectGroup::DocumentObjectGroup(void): DocumentObject(), GroupExtension() { +DocumentObjectGroup::DocumentObjectGroup(): DocumentObject(), GroupExtension() { GroupExtension::initExtension(this); _GroupTouched.setStatus(App::Property::Output,true); } -DocumentObjectGroup::~DocumentObjectGroup() { - -} +DocumentObjectGroup::~DocumentObjectGroup() = default; PyObject *DocumentObjectGroup::getPyObject() { @@ -57,10 +55,10 @@ namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(App::DocumentObjectGroupPython, App::DocumentObjectGroup) -template<> const char* App::DocumentObjectGroupPython::getViewProviderName(void) const { +template<> const char* App::DocumentObjectGroupPython::getViewProviderName() const { return "Gui::ViewProviderDocumentObjectGroupPython"; } -template<> PyObject* App::DocumentObjectGroupPython::getPyObject(void) { +template<> PyObject* App::DocumentObjectGroupPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new FeaturePythonPyT(this),true); diff --git a/src/App/DocumentObjectGroup.h b/src/App/DocumentObjectGroup.h index f0fa9301d3..d40b027cd4 100644 --- a/src/App/DocumentObjectGroup.h +++ b/src/App/DocumentObjectGroup.h @@ -39,14 +39,14 @@ class AppExport DocumentObjectGroup : public DocumentObject, public GroupExtensi public: /// Constructor DocumentObjectGroup(); - virtual ~DocumentObjectGroup(); + ~DocumentObjectGroup() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const override { + const char* getViewProviderName() const override { return "Gui::ViewProviderDocumentObjectGroup"; } - virtual PyObject *getPyObject() override; + PyObject *getPyObject() override; }; typedef App::FeaturePythonT DocumentObjectGroupPython; diff --git a/src/App/DocumentObjectGroupPyImp.cpp b/src/App/DocumentObjectGroupPyImp.cpp index c08da1dfc3..15e23c1084 100644 --- a/src/App/DocumentObjectGroupPyImp.cpp +++ b/src/App/DocumentObjectGroupPyImp.cpp @@ -32,7 +32,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string DocumentObjectGroupPy::representation(void) const +std::string DocumentObjectGroupPy::representation() const { return std::string(""); } diff --git a/src/App/DocumentObjectPyImp.cpp b/src/App/DocumentObjectPyImp.cpp index 314936b57a..5e160296ad 100644 --- a/src/App/DocumentObjectPyImp.cpp +++ b/src/App/DocumentObjectPyImp.cpp @@ -40,7 +40,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string DocumentObjectPy::representation(void) const +std::string DocumentObjectPy::representation() const { DocumentObject* object = this->getDocumentObjectPtr(); std::stringstream str; @@ -48,7 +48,7 @@ std::string DocumentObjectPy::representation(void) const return str.str(); } -Py::String DocumentObjectPy::getName(void) const +Py::String DocumentObjectPy::getName() const { DocumentObject* object = this->getDocumentObjectPtr(); const char* internal = object->getNameInDocument(); @@ -58,12 +58,12 @@ Py::String DocumentObjectPy::getName(void) const return Py::String(std::string(internal)); } -Py::String DocumentObjectPy::getFullName(void) const +Py::String DocumentObjectPy::getFullName() const { return Py::String(getDocumentObjectPtr()->getFullName()); } -Py::Object DocumentObjectPy::getDocument(void) const +Py::Object DocumentObjectPy::getDocument() const { DocumentObject* object = this->getDocumentObjectPtr(); Document* doc = object->getDocument(); @@ -135,7 +135,7 @@ PyObject* DocumentObjectPy::touch(PyObject * args) Py_Return; } auto prop = getDocumentObjectPtr()->getPropertyByName(propName); - if(!prop) + if(!prop) throw Py::RuntimeError("Property not found"); prop->touch(); Py_Return; @@ -161,7 +161,7 @@ PyObject* DocumentObjectPy::enforceRecompute(PyObject * args) Py_Return; } -Py::List DocumentObjectPy::getState(void) const +Py::List DocumentObjectPy::getState() const { DocumentObject* object = this->getDocumentObjectPtr(); Py::List list; @@ -200,7 +200,7 @@ Py::List DocumentObjectPy::getState(void) const return list; } -Py::Object DocumentObjectPy::getViewObject(void) const +Py::Object DocumentObjectPy::getViewObject() const { try { PyObject *dict = PySys_GetObject("modules"); @@ -248,7 +248,7 @@ Py::Object DocumentObjectPy::getViewObject(void) const } } -Py::List DocumentObjectPy::getInList(void) const +Py::List DocumentObjectPy::getInList() const { Py::List ret; std::vector list = getDocumentObjectPtr()->getInList(); @@ -259,7 +259,7 @@ Py::List DocumentObjectPy::getInList(void) const return ret; } -Py::List DocumentObjectPy::getInListRecursive(void) const +Py::List DocumentObjectPy::getInListRecursive() const { Py::List ret; try { @@ -267,15 +267,14 @@ Py::List DocumentObjectPy::getInListRecursive(void) const for (std::vector::iterator It = list.begin(); It != list.end(); ++It) ret.append(Py::Object((*It)->getPyObject(), true)); - } catch (const Base::Exception& e) { throw Py::IndexError(e.what()); } - return ret; + return ret; } -Py::List DocumentObjectPy::getOutList(void) const +Py::List DocumentObjectPy::getOutList() const { Py::List ret; std::vector list = getDocumentObjectPtr()->getOutList(); @@ -286,7 +285,7 @@ Py::List DocumentObjectPy::getOutList(void) const return ret; } -Py::List DocumentObjectPy::getOutListRecursive(void) const +Py::List DocumentObjectPy::getOutListRecursive() const { Py::List ret; try { @@ -448,7 +447,7 @@ PyObject* DocumentObjectPy::getSubObject(PyObject *args, PyObject *keywds) bool single = true; if (PyUnicode_Check(obj)) { - subs.push_back(PyUnicode_AsUTF8(obj)); + subs.emplace_back(PyUnicode_AsUTF8(obj)); } else if (PySequence_Check(obj)) { single = false; @@ -456,7 +455,7 @@ PyObject* DocumentObjectPy::getSubObject(PyObject *args, PyObject *keywds) for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) { PyObject* item = (*it).ptr(); if (PyUnicode_Check(item)) { - subs.push_back(PyUnicode_AsUTF8(item)); + subs.emplace_back(PyUnicode_AsUTF8(item)); } else { PyErr_SetString(PyExc_TypeError, "non-string object in sequence"); @@ -476,7 +475,7 @@ PyObject* DocumentObjectPy::getSubObject(PyObject *args, PyObject *keywds) Py::Object obj; Py::Object pyObj; Base::Matrix4D mat; - SubInfo(const Base::Matrix4D &mat) : sobj(nullptr), mat(mat){} + explicit SubInfo(const Base::Matrix4D &mat) : sobj(nullptr), mat(mat){} }; Base::Matrix4D mat; @@ -696,7 +695,7 @@ PyObject* DocumentObjectPy::getPathsByOutList(PyObject *args) (o)->getDocumentObjectPtr(); auto array = getDocumentObjectPtr()->getPathsByOutList(target); Py::List list; - for (auto it : array) { + for (const auto& it : array) { Py::List path; for (auto jt : it) { path.append(Py::asObject(jt->getPyObject())); @@ -710,87 +709,13 @@ PyObject* DocumentObjectPy::getPathsByOutList(PyObject *args) } } -PyObject *DocumentObjectPy::getCustomAttributes(const char* attr) const +PyObject *DocumentObjectPy::getCustomAttributes(const char* ) const { - // Dynamic property is now directly supported in PropertyContainer. So we - // can comment out here and let PropertyContainerPy handle it. -#if 1 - (void)attr; -#else - // search for dynamic property - Property* prop = getDocumentObjectPtr()->getDynamicPropertyByName(attr); - if (prop) - return prop->getPyObject(); - else -#endif return nullptr; } - -int DocumentObjectPy::setCustomAttributes(const char* attr, PyObject *obj) +//remove +int DocumentObjectPy::setCustomAttributes(const char* , PyObject *) { - // The following code is practically the same as in PropertyContainerPy, - // especially since now dynamic property is directly supported in - // PropertyContainer. So we can comment out here and let PropertyContainerPy - // handle it. -#if 1 - (void)attr; - (void)obj; -#else - // explicitly search for dynamic property - try { - Property* prop = getDocumentObjectPtr()->getDynamicPropertyByName(attr); - if (prop) { - if(prop->testStatus(Property::Immutable)) { - std::stringstream s; - s << "'DocumentObject' attribute '" << attr << "' is read-only"; - throw Py::AttributeError(s.str()); - } - prop->setPyObject(obj); - return 1; - } - } - catch (Base::ValueError &exc) { - std::stringstream s; - s << "Property '" << attr << "': " << exc.what(); - throw Py::ValueError(s.str()); - } - catch (Base::Exception &exc) { - std::stringstream s; - s << "Attribute (Name: " << attr << ") error: '" << exc.what() << "' "; - throw Py::AttributeError(s.str()); - } - catch (Py::AttributeError &) { - throw; - }catch (...) { - std::stringstream s; - s << "Unknown error in attribute " << attr; - throw Py::AttributeError(s.str()); - } - - // search in PropertyList - Property *prop = getDocumentObjectPtr()->getPropertyByName(attr); - if (prop) { - // Read-only attributes must not be set over its Python interface - if(prop->testStatus(Property::Immutable) || - (getDocumentObjectPtr()->getPropertyType(prop) & Prop_ReadOnly)) - { - std::stringstream s; - s << "'DocumentObject' attribute '" << attr << "' is read-only"; - throw Py::AttributeError(s.str()); - } - - try { - prop->setPyObject(obj); - } - catch (const Base::TypeError& e) { - std::stringstream s; - s << "Property '" << prop->getName() << "': " << e.what(); - throw Py::TypeError(s.str()); - } - return 1; - } -#endif - return 0; } diff --git a/src/App/DocumentObserver.cpp b/src/App/DocumentObserver.cpp index dfc4eeac59..eead2a0769 100644 --- a/src/App/DocumentObserver.cpp +++ b/src/App/DocumentObserver.cpp @@ -35,9 +35,7 @@ using namespace App; namespace sp = std::placeholders; -DocumentT::DocumentT() -{ -} +DocumentT::DocumentT() = default; DocumentT::DocumentT(Document* doc) { @@ -54,9 +52,7 @@ DocumentT::DocumentT(const DocumentT& doc) document = doc.document; } -DocumentT::~DocumentT() -{ -} +DocumentT::~DocumentT() = default; void DocumentT::operator=(const DocumentT& doc) { @@ -94,9 +90,7 @@ std::string DocumentT::getDocumentPython() const // ----------------------------------------------------------------------------- -DocumentObjectT::DocumentObjectT() -{ -} +DocumentObjectT::DocumentObjectT() = default; DocumentObjectT::DocumentObjectT(const DocumentObjectT &other) { @@ -133,9 +127,7 @@ DocumentObjectT::DocumentObjectT(const char *docName, const char *objName) object = objName; } -DocumentObjectT::~DocumentObjectT() -{ -} +DocumentObjectT::~DocumentObjectT() = default; DocumentObjectT &DocumentObjectT::operator=(const DocumentObjectT& obj) { @@ -251,7 +243,7 @@ std::string DocumentObjectT::getPropertyPython() const { std::stringstream str; str << getObjectPython(); - if (property.size()) + if (!property.empty()) str << '.' << property; return str.str(); } @@ -265,8 +257,7 @@ Property *DocumentObjectT::getProperty() const { // ----------------------------------------------------------------------------- -SubObjectT::SubObjectT() -{} +SubObjectT::SubObjectT() = default; SubObjectT::SubObjectT(const SubObjectT &other) :DocumentObjectT(other), subname(other.subname) @@ -431,7 +422,7 @@ std::string SubObjectT::getObjectFullName(const char *docName) const ss << "#"; } ss << getObjectName(); - if (getObjectLabel().size() && getObjectLabel() != getObjectName()) + if (!getObjectLabel().empty() && getObjectLabel() != getObjectName()) ss << " (" << getObjectLabel() << ")"; return ss.str(); } @@ -553,7 +544,7 @@ std::string PropertyLinkT::getPropertyPython() const class DocumentWeakPtrT::Private { public: - Private(App::Document* doc) : _document(doc) { + explicit Private(App::Document* doc) : _document(doc) { if (doc) { connectApplicationDeletedDocument = App::GetApplication().signalDeleteDocument.connect(std::bind (&Private::deletedDocument, this, sp::_1)); @@ -579,9 +570,7 @@ DocumentWeakPtrT::DocumentWeakPtrT(App::Document* doc) noexcept { } -DocumentWeakPtrT::~DocumentWeakPtrT() -{ -} +DocumentWeakPtrT::~DocumentWeakPtrT() = default; void DocumentWeakPtrT::reset() noexcept { @@ -607,7 +596,7 @@ App::Document* DocumentWeakPtrT::operator->() const noexcept class DocumentObjectWeakPtrT::Private { public: - Private(App::DocumentObject* obj) : object(obj), indocument(false) { + explicit Private(App::DocumentObject* obj) : object(obj), indocument(false) { set(obj); } void deletedDocument(const App::Document& doc) { @@ -664,10 +653,7 @@ DocumentObjectWeakPtrT::DocumentObjectWeakPtrT(App::DocumentObject* obj) { } -DocumentObjectWeakPtrT::~DocumentObjectWeakPtrT() -{ - -} +DocumentObjectWeakPtrT::~DocumentObjectWeakPtrT() = default; App::DocumentObject* DocumentObjectWeakPtrT::_get() const noexcept { @@ -809,13 +795,9 @@ void DocumentObserver::slotRecomputedDocument(const Document& /*doc*/) // ----------------------------------------------------------------------------- -DocumentObjectObserver::DocumentObjectObserver() -{ -} +DocumentObjectObserver::DocumentObjectObserver() = default; -DocumentObjectObserver::~DocumentObjectObserver() -{ -} +DocumentObjectObserver::~DocumentObjectObserver() = default; DocumentObjectObserver::const_iterator DocumentObjectObserver::begin() const { diff --git a/src/App/DocumentObserver.h b/src/App/DocumentObserver.h index 2ac41a868f..62a7a9c9f3 100644 --- a/src/App/DocumentObserver.h +++ b/src/App/DocumentObserver.h @@ -49,9 +49,9 @@ public: /*! Constructor */ DocumentT(); /*! Constructor */ - DocumentT(Document*); + DocumentT(Document*); // explicit bombs /*! Constructor */ - DocumentT(const std::string&); + explicit DocumentT(const std::string&); /*! Constructor */ DocumentT(const DocumentT&); /*! Destructor */ @@ -99,13 +99,13 @@ public: /*! Constructor */ DocumentObjectT(DocumentObjectT &&); /*! Constructor */ - DocumentObjectT(const DocumentObject*); + explicit DocumentObjectT(const DocumentObject*); /*! Constructor */ DocumentObjectT(const Document*, const std::string& objName); /*! Constructor */ DocumentObjectT(const char *docName, const char *objName); /*! Constructor */ - DocumentObjectT(const Property*); + explicit DocumentObjectT(const Property*); /*! Destructor */ ~DocumentObjectT(); /*! Assignment operator */ @@ -177,7 +177,7 @@ public: SubObjectT(const DocumentObject*, const char *subname); /*! Constructor */ - SubObjectT(const DocumentObject*); + SubObjectT(const DocumentObject*);// explicit bombs /*! Constructor */ SubObjectT(const char *docName, const char *objName, const char *subname); @@ -257,13 +257,13 @@ public: PropertyLinkT(); /*! Constructor */ - PropertyLinkT(DocumentObject *obj); + explicit PropertyLinkT(DocumentObject *obj); /*! Constructor */ PropertyLinkT(DocumentObject *obj, const std::vector& subNames); /*! Constructor */ - PropertyLinkT(const std::vector& objs); + explicit PropertyLinkT(const std::vector& objs); /*! Constructor */ PropertyLinkT(const std::vector& objs, const std::vector& subNames); @@ -281,7 +281,7 @@ private: class AppExport DocumentWeakPtrT { public: - DocumentWeakPtrT(App::Document*) noexcept; + explicit DocumentWeakPtrT(App::Document*) noexcept; ~DocumentWeakPtrT(); /*! @@ -320,7 +320,7 @@ private: class AppExport DocumentObjectWeakPtrT { public: - DocumentObjectWeakPtrT(App::DocumentObject*); + explicit DocumentObjectWeakPtrT(App::DocumentObject*); ~DocumentObjectWeakPtrT(); /*! @@ -383,10 +383,9 @@ template class WeakPtrT { public: - WeakPtrT(T* t) : ptr(t) { - } - ~WeakPtrT() { + explicit WeakPtrT(T* t) : ptr(t) { } + ~WeakPtrT() = default; /*! * \brief reset @@ -467,7 +466,7 @@ class AppExport DocumentObserver public: /// Constructor DocumentObserver(); - DocumentObserver(Document*); + explicit DocumentObserver(Document*); virtual ~DocumentObserver(); /** Attaches to another document, the old document @@ -527,7 +526,7 @@ public: /// Constructor DocumentObjectObserver(); - virtual ~DocumentObjectObserver(); + ~DocumentObjectObserver() override; const_iterator begin() const; const_iterator end() const; @@ -536,15 +535,15 @@ public: private: /** Checks if a new document was created */ - virtual void slotCreatedDocument(const App::Document& Doc); + void slotCreatedDocument(const App::Document& Doc) override; /** Checks if the given document is about to be closed */ - virtual void slotDeletedDocument(const App::Document& Doc); + void slotDeletedDocument(const App::Document& Doc) override; /** Checks if a new object was added. */ - virtual void slotCreatedObject(const App::DocumentObject& Obj); + void slotCreatedObject(const App::DocumentObject& Obj) override; /** Checks if the given object is about to be removed. */ - virtual void slotDeletedObject(const App::DocumentObject& Obj); + void slotDeletedObject(const App::DocumentObject& Obj) override; /** The property of an observed object has changed */ - virtual void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); + void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) override; /** This method gets called when all observed objects are deleted or the whole document is deleted. * This method can be re-implemented to perform an extra step like closing a dialog that observes * a document. diff --git a/src/App/DocumentObserverPython.cpp b/src/App/DocumentObserverPython.cpp index bc8a01a51a..8032a714af 100644 --- a/src/App/DocumentObserverPython.cpp +++ b/src/App/DocumentObserverPython.cpp @@ -114,9 +114,7 @@ DocumentObserverPython::DocumentObserverPython(const Py::Object& obj) : inst(obj FC_PY_ELEMENT_ARG2(AddedDynamicExtension, AddedDynamicExtension) } -DocumentObserverPython::~DocumentObserverPython() -{ -} +DocumentObserverPython::~DocumentObserverPython() = default; void DocumentObserverPython::slotCreatedDocument(const App::Document& Doc) { @@ -255,8 +253,8 @@ void DocumentObserverPython::slotCloseTransaction(bool abort) } } -void DocumentObserverPython::slotBeforeChangeDocument(const App::Document& Doc, const App::Property& Prop) -{ +void DocumentObserverPython::slotBeforeChangeDocument(const App::Document& Doc, const App::Property& Prop) +{ Base::PyGILStateLocker lock; try { Py::Tuple args(2); @@ -275,7 +273,7 @@ void DocumentObserverPython::slotBeforeChangeDocument(const App::Document& Doc, } } -void DocumentObserverPython::slotChangedDocument(const App::Document& Doc, const App::Property& Prop) +void DocumentObserverPython::slotChangedDocument(const App::Document& Doc, const App::Property& Prop) { Base::PyGILStateLocker lock; try { @@ -489,7 +487,7 @@ void DocumentObserverPython::slotRemoveDynamicProperty(const App::Property& Prop catch (Py::Exception&) { Base::PyException e; // extract the Python error text e.ReportException(); - } + } } void DocumentObserverPython::slotChangePropertyEditor(const App::Document &, const App::Property& Prop) diff --git a/src/App/DocumentPyImp.cpp b/src/App/DocumentPyImp.cpp index b7caacbe9a..42613447ef 100644 --- a/src/App/DocumentPyImp.cpp +++ b/src/App/DocumentPyImp.cpp @@ -41,7 +41,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string DocumentPy::representation(void) const +std::string DocumentPy::representation() const { std::stringstream str; str << ""; @@ -275,7 +275,9 @@ PyObject* DocumentPy::addObject(PyObject *args, PyObject *kwd) if (pyvp.hasAttr("__vobject__")) { pyvp.setAttr("__vobject__", pyftr.getAttr("ViewObject")); } - pyftr.getAttr("ViewObject").setAttr("Proxy", pyvp); + + Py::Object pyprx(pyftr.getAttr("ViewObject")); + pyprx.setAttr("Proxy", pyvp); return Py::new_reference_to(pyftr); } catch (Py::Exception& e) { @@ -642,7 +644,7 @@ PyObject* DocumentPy::findObjects(PyObject *args, PyObject *kwds) return list; } -Py::Object DocumentPy::getActiveObject(void) const +Py::Object DocumentPy::getActiveObject() const { DocumentObject *pcFtr = getDocumentPtr()->getActiveObject(); if (pcFtr) @@ -663,7 +665,7 @@ PyObject* DocumentPy::supportedTypes(PyObject *args) return Py::new_reference_to(res); } -Py::List DocumentPy::getObjects(void) const +Py::List DocumentPy::getObjects() const { std::vector objs = getDocumentPtr()->getObjects(); Py::List res; @@ -675,7 +677,7 @@ Py::List DocumentPy::getObjects(void) const return res; } -Py::List DocumentPy::getTopologicalSortedObjects(void) const +Py::List DocumentPy::getTopologicalSortedObjects() const { std::vector objs = getDocumentPtr()->topologicalSort(); Py::List res; @@ -687,7 +689,7 @@ Py::List DocumentPy::getTopologicalSortedObjects(void) const return res; } -Py::List DocumentPy::getRootObjects(void) const +Py::List DocumentPy::getRootObjects() const { std::vector objs = getDocumentPtr()->getRootObjects(); Py::List res; @@ -699,7 +701,7 @@ Py::List DocumentPy::getRootObjects(void) const return res; } -Py::Int DocumentPy::getUndoMode(void) const +Py::Int DocumentPy::getUndoMode() const { return Py::Int(getDocumentPtr()->getUndoMode()); } @@ -710,22 +712,22 @@ void DocumentPy::setUndoMode(Py::Int arg) } -Py::Int DocumentPy::getUndoRedoMemSize(void) const +Py::Int DocumentPy::getUndoRedoMemSize() const { return Py::Int((long)getDocumentPtr()->getUndoMemSize()); } -Py::Int DocumentPy::getUndoCount(void) const +Py::Int DocumentPy::getUndoCount() const { return Py::Int((long)getDocumentPtr()->getAvailableUndos()); } -Py::Int DocumentPy::getRedoCount(void) const +Py::Int DocumentPy::getRedoCount() const { return Py::Int((long)getDocumentPtr()->getAvailableRedos()); } -Py::List DocumentPy::getUndoNames(void) const +Py::List DocumentPy::getUndoNames() const { std::vector vList = getDocumentPtr()->getAvailableUndoNames(); Py::List res; @@ -736,7 +738,7 @@ Py::List DocumentPy::getUndoNames(void) const return res; } -Py::List DocumentPy::getRedoNames(void) const +Py::List DocumentPy::getRedoNames() const { std::vector vList = getDocumentPtr()->getAvailableRedoNames(); Py::List res; @@ -747,19 +749,19 @@ Py::List DocumentPy::getRedoNames(void) const return res; } -Py::String DocumentPy::getDependencyGraph(void) const +Py::String DocumentPy::getDependencyGraph() const { std::stringstream out; getDocumentPtr()->exportGraphviz(out); return Py::String(out.str()); } -Py::String DocumentPy::getName(void) const +Py::String DocumentPy::getName() const { return Py::String(getDocumentPtr()->getName()); } -Py::Boolean DocumentPy::getRecomputesFrozen(void) const +Py::Boolean DocumentPy::getRecomputesFrozen() const { return Py::Boolean(getDocumentPtr()->testStatus(Document::Status::SkipRecompute)); } @@ -808,7 +810,7 @@ PyObject *DocumentPy::getCustomAttributes(const char* attr) const App::Property* prop = getPropertyContainerPtr()->getPropertyByName(attr); if (prop) return nullptr; - if (this->ob_type->tp_dict == nullptr) { + if (!this->ob_type->tp_dict) { if (PyType_Ready(this->ob_type) < 0) return nullptr; } @@ -830,7 +832,7 @@ int DocumentPy::setCustomAttributes(const char* attr, PyObject *) App::Property* prop = getPropertyContainerPtr()->getPropertyByName(attr); if (prop) return 0; - if (this->ob_type->tp_dict == nullptr) { + if (!this->ob_type->tp_dict) { if (PyType_Ready(this->ob_type) < 0) return 0; } @@ -877,7 +879,7 @@ PyObject* DocumentPy::getLinksTo(PyObject *args) } PY_CATCH } -Py::List DocumentPy::getInList(void) const +Py::List DocumentPy::getInList() const { Py::List ret; auto lists = PropertyXLink::getDocumentInList(getDocumentPtr()); @@ -888,7 +890,7 @@ Py::List DocumentPy::getInList(void) const return ret; } -Py::List DocumentPy::getOutList(void) const +Py::List DocumentPy::getOutList() const { Py::List ret; auto lists = PropertyXLink::getDocumentOutList(getDocumentPtr()); @@ -912,22 +914,22 @@ PyObject *DocumentPy::getDependentDocuments(PyObject *args) { } PY_CATCH; } -Py::Boolean DocumentPy::getRestoring(void) const +Py::Boolean DocumentPy::getRestoring() const { return Py::Boolean(getDocumentPtr()->testStatus(Document::Status::Restoring)); } -Py::Boolean DocumentPy::getPartial(void) const +Py::Boolean DocumentPy::getPartial() const { return Py::Boolean(getDocumentPtr()->testStatus(Document::Status::PartialDoc)); } -Py::Boolean DocumentPy::getImporting(void) const +Py::Boolean DocumentPy::getImporting() const { return Py::Boolean(getDocumentPtr()->testStatus(Document::Status::Importing)); } -Py::Boolean DocumentPy::getRecomputing(void) const +Py::Boolean DocumentPy::getRecomputing() const { return Py::Boolean(getDocumentPtr()->testStatus(Document::Status::Recomputing)); } diff --git a/src/App/DynamicProperty.cpp b/src/App/DynamicProperty.cpp index 821d09c873..7ad6419b33 100644 --- a/src/App/DynamicProperty.cpp +++ b/src/App/DynamicProperty.cpp @@ -39,9 +39,7 @@ FC_LOG_LEVEL_INIT("Property",true,true) using namespace App; -DynamicProperty::DynamicProperty() -{ -} +DynamicProperty::DynamicProperty() = default; DynamicProperty::~DynamicProperty() { @@ -174,7 +172,7 @@ Property* DynamicProperty::addDynamicProperty(PropertyContainer &pc, const char* if(prop && prop->getContainer()==&pc) FC_THROWM(Base::NameError, "Property " << pc.getFullName() << '.' << name << " already exists"); - if(Base::Tools::getIdentifier(name) != name) + if(Base::Tools::getIdentifier(name) != name) FC_THROWM(Base::NameError, "Invalid property name '" << name << "'"); Base::Type propType = Base::Type::getTypeIfDerivedFrom(type, App::Property::getClassTypeId(), true); diff --git a/src/App/Enumeration.cpp b/src/App/Enumeration.cpp index affad5084a..1d85767232 100644 --- a/src/App/Enumeration.cpp +++ b/src/App/Enumeration.cpp @@ -34,15 +34,15 @@ using namespace App; namespace { struct StringCopy : public Enumeration::Object { - StringCopy(const char* str) : d(str) { + explicit StringCopy(const char* str) : d(str) { } - const char* data() const { + const char* data() const override { return d.data(); } - bool isEqual(const char* str) const { + bool isEqual(const char* str) const override { return d == str; } - bool isCustom() const { + bool isCustom() const override { return true; } @@ -51,15 +51,15 @@ private: }; struct StringView : public Enumeration::Object { - StringView(const char* str) : d(str) { + explicit StringView(const char* str) : d(str) { } - const char* data() const { + const char* data() const override { return d.data(); } - bool isEqual(const char* str) const { + bool isEqual(const char* str) const override { return d == str; } - bool isCustom() const { + bool isCustom() const override { return false; } @@ -274,7 +274,7 @@ bool Enumeration::operator==(const Enumeration &other) const for (size_t i = 0; i < enumArray.size(); ++i) { if (enumArray[i]->data() == other.enumArray[i]->data()) continue; - if (enumArray[i]->data() == nullptr || other.enumArray[i]->data() == nullptr) + if (!enumArray[i]->data() || !other.enumArray[i]->data()) return false; if (!enumArray[i]->isEqual(other.enumArray[i]->data())) return false; @@ -284,7 +284,7 @@ bool Enumeration::operator==(const Enumeration &other) const bool Enumeration::operator==(const char *other) const { - if (getCStr() == nullptr) { + if (!getCStr()) { return false; } diff --git a/src/App/Enumeration.h b/src/App/Enumeration.h index 6f9912c15e..64320ac9b4 100644 --- a/src/App/Enumeration.h +++ b/src/App/Enumeration.h @@ -54,7 +54,7 @@ namespace App public: class Object { public: - virtual ~Object() {} + virtual ~Object() = default; virtual const char* data() const = 0; virtual bool isEqual(const char*) const = 0; virtual bool isCustom() const = 0; @@ -68,7 +68,7 @@ namespace App Enumeration(const Enumeration& other); /// Constructs an Enumeration with a single element - Enumeration(const char *valStr); + explicit Enumeration(const char *valStr); /// Constructs an Enumeration using val within list Enumeration(const char **list, const char *valStr); diff --git a/src/App/Expression.cpp b/src/App/Expression.cpp index a682d9422a..e269e8c360 100644 --- a/src/App/Expression.cpp +++ b/src/App/Expression.cpp @@ -380,7 +380,7 @@ struct PyObjectWrapper { public: typedef std::shared_ptr Pointer; - PyObjectWrapper(PyObject *obj):pyobj(obj) { + explicit PyObjectWrapper(PyObject *obj):pyobj(obj) { Py::_XINCREF(pyobj); } ~PyObjectWrapper() { @@ -909,7 +909,7 @@ ExpressionDeps Expression::getDeps(int option) const { } void Expression::getDepObjects( - std::map &deps, std::vector *labels) const + std::map &deps, std::vector *labels) const { for(auto &v : getIdentifiers()) { bool hidden = v.second; @@ -940,11 +940,11 @@ std::map Expression::getDepObjects(std::vector &deps) + explicit GetIdentifiersExpressionVisitor(std::map &deps) :deps(deps) {} - virtual void visit(Expression &e) { + void visit(Expression &e) override { this->getIdentifiers(e,deps); } @@ -964,11 +964,11 @@ std::map Expression::getIdentifiers() const { class AdjustLinksExpressionVisitor : public ExpressionVisitor { public: - AdjustLinksExpressionVisitor(const std::set &inList) + explicit AdjustLinksExpressionVisitor(const std::set &inList) :inList(inList),res(false) {} - virtual void visit(Expression &e) { + void visit(Expression &e) override { if(this->adjustLinks(e,inList)) res = true; } @@ -985,11 +985,11 @@ bool Expression::adjustLinks(const std::set &inList) { class ImportSubNamesExpressionVisitor : public ExpressionVisitor { public: - ImportSubNamesExpressionVisitor(const ObjectIdentifier::SubNameMap &subNameMap) + explicit ImportSubNamesExpressionVisitor(const ObjectIdentifier::SubNameMap &subNameMap) :subNameMap(subNameMap) {} - virtual void visit(Expression &e) { + void visit(Expression &e) override { this->importSubNames(e,subNameMap); } @@ -1014,7 +1014,7 @@ ExpressionPtr Expression::importSubNames(const std::map continue; std::string imported = PropertyLinkBase::tryImportSubName( obj,key.second.c_str(),owner->getDocument(), nameMap); - if(imported.size()) + if(!imported.empty()) subNameMap.emplace(std::move(key),std::move(imported)); } } @@ -1033,7 +1033,7 @@ public: :obj(obj),ref(ref),newLabel(newLabel) {} - virtual void visit(Expression &e) { + void visit(Expression &e) override { this->updateLabelReference(e,obj,ref,newLabel); } @@ -1070,7 +1070,7 @@ public: { } - void visit(Expression &e) { + void visit(Expression &e) override { if(collect) this->collectReplacement(e,paths,parent,oldObj,newObj); else @@ -1112,7 +1112,7 @@ App::any Expression::getValueAsAny() const { Py::Object Expression::getPyValue() const { try { Py::Object pyobj = _getPyValue(); - if(components.size()) { + if(!components.empty()) { for(auto &c : components) pyobj = c->get(this,pyobj); } @@ -1698,7 +1698,7 @@ TYPESYSTEM_SOURCE(App::FunctionExpression, App::UnitExpression) static int _HiddenReference; struct HiddenReference { - HiddenReference(bool cond) + explicit HiddenReference(bool cond) :cond(cond) { if(cond) @@ -1772,7 +1772,7 @@ FunctionExpression::FunctionExpression(const DocumentObject *_owner, Function _f case MAX: case CREATE: case MSCALE: - if (args.size() == 0) + if (args.empty()) EXPR_THROW("Invalid number of arguments: at least one required."); break; case LIST: @@ -1821,7 +1821,7 @@ bool FunctionExpression::isTouched() const class Collector { public: Collector() : first(true) { } - virtual ~Collector() {} + virtual ~Collector() = default; virtual void collect(Quantity value) { if (first) q.setUnit(value.getUnit()); @@ -1838,7 +1838,7 @@ class SumCollector : public Collector { public: SumCollector() : Collector() { } - void collect(Quantity value) { + void collect(Quantity value) override { Collector::collect(value); q += value; first = false; @@ -1850,14 +1850,14 @@ class AverageCollector : public Collector { public: AverageCollector() : Collector(), n(0) { } - void collect(Quantity value) { + void collect(Quantity value) override { Collector::collect(value); q += value; ++n; first = false; } - virtual Quantity getQuantity() const { return q/(double)n; } + Quantity getQuantity() const override { return q/(double)n; } private: unsigned int n; @@ -1867,7 +1867,7 @@ class StdDevCollector : public Collector { public: StdDevCollector() : Collector(), n(0) { } - void collect(Quantity value) { + void collect(Quantity value) override { Collector::collect(value); if (first) { M2 = Quantity(0, value.getUnit() * value.getUnit()); @@ -1882,7 +1882,7 @@ public: first = false; } - virtual Quantity getQuantity() const { + Quantity getQuantity() const override { if (n < 2) throw ExpressionError("Invalid number of entries: at least two required."); else @@ -1899,13 +1899,13 @@ class CountCollector : public Collector { public: CountCollector() : Collector(), n(0) { } - void collect(Quantity value) { + void collect(Quantity value) override { Collector::collect(value); ++n; first = false; } - virtual Quantity getQuantity() const { return Quantity(n); } + Quantity getQuantity() const override { return Quantity(n); } private: unsigned int n; @@ -1915,7 +1915,7 @@ class MinCollector : public Collector { public: MinCollector() : Collector() { } - void collect(Quantity value) { + void collect(Quantity value) override { Collector::collect(value); if (first || value < q) q = value; @@ -1927,7 +1927,7 @@ class MaxCollector : public Collector { public: MaxCollector() : Collector() { } - void collect(Quantity value) { + void collect(Quantity value) override { Collector::collect(value); if (first || value > q) q = value; @@ -1976,11 +1976,11 @@ Py::Object FunctionExpression::evalAggregate( if (!p) continue; - if ((qp = freecad_dynamic_cast(p)) != nullptr) + if ((qp = freecad_dynamic_cast(p))) c->collect(qp->getQuantityValue()); - else if ((fp = freecad_dynamic_cast(p)) != nullptr) + else if ((fp = freecad_dynamic_cast(p))) c->collect(Quantity(fp->getValue())); - else if ((ip = freecad_dynamic_cast(p)) != nullptr) + else if ((ip = freecad_dynamic_cast(p))) c->collect(Quantity(ip->getValue())); else _EXPR_THROW("Invalid property type for aggregate.", owner); @@ -2493,9 +2493,7 @@ VariableExpression::VariableExpression(const DocumentObject *_owner, const Objec { } -VariableExpression::~VariableExpression() -{ -} +VariableExpression::~VariableExpression() = default; /** * Determine if the expression is touched or not, i.e whether the Property object it @@ -2533,7 +2531,7 @@ const Property * VariableExpression::getProperty() const void VariableExpression::addComponent(Component *c) { do { - if(components.size()) + if(!components.empty()) break; if(!c->e1 && !c->e2) { var << c->comp; @@ -2858,7 +2856,7 @@ Expression *ConditionalExpression::simplify() const std::unique_ptr e(condition->simplify()); NumberExpression * v = freecad_dynamic_cast(e.get()); - if (v == nullptr) + if (!v) return new ConditionalExpression(owner, condition->simplify(), trueExpr->simplify(), falseExpr->simplify()); else { if (fabs(v->getValue()) > 0.5) @@ -3193,7 +3191,7 @@ static int column; // show the parser the lexer method #define yylex ExpressionParserlex -int ExpressionParserlex(void); +int ExpressionParserlex(); // Parser, defined in ExpressionParser.y # define YYTOKENTYPE @@ -3286,7 +3284,7 @@ std::vector > tokenize(const std::string &str) column = 0; try { while ( (token = ExpressionParserlex()) != 0) - result.push_back(std::make_tuple(token, ExpressionParser::last_column, yytext)); + result.emplace_back(token, ExpressionParser::last_column, yytext); } catch (...) { // Ignore all exceptions @@ -3327,7 +3325,7 @@ Expression * App::ExpressionParser::parse(const App::DocumentObject *owner, cons if (result != 0) throw ParserError("Failed to parse expression."); - if (ScanResult == nullptr) + if (!ScanResult) throw ParserError("Unknown error in expression"); if (valueExpression) @@ -3355,7 +3353,7 @@ UnitExpression * ExpressionParser::parseUnit(const App::DocumentObject *owner, c if (result != 0) throw ParserError("Failed to parse expression."); - if (ScanResult == nullptr) + if (!ScanResult) throw ParserError("Unknown error in expression"); // Simplify expression diff --git a/src/App/Expression.h b/src/App/Expression.h index 2e45116b63..88bad3e2b8 100644 --- a/src/App/Expression.h +++ b/src/App/Expression.h @@ -55,7 +55,7 @@ typedef std::map &); + void getIdentifiers(Expression &e, std::map &); bool adjustLinks(Expression &e, const std::set &inList); bool relabeledDocument(Expression &e, const std::string &oldName, const std::string &newName); bool renameObjectIdentifier(Expression &e, const std::map &, const ObjectIdentifier &); - void collectReplacement(Expression &e, std::map &, + void collectReplacement(Expression &e, std::map &, const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const; bool updateElementReference(Expression &e, App::DocumentObject *feature,bool reverse); void importSubNames(Expression &e, const ObjectIdentifier::SubNameMap &subNameMap); - void updateLabelReference(Expression &e, App::DocumentObject *obj, + void updateLabelReference(Expression &e, App::DocumentObject *obj, const std::string &ref, const char *newLabel); void moveCells(Expression &e, const CellAddress &address, int rowCount, int colCount); void offsetCells(Expression &e, int rowOffset, int colOffset); @@ -80,25 +80,25 @@ protected: template class ExpressionModifier : public ExpressionVisitor { public: - ExpressionModifier(P & _prop) + explicit ExpressionModifier(P & _prop) : prop(_prop) , propLink(Base::freecad_dynamic_cast(&prop)) , signaller(_prop,false) - , _changed(0) + , _changed(0) {} - virtual ~ExpressionModifier() { } + ~ExpressionModifier() override = default; - virtual void aboutToChange() override{ + void aboutToChange() override{ ++_changed; signaller.aboutToChange(); } - virtual int changed() const override { return _changed; } + int changed() const override { return _changed; } - virtual void reset() override {_changed = 0;} + void reset() override {_changed = 0;} - virtual App::PropertyLinkBase* getPropertyLink() override {return propLink;} + App::PropertyLinkBase* getPropertyLink() override {return propLink;} protected: P & prop; @@ -113,13 +113,13 @@ protected: */ class AppExport Expression : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - Expression(const App::DocumentObject * _owner); + explicit Expression(const App::DocumentObject * _owner); - virtual ~Expression(); + ~Expression() override; virtual bool isTouched() const { return false; } @@ -150,7 +150,7 @@ public: ExpressionPtr importSubNames(const std::map &nameMap) const; - ExpressionPtr updateLabelReference(App::DocumentObject *obj, + ExpressionPtr updateLabelReference(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const; ExpressionPtr replaceObject(const App::DocumentObject *parent, @@ -164,7 +164,7 @@ public: class Exception : public Base::Exception { public: - Exception(const char *sMessage) : Base::Exception(sMessage) { } + explicit Exception(const char *sMessage) : Base::Exception(sMessage) { } }; App::DocumentObject * getOwner() const { return owner; } @@ -186,7 +186,7 @@ public: bool isSame(const Expression &other, bool checkComment=true) const; - friend ExpressionVisitor; + friend class ExpressionVisitor; protected: virtual bool _isIndexable() const {return false;} @@ -198,10 +198,10 @@ protected: virtual bool _relabeledDocument(const std::string &, const std::string &, ExpressionVisitor &) {return false;} virtual void _importSubNames(const ObjectIdentifier::SubNameMap &) {} virtual void _updateLabelReference(App::DocumentObject *, const std::string &, const char *) {} - virtual bool _renameObjectIdentifier(const std::map &, + virtual bool _renameObjectIdentifier(const std::map &, const ObjectIdentifier &, ExpressionVisitor &) {return false;} virtual void _collectReplacement(std::map &, - const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const + const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const { (void)parent; (void)oldObj; diff --git a/src/App/ExpressionParser.h b/src/App/ExpressionParser.h index 72f4254ae6..d569c86bcc 100644 --- a/src/App/ExpressionParser.h +++ b/src/App/ExpressionParser.h @@ -43,9 +43,9 @@ struct AppExport Expression::Component { Expression* e2; Expression* e3; - Component(const std::string &n); + explicit Component(const std::string &n); Component(Expression *e1, Expression *e2, Expression *e3, bool isRange=false); - Component(const ObjectIdentifier::Component &comp); + explicit Component(const ObjectIdentifier::Component &comp); Component(const Component &other); ~Component(); Component &operator=(const Component &)=delete; @@ -71,11 +71,11 @@ struct AppExport Expression::Component { class AppExport UnitExpression : public Expression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - UnitExpression(const App::DocumentObject *_owner = nullptr, const Base::Quantity & _quantity = Base::Quantity(), const std::string & _unitStr = std::string()); + explicit UnitExpression(const App::DocumentObject *_owner = nullptr, const Base::Quantity & _quantity = Base::Quantity(), const std::string & _unitStr = std::string()); - ~UnitExpression(); + ~UnitExpression() override; - virtual Expression * simplify() const override; + Expression * simplify() const override; void setUnit(const Base::Quantity &_quantity); @@ -92,9 +92,9 @@ public: double getScaler() const { return quantity.getValue(); } protected: - virtual Expression * _copy() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual Py::Object _getPyValue() const override; + Expression * _copy() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + Py::Object _getPyValue() const override; protected: mutable PyObject *cache = nullptr; @@ -111,23 +111,23 @@ private: class AppExport NumberExpression : public UnitExpression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - NumberExpression(const App::DocumentObject *_owner = nullptr, const Base::Quantity & quantity = Base::Quantity()); + explicit NumberExpression(const App::DocumentObject *_owner = nullptr, const Base::Quantity & quantity = Base::Quantity()); - virtual Expression * simplify() const override; + Expression * simplify() const override; void negate(); bool isInteger(long *v=nullptr) const; protected: - virtual Expression * _copy() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; + Expression * _copy() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; }; class AppExport ConstantExpression : public NumberExpression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - ConstantExpression(const App::DocumentObject *_owner = nullptr, + explicit ConstantExpression(const App::DocumentObject *_owner = nullptr, const char *_name = "", const Base::Quantity &_quantity = Base::Quantity()); @@ -136,9 +136,9 @@ public: bool isNumber() const; protected: - virtual Py::Object _getPyValue() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual Expression* _copy() const override; + Py::Object _getPyValue() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + Expression* _copy() const override; protected: const char *name; @@ -170,15 +170,15 @@ public: NEG, POS }; - OperatorExpression(const App::DocumentObject *_owner = nullptr, Expression * _left = nullptr, Operator _op = NONE, Expression * _right = nullptr); + explicit OperatorExpression(const App::DocumentObject *_owner = nullptr, Expression * _left = nullptr, Operator _op = NONE, Expression * _right = nullptr); - virtual ~OperatorExpression(); + ~OperatorExpression() override; - virtual bool isTouched() const override; + bool isTouched() const override; - virtual Expression * simplify() const override; + Expression * simplify() const override; - virtual int priority() const override; + int priority() const override; Operator getOperator() const { return op; } @@ -187,13 +187,13 @@ public: Expression * getRight() const { return right; } protected: - virtual Expression * _copy() const override; + Expression * _copy() const override; - virtual Py::Object _getPyValue() const override; + Py::Object _getPyValue() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual void _visit(ExpressionVisitor & v) override; + void _visit(ExpressionVisitor & v) override; virtual bool isCommutative() const; @@ -209,21 +209,21 @@ protected: class AppExport ConditionalExpression : public Expression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - ConditionalExpression(const App::DocumentObject *_owner = nullptr, Expression * _condition = nullptr,Expression * _trueExpr = nullptr, Expression * _falseExpr = nullptr); + explicit ConditionalExpression(const App::DocumentObject *_owner = nullptr, Expression * _condition = nullptr,Expression * _trueExpr = nullptr, Expression * _falseExpr = nullptr); - virtual ~ConditionalExpression(); + ~ConditionalExpression() override; - virtual bool isTouched() const override; + bool isTouched() const override; - virtual Expression * simplify() const override; + Expression * simplify() const override; - virtual int priority() const override; + int priority() const override; protected: - virtual Expression * _copy() const override; - virtual void _visit(ExpressionVisitor & v) override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual Py::Object _getPyValue() const override; + Expression * _copy() const override; + void _visit(ExpressionVisitor & v) override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + Py::Object _getPyValue() const override; protected: @@ -290,14 +290,14 @@ public: LAST, }; - FunctionExpression(const App::DocumentObject *_owner = nullptr, Function _f = NONE, + explicit FunctionExpression(const App::DocumentObject *_owner = nullptr, Function _f = NONE, std::string &&name = std::string(), std::vector _args = std::vector()); - virtual ~FunctionExpression(); + ~FunctionExpression() override; - virtual bool isTouched() const override; + bool isTouched() const override; - virtual Expression * simplify() const override; + Expression * simplify() const override; static Py::Object evaluate(const Expression *owner, int type, const std::vector &args); @@ -306,10 +306,10 @@ public: protected: static Py::Object evalAggregate(const Expression *owner, int type, const std::vector &args); - virtual Py::Object _getPyValue() const override; - virtual Expression * _copy() const override; - virtual void _visit(ExpressionVisitor & v) override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; + Py::Object _getPyValue() const override; + Expression * _copy() const override; + void _visit(ExpressionVisitor & v) override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; Function f; /**< Function to execute */ std::string fname; @@ -327,13 +327,13 @@ protected: class AppExport VariableExpression : public UnitExpression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - VariableExpression(const App::DocumentObject *_owner = nullptr, const ObjectIdentifier& _var = ObjectIdentifier()); + explicit VariableExpression(const App::DocumentObject *_owner = nullptr, const ObjectIdentifier& _var = ObjectIdentifier()); - ~VariableExpression(); + ~VariableExpression() override; - virtual bool isTouched() const override; + bool isTouched() const override; - virtual Expression * simplify() const override; + Expression * simplify() const override; std::string name() const { return var.getPropertyName(); } @@ -343,26 +343,26 @@ public: const App::Property *getProperty() const; - virtual void addComponent(Component* component) override; + void addComponent(Component* component) override; protected: - virtual Expression * _copy() const override; - virtual Py::Object _getPyValue() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual bool _isIndexable() const override; - virtual void _getIdentifiers(std::map &) const override; - virtual bool _adjustLinks(const std::set &, ExpressionVisitor &) override; - virtual void _importSubNames(const ObjectIdentifier::SubNameMap &) override; - virtual void _updateLabelReference(App::DocumentObject *, const std::string &, const char *) override; - virtual bool _updateElementReference(App::DocumentObject *,bool,ExpressionVisitor &) override; - virtual bool _relabeledDocument(const std::string &, const std::string &, ExpressionVisitor &) override; - virtual bool _renameObjectIdentifier(const std::map &, + Expression * _copy() const override; + Py::Object _getPyValue() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + bool _isIndexable() const override; + void _getIdentifiers(std::map &) const override; + bool _adjustLinks(const std::set &, ExpressionVisitor &) override; + void _importSubNames(const ObjectIdentifier::SubNameMap &) override; + void _updateLabelReference(App::DocumentObject *, const std::string &, const char *) override; + bool _updateElementReference(App::DocumentObject *,bool,ExpressionVisitor &) override; + bool _relabeledDocument(const std::string &, const std::string &, ExpressionVisitor &) override; + bool _renameObjectIdentifier(const std::map &, const ObjectIdentifier &, ExpressionVisitor &) override; - virtual void _collectReplacement(std::map &, + void _collectReplacement(std::map &, const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - virtual void _moveCells(const CellAddress &, int, int, ExpressionVisitor &) override; - virtual void _offsetCells(int, int, ExpressionVisitor &) override; + void _moveCells(const CellAddress &, int, int, ExpressionVisitor &) override; + void _offsetCells(int, int, ExpressionVisitor &) override; protected: @@ -375,22 +375,22 @@ class AppExport PyObjectExpression : public Expression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PyObjectExpression(const App::DocumentObject *_owner=nullptr, PyObject *pyobj=nullptr, bool owned=false) + explicit PyObjectExpression(const App::DocumentObject *_owner=nullptr, PyObject *pyobj=nullptr, bool owned=false) :Expression(_owner) { setPyValue(pyobj,owned); } - virtual ~PyObjectExpression(); + ~PyObjectExpression() override; void setPyValue(Py::Object pyobj); void setPyValue(PyObject *pyobj, bool owned=false); - virtual Expression * simplify() const override { return copy(); } + Expression * simplify() const override { return copy(); } protected: - virtual Expression* _copy() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual Py::Object _getPyValue() const override; + Expression* _copy() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + Py::Object _getPyValue() const override; protected: PyObject *pyObj = nullptr; @@ -404,17 +404,17 @@ protected: class AppExport StringExpression : public Expression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - StringExpression(const App::DocumentObject *_owner = nullptr, const std::string & _text = std::string()); - ~StringExpression(); + explicit StringExpression(const App::DocumentObject *_owner = nullptr, const std::string & _text = std::string()); + ~StringExpression() override; - virtual Expression * simplify() const override; + Expression * simplify() const override; virtual std::string getText() const { return text; } protected: - virtual Expression * _copy() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual Py::Object _getPyValue() const override; - virtual bool _isIndexable() const override { return true; } + Expression * _copy() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + Py::Object _getPyValue() const override; + bool _isIndexable() const override { return true; } private: std::string text; /**< Text string */ @@ -424,25 +424,25 @@ private: class AppExport RangeExpression : public App::Expression { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - RangeExpression(const App::DocumentObject * _owner = nullptr, const std::string & begin = std::string(), const std::string & end = std::string()); + explicit RangeExpression(const App::DocumentObject * _owner = nullptr, const std::string & begin = std::string(), const std::string & end = std::string()); - virtual ~RangeExpression() { } + ~RangeExpression() override = default; - virtual bool isTouched() const override; + bool isTouched() const override; - virtual App::Expression * simplify() const override; + App::Expression * simplify() const override; Range getRange() const; protected: - virtual Expression * _copy() const override; - virtual void _toString(std::ostream &ss, bool persistent, int indent) const override; - virtual Py::Object _getPyValue() const override; - virtual void _getIdentifiers(std::map &) const override; - virtual bool _renameObjectIdentifier(const std::map &, + Expression * _copy() const override; + void _toString(std::ostream &ss, bool persistent, int indent) const override; + Py::Object _getPyValue() const override; + void _getIdentifiers(std::map &) const override; + bool _renameObjectIdentifier(const std::map &, const ObjectIdentifier &, ExpressionVisitor &) override; - virtual void _moveCells(const CellAddress &, int, int, ExpressionVisitor &) override; - virtual void _offsetCells(int, int, ExpressionVisitor &) override; + void _moveCells(const CellAddress &, int, int, ExpressionVisitor &) override; + void _offsetCells(int, int, ExpressionVisitor &) override; protected: std::string begin; @@ -460,7 +460,7 @@ AppExport std::vector > tokenize(const std::st /// Convenient class to mark begin of importing class AppExport ExpressionImporter { public: - ExpressionImporter(Base::XMLReader &reader); + explicit ExpressionImporter(Base::XMLReader &reader); ~ExpressionImporter(); static Base::XMLReader *reader(); }; diff --git a/src/App/ExpressionVisitors.h b/src/App/ExpressionVisitors.h index af1ad9d2b2..93527ac6f1 100644 --- a/src/App/ExpressionVisitors.h +++ b/src/App/ExpressionVisitors.h @@ -34,11 +34,13 @@ namespace App { template class RenameObjectIdentifierExpressionVisitor : public ExpressionModifier

{ public: - RenameObjectIdentifierExpressionVisitor(P & _prop, - const std::map &_paths, const ObjectIdentifier & _owner) + RenameObjectIdentifierExpressionVisitor( + P &_prop, + const std::map &_paths, + const ObjectIdentifier &_owner) : ExpressionModifier

(_prop) - , paths(_paths) - , owner(_owner) + , paths( _paths ) + , owner( _owner ) { } @@ -46,7 +48,6 @@ public: this->renameObjectIdentifier(node,paths,owner); } - private: const std::map &paths; /**< Map with current and new object identifiers */ const ObjectIdentifier owner; /**< Owner of expression */ @@ -55,7 +56,7 @@ private: template class UpdateElementReferenceExpressionVisitor : public ExpressionModifier

{ public: - UpdateElementReferenceExpressionVisitor(P & _prop, App::DocumentObject *feature=nullptr, bool reverse=false) + explicit UpdateElementReferenceExpressionVisitor(P & _prop, App::DocumentObject *feature=nullptr, bool reverse=false) : ExpressionModifier

(_prop),feature(feature),reverse(reverse) { } @@ -76,12 +77,12 @@ private: class RelabelDocumentExpressionVisitor : public ExpressionVisitor { public: - RelabelDocumentExpressionVisitor(const App::Document &doc) + explicit RelabelDocumentExpressionVisitor(const App::Document &doc) : doc(doc) { } - void visit(Expression &node) { + void visit(Expression &node) override { this->relabeledDocument(node,doc.getOldLabel(),doc.Label.getStrValue()); } diff --git a/src/App/Extension.cpp b/src/App/Extension.cpp index ba30561c95..fdbbe695e9 100644 --- a/src/App/Extension.cpp +++ b/src/App/Extension.cpp @@ -39,10 +39,10 @@ * PropertyData in the extension chain, there is no parent property data. */ EXTENSION_TYPESYSTEM_SOURCE_P(App::Extension) -const App::PropertyData * App::Extension::extensionGetPropertyDataPtr(void){return &propertyData;} -const App::PropertyData & App::Extension::extensionGetPropertyData(void) const{return propertyData;} +const App::PropertyData * App::Extension::extensionGetPropertyDataPtr(){return &propertyData;} +const App::PropertyData & App::Extension::extensionGetPropertyData() const{return propertyData;} App::PropertyData App::Extension::propertyData; -void App::Extension::init(void){ +void App::Extension::init(){ assert(Extension::classTypeId == Base::Type::badType() && "don't init() twice!"); @@ -95,7 +95,7 @@ void Extension::initExtension(ExtensionContainer* obj) { } -PyObject* Extension::getExtensionPyObject(void) { +PyObject* Extension::getExtensionPyObject() { if (ExtensionPythonObject.is(Py::_None())){ // ref counter is set to 1 diff --git a/src/App/ExtensionContainer.cpp b/src/App/ExtensionContainer.cpp index b2fc999ba8..855cbfa73d 100644 --- a/src/App/ExtensionContainer.cpp +++ b/src/App/ExtensionContainer.cpp @@ -36,9 +36,7 @@ using namespace App; TYPESYSTEM_SOURCE(App::ExtensionContainer, App::PropertyContainer) -ExtensionContainer::ExtensionContainer() { - -} +ExtensionContainer::ExtensionContainer() = default; ExtensionContainer::~ExtensionContainer() { @@ -204,12 +202,12 @@ short int ExtensionContainer::getPropertyType(const char* name) const { const char* ExtensionContainer::getPropertyName(const Property* prop) const { const char* res = App::PropertyContainer::getPropertyName(prop); - if(res != nullptr) + if (res) return res; - for(const auto& entry : _extensions) { + for (const auto& entry : _extensions) { res = entry.second->extensionGetPropertyName(prop); - if(res != nullptr) + if (res) return res; } @@ -219,12 +217,12 @@ const char* ExtensionContainer::getPropertyName(const Property* prop) const { const char* ExtensionContainer::getPropertyGroup(const Property* prop) const { const char* res = App::PropertyContainer::getPropertyGroup(prop); - if(res != nullptr) + if (res) return res; - for(const auto& entry : _extensions) { + for (const auto& entry : _extensions) { res = entry.second->extensionGetPropertyGroup(prop); - if(res != nullptr) + if (res) return res; } @@ -234,12 +232,12 @@ const char* ExtensionContainer::getPropertyGroup(const Property* prop) const { const char* ExtensionContainer::getPropertyGroup(const char* name) const { const char* res = App::PropertyContainer::getPropertyGroup(name); - if(res != nullptr) + if (res) return res; - for(const auto& entry : _extensions) { + for (const auto& entry : _extensions) { res = entry.second->extensionGetPropertyGroup(name); - if(res != nullptr) + if (res) return res; } @@ -250,12 +248,12 @@ const char* ExtensionContainer::getPropertyGroup(const char* name) const { const char* ExtensionContainer::getPropertyDocumentation(const Property* prop) const { const char* res = App::PropertyContainer::getPropertyDocumentation(prop); - if(res != nullptr) + if (res) return res; - for(const auto& entry : _extensions) { + for (const auto& entry : _extensions) { res = entry.second->extensionGetPropertyDocumentation(prop); - if(res != nullptr) + if (res) return res; } @@ -265,12 +263,12 @@ const char* ExtensionContainer::getPropertyDocumentation(const Property* prop) c const char* ExtensionContainer::getPropertyDocumentation(const char* name) const { const char* res = App::PropertyContainer::getPropertyDocumentation(name); - if(res != nullptr) + if (res) return res; for(const auto& entry : _extensions) { res = entry.second->extensionGetPropertyDocumentation(name); - if(res != nullptr) + if (res) return res; } diff --git a/src/App/ExtensionContainer.h b/src/App/ExtensionContainer.h index 30d28adecf..43132b5c89 100644 --- a/src/App/ExtensionContainer.h +++ b/src/App/ExtensionContainer.h @@ -117,7 +117,7 @@ public: typedef std::map::iterator ExtensionIterator; ExtensionContainer(); - virtual ~ExtensionContainer(); + ~ExtensionContainer() override; void registerExtension(Base::Type extension, App::Extension* ext); bool hasExtension(Base::Type, bool derived=true) const; //returns first of type (or derived from if set to true) and throws otherwise @@ -137,7 +137,7 @@ public: template std::vector getExtensionsDerivedFromType() const { std::vector typevec; - for(auto entry : _extensions) { + for(const auto& entry : _extensions) { if(entry.first.isDerivedFrom(ExtensionT::getExtensionClassTypeId())) typevec.push_back(static_cast(entry.second)); } @@ -151,32 +151,32 @@ public: /** @name Access properties */ //@{ /// find a property by its name - virtual Property *getPropertyByName(const char* name) const override; + Property *getPropertyByName(const char* name) const override; /// get the name of a property - virtual const char* getPropertyName(const Property* prop) const override; + const char* getPropertyName(const Property* prop) const override; /// get all properties of the class (including properties of the parent) - virtual void getPropertyMap(std::map &Map) const override; + void getPropertyMap(std::map &Map) const override; /// get all properties of the class (including properties of the parent) - virtual void getPropertyList(std::vector &List) const override; + void getPropertyList(std::vector &List) const override; /// get the Type of a Property - virtual short getPropertyType(const Property* prop) const override; + short getPropertyType(const Property* prop) const override; /// get the Type of a named Property - virtual short getPropertyType(const char *name) const override; + short getPropertyType(const char *name) const override; /// get the Group of a Property - virtual const char* getPropertyGroup(const Property* prop) const override; + const char* getPropertyGroup(const Property* prop) const override; /// get the Group of a named Property - virtual const char* getPropertyGroup(const char *name) const override; + const char* getPropertyGroup(const char *name) const override; /// get the Group of a Property - virtual const char* getPropertyDocumentation(const Property* prop) const override; + const char* getPropertyDocumentation(const Property* prop) const override; /// get the Group of a named Property - virtual const char* getPropertyDocumentation(const char *name) const override; + const char* getPropertyDocumentation(const char *name) const override; //@} - virtual void onChanged(const Property*) override; + void onChanged(const Property*) override; - virtual void Save(Base::Writer& writer) const override; - virtual void Restore(Base::XMLReader& reader) 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. diff --git a/src/App/ExtensionContainerPyImp.cpp b/src/App/ExtensionContainerPyImp.cpp index 76b03308cf..2ddb0b4cca 100644 --- a/src/App/ExtensionContainerPyImp.cpp +++ b/src/App/ExtensionContainerPyImp.cpp @@ -36,14 +36,14 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string ExtensionContainerPy::representation(void) const +std::string ExtensionContainerPy::representation() const { return std::string(""); } int ExtensionContainerPy::initialization() { - if (this->ob_type->tp_dict == nullptr) { + if (!this->ob_type->tp_dict) { if (PyType_Ready(this->ob_type) < 0) return 0; } @@ -61,7 +61,7 @@ int ExtensionContainerPy::initialization() { // make sure to do the initialization only once if (meth->ml_name) { PyObject* item = PyDict_GetItemString(dict, meth->ml_name); - if (item == nullptr) { + if (!item) { // Note: this adds the methods to the type object to make sure // it appears in the call tips. The function will not be bound // to an instance @@ -69,7 +69,7 @@ int ExtensionContainerPy::initialization() { while (meth->ml_name) { PyObject *func; func = PyCFunction_New(meth, 0); - if (func == nullptr) + if (!func) break; if (PyDict_SetItemString(dict, meth->ml_name, func) < 0) break; @@ -238,7 +238,7 @@ PyObject* ExtensionContainerPy::addExtension(PyObject *args) { // make sure to do the initialization only once if (meth->ml_name) { PyObject* item = PyDict_GetItemString(dict, meth->ml_name); - if (item == nullptr) { + if (!item) { // Note: this adds the methods to the type object to make sure // it appears in the call tips. The function will not be bound // to an instance @@ -246,7 +246,7 @@ PyObject* ExtensionContainerPy::addExtension(PyObject *args) { while (meth->ml_name) { PyObject *func; func = PyCFunction_New(meth, 0); - if (func == nullptr) + if (!func) break; if (PyDict_SetItemString(dict, meth->ml_name, func) < 0) break; diff --git a/src/App/ExtensionPyImp.cpp b/src/App/ExtensionPyImp.cpp index 059e7ea2a1..03d5ec308a 100644 --- a/src/App/ExtensionPyImp.cpp +++ b/src/App/ExtensionPyImp.cpp @@ -32,7 +32,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string ExtensionPy::representation(void) const +std::string ExtensionPy::representation() const { return std::string(""); } diff --git a/src/App/ExtensionPython.h b/src/App/ExtensionPython.h index 459517669a..275eedb483 100644 --- a/src/App/ExtensionPython.h +++ b/src/App/ExtensionPython.h @@ -46,8 +46,7 @@ public: ExtensionT::m_isPythonExtension = true; ExtensionT::initExtensionType(ExtensionPythonT::getExtensionClassTypeId()); } - virtual ~ExtensionPythonT() { - } + virtual ~ExtensionPythonT() = default; ExtensionPythonT(const ExtensionPythonT&) = delete; ExtensionPythonT(ExtensionPythonT&&) = delete; diff --git a/src/App/FeatureCustom.h b/src/App/FeatureCustom.h index ad8c49cec8..6fbce3f8ff 100644 --- a/src/App/FeatureCustom.h +++ b/src/App/FeatureCustom.h @@ -45,11 +45,9 @@ class FeatureCustomT : public FeatureT PROPERTY_HEADER(App::FeatureCustomT); public: - FeatureCustomT() { - } + FeatureCustomT() = default; - virtual ~FeatureCustomT() { - } + virtual ~FeatureCustomT() = default; /** @name methods override DocumentObject */ //@{ @@ -57,15 +55,15 @@ public: return FeatureT::mustExecute(); } /// recalculate the Feature - virtual DocumentObjectExecReturn *execute(void) { + virtual DocumentObjectExecReturn *execute() { return FeatureT::execute(); } /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + virtual const char* getViewProviderName() const { return FeatureT::getViewProviderName(); } - PyObject *getPyObject(void) { + PyObject *getPyObject() { return FeatureT::getPyObject(); } void setPyObject(PyObject *obj) { diff --git a/src/App/FeaturePython.cpp b/src/App/FeaturePython.cpp index 0fd6c3a4d2..646e1a599e 100644 --- a/src/App/FeaturePython.cpp +++ b/src/App/FeaturePython.cpp @@ -129,14 +129,14 @@ bool FeaturePythonImp::mustExecute() const void FeaturePythonImp::onBeforeChange(const Property* prop) { - if(py_onBeforeChange.isNone()) + if (py_onBeforeChange.isNone()) return; // Run the execute method of the proxy object. Base::PyGILStateLocker lock; try { const char *prop_name = object->getPropertyName(prop); - if(prop_name == nullptr) + if (!prop_name) return; if (has__object__) { Py::Tuple args(1); @@ -184,13 +184,13 @@ bool FeaturePythonImp::onBeforeChangeLabel(std::string &newLabel) void FeaturePythonImp::onChanged(const Property* prop) { - if(py_onChanged.isNone()) + if (py_onChanged.isNone()) return; // Run the execute method of the proxy object. Base::PyGILStateLocker lock; try { const char *prop_name = object->getPropertyName(prop); - if(prop_name == nullptr) + if (!prop_name) return; if (has__object__) { Py::Tuple args(1); @@ -374,7 +374,7 @@ bool FeaturePythonImp::getLinkedObject(DocumentObject *&ret, bool recurse, } } -PyObject *FeaturePythonImp::getPyObject(void) +PyObject *FeaturePythonImp::getPyObject() { // ref counter is set to 1 return new FeaturePythonPyT(object); @@ -584,10 +584,10 @@ bool FeaturePythonImp::editProperty(const char *name) namespace App { PROPERTY_SOURCE_TEMPLATE(App::FeaturePython, App::DocumentObject) -template<> const char* App::FeaturePython::getViewProviderName(void) const { +template<> const char* App::FeaturePython::getViewProviderName() const { return "Gui::ViewProviderPythonFeature"; } -template<> PyObject* App::FeaturePython::getPyObject(void) { +template<> PyObject* App::FeaturePython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new FeaturePythonPyT(this),true); @@ -602,7 +602,7 @@ template class AppExport FeaturePythonT; namespace App { PROPERTY_SOURCE_TEMPLATE(App::GeometryPython, App::GeoFeature) -template<> const char* App::GeometryPython::getViewProviderName(void) const { +template<> const char* App::GeometryPython::getViewProviderName() const { return "Gui::ViewProviderPythonGeometry"; } // explicit template instantiation diff --git a/src/App/FeaturePython.h b/src/App/FeaturePython.h index ec8a0efbf1..9223a7bf28 100644 --- a/src/App/FeaturePython.h +++ b/src/App/FeaturePython.h @@ -44,7 +44,7 @@ public: Rejected = 2 // handled and rejected }; - FeaturePythonImp(App::DocumentObject*); + explicit FeaturePythonImp(App::DocumentObject*); ~FeaturePythonImp(); bool execute(); @@ -54,14 +54,14 @@ public: void onChanged(const Property* prop); void onDocumentRestored(); std::string getViewProviderName(); - PyObject *getPyObject(void); + PyObject *getPyObject(); - bool getSubObject(App::DocumentObject *&ret, const char *subname, PyObject **pyObj, + bool getSubObject(App::DocumentObject *&ret, const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const; bool getSubObjects(std::vector &ret, int reason) const; - bool getLinkedObject(App::DocumentObject *&ret, bool recurse, + bool getLinkedObject(App::DocumentObject *&ret, bool recurse, Base::Matrix4D *mat, bool transform, int depth) const; ValueT canLinkProperties() const; @@ -187,7 +187,7 @@ public: return imp->mustExecute()?1:0; } /// recalculate the Feature - virtual DocumentObjectExecReturn *execute(void) override { + DocumentObjectExecReturn *execute() override { try { bool handled = imp->execute(); if (!handled) @@ -198,19 +198,19 @@ public: } return DocumentObject::StdReturn; } - virtual const char* getViewProviderNameOverride(void) const override { + const char* getViewProviderNameOverride() const override { viewProviderName = imp->getViewProviderName(); - if(viewProviderName.size()) + if(!viewProviderName.empty()) return viewProviderName.c_str(); return FeatureT::getViewProviderNameOverride(); } /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return FeatureT::getViewProviderName(); //return "Gui::ViewProviderPythonFeature"; } - virtual App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, + App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const override { App::DocumentObject *ret = nullptr; @@ -219,14 +219,14 @@ public: return FeatureT::getSubObject(subname,pyObj,mat,transform,depth); } - virtual std::vector getSubObjects(int reason=0) const override { + std::vector getSubObjects(int reason=0) const override { std::vector ret; if(imp->getSubObjects(ret,reason)) return ret; return FeatureT::getSubObjects(reason); } - virtual App::DocumentObject *getLinkedObject(bool recurse, + App::DocumentObject *getLinkedObject(bool recurse, Base::Matrix4D *mat, bool transform, int depth) const override { App::DocumentObject *ret = nullptr; @@ -236,7 +236,7 @@ public: } /// return true to activate tree view group object handling - virtual bool hasChildElement() const override { + bool hasChildElement() const override { switch (imp->hasChildElement()) { case FeaturePythonImp::Accepted: return true; @@ -247,21 +247,21 @@ public: } } /// Get sub-element visibility - virtual int isElementVisible(const char *element) const override { + int isElementVisible(const char *element) const override { int ret = imp->isElementVisible(element); if(ret == -2) return FeatureT::isElementVisible(element); return ret; } /// Set sub-element visibility - virtual int setElementVisible(const char *element, bool visible) override { + int setElementVisible(const char *element, bool visible) override { int ret = imp->setElementVisible(element,visible); if(ret == -2) return FeatureT::setElementVisible(element,visible); return ret; } - virtual bool canLinkProperties() const override { + bool canLinkProperties() const override { switch (imp->canLinkProperties()) { case FeaturePythonImp::Accepted: return true; @@ -272,7 +272,7 @@ public: } } - virtual bool allowDuplicateLabel() const override { + bool allowDuplicateLabel() const override { switch (imp->allowDuplicateLabel()) { case FeaturePythonImp::Accepted: return true; @@ -283,7 +283,7 @@ public: } } - virtual bool redirectSubName(std::ostringstream &ss, + bool redirectSubName(std::ostringstream &ss, App::DocumentObject *topParent, App::DocumentObject *child) const override { switch (imp->redirectSubName(ss,topParent,child)) { @@ -296,19 +296,19 @@ public: } } - virtual int canLoadPartial() const override { + int canLoadPartial() const override { int ret = imp->canLoadPartial(); if(ret>=0) return ret; return FeatureT::canLoadPartial(); } - virtual void editProperty(const char *propName) override { + void editProperty(const char *propName) override { if (!imp->editProperty(propName)) FeatureT::editProperty(propName); } - PyObject *getPyObject(void) override { + PyObject *getPyObject() override { if (FeatureT::PythonObject.is(Py::_None())) { // ref counter is set to 1 FeatureT::PythonObject = Py::Object(imp->getPyObject(),true); @@ -323,21 +323,21 @@ public: } protected: - virtual void onBeforeChange(const Property* prop) override { + void onBeforeChange(const Property* prop) override { FeatureT::onBeforeChange(prop); imp->onBeforeChange(prop); } - virtual void onBeforeChangeLabel(std::string &newLabel) override{ + void onBeforeChangeLabel(std::string &newLabel) override{ if(!imp->onBeforeChangeLabel(newLabel)) FeatureT::onBeforeChangeLabel(newLabel); } - virtual void onChanged(const Property* prop) override { + void onChanged(const Property* prop) override { if(prop == &Proxy) imp->init(Proxy.getValue().ptr()); imp->onChanged(prop); FeatureT::onChanged(prop); } - virtual void onDocumentRestored() override { + void onDocumentRestored() override { imp->onDocumentRestored(); FeatureT::onDocumentRestored(); } diff --git a/src/App/FeaturePythonPyImp.h b/src/App/FeaturePythonPyImp.h index a31f8095fe..4e2bd58a15 100644 --- a/src/App/FeaturePythonPyImp.h +++ b/src/App/FeaturePythonPyImp.h @@ -88,7 +88,7 @@ public: static PyTypeObject Type; public: - FeaturePythonPyT(Base::BaseClass *pcObject, PyTypeObject *T = &Type); + explicit FeaturePythonPyT(Base::BaseClass *pcObject, PyTypeObject *T = &Type); virtual ~FeaturePythonPyT(); /** @name callbacks and implementers for the python object methods */ diff --git a/src/App/FeaturePythonPyImp.inl b/src/App/FeaturePythonPyImp.inl index 0e89e651f7..8abfda8b34 100644 --- a/src/App/FeaturePythonPyImp.inl +++ b/src/App/FeaturePythonPyImp.inl @@ -168,7 +168,7 @@ PyObject *FeaturePythonPyT::_getattr(const char *attr) // Return the default dict PyTypeObject *tp = this->ob_type; // register type if needed - if (tp->tp_dict == nullptr) { + if (!tp->tp_dict) { if (PyType_Ready(tp) < 0) return nullptr; } diff --git a/src/App/FeatureTest.cpp b/src/App/FeatureTest.cpp index 430bcc5e97..e5ef2875ff 100644 --- a/src/App/FeatureTest.cpp +++ b/src/App/FeatureTest.cpp @@ -24,13 +24,18 @@ #include "PreCompiled.h" #ifndef _PreComp_ #include +#include #endif +#include #include +#include #include +#include #include "FeatureTest.h" #include "Material.h" +#include "Range.h" #ifdef _MSC_VER #pragma warning( disable : 4700 ) @@ -109,17 +114,9 @@ FeatureTest::FeatureTest() QuantityLength.setUnit(Base::Unit::Length); ADD_PROPERTY(QuantityOther,(5.0)); QuantityOther.setUnit(Base::Unit(-3,1)); - //ADD_PROPERTY(QuantityMass,(1.0)); - //QuantityMass.setUnit(Base::Unit::Mass); - //ADD_PROPERTY(QuantityAngle,(1.0)); - //QuantityAngle.setUnit(Base::Unit::Angle); - } -FeatureTest::~FeatureTest() -{ - -} +FeatureTest::~FeatureTest() = default; short FeatureTest::mustExecute() const { @@ -161,31 +158,7 @@ DocumentObjectExecReturn *FeatureTest::execute() list.emplace_back("World"); enumObj6.setEnums(list); enumObj6.setValue(list.back()); - /* -doc=App.newDocument() -obj=doc.addObject("App::FeatureTest") -obj.ExceptionType=0 # good -doc.recompute() - -obj.ExceptionType=1 # unknown exception -doc.recompute() - -obj.ExceptionType=2 # Runtime error -doc.recompute() - -obj.ExceptionType=3 # segfault -doc.recompute() - -obj.ExceptionType=4 # segfault -doc.recompute() - -obj.ExceptionType=5 # int division by zero -doc.recompute() - -obj.ExceptionType=6 # float division by zero -doc.recompute() - */ int *i=nullptr,j; float f; void *s; @@ -198,15 +171,7 @@ doc.recompute() case 0: break; case 1: throw std::runtime_error("Test Exception"); case 2: throw Base::RuntimeError("FeatureTestException::execute(): Testexception"); -#if 0 // only allow these error types on purpose - case 3: *i=0;printf("%i",*i);break; // seg-fault - case 4: t = nullptr; break; // seg-fault - case 5: j=0; printf("%i",1/j); break; // int division by zero - case 6: f=0.0; printf("%f",1/f); break; // float division by zero - case 7: s = malloc(3600000000ul); free(s); break; // out-of-memory -#else default: (void)i; (void)j; (void)f; (void)s; (void)t; break; -#endif } ExecCount.setValue(ExecCount.getValue() + 1); @@ -216,6 +181,7 @@ doc.recompute() return DocumentObject::StdReturn; } +// ---------------------------------------------------------------------------- PROPERTY_SOURCE(App::FeatureTestException, App::FeatureTest) @@ -232,3 +198,97 @@ DocumentObjectExecReturn *FeatureTestException::execute() return nullptr; } + +// ---------------------------------------------------------------------------- + +PROPERTY_SOURCE(App::FeatureTestColumn, App::DocumentObject) + + +FeatureTestColumn::FeatureTestColumn() +{ + ADD_PROPERTY_TYPE(Column, ("A"), "Test", App::Prop_None, ""); + ADD_PROPERTY_TYPE(Silent, (false), "Test", App::Prop_None, ""); + ADD_PROPERTY_TYPE(Value, (0L), "Test", App::Prop_Output, ""); +} + +DocumentObjectExecReturn *FeatureTestColumn::execute() +{ + Value.setValue(decodeColumn(Column.getStrValue(), Silent.getValue())); + return nullptr; +} + +// ---------------------------------------------------------------------------- + +PROPERTY_SOURCE(App::FeatureTestPlacement, App::DocumentObject) + + +FeatureTestPlacement::FeatureTestPlacement() +{ + ADD_PROPERTY_TYPE(Input1, (Base::Placement()), "Test", Prop_None, ""); + ADD_PROPERTY_TYPE(Input2, (Base::Placement()), "Test", Prop_None, ""); + ADD_PROPERTY_TYPE(MultLeft, (Base::Placement()), "Test", Prop_Output, ""); + ADD_PROPERTY_TYPE(MultRight, (Base::Placement()), "Test", Prop_Output, ""); +} + +DocumentObjectExecReturn *FeatureTestPlacement::execute() +{ + Base::Placement p1 = Input1.getValue(); + Base::Placement q1 = Input1.getValue(); + Base::Placement p2 = Input2.getValue(); + MultLeft.setValue(p1.multLeft(p2)); + MultRight.setValue(q1.multRight(p2)); + return nullptr; +} + +// ---------------------------------------------------------------------------- + +PROPERTY_SOURCE(App::FeatureTestAttribute, App::DocumentObject) + + +FeatureTestAttribute::FeatureTestAttribute() +{ + ADD_PROPERTY(Object, (Py::Object())); + ADD_PROPERTY(Attribute, ("Name")); +} + +FeatureTestAttribute::~FeatureTestAttribute() +{ + Base::PyGILStateLocker lock; + try { + Object.getValue().getAttr("Name"); +#if PYCXX_VERSION_MAJOR >= 7 + Py::ifPyErrorThrowCxxException(); +#else + if (PyErr_Occurred()) + throw Py::RuntimeError(); +#endif + } + catch (Py::RuntimeError& e) { + e.clear(); + } + catch (Py::Exception& e) { + e.clear(); + Base::Console().Error("Unexpected exception in ~FeatureTestRemoval()\n"); + } +} + +DocumentObjectExecReturn *FeatureTestAttribute::execute() +{ + Base::PyGILStateLocker lock; + try { + Object.getValue().getAttr(Attribute.getValue()); +#if PYCXX_VERSION_MAJOR >= 7 + Py::ifPyErrorThrowCxxException(); +#else + if (PyErr_Occurred()) + throw Py::AttributeError(); +#endif + } + catch (Py::AttributeError& e) { + e.clear(); + std::stringstream str; + str << "No such attribute '" << Attribute.getValue() << "'"; + throw Base::AttributeError(str.str()); + } + return StdReturn; +} diff --git a/src/App/FeatureTest.h b/src/App/FeatureTest.h index 0d99ac1234..032e9473cd 100644 --- a/src/App/FeatureTest.h +++ b/src/App/FeatureTest.h @@ -27,6 +27,7 @@ #include "DocumentObject.h" #include "PropertyGeo.h" #include "PropertyLinks.h" +#include "PropertyPythonObject.h" #include "PropertyUnits.h" @@ -36,12 +37,12 @@ namespace App /// The testing feature class FeatureTest : public DocumentObject { - PROPERTY_HEADER(App::FeatureTest); + PROPERTY_HEADER_WITH_OVERRIDE(App::FeatureTest); public: FeatureTest(); - ~FeatureTest(); + ~FeatureTest() override; // Standard Properties (PropertyStandard.h) App::PropertyInteger Integer; @@ -104,12 +105,12 @@ public: /** @name methods override Feature */ //@{ - virtual short mustExecute(void) const; + short mustExecute() const override; /// recalculate the Feature - virtual DocumentObjectExecReturn *execute(void); + DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider //Hint: Probably it makes sense to have a view provider for unittests (e.g. Gui::ViewProviderTest) - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderFeature"; } //@} @@ -118,7 +119,7 @@ public: /// The exception testing feature class FeatureTestException :public FeatureTest { - PROPERTY_HEADER(App::FeatureTestException); + PROPERTY_HEADER_WITH_OVERRIDE(App::FeatureTestException); public: FeatureTestException(); @@ -127,13 +128,62 @@ public: App::PropertyInteger ExceptionType; /// recalculate the Feature and throw an exception - virtual DocumentObjectExecReturn *execute(void); + DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderFeature"; } }; +class FeatureTestColumn : public DocumentObject +{ + PROPERTY_HEADER_WITH_OVERRIDE(App::FeatureTestColumn); + +public: + FeatureTestColumn(); + + // Standard Properties (PropertyStandard.h) + App::PropertyString Column; + App::PropertyBool Silent; + App::PropertyInteger Value; + + /** @name methods override Feature */ + //@{ + DocumentObjectExecReturn *execute() override; + //@} +}; + +class FeatureTestPlacement : public DocumentObject +{ + PROPERTY_HEADER_WITH_OVERRIDE(App::FeatureTestPlacement); + +public: + FeatureTestPlacement(); + + // Standard Properties (PropertyStandard.h) + App::PropertyPlacement Input1; + App::PropertyPlacement Input2; + App::PropertyPlacement MultLeft; + App::PropertyPlacement MultRight; + + /** @name methods override Feature */ + //@{ + DocumentObjectExecReturn *execute() override; + //@} +}; + +class FeatureTestAttribute : public DocumentObject +{ + PROPERTY_HEADER_WITH_OVERRIDE(App::FeatureTestAttribute); + +public: + FeatureTestAttribute(); + ~FeatureTestAttribute() override; + DocumentObjectExecReturn *execute() override; + + App::PropertyPythonObject Object; + App::PropertyString Attribute; +}; } //namespace App diff --git a/src/App/FreeCADInit.py b/src/App/FreeCADInit.py index a291be8030..4e0a075b54 100644 --- a/src/App/FreeCADInit.py +++ b/src/App/FreeCADInit.py @@ -24,7 +24,7 @@ # FreeCAD init module # # Gathering all the information to start FreeCAD. -# This is the second of of three init scripts. +# This is the second of three init scripts. # The third one runs when the gui is up, # imports the one and only @@ -311,12 +311,6 @@ except ImportError: FreeCAD.Console.PrintError("\n\nSeems the python standard libs are not installed, bailing out!\n\n") raise -# Backward compatibility to Py2 -import sys -if sys.version_info.major < 3: - import time - time.process_time = time.clock - class FCADLogger(object): '''Convenient class for tagged logging. @@ -915,6 +909,13 @@ class Scheme(IntEnum): App.Units.Scheme = Scheme +class NumberFormat(IntEnum): + Default = 0 + Fixed = 1 + Scientific = 2 + +App.Units.NumberFormat = NumberFormat + class ScaleType(IntEnum): Other = -1 NoScaling = 0 diff --git a/src/App/GeoFeature.cpp b/src/App/GeoFeature.cpp index 0015d545d0..26b48f7a75 100644 --- a/src/App/GeoFeature.cpp +++ b/src/App/GeoFeature.cpp @@ -40,14 +40,12 @@ PROPERTY_SOURCE(App::GeoFeature, App::DocumentObject) // Feature //=========================================================================== -GeoFeature::GeoFeature(void) +GeoFeature::GeoFeature() { ADD_PROPERTY_TYPE(Placement,(Base::Placement()),nullptr,Prop_NoRecompute,nullptr); } -GeoFeature::~GeoFeature(void) -{ -} +GeoFeature::~GeoFeature() = default; void GeoFeature::transformPlacement(const Base::Placement &transform) { @@ -71,7 +69,7 @@ const PropertyComplexGeoData* GeoFeature::getPropertyOfGeometry() const return nullptr; } -PyObject* GeoFeature::getPyObject(void) +PyObject* GeoFeature::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -87,7 +85,7 @@ std::pair GeoFeature::getElementName( (void)type; std::pair ret; - if(!name) + if(!name) return ret; ret.second = name; @@ -132,7 +130,7 @@ DocumentObject *GeoFeature::resolveElement(DocumentObject *obj, const char *subn else{ const auto &names = geo->getElementName(element,type); std::string prefix(subname,element-subname); - if(names.first.size()) + if(!names.first.empty()) elementName.first = prefix + names.first; elementName.second = prefix + names.second; } diff --git a/src/App/GeoFeature.h b/src/App/GeoFeature.h index c9d79dda58..9f71ee58c7 100644 --- a/src/App/GeoFeature.h +++ b/src/App/GeoFeature.h @@ -36,14 +36,14 @@ namespace App */ class AppExport GeoFeature : public App::DocumentObject { - PROPERTY_HEADER(App::GeoFeature); + PROPERTY_HEADER_WITH_OVERRIDE(App::GeoFeature); public: PropertyPlacement Placement; /// Constructor - GeoFeature(void); - virtual ~GeoFeature(); + GeoFeature(); + ~GeoFeature() override; /** * @brief transformPlacement applies transform to placement of this shape. @@ -64,7 +64,7 @@ public: * @brief getPyObject returns the Python binding object * @return the Python binding object */ - virtual PyObject* getPyObject(void); + PyObject* getPyObject() override; /// Specify the type of element name to return when calling getElementName() enum ElementNameType { diff --git a/src/App/GeoFeatureGroupExtension.cpp b/src/App/GeoFeatureGroupExtension.cpp index 22ec309c39..db154a8f0a 100644 --- a/src/App/GeoFeatureGroupExtension.cpp +++ b/src/App/GeoFeatureGroupExtension.cpp @@ -44,15 +44,13 @@ EXTENSION_PROPERTY_SOURCE(App::GeoFeatureGroupExtension, App::GroupExtension) // Feature //=========================================================================== -GeoFeatureGroupExtension::GeoFeatureGroupExtension(void) +GeoFeatureGroupExtension::GeoFeatureGroupExtension() { initExtensionType(GeoFeatureGroupExtension::getExtensionClassTypeId()); Group.setScope(LinkScope::Child); } -GeoFeatureGroupExtension::~GeoFeatureGroupExtension(void) -{ -} +GeoFeatureGroupExtension::~GeoFeatureGroupExtension() = default; void GeoFeatureGroupExtension::initExtension(ExtensionContainer* obj) { diff --git a/src/App/GeoFeatureGroupExtension.h b/src/App/GeoFeatureGroupExtension.h index 470167d419..3069846a20 100644 --- a/src/App/GeoFeatureGroupExtension.h +++ b/src/App/GeoFeatureGroupExtension.h @@ -56,7 +56,7 @@ class AppExport GeoFeatureGroupExtension : public App::GroupExtension public: PropertyPlacement& placement(); - virtual void initExtension(ExtensionContainer* obj) override; + void initExtension(ExtensionContainer* obj) override; /** * @brief transformPlacement applies transform to placement of this shape. @@ -67,10 +67,10 @@ public: virtual void transformPlacement(const Base::Placement &transform); /// Constructor - GeoFeatureGroupExtension(void); - virtual ~GeoFeatureGroupExtension(); + GeoFeatureGroupExtension(); + ~GeoFeatureGroupExtension() override; - virtual void extensionOnChanged(const Property* p) override; + void extensionOnChanged(const Property* p) override; /** Returns the geo feature group which contains this object. * In case this object is not part of any geoFeatureGroup 0 is returned. @@ -97,13 +97,13 @@ public: !obj->hasExtension(GeoFeatureGroupExtension::getExtensionClassTypeId()); } - virtual bool extensionGetSubObject(DocumentObject *&ret, const char *subname, PyObject **pyObj, + bool extensionGetSubObject(DocumentObject *&ret, const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const override; - virtual bool extensionGetSubObjects(std::vector &ret, int reason) const override; + bool extensionGetSubObjects(std::vector &ret, int reason) const override; - virtual std::vector< DocumentObject* > addObjects(std::vector< DocumentObject* > obj) override; - virtual std::vector< DocumentObject* > removeObjects(std::vector< DocumentObject* > obj) override; + std::vector< DocumentObject* > addObjects(std::vector< DocumentObject* > obj) override; + std::vector< DocumentObject* > removeObjects(std::vector< DocumentObject* > obj) override; /// Collects all links that are relevant for the coordinate system, meaning all recursive links to /// obj and from obj excluding expressions and stopping the recursion at other geofeaturegroups. diff --git a/src/App/GeoFeatureGroupExtensionPyImp.cpp b/src/App/GeoFeatureGroupExtensionPyImp.cpp index 7d0dde7432..884886af51 100644 --- a/src/App/GeoFeatureGroupExtensionPyImp.cpp +++ b/src/App/GeoFeatureGroupExtensionPyImp.cpp @@ -31,7 +31,7 @@ using namespace App; // returns a string which represents the object e.g. when printed in python -std::string GeoFeatureGroupExtensionPy::representation(void) const +std::string GeoFeatureGroupExtensionPy::representation() const { return std::string(""); } diff --git a/src/App/GeoFeaturePyImp.cpp b/src/App/GeoFeaturePyImp.cpp index 8fe282131d..c5b341bafe 100644 --- a/src/App/GeoFeaturePyImp.cpp +++ b/src/App/GeoFeaturePyImp.cpp @@ -32,7 +32,7 @@ using namespace App; // returns a string which represents the object e.g. when printed in python -std::string GeoFeaturePy::representation(void) const +std::string GeoFeaturePy::representation() const { return std::string(""); } diff --git a/src/App/GroupExtension.cpp b/src/App/GroupExtension.cpp index 2b70446f0b..e3fd311331 100644 --- a/src/App/GroupExtension.cpp +++ b/src/App/GroupExtension.cpp @@ -52,9 +52,7 @@ GroupExtension::GroupExtension() PropertyType(Prop_Hidden|Prop_Transient),0); } -GroupExtension::~GroupExtension() -{ -} +GroupExtension::~GroupExtension() = default; DocumentObject* GroupExtension::addObject(const char* sType, const char* pObjectName) { @@ -148,7 +146,6 @@ std::vector< DocumentObject* > GroupExtension::removeObjects(std::vector< Docume void GroupExtension::removeObjectsFromDocument() { -#if 1 while (Group.getSize() > 0) { // Remove the objects step by step because it can happen // that an object is part of several groups and thus a @@ -156,15 +153,6 @@ void GroupExtension::removeObjectsFromDocument() const std::vector & grp = Group.getValues(); removeObjectFromDocument(grp.front()); } -#else - const std::vector & grp = Group.getValues(); - // Use set so iterate on each linked object exactly one time (in case of multiple links to the same document) - std::set grpSet (grp.begin(), grp.end()); - - for (std::set::iterator it = grpSet.begin(); it != grpSet.end(); ++it) { - removeObjectFromDocument(*it); - } -#endif } void GroupExtension::removeObjectFromDocument(DocumentObject* obj) @@ -307,7 +295,7 @@ DocumentObject* GroupExtension::getGroupOfObject(const DocumentObject* obj) return nullptr; } -PyObject* GroupExtension::getExtensionPyObject(void) { +PyObject* GroupExtension::getExtensionPyObject() { if (ExtensionPythonObject.is(Py::_None())){ // ref counter is set to 1 @@ -406,7 +394,7 @@ bool GroupExtension::extensionGetSubObjects(std::vector &ret, int) return true; } -App::DocumentObjectExecReturn *GroupExtension::extensionExecute(void) { +App::DocumentObjectExecReturn *GroupExtension::extensionExecute() { // This touch property is for propagating changes to upper group _GroupTouched.touch(); return inherited::extensionExecute(); diff --git a/src/App/GroupExtension.h b/src/App/GroupExtension.h index 47a301cce9..05588df0b7 100644 --- a/src/App/GroupExtension.h +++ b/src/App/GroupExtension.h @@ -42,8 +42,8 @@ class AppExport GroupExtension : public DocumentObjectExtension public: /// Constructor - GroupExtension(void); - virtual ~GroupExtension(); + GroupExtension(); + ~GroupExtension() override; /** @name Object handling */ //@{ @@ -107,16 +107,16 @@ public: static DocumentObject* getGroupOfObject(const DocumentObject* obj); //@} - virtual PyObject* getExtensionPyObject(void) override; + PyObject* getExtensionPyObject() override; - virtual void extensionOnChanged(const Property* p) override; + void extensionOnChanged(const Property* p) override; - virtual bool extensionGetSubObject(DocumentObject *&ret, const char *subname, + bool extensionGetSubObject(DocumentObject *&ret, const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const override; - virtual bool extensionGetSubObjects(std::vector &ret, int reason) const override; + bool extensionGetSubObjects(std::vector &ret, int reason) const override; - virtual App::DocumentObjectExecReturn *extensionExecute(void) override; + App::DocumentObjectExecReturn *extensionExecute() override; std::vector getAllChildren() const; void getAllChildren(std::vector &, std::set &) const; @@ -142,11 +142,11 @@ class GroupExtensionPythonT : public ExtensionT { public: - GroupExtensionPythonT() {} - virtual ~GroupExtensionPythonT() {} + GroupExtensionPythonT() = default; + virtual ~GroupExtensionPythonT() = default; //override the documentobjectextension functions to make them available in python - virtual bool allowObject(DocumentObject* obj) override { + bool allowObject(DocumentObject* obj) override { Py::Object pyobj = Py::asObject(obj->getPyObject()); EXTENSION_PROXY_ONEARG(allowObject, pyobj); diff --git a/src/App/GroupExtensionPyImp.cpp b/src/App/GroupExtensionPyImp.cpp index f4fd6f6ecd..62d4aea805 100644 --- a/src/App/GroupExtensionPyImp.cpp +++ b/src/App/GroupExtensionPyImp.cpp @@ -34,7 +34,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string GroupExtensionPy::representation(void) const +std::string GroupExtensionPy::representation() const { return std::string(""); } diff --git a/src/App/InventorObject.cpp b/src/App/InventorObject.cpp index a005c6d4ef..eded2a6f57 100644 --- a/src/App/InventorObject.cpp +++ b/src/App/InventorObject.cpp @@ -38,11 +38,9 @@ InventorObject::InventorObject() ADD_PROPERTY_TYPE(FileName,(""),"",Prop_None,"Path to an Inventor file"); } -InventorObject::~InventorObject() -{ -} +InventorObject::~InventorObject() = default; -short InventorObject::mustExecute(void) const +short InventorObject::mustExecute() const { return 0; } diff --git a/src/App/InventorObject.h b/src/App/InventorObject.h index e2823e6eb0..af0c9825ac 100644 --- a/src/App/InventorObject.h +++ b/src/App/InventorObject.h @@ -33,22 +33,22 @@ namespace App class AppExport InventorObject : public GeoFeature { - PROPERTY_HEADER(App::InventorObject); + PROPERTY_HEADER_WITH_OVERRIDE(App::InventorObject); public: /// Constructor - InventorObject(void); - virtual ~InventorObject(); + InventorObject(); + ~InventorObject() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderInventorObject"; } - virtual DocumentObjectExecReturn *execute(void) { + DocumentObjectExecReturn *execute() override { return DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; PropertyString Buffer; PropertyString FileName; diff --git a/src/App/Link.cpp b/src/App/Link.cpp index 62180f05ac..8663439018 100644 --- a/src/App/Link.cpp +++ b/src/App/Link.cpp @@ -81,11 +81,11 @@ public: } // Auto generated code. See class document of LinkParams. - ~LinkParamsP() { + ~LinkParamsP() override { } // Auto generated code. See class document of LinkParams. - void OnChange(Base::Subject &, const char* sReason) { + void OnChange(Base::Subject &, const char* sReason) override { if(!sReason) return; auto it = funcs.find(sReason); @@ -148,7 +148,7 @@ void LinkParams::removeCopyOnChangeApplyToAll() { EXTENSION_PROPERTY_SOURCE(App::LinkBaseExtension, App::DocumentObjectExtension) -LinkBaseExtension::LinkBaseExtension(void) +LinkBaseExtension::LinkBaseExtension() :enableLabelCache(false),hasOldSubElement(false),hasCopyOnChange(true) { initExtensionType(LinkBaseExtension::getExtensionClassTypeId()); @@ -166,7 +166,7 @@ LinkBaseExtension::~LinkBaseExtension() { } -PyObject* LinkBaseExtension::getExtensionPyObject(void) { +PyObject* LinkBaseExtension::getExtensionPyObject() { if (ExtensionPythonObject.is(Py::_None())){ // ref counter is set to 1 ExtensionPythonObject = Py::Object(new LinkBaseExtensionPy(this),true); @@ -256,24 +256,24 @@ void LinkBaseExtension::setProperty(int idx, Property *prop) { getPlacementProperty()) { bool transform = getLinkTransformValue(); - getPlacementProperty()->setStatus(Property::Hidden,transform); - getLinkPlacementProperty()->setStatus(Property::Hidden,!transform); + getPlacementProperty()->setStatus(Property::Hidden, transform); + getLinkPlacementProperty()->setStatus(Property::Hidden, !transform); } break; case PropElementList: getElementListProperty()->setScope(LinkScope::Global); - getElementListProperty()->setStatus(Property::Hidden,true); + getElementListProperty()->setStatus(Property::Hidden, true); // fall through case PropLinkedObject: // Make ElementList as read-only if we are not a group (i.e. having // LinkedObject property), because it is for holding array elements. if(getElementListProperty()) getElementListProperty()->setStatus( - Property::Immutable,getLinkedObjectProperty()!=nullptr); + Property::Immutable, getLinkedObjectProperty() != nullptr); break; case PropVisibilityList: - getVisibilityListProperty()->setStatus(Property::Immutable,true); - getVisibilityListProperty()->setStatus(Property::Hidden,true); + getVisibilityListProperty()->setStatus(Property::Immutable, true); + getVisibilityListProperty()->setStatus(Property::Hidden, true); break; } @@ -293,7 +293,7 @@ void LinkBaseExtension::setProperty(int idx, Property *prop) { static const char _GroupPrefix[] = "Configuration ("; -App::DocumentObjectExecReturn *LinkBaseExtension::extensionExecute(void) { +App::DocumentObjectExecReturn *LinkBaseExtension::extensionExecute() { // The actual value of LinkTouched is not important, just to notify view // provider that the link (in fact, its dependents, i.e. linked ones) have // recomputed. @@ -328,7 +328,7 @@ App::DocumentObjectExecReturn *LinkBaseExtension::extensionExecute(void) { PropertyPythonObject *proxy = nullptr; if(getLinkExecuteProperty() && !boost::iequals(getLinkExecuteValue(), "none") - && (!_LinkOwner.getValue() + && (!_LinkOwner.getValue() || !container->getDocument()->getObjectByID(_LinkOwner.getValue()))) { // Check if this is an element link. Do not invoke appLinkExecute() @@ -398,7 +398,7 @@ App::DocumentObjectExecReturn *LinkBaseExtension::extensionExecute(void) { return inherited::extensionExecute(); } -short LinkBaseExtension::extensionMustExecute(void) { +short LinkBaseExtension::extensionMustExecute() { auto link = getLink(); if(!link) return 0; @@ -502,7 +502,7 @@ void LinkBaseExtension::syncCopyOnChange() auto parent = getContainer(); auto linked = linkProp->getValue(); - + std::vector oldObjs; std::vector objs; @@ -540,7 +540,7 @@ void LinkBaseExtension::syncCopyOnChange() // Obtain the original linked object and its dependency in depending order. // The last being the original linked object. auto srcObjs = getOnChangeCopyObjects(); - // Refresh signal connection to monitor changes + // Refresh signal connection to monitor changes monitorOnChangeCopyObjects(srcObjs); // Copy the objects. Document::export/importObjects() (called by @@ -656,7 +656,7 @@ void LinkBaseExtension::syncCopyOnChange() // Finally, remove all old copies. oldObjs stores type of DocumentObjectT // which stores the object name. Before removing, we need to make sure the // object exists, and it is not some new object with the same name, by - // checking objs which stores DocumentObject pointer. + // checking objs which stores DocumentObject pointer. for (const auto &objT : oldObjs) { auto obj = objT.getObject(); if (obj && std::binary_search(objs.begin(), objs.end(), obj)) @@ -811,8 +811,7 @@ bool LinkBaseExtension::setupCopyOnChange(DocumentObject *parent, DocumentObject return res; } -void LinkBaseExtension::checkCopyOnChange( - App::DocumentObject *parent, const App::Property &prop) +void LinkBaseExtension::checkCopyOnChange(App::DocumentObject *parent, const App::Property &prop) { if(!parent || !parent->getDocument() || parent->getDocument()->isPerformingTransaction()) @@ -906,7 +905,7 @@ void LinkBaseExtension::monitorOnChangeCopyObjects( return; for(auto obj : objs) { obj->setStatus(App::ObjectStatus::TouchOnColorChange, true); - copyOnChangeSrcConns.push_back(obj->signalChanged.connect( + copyOnChangeSrcConns.emplace_back(obj->signalChanged.connect( [this](const DocumentObject &, const Property &) { if (auto prop = this->getLinkCopyOnChangeTouchedProperty()) { if (this->getLinkCopyOnChangeValue() != CopyOnChangeDisabled) @@ -917,7 +916,7 @@ void LinkBaseExtension::monitorOnChangeCopyObjects( } App::GroupExtension *LinkBaseExtension::linkedPlainGroup() const { - if(mySubElements.size() && mySubElements[0].size()) + if(!mySubElements.empty() && !mySubElements[0].empty()) return nullptr; auto linked = getTrueLinkedObject(false); if(!linked) @@ -970,7 +969,7 @@ int LinkBaseExtension::_getElementCountValue() const { } bool LinkBaseExtension::extensionHasChildElement() const { - if(_getElementListValue().size() + if(!_getElementListValue().empty() || (_getElementCountValue() && _getShowElementValue())) return true; if (getLinkClaimChildValue()) @@ -1247,7 +1246,7 @@ bool LinkBaseExtension::extensionGetSubObjects(std::vector &ret, in char index[30]; for(int i=0,count=_getElementCountValue();i=0) { const auto &elements = _getElementListValue(); - if(elements.size()) { + if(!elements.empty()) { if(idx>=(int)elements.size() || !elements[idx] || !elements[idx]->getNameInDocument()) return true; ret = elements[idx]->getSubObject(subname,pyObj,mat,true,depth+1); @@ -1402,7 +1401,7 @@ bool LinkBaseExtension::extensionGetSubObject(DocumentObject *&ret, const char * *mat = matNext; } } - checkGeoElementMap(obj,linked,pyObj,postfix.size()?postfix.c_str():nullptr); + checkGeoElementMap(obj,linked,pyObj,!postfix.empty()?postfix.c_str():nullptr); return true; } @@ -1496,13 +1495,13 @@ void LinkBaseExtension::parseSubName() const { mySubElements.emplace_back(""); return; } - mySubElements.push_back(element); + mySubElements.emplace_back(element); mySubName = std::string(subname,element-subname); for(std::size_t i=1;i children; - if(groups.size()) { + if(!groups.empty()) { children = getElementListValue(); std::set childSet(children.begin(),children.end()); for(auto ext : groups) { @@ -1624,16 +1623,16 @@ void LinkBaseExtension::update(App::DocumentObject *parent, const Property *prop } // touch the property again to make sure view provider has been // signaled before clearing the elements - getShowElementProperty()->setStatus(App::Property::User3,true); + getShowElementProperty()->setStatus(App::Property::User3, true); getShowElementProperty()->touch(); - getShowElementProperty()->setStatus(App::Property::User3,false); + getShowElementProperty()->setStatus(App::Property::User3, false); getElementListProperty()->setValues(std::vector()); if(getPlacementListProperty()) { - getPlacementListProperty()->setStatus(Property::User3,getScaleListProperty()!=nullptr); + getPlacementListProperty()->setStatus(Property::User3, getScaleListProperty() != nullptr); getPlacementListProperty()->setValue(placements); - getPlacementListProperty()->setStatus(Property::User3,false); + getPlacementListProperty()->setStatus(Property::User3, false); } if(getScaleListProperty()) getScaleListProperty()->setValue(scales); @@ -1829,8 +1828,8 @@ void LinkBaseExtension::update(App::DocumentObject *parent, const Property *prop if (src != &obj || getLinkCopyOnChangeValue()==CopyOnChangeDisabled) return; if (App::Document::isAnyRestoring() - || obj.testStatus(ObjectStatus::NoTouch) - || (prop.getType() & Prop_Output) + || obj.testStatus(ObjectStatus::NoTouch) + || (prop.getType() & Prop_Output) || prop.testStatus(Property::Output)) return; if (auto propTouch = getLinkCopyOnChangeTouchedProperty()) @@ -1884,34 +1883,33 @@ void LinkBaseExtension::syncElementList() { auto owner = getContainer(); auto ownerID = owner?owner->getID():0; auto elements = getElementListValue(); - for(size_t i=0;i(elements[i]); - if(!element - || (element->_LinkOwner.getValue() - && element->_LinkOwner.getValue()!=ownerID)) + if (!element + || (element->_LinkOwner.getValue() + && element->_LinkOwner.getValue() != ownerID)) continue; element->_LinkOwner.setValue(ownerID); - element->LinkTransform.setStatus(Property::Hidden,transform!=nullptr); - element->LinkTransform.setStatus(Property::Immutable,transform!=nullptr); - if(transform && element->LinkTransform.getValue()!=transform->getValue()) + element->LinkTransform.setStatus(Property::Hidden, transform != nullptr); + element->LinkTransform.setStatus(Property::Immutable, transform != nullptr); + if (transform && element->LinkTransform.getValue() != transform->getValue()) element->LinkTransform.setValue(transform->getValue()); - element->LinkedObject.setStatus(Property::Hidden,link!=nullptr); - element->LinkedObject.setStatus(Property::Immutable,link!=nullptr); - if(element->LinkCopyOnChange.getValue()==2) + element->LinkedObject.setStatus(Property::Hidden, link != nullptr); + element->LinkedObject.setStatus(Property::Immutable, link != nullptr); + if (element->LinkCopyOnChange.getValue() == 2) continue; - if(xlink) { - if(element->LinkedObject.getValue()!=xlink->getValue() || - element->LinkedObject.getSubValues()!=xlink->getSubValues()) - { + if (xlink) { + if (element->LinkedObject.getValue() != xlink->getValue() + || element->LinkedObject.getSubValues() != xlink->getSubValues()) { element->LinkedObject.setValue(xlink->getValue(), xlink->getSubValues()); } - } else if(element->LinkedObject.getValue()!=link->getValue() || - element->LinkedObject.getSubValues().size()) - { - element->setLink(-1,link->getValue()); + } + else if (element->LinkedObject.getValue() != link->getValue() + || !element->LinkedObject.getSubValues().empty()) { + element->setLink(-1, link->getValue()); } } } @@ -2037,7 +2035,7 @@ void LinkBaseExtension::setLink(int index, DocumentObject *obj, int idx = -1; if(getLinkModeValue()>=LinkModeAutoLink || (subname && subname[0]) || - subElements.size() || + !subElements.empty() || obj->getDocument()!=parent->getDocument() || (getElementListProperty()->find(obj->getNameInDocument(),&idx) && idx!=index)) { @@ -2088,14 +2086,14 @@ void LinkBaseExtension::setLink(int index, DocumentObject *obj, } if(!xlink) { - if(subElements.size() || (subname && subname[0])) + if(!subElements.empty() || (subname && subname[0])) LINK_THROW(Base::RuntimeError,"SubName/SubElement link requires PropertyXLink"); linkProp->setValue(obj); return; } std::vector subs; - if(subElements.size()) { + if(!subElements.empty()) { subs.reserve(subElements.size()); for(const auto &s : subElements) { subs.emplace_back(subname?subname:""); @@ -2110,7 +2108,7 @@ void LinkBaseExtension::detachElements() { std::vector objs; for (auto obj : getElementListValue()) - objs.push_back(obj); + objs.emplace_back(obj); getElementListProperty()->setValue(); for(const auto &objT : objs) detachElement(objT.getObject()); @@ -2226,7 +2224,7 @@ template class AppExport ExtensionPythonT; EXTENSION_PROPERTY_SOURCE(App::LinkExtension, App::LinkBaseExtension) -LinkExtension::LinkExtension(void) +LinkExtension::LinkExtension() { initExtensionType(LinkExtension::getExtensionClassTypeId()); @@ -2266,7 +2264,7 @@ bool Link::canLinkProperties() const { namespace App { PROPERTY_SOURCE_TEMPLATE(App::LinkPython, App::Link) -template<> const char* App::LinkPython::getViewProviderName(void) const { +template<> const char* App::LinkPython::getViewProviderName() const { return "Gui::ViewProviderLinkPython"; } template class AppExport FeaturePythonT; @@ -2293,7 +2291,7 @@ bool LinkElement::canDelete() const { namespace App { PROPERTY_SOURCE_TEMPLATE(App::LinkElementPython, App::LinkElement) -template<> const char* App::LinkElementPython::getViewProviderName(void) const { +template<> const char* App::LinkElementPython::getViewProviderName() const { return "Gui::ViewProviderLinkPython"; } template class AppExport FeaturePythonT; @@ -2312,7 +2310,7 @@ LinkGroup::LinkGroup() { namespace App { PROPERTY_SOURCE_TEMPLATE(App::LinkGroupPython, App::LinkGroup) -template<> const char* App::LinkGroupPython::getViewProviderName(void) const { +template<> const char* App::LinkGroupPython::getViewProviderName() const { return "Gui::ViewProviderLinkPython"; } template class AppExport FeaturePythonT; diff --git a/src/App/Link.h b/src/App/Link.h index a9b3adc6b0..71b7d74d8b 100644 --- a/src/App/Link.h +++ b/src/App/Link.h @@ -55,7 +55,7 @@ class AppExport LinkBaseExtension : public App::DocumentObjectExtension public: LinkBaseExtension(); - virtual ~LinkBaseExtension(); + ~LinkBaseExtension() override; PropertyBool _LinkTouched; PropertyInteger _LinkOwner; @@ -270,7 +270,7 @@ public: const char *getSubName() const { parseSubName(); - return mySubName.size()?mySubName.c_str():nullptr; + return !mySubName.empty()?mySubName.c_str():nullptr; } const std::vector &getSubElements() const { @@ -286,19 +286,19 @@ public: bool extensionGetLinkedObject(DocumentObject *&ret, bool recurse, Base::Matrix4D *mat, bool transform, int depth) const override; - virtual App::DocumentObjectExecReturn *extensionExecute(void) override; - virtual short extensionMustExecute(void) override; - virtual void extensionOnChanged(const Property* p) override; - virtual void onExtendedUnsetupObject () override; - virtual void onExtendedDocumentRestored() override; + App::DocumentObjectExecReturn *extensionExecute() override; + short extensionMustExecute() override; + void extensionOnChanged(const Property* p) override; + void onExtendedUnsetupObject () override; + void onExtendedDocumentRestored() override; - virtual int extensionSetElementVisible(const char *, bool) override; - virtual int extensionIsElementVisible(const char *) override; - virtual bool extensionHasChildElement() const override; + int extensionSetElementVisible(const char *, bool) override; + int extensionIsElementVisible(const char *) override; + bool extensionHasChildElement() const override; - virtual PyObject* getExtensionPyObject(void) override; + PyObject* getExtensionPyObject() override; - virtual Property *extensionGetPropertyByName(const char* name) const override; + Property *extensionGetPropertyByName(const char* name) const override; static int getArrayIndex(const char *subname, const char **psubname=nullptr); int getElementIndex(const char *subname, const char **psubname=nullptr) const; @@ -409,7 +409,7 @@ class AppExport LinkExtension : public LinkBaseExtension public: LinkExtension(); - virtual ~LinkExtension(); + ~LinkExtension() override; /** \name Helpers for defining extended parameter * @@ -536,9 +536,9 @@ public: LINK_PROPS_DEFINE(LINK_PARAMS_LINK) - Link(void); + Link(); - const char* getViewProviderName(void) const override{ + const char* getViewProviderName() const override{ return "Gui::ViewProviderLink"; } @@ -581,7 +581,7 @@ public: LINK_PROPS_DEFINE(LINK_PARAMS_ELEMENT) LinkElement(); - const char* getViewProviderName(void) const override{ + const char* getViewProviderName() const override{ return "Gui::ViewProviderLink"; } @@ -620,7 +620,7 @@ public: LinkGroup(); - const char* getViewProviderName(void) const override{ + const char* getViewProviderName() const override{ return "Gui::ViewProviderLink"; } diff --git a/src/App/LinkBaseExtensionPy.xml b/src/App/LinkBaseExtensionPy.xml index 20d7cbf4c7..0488a12213 100644 --- a/src/App/LinkBaseExtensionPy.xml +++ b/src/App/LinkBaseExtensionPy.xml @@ -35,7 +35,7 @@ depending on the actual extension object underlying this python object. If 'val' is omitted, i.e. calling configLinkProperty(key,...), then -it is assumed the the actually property name is the same as 'key' +it is assumed that the actual property name is the same as 'key' diff --git a/src/App/LinkBaseExtensionPyImp.cpp b/src/App/LinkBaseExtensionPyImp.cpp index 8fcddb3fb4..f84ff7a7bb 100644 --- a/src/App/LinkBaseExtensionPyImp.cpp +++ b/src/App/LinkBaseExtensionPyImp.cpp @@ -33,7 +33,7 @@ using namespace App; // returns a string which represent the object e.g. when printed in python -std::string LinkBaseExtensionPy::representation(void) const +std::string LinkBaseExtensionPy::representation() const { std::ostringstream str; str << "<" << getLinkBaseExtensionPtr()->getExtensionClassTypeId().getName() << ">"; diff --git a/src/App/Material.h b/src/App/Material.h index 18f1f9f470..4179015ee6 100644 --- a/src/App/Material.h +++ b/src/App/Material.h @@ -50,7 +50,7 @@ public: * Does basically the same as the constructor above unless that (R,G,B,A) is * encoded as an unsigned int. */ - Color(uint32_t rgba) + explicit Color(uint32_t rgba) { setPackedValue( rgba ); } /** Copy constructor. */ Color(const Color& c) @@ -130,12 +130,7 @@ public: << std::setw(2) << int(b*255.0f); return ss.str(); } - /** - * \deprecated - */ - std::string asCSSString() const { - return asHexString(); - } + /** * gets color from hex color "#RRGGBB" * @@ -227,9 +222,9 @@ public: /** Defines the colors and shininess for the material \a MatName. If \a MatName isn't defined then USER_DEFINED is * set and the user must define the colors itself. */ - Material(const char* MatName); + explicit Material(const char* MatName); /** Does basically the same as the constructor above unless that it accepts a MaterialType as argument. */ - Material(const MaterialType MatType); + explicit Material(const MaterialType MatType); //@} ~Material(); diff --git a/src/App/MaterialObject.cpp b/src/App/MaterialObject.cpp index d4e413db2c..5a8bbb3f7e 100644 --- a/src/App/MaterialObject.cpp +++ b/src/App/MaterialObject.cpp @@ -46,7 +46,7 @@ MaterialObject::~MaterialObject() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(App::MaterialObjectPython, App::MaterialObject) -template<> const char* App::MaterialObjectPython::getViewProviderName(void) const { +template<> const char* App::MaterialObjectPython::getViewProviderName() const { return "Gui::ViewProviderMaterialObjectPython"; } /// @endcond diff --git a/src/App/MaterialObject.h b/src/App/MaterialObject.h index 28da817109..67f15a2e1a 100644 --- a/src/App/MaterialObject.h +++ b/src/App/MaterialObject.h @@ -33,18 +33,18 @@ namespace App class AppExport MaterialObject : public DocumentObject { - PROPERTY_HEADER(App::MaterialObject); + PROPERTY_HEADER_WITH_OVERRIDE(App::MaterialObject); public: /// Constructor - MaterialObject(void); - virtual ~MaterialObject(); + MaterialObject(); + ~MaterialObject() override; App::PropertyMap Material; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderMaterialObject"; } diff --git a/src/App/MaterialPyImp.cpp b/src/App/MaterialPyImp.cpp index a4a5a8c60f..41a3600505 100644 --- a/src/App/MaterialPyImp.cpp +++ b/src/App/MaterialPyImp.cpp @@ -78,7 +78,7 @@ int MaterialPy::PyInit(PyObject* args, PyObject* kwds) } // returns a string which represents the object e.g. when printed in python -std::string MaterialPy::representation(void) const +std::string MaterialPy::representation() const { return std::string(""); } @@ -94,7 +94,7 @@ PyObject* MaterialPy::set(PyObject * args) Py_Return; } -Py::Tuple MaterialPy::getAmbientColor(void) const +Py::Tuple MaterialPy::getAmbientColor() const { Py::Tuple tuple(4); tuple.setItem(0, Py::Float(getMaterialPtr()->ambientColor.r)); @@ -115,7 +115,7 @@ void MaterialPy::setAmbientColor(Py::Tuple arg) getMaterialPtr()->ambientColor = c; } -Py::Tuple MaterialPy::getDiffuseColor(void) const +Py::Tuple MaterialPy::getDiffuseColor() const { Py::Tuple tuple(4); tuple.setItem(0, Py::Float(getMaterialPtr()->diffuseColor.r)); @@ -136,7 +136,7 @@ void MaterialPy::setDiffuseColor(Py::Tuple arg) getMaterialPtr()->diffuseColor = c; } -Py::Tuple MaterialPy::getEmissiveColor(void) const +Py::Tuple MaterialPy::getEmissiveColor() const { Py::Tuple tuple(4); tuple.setItem(0, Py::Float(getMaterialPtr()->emissiveColor.r)); @@ -157,7 +157,7 @@ void MaterialPy::setEmissiveColor(Py::Tuple arg) getMaterialPtr()->emissiveColor = c; } -Py::Tuple MaterialPy::getSpecularColor(void) const +Py::Tuple MaterialPy::getSpecularColor() const { Py::Tuple tuple(4); tuple.setItem(0, Py::Float(getMaterialPtr()->specularColor.r)); @@ -178,7 +178,7 @@ void MaterialPy::setSpecularColor(Py::Tuple arg) getMaterialPtr()->specularColor = c; } -Py::Float MaterialPy::getShininess(void) const +Py::Float MaterialPy::getShininess() const { return Py::Float(getMaterialPtr()->shininess); } @@ -188,7 +188,7 @@ void MaterialPy::setShininess(Py::Float arg) getMaterialPtr()->shininess = (float)arg; } -Py::Float MaterialPy::getTransparency(void) const +Py::Float MaterialPy::getTransparency() const { return Py::Float(getMaterialPtr()->transparency); } diff --git a/src/App/MeasureDistance.cpp b/src/App/MeasureDistance.cpp index 8132075eaf..08d6f63f36 100644 --- a/src/App/MeasureDistance.cpp +++ b/src/App/MeasureDistance.cpp @@ -39,11 +39,9 @@ MeasureDistance::MeasureDistance() } -MeasureDistance::~MeasureDistance() -{ -} +MeasureDistance::~MeasureDistance() = default; -DocumentObjectExecReturn *MeasureDistance::execute(void) +DocumentObjectExecReturn *MeasureDistance::execute() { Distance.setValue(Base::Distance(P1.getValue(), P2.getValue())); return DocumentObject::StdReturn; diff --git a/src/App/MeasureDistance.h b/src/App/MeasureDistance.h index 47e1e18f8d..a08668c008 100644 --- a/src/App/MeasureDistance.h +++ b/src/App/MeasureDistance.h @@ -34,27 +34,27 @@ namespace App class AppExport MeasureDistance : public DocumentObject { - PROPERTY_HEADER(App::MeasureDistance); + PROPERTY_HEADER_WITH_OVERRIDE(App::MeasureDistance); public: /// Constructor - MeasureDistance(void); - virtual ~MeasureDistance(); + MeasureDistance(); + ~MeasureDistance() override; App::PropertyVector P1; App::PropertyVector P2; App::PropertyDistance Distance; /// recalculate the object - virtual DocumentObjectExecReturn *execute(void); + DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderMeasureDistance"; } protected: - virtual void onChanged(const Property* prop); + void onChanged(const Property* prop) override; }; } //namespace App diff --git a/src/App/MergeDocuments.cpp b/src/App/MergeDocuments.cpp index 4726a9e975..81c365a2b3 100644 --- a/src/App/MergeDocuments.cpp +++ b/src/App/MergeDocuments.cpp @@ -45,11 +45,11 @@ public: : Base::XMLReader(FileName, str), nameMap(name) {} - void addName(const char* s1, const char* s2) + void addName(const char* s1, const char* s2) override { nameMap[s1] = s2; } - const char* getName(const char* name) const + const char* getName(const char* name) const override { std::map::const_iterator it = nameMap.find(name); if (it != nameMap.end()) @@ -57,64 +57,12 @@ public: else return name; } - bool doNameMapping() const + bool doNameMapping() const override { return true; } protected: - // It is not safe to change potential object name reference at this level. - // For example, a LinkSub with sub element name Face1 may also be some - // object's name that may potentially be mapped. In addition, with the - // introduction of full qualified SubName reference, the Sub value inside - // LinkSub may require customized mapping. So we move the mapping logic to - // various link property's Restore() function. -#if 0 - void startElement(const XMLCh* const uri, const XMLCh* const localname, - const XMLCh* const qname, - const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) - { - Base::XMLReader::startElement(uri, localname, qname, attrs); - if (LocalName == "Property") - propertyStack.push(std::make_pair(AttrMap["name"],AttrMap["type"])); - - if (!propertyStack.empty()) { - // replace the stored object name with the real one - if (LocalName == "Link" || LocalName == "LinkSub" || (LocalName == "String" && propertyStack.top().first == "Label")) { - for (std::map::iterator it = AttrMap.begin(); it != AttrMap.end(); ++it) { - std::map::const_iterator jt = nameMap.find(it->second); - if (jt != nameMap.end()) - it->second = jt->second; - } - } - // update the expression if name of the object is used - else if (LocalName == "Expression") { - std::map::iterator it = AttrMap.find("expression"); - if (it != AttrMap.end()) { - // search for the part before the first dot that should be the object name. - std::string expression = it->second; - std::string::size_type dotpos = expression.find_first_of("."); - if (dotpos != std::string::npos) { - std::string name = expression.substr(0, dotpos); - std::map::const_iterator jt = nameMap.find(name); - if (jt != nameMap.end()) { - std::string newexpression = jt->second; - newexpression += expression.substr(dotpos); - it->second = newexpression; - } - } - } - } - } - } - - void endElement(const XMLCh* const uri, const XMLCh *const localname, const XMLCh *const qname) - { - Base::XMLReader::endElement(uri, localname, qname); - if (LocalName == "Property") - propertyStack.pop(); - } -#endif private: std::map& nameMap; @@ -142,7 +90,7 @@ MergeDocuments::~MergeDocuments() connectImport.disconnect(); } -unsigned int MergeDocuments::getMemSize (void) const +unsigned int MergeDocuments::getMemSize () const { return 0; } diff --git a/src/App/MergeDocuments.h b/src/App/MergeDocuments.h index a33e5594b7..14e1ceca35 100644 --- a/src/App/MergeDocuments.h +++ b/src/App/MergeDocuments.h @@ -25,6 +25,7 @@ #define APP_MERGEDOCUMENTS_H #include +#include namespace zipios { class ZipInputStream; @@ -36,18 +37,18 @@ class DocumentObject; class AppExport MergeDocuments : public Base::Persistence { public: - MergeDocuments(App::Document* doc); - ~MergeDocuments(); + explicit MergeDocuments(App::Document* doc); + ~MergeDocuments() override; bool isVerbose() const { return verbose; } void setVerbose(bool on) { verbose = on; } - unsigned int getMemSize (void) const; + unsigned int getMemSize () const override; std::vector importObjects(std::istream&); void importObject(const std::vector& o, Base::XMLReader & r); void exportObject(const std::vector& o, Base::Writer & w); - void Save (Base::Writer & w) const; - void Restore(Base::XMLReader &r); - void SaveDocFile (Base::Writer & w) const; - void RestoreDocFile(Base::Reader & r); + void Save (Base::Writer & w) const override; + void Restore(Base::XMLReader &r) override; + void SaveDocFile (Base::Writer & w) const override; + void RestoreDocFile(Base::Reader & r) override; const std::map &getNameMap() const {return nameMap;} diff --git a/src/App/Metadata.cpp b/src/App/Metadata.cpp index 9ea5412be9..f2a2ad15da 100644 --- a/src/App/Metadata.cpp +++ b/src/App/Metadata.cpp @@ -59,13 +59,13 @@ XERCES_CPP_NAMESPACE_USE namespace MetadataInternal { class XMLErrorHandler : public HandlerBase { - void warning(const SAXParseException& toCatch) + void warning(const SAXParseException& toCatch) override { // Don't deal with warnings at all boost::ignore_unused(toCatch); } - void error(const SAXParseException& toCatch) + void error(const SAXParseException& toCatch) override { std::stringstream message; message << "Error at file \"" << StrX(toCatch.getSystemId()) @@ -75,7 +75,7 @@ namespace MetadataInternal { throw Base::XMLBaseException(message.str()); } - void fatalError(const SAXParseException& toCatch) + void fatalError(const SAXParseException& toCatch) override { std::stringstream message; message << "Fatal error at file \"" << StrX(toCatch.getSystemId()) @@ -99,7 +99,11 @@ Metadata::Metadata(const fs::path& metadataFile) auto errHandler = std::make_unique(); _parser->setErrorHandler(errHandler.get()); +#if defined (FC_OS_WIN32) + _parser->parse(reinterpret_cast(metadataFile.wstring().c_str())); +#else _parser->parse(metadataFile.string().c_str()); +#endif auto doc = _parser->getDocument(); _dom = doc->getDocumentElement(); @@ -136,9 +140,7 @@ Metadata::Metadata(const DOMNode* domNode, int format) : _dom(nullptr) } } -Metadata::~Metadata() -{ -} +Metadata::~Metadata() = default; std::string Metadata::name() const { diff --git a/src/App/Metadata.h b/src/App/Metadata.h index 968d91b51d..d5159583c8 100644 --- a/src/App/Metadata.h +++ b/src/App/Metadata.h @@ -94,7 +94,7 @@ namespace App { */ struct AppExport Version { Version(); - Version(int major, int minor = 0, int patch = 0, const std::string& suffix = std::string()); + explicit Version(int major, int minor = 0, int patch = 0, const std::string& suffix = std::string()); explicit Version(const std::string& semanticString); int major; diff --git a/src/App/MetadataPyImp.cpp b/src/App/MetadataPyImp.cpp index 3a35d42d22..7651068a94 100644 --- a/src/App/MetadataPyImp.cpp +++ b/src/App/MetadataPyImp.cpp @@ -33,7 +33,7 @@ using namespace Base; XERCES_CPP_NAMESPACE_USE // Returns a string which represents the object e.g. when printed in Python -std::string MetadataPy::representation(void) const +std::string MetadataPy::representation() const { MetadataPy::PointerType ptr = getMetadataPtr(); std::stringstream str; @@ -112,22 +112,22 @@ int MetadataPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Object MetadataPy::getName(void) const +Py::Object MetadataPy::getName() const { return Py::String(getMetadataPtr()->name()); } -Py::Object MetadataPy::getVersion(void) const +Py::Object MetadataPy::getVersion() const { return Py::String(getMetadataPtr()->version().str()); } -Py::Object MetadataPy::getDescription(void) const +Py::Object MetadataPy::getDescription() const { return Py::String(getMetadataPtr()->description()); } -Py::Object MetadataPy::getMaintainer(void) const +Py::Object MetadataPy::getMaintainer() const { auto maintainers = getMetadataPtr()->maintainer(); Py::List pyMaintainers; @@ -140,7 +140,7 @@ Py::Object MetadataPy::getMaintainer(void) const return pyMaintainers; } -Py::Object MetadataPy::getAuthor(void) const +Py::Object MetadataPy::getAuthor() const { auto authors = getMetadataPtr()->author(); Py::List pyAuthors; @@ -153,7 +153,7 @@ Py::Object MetadataPy::getAuthor(void) const return pyAuthors; } -Py::Object MetadataPy::getLicense(void) const +Py::Object MetadataPy::getLicense() const { auto licenses = getMetadataPtr()->license(); Py::List pyLicenses; @@ -166,7 +166,7 @@ Py::Object MetadataPy::getLicense(void) const return pyLicenses; } -Py::Object MetadataPy::getUrls(void) const +Py::Object MetadataPy::getUrls() const { auto urls = getMetadataPtr()->url (); Py::List pyUrls; @@ -200,7 +200,7 @@ Py::Object dependencyToPyObject(const Meta::Dependency& d) return pyDependency; } -Py::Object MetadataPy::getDepend(void) const +Py::Object MetadataPy::getDepend() const { auto dependencies = getMetadataPtr()->depend(); Py::List pyDependencies; @@ -210,7 +210,7 @@ Py::Object MetadataPy::getDepend(void) const return pyDependencies; } -Py::Object MetadataPy::getConflict(void) const +Py::Object MetadataPy::getConflict() const { auto dependencies = getMetadataPtr()->conflict(); Py::List pyDependencies; @@ -220,7 +220,7 @@ Py::Object MetadataPy::getConflict(void) const return pyDependencies; } -Py::Object MetadataPy::getReplace(void) const +Py::Object MetadataPy::getReplace() const { auto dependencies = getMetadataPtr()->replace(); Py::List pyDependencies; @@ -232,7 +232,7 @@ Py::Object MetadataPy::getReplace(void) const // Tag, icon, classname, file -Py::Object MetadataPy::getTag(void) const +Py::Object MetadataPy::getTag() const { auto tags = getMetadataPtr()->tag(); Py::List pyTags; @@ -242,22 +242,22 @@ Py::Object MetadataPy::getTag(void) const return pyTags; } -Py::Object MetadataPy::getIcon(void) const +Py::Object MetadataPy::getIcon() const { return Py::String(getMetadataPtr()->icon().string()); } -Py::Object MetadataPy::getClassname(void) const +Py::Object MetadataPy::getClassname() const { return Py::String(getMetadataPtr()->classname()); } -Py::Object MetadataPy::getSubdirectory(void) const +Py::Object MetadataPy::getSubdirectory() const { return Py::String(getMetadataPtr()->subdirectory().string()); } -Py::Object MetadataPy::getFile(void) const +Py::Object MetadataPy::getFile() const { auto files = getMetadataPtr()->file(); Py::List pyFiles; @@ -267,7 +267,7 @@ Py::Object MetadataPy::getFile(void) const return pyFiles; } -Py::Object MetadataPy::getContent(void) const +Py::Object MetadataPy::getContent() const { auto content = getMetadataPtr()->content(); std::set keys; diff --git a/src/App/ObjectIdentifier.cpp b/src/App/ObjectIdentifier.cpp index 3d1c2589a9..595bf72302 100644 --- a/src/App/ObjectIdentifier.cpp +++ b/src/App/ObjectIdentifier.cpp @@ -23,7 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +# include #endif #include @@ -122,11 +122,11 @@ ObjectIdentifier::ObjectIdentifier(const App::PropertyContainer * _owner, FC_THROWM(Base::RuntimeError,"Property must be owned by a document object."); owner = const_cast(docObj); - if (property.size() > 0) { + if (!property.empty()) { setDocumentObjectName(docObj); } } - if (property.size() > 0) { + if (!property.empty()) { addComponent(SimpleComponent(property)); if(index!=INT_MAX) addComponent(ArrayComponent(index)); @@ -331,7 +331,7 @@ bool ObjectIdentifier::verify(const App::Property &prop, bool silent) const { const std::string &ObjectIdentifier::toString() const { - if(_cache.size() || !owner) + if(!_cache.empty() || !owner) return _cache; std::ostringstream s; @@ -348,21 +348,21 @@ const std::string &ObjectIdentifier::toString() const result.propertyIndex==0)) { s << '.'; - }else if (documentNameSet && documentName.getString().size()) { - if(documentObjectNameSet && documentObjectName.getString().size()) + }else if (documentNameSet && !documentName.getString().empty()) { + if(documentObjectNameSet && !documentObjectName.getString().empty()) s << documentName.toString() << "#" << documentObjectName.toString() << '.'; - else if(result.resolvedDocumentObjectName.getString().size()) + else if(!result.resolvedDocumentObjectName.getString().empty()) s << documentName.toString() << "#" << result.resolvedDocumentObjectName.toString() << '.'; - } else if (documentObjectNameSet && documentObjectName.getString().size()) { + } else if (documentObjectNameSet && !documentObjectName.getString().empty()) { s << documentObjectName.toString() << '.'; } else if (result.propertyIndex > 0) { components[0].toString(s); s << '.'; } - if(subObjectName.getString().size()) + if(!subObjectName.getString().empty()) s << subObjectName.toString() << '.'; s << components[result.propertyIndex].getName(); @@ -398,21 +398,21 @@ std::string ObjectIdentifier::toPersistentString() const { if(documentObjectName.isRealString()) s << '@'; s << '.'; - } else if (documentNameSet && documentName.getString().size()) { - if(documentObjectNameSet && documentObjectName.getString().size()) + } else if (documentNameSet && !documentName.getString().empty()) { + if(documentObjectNameSet && !documentObjectName.getString().empty()) s << documentName.toString() << "#" << documentObjectName.toString() << '.'; - else if(result.resolvedDocumentObjectName.getString().size()) + else if(!result.resolvedDocumentObjectName.getString().empty()) s << documentName.toString() << "#" << result.resolvedDocumentObjectName.toString() << '.'; - } else if (documentObjectNameSet && documentObjectName.getString().size()) { + } else if (documentObjectNameSet && !documentObjectName.getString().empty()) { s << documentObjectName.toString() << '.'; } else if (result.propertyIndex > 0) { components[0].toString(s); s << '.'; } - if(subObjectName.getString().size()) { + if(!subObjectName.getString().empty()) { const char *subname = subObjectName.getString().c_str(); std::string exportName; s << String(PropertyLinkBase::exportSubName(exportName, @@ -426,7 +426,7 @@ std::string ObjectIdentifier::toPersistentString() const { std::size_t ObjectIdentifier::hash() const { - if(_hash && _cache.size()) + if(_hash && !_cache.empty()) return _hash; const_cast(this)->_hash = boost::hash_value(toString()); return _hash; @@ -484,10 +484,10 @@ bool ObjectIdentifier::updateLabelReference( ResolveResults result(*this); - if(subObjectName.getString().size() && result.resolvedDocumentObject) { + if(!subObjectName.getString().empty() && result.resolvedDocumentObject) { std::string sub = PropertyLinkBase::updateLabelReference( result.resolvedDocumentObject, subObjectName.getString().c_str(), obj,ref,newLabel); - if(sub.size()) { + if(!sub.empty()) { subObjectName = String(sub,true); _cache.clear(); return true; @@ -497,7 +497,7 @@ bool ObjectIdentifier::updateLabelReference( if(result.resolvedDocument != obj->getDocument()) return false; - if(documentObjectName.getString().size()) { + if(!documentObjectName.getString().empty()) { if(documentObjectName.isForceIdentifier()) return false; @@ -855,21 +855,21 @@ App::DocumentObject * ObjectIdentifier::getDocumentObject(const App::Document * for (std::vector::iterator j = docObjects.begin(); j != docObjects.end(); ++j) { if (strcmp((*j)->Label.getValue(), static_cast(name)) == 0) { // Found object with matching label - if (objectByLabel != nullptr) { - FC_WARN("duplicate object label " << doc->getName() << '#' << name); + if (objectByLabel) { + FC_WARN("duplicate object label " << doc->getName() << '#' << static_cast(name)); return nullptr; } objectByLabel = *j; } } - if (objectByLabel == nullptr && objectById == nullptr) // Not found at all + if (!objectByLabel && !objectById) // Not found at all return nullptr; - else if (objectByLabel == nullptr) { // Found by name + else if (!objectByLabel) { // Found by name flags.set(ResolveByIdentifier); return objectById; } - else if (objectById == nullptr) { // Found by label + else if (!objectById) { // Found by label flags.set(ResolveByLabel); return objectByLabel; } @@ -899,7 +899,7 @@ void ObjectIdentifier::resolve(ResolveResults &results) const bool docAmbiguous = false; /* Document name specified? */ - if (documentName.getString().size() > 0) { + if (!documentName.getString().empty()) { results.resolvedDocument = getDocument(documentName,&docAmbiguous); results.resolvedDocumentName = documentName; } @@ -913,35 +913,34 @@ void ObjectIdentifier::resolve(ResolveResults &results) const results.propertyIndex = 0; // Assume document name and object name from owner if not found - if (results.resolvedDocument == nullptr) { - if (documentName.getString().size() > 0) { + if (!results.resolvedDocument) { + if (!documentName.getString().empty()) { if(docAmbiguous) results.flags.set(ResolveAmbiguous); return; } results.resolvedDocument = owner->getDocument(); - if (results.resolvedDocument == nullptr) + if (!results.resolvedDocument) return; } results.resolvedDocumentName = String(results.resolvedDocument->getName(), false, true); /* Document object name specified? */ - if (documentObjectName.getString().size() > 0) { + if (!documentObjectName.getString().empty()) { results.resolvedDocumentObjectName = documentObjectName; results.resolvedDocumentObject = getDocumentObject( results.resolvedDocument, documentObjectName, results.flags); if (!results.resolvedDocumentObject) return; - if (components.size() > 0) { - results.propertyName = components[0].name.getString(); - results.propertyIndex = 0; - results.getProperty(*this); - } - else + if (components.empty()) return; + + results.propertyName = components[ 0 ].name.getString(); + results.propertyIndex = 0; + results.getProperty( *this ); } else { /* Document object name not specified, resolve from path */ @@ -966,8 +965,10 @@ void ObjectIdentifier::resolve(ResolveResults &results) const /* Possible to resolve component to a document object? */ if (results.resolvedDocumentObject) { /* Yes */ - results.resolvedDocumentObjectName = String( - components[0].name, false, results.flags.test(ResolveByIdentifier)); + results.resolvedDocumentObjectName = String { + components[0].name.getString(), + false, + results.flags.test(ResolveByIdentifier)}; results.propertyName = components[1].name.getString(); results.propertyIndex = 1; results.getProperty(*this); @@ -976,7 +977,10 @@ void ObjectIdentifier::resolve(ResolveResults &results) const // interpret the first component as the property name. DocumentObject *sobj = nullptr; results.resolvedProperty = resolveProperty( - owner,components[0].name,sobj,results.propertyType); + owner, + components[0].name.toString().c_str(), + sobj, + results.propertyType); if(results.resolvedProperty) { results.propertyName = components[0].name.getString(); results.resolvedDocument = owner->getDocument(); @@ -1012,13 +1016,13 @@ void ObjectIdentifier::resolve(ResolveResults &results) const Document * ObjectIdentifier::getDocument(String name, bool *ambiguous) const { - if (name.getString().size() == 0) + if (name.getString().empty()) name = getDocumentName(); App::Document * docById = nullptr; if(!name.isRealString()) { - docById = App::GetApplication().getDocument(name); + docById = App::GetApplication().getDocument(name.toString().c_str()); if (name.isForceIdentifier()) return docById; } @@ -1029,7 +1033,7 @@ Document * ObjectIdentifier::getDocument(String name, bool *ambiguous) const for (std::vector::const_iterator i = docs.begin(); i != docs.end(); ++i) { if ((*i)->Label.getValue() == name.getString()) { /* Multiple hits for same label? */ - if (docByLabel != nullptr) { + if (docByLabel) { if(ambiguous) *ambiguous = true; return nullptr; } @@ -1038,17 +1042,18 @@ Document * ObjectIdentifier::getDocument(String name, bool *ambiguous) const } /* Not found on id? */ - if (docById == nullptr) + if (!docById) return docByLabel; // Either not found at all, or on label else { /* Not found on label? */ - if (docByLabel == nullptr) /* Then return doc by id */ + if (!docByLabel) /* Then return doc by id */ return docById; /* docByLabel and docById could be equal; that is ok */ - if(docByLabel==docById) + if (docByLabel == docById) return docById; - if(ambiguous) *ambiguous = true; + if (ambiguous) + *ambiguous = true; return nullptr; } } @@ -1097,12 +1102,12 @@ void ObjectIdentifier::getDepLabels(std::vector &labels) const { void ObjectIdentifier::getDepLabels( const ResolveResults &result, std::vector &labels) const { - if(documentObjectName.getString().size()) { + if(!documentObjectName.getString().empty()) { if(documentObjectName.isRealString()) labels.push_back(documentObjectName.getString()); } else if(result.propertyIndex == 1) labels.push_back(components[0].name.getString()); - if(subObjectName.getString().size()) + if(!subObjectName.getString().empty()) PropertyLinkBase::getLabelReferences(labels,subObjectName.getString().c_str()); } @@ -1129,7 +1134,7 @@ void ObjectIdentifier::getDep(Dependencies &deps, bool needProps, std::vector ObjectIdentifier::getStringList() const if (documentObjectNameSet) l.push_back(documentObjectName.toString()); } - if(subObjectName.getString().size()) { + if(!subObjectName.getString().empty()) { l.back() += subObjectName.toString(); } std::vector::const_iterator i = components.begin(); @@ -1265,8 +1270,8 @@ Property *ObjectIdentifier::getProperty(int *ptype) const Property *ObjectIdentifier::resolveProperty(const App::DocumentObject *obj, const char *propertyName, App::DocumentObject *&sobj, int &ptype) const { - if(obj && subObjectName.getString().size()) { - sobj = obj->getSubObject(subObjectName); + if(obj && !subObjectName.getString().empty()) { + sobj = obj->getSubObject(subObjectName.toString().c_str()); obj = sobj; } if(!obj) @@ -1294,7 +1299,7 @@ Property *ObjectIdentifier::resolveProperty(const App::DocumentObject *obj, else { ptype = it->second; if(ptype != PseudoShape && - subObjectName.getString().size() && + !subObjectName.getString().empty() && !boost::ends_with(subObjectName.getString(),".")) { return nullptr; @@ -1357,7 +1362,7 @@ void ObjectIdentifier::setDocumentName(ObjectIdentifier::String &&name, bool for force = false; documentNameSet = force; _cache.clear(); - if(name.getString().size() && _DocumentMap) { + if(!name.getString().empty() && _DocumentMap) { if(name.isRealString()) { auto iter = _DocumentMap->find(name.toString()); if(iter!=_DocumentMap->end()) { @@ -1480,7 +1485,7 @@ std::string ObjectIdentifier::String::toString(bool toPython) const void ObjectIdentifier::String::checkImport(const App::DocumentObject *owner, const App::DocumentObject *obj, String *objName) { - if(owner && owner->getDocument() && str.size() && + if(owner && owner->getDocument() && !str.empty() && ExpressionParser::ExpressionImporter::reader()) { auto reader = ExpressionParser::ExpressionImporter::reader(); if (obj || objName) { @@ -1523,7 +1528,7 @@ Py::Object ObjectIdentifier::access(const ResolveResults &result, Py::Object *value, Dependencies *deps) const { if(!result.resolvedDocumentObject || !result.resolvedProperty || - (subObjectName.getString().size() && !result.resolvedSubObject)) + (!subObjectName.getString().empty() && !result.resolvedSubObject)) { FC_THROWM(Base::RuntimeError, result.resolveErrorString() << " in '" << toString() << "'"); @@ -1684,7 +1689,7 @@ Py::Object ObjectIdentifier::access(const ResolveResults &result, auto &propset = (*deps)[obj]; // inserting a blank name in the propset indicates the dependency is // on all properties of the corresponding object. - if (propset.size() != 1 || propset.begin()->size()) { + if (propset.size() != 1 || !propset.begin()->empty()) { if (!propName) { propset.clear(); propset.insert(""); @@ -1830,9 +1835,9 @@ void ObjectIdentifier::setValue(const App::any &value) const } const std::string &ObjectIdentifier::getSubObjectName(bool newStyle) const { - if(newStyle && shadowSub.first.size()) + if(newStyle && !shadowSub.first.empty()) return shadowSub.first; - if(shadowSub.second.size()) + if(!shadowSub.second.empty()) return shadowSub.second; return subObjectName.getString(); } @@ -1926,7 +1931,7 @@ bool ObjectIdentifier::isTouched() const { void ObjectIdentifier::resolveAmbiguity() { if(!owner || !owner->getNameInDocument() || isLocalProperty() || - (documentObjectNameSet && documentObjectName.getString().size() && + (documentObjectNameSet && !documentObjectName.getString().empty() && (documentObjectName.isRealString() || documentObjectName.isForceIdentifier()))) { return; @@ -1979,25 +1984,25 @@ ObjectIdentifier::ResolveResults::ResolveResults(const ObjectIdentifier &oi) std::string ObjectIdentifier::ResolveResults::resolveErrorString() const { std::ostringstream ss; - if (resolvedDocument == nullptr) { + if (!resolvedDocument) { if(flags.test(ResolveAmbiguous)) ss << "Ambiguous document name/label '" << resolvedDocumentName.getString() << "'"; else ss << "Document '" << resolvedDocumentName.toString() << "' not found"; - } else if (resolvedDocumentObject == nullptr) { + } else if (!resolvedDocumentObject) { if(flags.test(ResolveAmbiguous)) ss << "Ambiguous document object name '" << resolvedDocumentObjectName.getString() << "'"; else ss << "Document object '" << resolvedDocumentObjectName.toString() << "' not found"; - } else if (subObjectName.getString().size() && resolvedSubObject == nullptr) { + } else if (!subObjectName.getString().empty() && !resolvedSubObject) { ss << "Sub-object '" << resolvedDocumentObjectName.getString() << '.' << subObjectName.toString() << "' not found"; - } else if (resolvedProperty == nullptr) { + } else if (!resolvedProperty) { if(propertyType != PseudoShape && - subObjectName.getString().size() && + !subObjectName.getString().empty() && !boost::ends_with(subObjectName.getString(),".")) { ss << "Non geometry subname reference must end with '.'"; diff --git a/src/App/ObjectIdentifier.h b/src/App/ObjectIdentifier.h index c1e6db6cc1..133728e909 100644 --- a/src/App/ObjectIdentifier.h +++ b/src/App/ObjectIdentifier.h @@ -72,7 +72,7 @@ public: class AppExport DocumentMapper { public: - DocumentMapper(const std::map &); + explicit DocumentMapper(const std::map &); ~DocumentMapper(); }; @@ -81,14 +81,21 @@ public: public: - // Constructor - String(const std::string & s = "", bool _isRealString = false, bool _forceIdentifier = false) - : str(s), isString(_isRealString), forceIdentifier(_forceIdentifier) - { } + String(const std::string &s = "", + bool _isRealString = false, + bool _forceIdentifier = false) + : str(s), + isString(_isRealString), + forceIdentifier(_forceIdentifier) + {}//explicit bombs - String(std::string &&s, bool _isRealString = false, bool _forceIdentifier = false) - : str(std::move(s)), isString(_isRealString), forceIdentifier(_forceIdentifier) - { } + explicit String(std::string &&s, + bool _isRealString = false, + bool _forceIdentifier = false) + : str(std::move(s)), + isString(_isRealString), + forceIdentifier(_forceIdentifier) + {} FC_DEFAULT_CTORS(String) { str = std::move(other.str); @@ -112,9 +119,9 @@ public: // Operators - operator std::string() const { return str; } + explicit operator std::string() const { return str; } - operator const char *() const { return str.c_str(); } + explicit operator const char *() const { return str.c_str(); } bool operator==(const String & other) const { return str == other.str; } @@ -166,9 +173,9 @@ public: } Component(const String &_name = String(), typeEnum _type=SIMPLE, - int begin=INT_MAX, int end=INT_MAX, int step=1); + int begin=INT_MAX, int end=INT_MAX, int step=1);//explicit bombs Component(String &&_name, typeEnum _type=SIMPLE, - int begin=INT_MAX, int end=INT_MAX, int step=1); + int begin=INT_MAX, int end=INT_MAX, int step=1);//explicit bombs static Component SimpleComponent(const char * _component); @@ -234,6 +241,9 @@ public: static Component SimpleComponent(String &&_component) {return Component::SimpleComponent(std::move(_component));} + static Component SimpleComponent(const std::string _component) + {return Component::SimpleComponent(_component.c_str());} + static Component ArrayComponent(int _index) {return Component::ArrayComponent(_index); } @@ -246,12 +256,12 @@ public: static Component MapComponent(String &&_key) {return Component::MapComponent(_key);} - ObjectIdentifier(const App::PropertyContainer * _owner = nullptr, + explicit ObjectIdentifier(const App::PropertyContainer * _owner = nullptr, const std::string & property = std::string(), int index=INT_MAX); ObjectIdentifier(const App::PropertyContainer * _owner, bool localProperty); - ObjectIdentifier(const App::Property & prop, int index=INT_MAX); + ObjectIdentifier(const App::Property & prop, int index=INT_MAX);//explicit bombs FC_DEFAULT_CTORS(ObjectIdentifier) { owner = other.owner; @@ -268,7 +278,7 @@ public: return *this; } - virtual ~ObjectIdentifier() {} + virtual ~ObjectIdentifier() = default; App::DocumentObject *getOwner() const { return owner; } @@ -436,7 +446,7 @@ protected: struct ResolveResults { - ResolveResults(const ObjectIdentifier & oi); + explicit ResolveResults(const ObjectIdentifier & oi); int propertyIndex; App::Document * resolvedDocument; diff --git a/src/App/Origin.cpp b/src/App/Origin.cpp index 2d98938eb1..131ebaabc2 100644 --- a/src/App/Origin.cpp +++ b/src/App/Origin.cpp @@ -48,7 +48,7 @@ PROPERTY_SOURCE(App::Origin, App::DocumentObject) const char* Origin::AxisRoles[3] = {"X_Axis", "Y_Axis", "Z_Axis"}; const char* Origin::PlaneRoles[3] = {"XY_Plane", "XZ_Plane", "YZ_Plane"}; -Origin::Origin(void) : extension(this) { +Origin::Origin() : extension(this) { ADD_PROPERTY_TYPE ( OriginFeatures, (nullptr), 0, App::Prop_Hidden, "Axis and baseplanes controlled by the origin" ); @@ -57,8 +57,7 @@ Origin::Origin(void) : extension(this) { } -Origin::~Origin(void) -{ } +Origin::~Origin() = default; App::OriginFeature *Origin::getOriginFeature( const char *role) const { const auto & features = OriginFeatures.getValues (); @@ -107,7 +106,7 @@ bool Origin::hasObject (const DocumentObject *obj) const { return std::find (features.begin(), features.end(), obj) != features.end (); } -short Origin::mustExecute(void) const { +short Origin::mustExecute() const { if (OriginFeatures.isTouched ()) { return 1; } else { @@ -115,7 +114,7 @@ short Origin::mustExecute(void) const { } } -App::DocumentObjectExecReturn *Origin::execute(void) { +App::DocumentObjectExecReturn *Origin::execute() { try { // try to find all base axis and planes in the origin for (const char* role: AxisRoles) { App::Line *axis = getAxis (role); diff --git a/src/App/Origin.h b/src/App/Origin.h index 4b51a4bd6b..8deabce0b7 100644 --- a/src/App/Origin.h +++ b/src/App/Origin.h @@ -36,15 +36,15 @@ namespace App */ class AppExport Origin : public App::DocumentObject { - PROPERTY_HEADER(App::Origin); + PROPERTY_HEADER_WITH_OVERRIDE(App::Origin); public: /// Constructor - Origin(void); - virtual ~Origin(); + Origin(); + ~Origin() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderOrigin"; } @@ -112,7 +112,7 @@ public: static Base::BoundBox3d defaultBoundBox(); /// Returns true on changing OriginFeature set - virtual short mustExecute(void) const; + short mustExecute() const override; /// Axis types static const char* AxisRoles[3]; @@ -124,11 +124,11 @@ public: protected: /// Checks integrity of the Origin - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// Creates all corresponding Axes and Planes objects for the origin if they aren't linked yet - virtual void setupObject (); + void setupObject () override; /// Removes all planes and axis if they are still linked to the document - virtual void unsetupObject (); + void unsetupObject () override; private: struct SetupData; @@ -137,10 +137,10 @@ private: class OriginExtension : public GeoFeatureGroupExtension { Origin* obj; public: - OriginExtension(Origin* obj); - void initExtension(ExtensionContainer* obj); + explicit OriginExtension(Origin* obj); + void initExtension(ExtensionContainer* obj) override; bool extensionGetSubObject(DocumentObject *&ret, const char *subname, - PyObject **, Base::Matrix4D *, bool, int) const; + PyObject **, Base::Matrix4D *, bool, int) const override; }; OriginExtension extension; }; diff --git a/src/App/OriginFeature.cpp b/src/App/OriginFeature.cpp index 35c2acd0bd..2171207687 100644 --- a/src/App/OriginFeature.cpp +++ b/src/App/OriginFeature.cpp @@ -41,8 +41,7 @@ OriginFeature::OriginFeature() Placement.setStatus(Property::Hidden, true); } -OriginFeature::~OriginFeature() -{ } +OriginFeature::~OriginFeature() = default; Origin * OriginFeature::getOrigin () { App::Document *doc = getDocument(); diff --git a/src/App/OriginFeature.h b/src/App/OriginFeature.h index 3caf425d75..e8dc7fa22d 100644 --- a/src/App/OriginFeature.h +++ b/src/App/OriginFeature.h @@ -35,31 +35,31 @@ class Origin; */ class AppExport OriginFeature: public App::GeoFeature { - PROPERTY_HEADER(App::OriginFeature); + PROPERTY_HEADER_WITH_OVERRIDE(App::OriginFeature); public: /// additional information about the feature usage (e.g. "BasePlane-XY" or "Axis-X" in a Origin) PropertyString Role; /// Constructor - OriginFeature(void); - virtual ~OriginFeature(); + OriginFeature(); + ~OriginFeature() override; /// Finds the origin object this plane belongs to App::Origin *getOrigin (); }; class AppExport Plane: public App::OriginFeature { - PROPERTY_HEADER(App::OriginFeature); + PROPERTY_HEADER_WITH_OVERRIDE(App::OriginFeature); public: - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderPlane"; } }; class AppExport Line: public App::OriginFeature { - PROPERTY_HEADER(App::OriginFeature); + PROPERTY_HEADER_WITH_OVERRIDE(App::OriginFeature); public: - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderLine"; } }; diff --git a/src/App/OriginGroupExtension.cpp b/src/App/OriginGroupExtension.cpp index e8606c215d..d61a17cb55 100644 --- a/src/App/OriginGroupExtension.cpp +++ b/src/App/OriginGroupExtension.cpp @@ -46,8 +46,7 @@ OriginGroupExtension::OriginGroupExtension () { Origin.setScope(LinkScope::Child); } -OriginGroupExtension::~OriginGroupExtension () -{ } +OriginGroupExtension::~OriginGroupExtension () = default; App::Origin *OriginGroupExtension::getOrigin () const { App::DocumentObject *originObj = Origin.getValue (); diff --git a/src/App/OriginGroupExtension.h b/src/App/OriginGroupExtension.h index cf3a4f2251..f5ea25ad43 100644 --- a/src/App/OriginGroupExtension.h +++ b/src/App/OriginGroupExtension.h @@ -37,7 +37,7 @@ class AppExport OriginGroupExtension : public App::GeoFeatureGroupExtension public: OriginGroupExtension (); - virtual ~OriginGroupExtension (); + ~OriginGroupExtension () override; /// Returns the origin link or throws an exception App::Origin *getOrigin () const; @@ -55,7 +55,7 @@ public: static DocumentObject* getGroupOfObject (const DocumentObject* obj); /// Returns true on changing OriginFeature set - virtual short extensionMustExecute () override; + short extensionMustExecute () override; /// Origin linked to the group PropertyLink Origin; @@ -63,21 +63,21 @@ public: // changes all links of obj to a origin to point to this groups origin void relinkToOrigin(App::DocumentObject* obj); - virtual std::vector addObjects(std::vector obj) override; - virtual bool hasObject(const DocumentObject* obj, bool recursive = false) const override; + std::vector addObjects(std::vector obj) override; + bool hasObject(const DocumentObject* obj, bool recursive = false) const override; - virtual bool extensionGetSubObject(DocumentObject *&ret, const char *subname, PyObject **pyObj, + bool extensionGetSubObject(DocumentObject *&ret, const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const override; - virtual void extensionOnChanged(const Property* p) override; + void extensionOnChanged(const Property* p) override; protected: /// Checks integrity of the Origin - virtual App::DocumentObjectExecReturn *extensionExecute () override; + App::DocumentObjectExecReturn *extensionExecute () override; /// Creates the corresponding Origin object - virtual void onExtendedSetupObject () override; + void onExtendedSetupObject () override; /// Removes all planes and axis if they are still linked to the document - virtual void onExtendedUnsetupObject () override; + void onExtendedUnsetupObject () override; }; typedef ExtensionPythonT> OriginGroupExtensionPython; diff --git a/src/App/OriginGroupExtensionPyImp.cpp b/src/App/OriginGroupExtensionPyImp.cpp index 471e4d11ea..4eedc185a8 100644 --- a/src/App/OriginGroupExtensionPyImp.cpp +++ b/src/App/OriginGroupExtensionPyImp.cpp @@ -30,7 +30,7 @@ using namespace App; // returns a string which represents the object e.g. when printed in python -std::string OriginGroupExtensionPy::representation(void) const +std::string OriginGroupExtensionPy::representation() const { return std::string(""); } diff --git a/src/App/Part.cpp b/src/App/Part.cpp index de50bcf561..3ce9e5d207 100644 --- a/src/App/Part.cpp +++ b/src/App/Part.cpp @@ -40,7 +40,7 @@ PROPERTY_SOURCE_WITH_EXTENSIONS(App::Part, App::GeoFeature) //=========================================================================== -Part::Part(void) +Part::Part() { ADD_PROPERTY(Type,("")); ADD_PROPERTY_TYPE(Material, (nullptr), 0, App::Prop_None, "The Material for this Part"); @@ -60,9 +60,7 @@ Part::Part(void) GroupExtension::initExtension(this); } -Part::~Part(void) -{ -} +Part::~Part() = default; static App::Part *_getPartOfObject(const DocumentObject *obj, std::set *objset) diff --git a/src/App/Part.h b/src/App/Part.h index 2ae9d33e44..f217bc67c5 100644 --- a/src/App/Part.h +++ b/src/App/Part.h @@ -77,15 +77,15 @@ public: /// Constructor Part(); - virtual ~Part(); + ~Part() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const override { + const char* getViewProviderName() const override { return "Gui::ViewProviderPart"; } - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop) override; /** * Returns the part which contains this object. @@ -95,7 +95,7 @@ public: */ static App::Part* getPartOfObject (const DocumentObject* obj, bool recursive=true); - virtual PyObject *getPyObject() override; + PyObject *getPyObject() override; }; //typedef App::FeaturePythonT PartPython; diff --git a/src/App/PartPyImp.cpp b/src/App/PartPyImp.cpp index 88e566afca..6fd5228b51 100644 --- a/src/App/PartPyImp.cpp +++ b/src/App/PartPyImp.cpp @@ -30,7 +30,7 @@ using namespace App; // returns a string which represents the object e.g. when printed in python -std::string PartPy::representation(void) const +std::string PartPy::representation() const { return std::string(""); } diff --git a/src/App/Path.cpp b/src/App/Path.cpp index 80bb105a76..39773c0892 100644 --- a/src/App/Path.cpp +++ b/src/App/Path.cpp @@ -28,16 +28,7 @@ using namespace App; -Path::Path(void) -{ -} - Path::Path(const std::vector &PathVector) -:_PathVector(PathVector) + : _PathVector(PathVector) { } - -Path::~Path(void) -{ -} - diff --git a/src/App/Path.h b/src/App/Path.h index ce0714848f..eb77a65af9 100644 --- a/src/App/Path.h +++ b/src/App/Path.h @@ -25,6 +25,7 @@ #define APP_Path_H #include +#include namespace App @@ -35,17 +36,18 @@ namespace App class AppExport Path { protected: - std::vector _PathVector; + std::vector _PathVector; public: /// Constructor - Path(void); - Path(const std::vector & PathVector); + Path() = default; + explicit Path(const std::vector & PathVector); - virtual ~Path(); - - const std::vector & getVector(void)const{return _PathVector;} + virtual ~Path() = default; + const std::vector & getVector() const { + return _PathVector; + } }; } //namespace App diff --git a/src/App/Placement.cpp b/src/App/Placement.cpp index dadba176ad..6a47e88c8f 100644 --- a/src/App/Placement.cpp +++ b/src/App/Placement.cpp @@ -37,21 +37,16 @@ PROPERTY_SOURCE(App::Placement, App::GeoFeature) // Feature //=========================================================================== -Placement::Placement(void) -{ +Placement::Placement() = default; -} - -Placement::~Placement(void) -{ -} +Placement::~Placement() = default; // Python feature --------------------------------------------------------- namespace App { PROPERTY_SOURCE_TEMPLATE(App::PlacementPython, App::Placement) -template<> const char* App::PlacementPython::getViewProviderName(void) const { +template<> const char* App::PlacementPython::getViewProviderName() const { return "Gui::ViewProviderPlacementPython"; } template class AppExport FeaturePythonT; diff --git a/src/App/Placement.h b/src/App/Placement.h index b6aed5a508..8d371515c6 100644 --- a/src/App/Placement.h +++ b/src/App/Placement.h @@ -34,15 +34,15 @@ namespace App */ class AppExport Placement: public App::GeoFeature { - PROPERTY_HEADER(App::Placement); + PROPERTY_HEADER_WITH_OVERRIDE(App::Placement); public: /// Constructor - Placement(void); - virtual ~Placement(); + Placement(); + ~Placement() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderPlacement"; } diff --git a/src/App/Property.cpp b/src/App/Property.cpp index a1fc917b8e..edc9b1502e 100644 --- a/src/App/Property.cpp +++ b/src/App/Property.cpp @@ -58,10 +58,7 @@ Property::Property() { } -Property::~Property() -{ - -} +Property::~Property() = default; const char* Property::getName() const { @@ -91,7 +88,7 @@ std::string Property::getFullName() const { return name; } -short Property::getType(void) const +short Property::getType() const { short type = 0; #define GET_PTYPE(_name) do {\ @@ -118,12 +115,12 @@ void Property::syncType(unsigned type) { SYNC_PTYPE(NoPersist); } -const char* Property::getGroup(void) const +const char* Property::getGroup() const { return father->getPropertyGroup(this); } -const char* Property::getDocumentation(void) const +const char* Property::getDocumentation() const { return father->getPropertyDocumentation(this); } @@ -165,7 +162,7 @@ namespace App { * active. */ struct PropertyCleaner { - PropertyCleaner(Property *p) + explicit PropertyCleaner(Property *p) : prop(p) { ++_PropCleanerCounter; @@ -174,7 +171,7 @@ struct PropertyCleaner { if(--_PropCleanerCounter) return; bool found = false; - while (_RemovedProps.size()) { + while (!_RemovedProps.empty()) { auto p = _RemovedProps.back(); _RemovedProps.pop_back(); if(p != prop) @@ -224,7 +221,7 @@ void Property::setReadOnly(bool readOnly) this->setStatus(App::Property::ReadOnly, readOnly); } -void Property::hasSetValue(void) +void Property::hasSetValue() { PropertyCleaner guard(this); if (father) { @@ -237,7 +234,7 @@ void Property::hasSetValue(void) StatusBits.set(Touched); } -void Property::aboutToSetValue(void) +void Property::aboutToSetValue() { if (father) father->onBeforeChange(this); @@ -248,7 +245,7 @@ void Property::verifyPath(const ObjectIdentifier &p) const p.verify(*this); } -Property *Property::Copy(void) const +Property *Property::Copy() const { // have to be reimplemented by a subclass! assert(0); diff --git a/src/App/Property.h b/src/App/Property.h index c124205766..d10b7994e4 100644 --- a/src/App/Property.h +++ b/src/App/Property.h @@ -101,7 +101,7 @@ public: }; Property(); - virtual ~Property(); + ~Property() override; /// For safe deleting of a dynamic property static void destroy(Property *p); @@ -112,7 +112,7 @@ public: * This method is defined in Base::Persistence * @see Base::Persistence */ - virtual unsigned int getMemSize (void) const override { + unsigned int getMemSize () const override { // you have to implement this method in all property classes! return sizeof(father) + sizeof(StatusBits); } @@ -121,7 +121,7 @@ public: * 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. "". */ - const char* getName(void) const; + const char* getName() const; /** Check if the property has a name set. * If no name is set then \ref getName() will return an empty string */ @@ -135,22 +135,22 @@ public: std::string getFullName() const; /// Get the class name of the associated property editor item - virtual const char* getEditorName(void) const { return ""; } + virtual const char* getEditorName() const { return ""; } /// Get the type of the property in the container - short getType(void) const; + short getType() const; /// Get the group of this property - const char* getGroup(void) const; + const char* getGroup() const; /// Get the documentation of this property - const char* getDocumentation(void) const; + const char* getDocumentation() const; /// Is called by the framework to set the father (container) void setContainer(PropertyContainer *Father); /// Get a pointer to the PropertyContainer derived class the property belongs to - PropertyContainer *getContainer(void) const {return father;} + PropertyContainer *getContainer() const {return father;} /// Set value of property virtual void setPathValue(const App::ObjectIdentifier & path, const boost::any & value); @@ -206,11 +206,11 @@ public: /// Set the property touched void touch(); /// Test if this property is touched - inline bool isTouched(void) const { + inline bool isTouched() const { return StatusBits.test(Touched); } /// Reset this property touched - inline void purgeTouched(void) { + inline void purgeTouched() { StatusBits.reset(Touched); } /// return the status bits @@ -239,7 +239,7 @@ public: //@} /// Returns a new copy of the property (mainly for Undo/Redo and transactions) - virtual Property *Copy(void) const = 0; + virtual Property *Copy() const = 0; /// Paste the value from the property (mainly for Undo/Redo and transactions) virtual void Paste(const Property &from) = 0; @@ -279,9 +279,9 @@ protected: protected: /// Gets called by all setValue() methods after the value has changed - virtual void hasSetValue(void); + virtual void hasSetValue(); /// Gets called by all setValue() methods before the value has changed - virtual void aboutToSetValue(void); + virtual void aboutToSetValue(); /// Verify a path for the current property virtual void verifyPath(const App::ObjectIdentifier & p) const; @@ -345,7 +345,7 @@ public: * hasn't been marked before, and calls its * aboutToSetValue(). */ - AtomicPropertyChange(P & prop, bool markChange=true) : mProp(prop) { + explicit AtomicPropertyChange(P & prop, bool markChange=true) : mProp(prop) { mProp.signalCounter++; if (markChange) aboutToChange(); @@ -423,7 +423,7 @@ class AppExport PropertyListsBase { public: virtual void setSize(int newSize)=0; - virtual int getSize(void) const =0; + virtual int getSize() const =0; const std::set &getTouchList() const { return _touchList; @@ -456,7 +456,7 @@ class AppExport PropertyLists : public Property, public PropertyListsBase { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual void setPyObject(PyObject *obj) override { + void setPyObject(PyObject *obj) override { _setPyObject(obj); } @@ -486,11 +486,11 @@ public: _lValueList.resize(newSize,def); } - virtual void setSize(int newSize) override { + void setSize(int newSize) override { _lValueList.resize(newSize); } - virtual int getSize(void) const override { + int getSize() const override { return static_cast(_lValueList.size()); } @@ -511,21 +511,21 @@ public: setValues(newValues); } - const ListT &getValues(void) const{return _lValueList;} + const ListT &getValues() const{return _lValueList;} // alias to getValues - const ListT &getValue(void) const{return getValues();} + const ListT &getValue() const{return getValues();} const_reference operator[] (int idx) const {return _lValueList[idx];} - virtual bool isSame(const Property &other) const override { + bool isSame(const Property &other) const override { if (&other == this) return true; return this->getTypeId() == other.getTypeId() && this->getValue() == static_cast(&other)->getValue(); } - virtual void setPyObject(PyObject *value) override { + void setPyObject(PyObject *value) override { try { setValue(getPyValue(value)); return; diff --git a/src/App/PropertyContainer.cpp b/src/App/PropertyContainer.cpp index 97e6a4b539..d12c89c3bf 100644 --- a/src/App/PropertyContainer.cpp +++ b/src/App/PropertyContainer.cpp @@ -50,12 +50,9 @@ PropertyContainer::PropertyContainer() propertyData.parentPropertyData = nullptr; } -PropertyContainer::~PropertyContainer() -{ +PropertyContainer::~PropertyContainer() = default; -} - -unsigned int PropertyContainer::getMemSize (void) const +unsigned int PropertyContainer::getMemSize () const { std::map Map; getPropertyMap(Map); @@ -77,7 +74,7 @@ App::Property* PropertyContainer::addDynamicProperty( Property *PropertyContainer::getPropertyByName(const char* name) const { auto prop = dynamicProps.getDynamicPropertyByName(name); - if(prop) + if(prop) return prop; return getPropertyData().getPropertyByName(this,name); } @@ -121,7 +118,7 @@ short PropertyContainer::getPropertyType(const char *name) const const char* PropertyContainer::getPropertyGroup(const Property* prop) const { auto group = dynamicProps.getPropertyGroup(prop); - if(group) + if(group) return group; return getPropertyData().getGroup(this,prop); } @@ -129,7 +126,7 @@ const char* PropertyContainer::getPropertyGroup(const Property* prop) const const char* PropertyContainer::getPropertyGroup(const char *name) const { auto group = dynamicProps.getPropertyGroup(name); - if(group) + if(group) return group; return getPropertyData().getGroup(this,name); } @@ -137,7 +134,7 @@ const char* PropertyContainer::getPropertyGroup(const char *name) const const char* PropertyContainer::getPropertyDocumentation(const Property* prop) const { auto doc = dynamicProps.getPropertyDocumentation(prop); - if(doc) + if(doc) return doc; return getPropertyData().getDocumentation(this,prop); } @@ -145,7 +142,7 @@ const char* PropertyContainer::getPropertyDocumentation(const Property* prop) co const char* PropertyContainer::getPropertyDocumentation(const char *name) const { auto doc = dynamicProps.getPropertyDocumentation(name); - if(doc) + if(doc) return doc; return getPropertyData().getDocumentation(this,name); } @@ -178,8 +175,8 @@ const char* PropertyContainer::getPropertyName(const Property* prop)const return res; } -const PropertyData * PropertyContainer::getPropertyDataPtr(void){return &propertyData;} -const PropertyData & PropertyContainer::getPropertyData(void) const{return propertyData;} +const PropertyData * PropertyContainer::getPropertyDataPtr(){return &propertyData;} +const PropertyData & PropertyContainer::getPropertyData() const{return propertyData;} /** * @brief PropertyContainer::handleChangedPropertyName is called during restore to possibly diff --git a/src/App/PropertyContainer.h b/src/App/PropertyContainer.h index feddcfe5e5..e2ecac07fa 100644 --- a/src/App/PropertyContainer.h +++ b/src/App/PropertyContainer.h @@ -73,8 +73,8 @@ struct AppExport PropertyData //accepting void* struct OffsetBase { - OffsetBase(const App::PropertyContainer* container) : m_container(container) {} - OffsetBase(const App::Extension* container) : m_container(container) {} + OffsetBase(const App::PropertyContainer* container) : m_container(container) {}//explicit bombs + OffsetBase(const App::Extension* container) : m_container(container) {}//explicit bombs short int getOffsetTo(const App::Property* prop) const { auto *pt = (const char*)prop; @@ -82,7 +82,7 @@ struct AppExport PropertyData if(ptbase+SHRT_MAX) return -1; return (short) (pt-base); - }; + } char* getOffset() const {return (char*) m_container;} private: @@ -141,7 +141,7 @@ struct AppExport PropertyData class AppExport PropertyContainer: public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -154,9 +154,9 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyContainer(); + ~PropertyContainer() override; - virtual unsigned int getMemSize (void) const; + unsigned int getMemSize () const override; virtual std::string getFullName() const {return std::string();} @@ -218,8 +218,8 @@ public: virtual void onPropertyStatusChanged(const Property &prop, unsigned long oldStatus); - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; virtual void editProperty(const char * /*propName*/) {} @@ -242,8 +242,8 @@ protected: virtual void onBeforeChange(const Property* /*prop*/){} //void hasChanged(Property* prop); - static const PropertyData * getPropertyDataPtr(void); - virtual const PropertyData& getPropertyData(void) const; + static const PropertyData * getPropertyDataPtr(); + virtual const PropertyData& getPropertyData() const; virtual void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName); virtual void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, Property * prop); diff --git a/src/App/PropertyContainerPyImp.cpp b/src/App/PropertyContainerPyImp.cpp index 591d03544c..03e84a5d59 100644 --- a/src/App/PropertyContainerPyImp.cpp +++ b/src/App/PropertyContainerPyImp.cpp @@ -43,7 +43,7 @@ FC_LOG_LEVEL_INIT("Property", true, 2) using namespace App; // returns a string which represent the object e.g. when printed in python -std::string PropertyContainerPy::representation(void) const +std::string PropertyContainerPy::representation() const { return std::string(""); } @@ -448,7 +448,7 @@ PyObject* PropertyContainerPy::getEnumerationsOfProperty(PyObject *args) return Py::new_reference_to(ret); } -Py::List PropertyContainerPy::getPropertiesList(void) const +Py::List PropertyContainerPy::getPropertiesList() const { Py::List ret; std::map Map; diff --git a/src/App/PropertyExpressionEngine.cpp b/src/App/PropertyExpressionEngine.cpp index 5f65e20cbe..cb7605af42 100644 --- a/src/App/PropertyExpressionEngine.cpp +++ b/src/App/PropertyExpressionEngine.cpp @@ -96,9 +96,7 @@ PropertyExpressionEngine::PropertyExpressionEngine() * @brief Destroy the PropertyExpressionEngine object. */ -PropertyExpressionEngine::~PropertyExpressionEngine() -{ -} +PropertyExpressionEngine::~PropertyExpressionEngine() = default; /** * @brief Estimate memory size of this property. @@ -182,11 +180,11 @@ void PropertyExpressionEngine::hasSetValue() std::string key = objName + propName; auto &propDeps = pimpl->propMap[key]; if(propDeps.empty()) { - if(propName.size()) - pimpl->conns.push_back(obj->signalChanged.connect(boost::bind( + if(!propName.empty()) + pimpl->conns.emplace_back(obj->signalChanged.connect(boost::bind( &PropertyExpressionEngine::slotChangedProperty,this,_1,_2))); else - pimpl->conns.push_back(obj->signalChanged.connect(boost::bind( + pimpl->conns.emplace_back(obj->signalChanged.connect(boost::bind( &PropertyExpressionEngine::slotChangedObject,this,_1,_2))); } propDeps.push_back(e.first); @@ -484,7 +482,7 @@ void PropertyExpressionEngine::setValue(const ObjectIdentifier & path, std::shar if (expr) { std::string error = validateExpression(usePath, expr); - if (error.size() > 0) + if (!error.empty()) throw Base::RuntimeError(error.c_str()); AtomicPropertyChange signaller(*this); expressions[usePath] = ExpressionInfo(expr); @@ -634,7 +632,7 @@ DocumentObjectExecReturn *App::PropertyExpressionEngine::execute(ExecuteOption o class resetter { public: - resetter(bool & b) : _b(b) { _b = true; } + explicit resetter(bool & b) : _b(b) { _b = true; } ~resetter() { _b = false; } private: @@ -724,7 +722,7 @@ void PropertyExpressionEngine::getPathsToDocumentObject(DocumentObject* obj, { DocumentObject * owner = freecad_dynamic_cast(getContainer()); - if (owner == nullptr || owner==obj) + if (!owner || owner==obj) return; for(auto &v : expressions) { @@ -768,7 +766,7 @@ std::string PropertyExpressionEngine::validateExpression(const ObjectIdentifier if (validator) { error = validator(usePath, expr); - if (error.size() > 0) + if (!error.empty()) return error; } @@ -854,7 +852,7 @@ void PropertyExpressionEngine::renameObjectIdentifiers(const std::map; class AppExport PropertyExpressionContainer : public App::PropertyXLinkContainer { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyExpressionContainer(); - virtual ~PropertyExpressionContainer(); + ~PropertyExpressionContainer() override; virtual std::map getExpressions() const = 0; virtual void setExpressions(std::map &&exprs) = 0; @@ -67,14 +67,14 @@ class AppExport PropertyExpressionEngine : public App::PropertyExpressionContain TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual void updateElementReference( + void updateElementReference( App::DocumentObject *feature, bool reverse=false, bool notify=false) override; - virtual bool referenceChanged() const override; - virtual bool adjustLink(const std::set &inList) override; - virtual Property *CopyOnImportExternal(const std::map &nameMap) const override; - virtual Property *CopyOnLabelChange(App::DocumentObject *obj, + bool referenceChanged() const override; + bool adjustLink(const std::set &inList) override; + Property *CopyOnImportExternal(const std::map &nameMap) const override; + Property *CopyOnLabelChange(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; typedef std::function expr)> ValidatorFunc; @@ -87,7 +87,7 @@ public: std::shared_ptr expression; /**< The actual expression tree */ bool busy; - ExpressionInfo(std::shared_ptr expression = std::shared_ptr()) { + explicit ExpressionInfo(std::shared_ptr expression = std::shared_ptr()) { this->expression = expression; this->busy = false; } @@ -105,17 +105,17 @@ public: }; PropertyExpressionEngine(); - ~PropertyExpressionEngine(); + ~PropertyExpressionEngine() override; - unsigned int getMemSize (void) const override; + unsigned int getMemSize () const override; - virtual std::map getExpressions() const override; - virtual void setExpressions(std::map &&exprs) override; - virtual void onRelabeledDocument(const App::Document &doc) override; + std::map getExpressions() const override; + void setExpressions(std::map &&exprs) override; + void onRelabeledDocument(const App::Document &doc) override; void setValue() { } // Dummy - Property *Copy(void) const override; + Property *Copy() const override; void Paste(const Property &from) override; @@ -164,15 +164,15 @@ public: ///signal called when an expression was changed boost::signals2::signal expressionChanged; - virtual void afterRestore() override; - virtual void onContainerRestored() override; + void afterRestore() override; + void onContainerRestored() override; /* Python interface */ - PyObject *getPyObject(void) override; + PyObject *getPyObject() override; void setPyObject(PyObject *) override; protected: - virtual void hasSetValue() override; + void hasSetValue() override; private: diff --git a/src/App/PropertyFile.cpp b/src/App/PropertyFile.cpp index 368eef20fb..60870f1b79 100644 --- a/src/App/PropertyFile.cpp +++ b/src/App/PropertyFile.cpp @@ -49,10 +49,7 @@ using namespace std; TYPESYSTEM_SOURCE(App::PropertyFileIncluded , App::Property) -PropertyFileIncluded::PropertyFileIncluded() -{ - -} +PropertyFileIncluded::PropertyFileIncluded() = default; PropertyFileIncluded::~PropertyFileIncluded() { @@ -583,17 +580,14 @@ PropertyFile::PropertyFile() m_filter = ""; } -PropertyFile::~PropertyFile() -{ - -} +PropertyFile::~PropertyFile() = default; void PropertyFile::setFilter(const std::string f) { m_filter = f; } -std::string PropertyFile::getFilter(void) const +std::string PropertyFile::getFilter() const { return m_filter; } diff --git a/src/App/PropertyFile.h b/src/App/PropertyFile.h index 97061023f4..e593f5cf19 100644 --- a/src/App/PropertyFile.h +++ b/src/App/PropertyFile.h @@ -41,17 +41,17 @@ namespace App */ class AppExport PropertyFile : public PropertyString { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyFile(); - virtual ~PropertyFile(); + ~PropertyFile() override; - virtual const char* getEditorName() const + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyFileItem"; } virtual void setFilter(const std::string filter); - virtual std::string getFilter(void) const; + virtual std::string getFilter() const; private: std::string m_filter; @@ -73,31 +73,31 @@ private: */ class AppExport PropertyFileIncluded : public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyFileIncluded(); - virtual ~PropertyFileIncluded(); + ~PropertyFileIncluded() override; void setValue(const char* sFile, const char* sName=nullptr); const char* getValue() const; - virtual const char* getEditorName() const + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyTransientFileItem"; } - virtual PyObject *getPyObject(); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy() const; - virtual void Paste(const Property &from); - virtual unsigned int getMemSize () const; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -114,13 +114,13 @@ public: std::string getExchangeTempFile() const; std::string getOriginalFileName() const; - bool isEmpty(void) const {return _cValue.empty();} + bool isEmpty() const {return _cValue.empty();} protected: // get the transient path if the property is in a DocumentObject std::string getDocTransientPath() const; std::string getUniqueFileName(const std::string&, const std::string&) const; - void aboutToSetValue(); + void aboutToSetValue() override; protected: mutable std::string _cValue; diff --git a/src/App/PropertyGeo.cpp b/src/App/PropertyGeo.cpp index aa8ebe810c..2eef5db185 100644 --- a/src/App/PropertyGeo.cpp +++ b/src/App/PropertyGeo.cpp @@ -59,16 +59,10 @@ TYPESYSTEM_SOURCE(App::PropertyVector , App::Property) // Construction/Destruction -PropertyVector::PropertyVector() -{ - -} +PropertyVector::PropertyVector() = default; -PropertyVector::~PropertyVector() -{ - -} +PropertyVector::~PropertyVector() = default; //************************************************************************** // Base class implementer @@ -88,12 +82,12 @@ void PropertyVector::setValue(double x, double y, double z) hasSetValue(); } -const Base::Vector3d & PropertyVector::getValue(void)const +const Base::Vector3d & PropertyVector::getValue()const { return _cVec; } -PyObject *PropertyVector::getPyObject(void) +PyObject *PropertyVector::getPyObject() { return new Base::VectorPy(_cVec); } @@ -159,7 +153,7 @@ void PropertyVector::Restore(Base::XMLReader &reader) } -Property *PropertyVector::Copy(void) const +Property *PropertyVector::Copy() const { PropertyVector *p= new PropertyVector(); p->_cVec = _cVec; @@ -225,15 +219,9 @@ TYPESYSTEM_SOURCE(App::PropertyVectorDistance , App::PropertyVector) // Construction/Destruction -PropertyVectorDistance::PropertyVectorDistance() -{ +PropertyVectorDistance::PropertyVectorDistance() = default; -} - -PropertyVectorDistance::~PropertyVectorDistance() -{ - -} +PropertyVectorDistance::~PropertyVectorDistance() = default; //************************************************************************** // PropertyPosition @@ -245,15 +233,9 @@ TYPESYSTEM_SOURCE(App::PropertyPosition , App::PropertyVector) // Construction/Destruction -PropertyPosition::PropertyPosition() -{ +PropertyPosition::PropertyPosition() = default; -} - -PropertyPosition::~PropertyPosition() -{ - -} +PropertyPosition::~PropertyPosition() = default; //************************************************************************** // PropertyPosition @@ -265,15 +247,9 @@ TYPESYSTEM_SOURCE(App::PropertyDirection , App::PropertyVector) // Construction/Destruction -PropertyDirection::PropertyDirection() -{ +PropertyDirection::PropertyDirection() = default; -} - -PropertyDirection::~PropertyDirection() -{ - -} +PropertyDirection::~PropertyDirection() = default; //************************************************************************** // PropertyVectorList @@ -284,15 +260,9 @@ TYPESYSTEM_SOURCE(App::PropertyVectorList , App::PropertyLists) //************************************************************************** // Construction/Destruction -PropertyVectorList::PropertyVectorList() -{ +PropertyVectorList::PropertyVectorList() = default; -} - -PropertyVectorList::~PropertyVectorList() -{ - -} +PropertyVectorList::~PropertyVectorList() = default; //************************************************************************** // Base class implementer @@ -302,12 +272,12 @@ void PropertyVectorList::setValue(double x, double y, double z) setValue(Base::Vector3d(x,y,z)); } -PyObject *PropertyVectorList::getPyObject(void) +PyObject *PropertyVectorList::getPyObject() { - PyObject* list = PyList_New( getSize() ); + PyObject* list = PyList_New(getSize()); - for (int i = 0;i_lValueList = _lValueList; @@ -389,7 +359,7 @@ void PropertyVectorList::Paste(const Property &from) setValues(dynamic_cast(from)._lValueList); } -unsigned int PropertyVectorList::getMemSize (void) const +unsigned int PropertyVectorList::getMemSize () const { return static_cast(_lValueList.size() * sizeof(Base::Vector3d)); } @@ -405,16 +375,10 @@ TYPESYSTEM_SOURCE(App::PropertyMatrix , App::Property) // Construction/Destruction -PropertyMatrix::PropertyMatrix() -{ - -} +PropertyMatrix::PropertyMatrix() = default; -PropertyMatrix::~PropertyMatrix() -{ - -} +PropertyMatrix::~PropertyMatrix() = default; //************************************************************************** // Base class implementer @@ -428,12 +392,12 @@ void PropertyMatrix::setValue(const Base::Matrix4D &mat) } -const Base::Matrix4D & PropertyMatrix::getValue(void)const +const Base::Matrix4D & PropertyMatrix::getValue()const { return _cMat; } -PyObject *PropertyMatrix::getPyObject(void) +PyObject *PropertyMatrix::getPyObject() { return new Base::MatrixPy(_cMat); } @@ -508,7 +472,7 @@ void PropertyMatrix::Restore(Base::XMLReader &reader) } -Property *PropertyMatrix::Copy(void) const +Property *PropertyMatrix::Copy() const { PropertyMatrix *p= new PropertyMatrix(); p->_cMat = _cMat; @@ -533,16 +497,10 @@ TYPESYSTEM_SOURCE(App::PropertyPlacement , App::Property) // Construction/Destruction -PropertyPlacement::PropertyPlacement() -{ - -} +PropertyPlacement::PropertyPlacement() = default; -PropertyPlacement::~PropertyPlacement() -{ - -} +PropertyPlacement::~PropertyPlacement() = default; //************************************************************************** // Base class implementer @@ -567,7 +525,7 @@ bool PropertyPlacement::setValueIfChanged(const Base::Placement &pos,double tol, } -const Base::Placement & PropertyPlacement::getValue(void)const +const Base::Placement & PropertyPlacement::getValue()const { return _cPos; } @@ -664,7 +622,7 @@ bool PropertyPlacement::getPyPathValue(const ObjectIdentifier &path, Py::Object return true; } -PyObject *PropertyPlacement::getPyObject(void) +PyObject *PropertyPlacement::getPyObject() { return new Base::PlacementPy(new Base::Placement(_cPos)); } @@ -739,7 +697,7 @@ void PropertyPlacement::Restore(Base::XMLReader &reader) } -Property *PropertyPlacement::Copy(void) const +Property *PropertyPlacement::Copy() const { PropertyPlacement *p= new PropertyPlacement(); p->_cPos = _cPos; @@ -763,20 +721,14 @@ TYPESYSTEM_SOURCE(App::PropertyPlacementList , App::PropertyLists) //************************************************************************** // Construction/Destruction -PropertyPlacementList::PropertyPlacementList() -{ +PropertyPlacementList::PropertyPlacementList() = default; -} - -PropertyPlacementList::~PropertyPlacementList() -{ - -} +PropertyPlacementList::~PropertyPlacementList() = default; //************************************************************************** // Base class implementer -PyObject *PropertyPlacementList::getPyObject(void) +PyObject *PropertyPlacementList::getPyObject() { PyObject* list = PyList_New( getSize() ); @@ -864,7 +816,7 @@ void PropertyPlacementList::RestoreDocFile(Base::Reader &reader) setValues(values); } -Property *PropertyPlacementList::Copy(void) const +Property *PropertyPlacementList::Copy() const { PropertyPlacementList *p= new PropertyPlacementList(); p->_lValueList = _lValueList; @@ -876,7 +828,7 @@ void PropertyPlacementList::Paste(const Property &from) setValues(dynamic_cast(from)._lValueList); } -unsigned int PropertyPlacementList::getMemSize (void) const +unsigned int PropertyPlacementList::getMemSize () const { return static_cast(_lValueList.size() * sizeof(Base::Vector3d)); } @@ -895,18 +847,12 @@ TYPESYSTEM_SOURCE(App::PropertyPlacementLink , App::PropertyLink) // Construction/Destruction -PropertyPlacementLink::PropertyPlacementLink() -{ - -} +PropertyPlacementLink::PropertyPlacementLink() = default; -PropertyPlacementLink::~PropertyPlacementLink() -{ +PropertyPlacementLink::~PropertyPlacementLink() = default; -} - -App::Placement * PropertyPlacementLink::getPlacementObject(void) const +App::Placement * PropertyPlacementLink::getPlacementObject() const { if (_pcLink->getTypeId().isDerivedFrom(App::Placement::getClassTypeId())) return dynamic_cast(_pcLink); @@ -918,7 +864,7 @@ App::Placement * PropertyPlacementLink::getPlacementObject(void) const //************************************************************************** // Base class implementer -Property *PropertyPlacementLink::Copy(void) const +Property *PropertyPlacementLink::Copy() const { PropertyPlacementLink *p= new PropertyPlacementLink(); p->_pcLink = _pcLink; @@ -939,16 +885,10 @@ void PropertyPlacementLink::Paste(const Property &from) TYPESYSTEM_SOURCE(App::PropertyRotation , App::Property) -PropertyRotation::PropertyRotation() -{ - -} +PropertyRotation::PropertyRotation() = default; -PropertyRotation::~PropertyRotation() -{ - -} +PropertyRotation::~PropertyRotation() = default; void PropertyRotation::setValue(const Base::Rotation &rot) { @@ -1113,26 +1053,14 @@ void PropertyRotation::Paste(const Property &from) TYPESYSTEM_SOURCE_ABSTRACT(App::PropertyGeometry , App::Property) -PropertyGeometry::PropertyGeometry() -{ +PropertyGeometry::PropertyGeometry() = default; -} - -PropertyGeometry::~PropertyGeometry() -{ - -} +PropertyGeometry::~PropertyGeometry() = default; // ------------------------------------------------------------ TYPESYSTEM_SOURCE_ABSTRACT(App::PropertyComplexGeoData , App::PropertyGeometry) -PropertyComplexGeoData::PropertyComplexGeoData() -{ +PropertyComplexGeoData::PropertyComplexGeoData() = default; -} - -PropertyComplexGeoData::~PropertyComplexGeoData() -{ - -} +PropertyComplexGeoData::~PropertyComplexGeoData() = default; diff --git a/src/App/PropertyGeo.h b/src/App/PropertyGeo.h index 1515809be7..a9268fdea4 100644 --- a/src/App/PropertyGeo.h +++ b/src/App/PropertyGeo.h @@ -67,7 +67,7 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyVector(); + ~PropertyVector() override; /** Sets the property */ @@ -79,37 +79,37 @@ public: /** This method returns a string representation of the property */ - const Base::Vector3d &getValue(void) const; - const char* getEditorName(void) const override { + const Base::Vector3d &getValue() const; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyVectorItem"; } - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override { + unsigned int getMemSize () const override { return sizeof(Base::Vector3d); } - virtual const boost::any getPathValue(const ObjectIdentifier &path) const override; + const boost::any getPathValue(const ObjectIdentifier &path) const override; - virtual bool getPyPathValue(const ObjectIdentifier &path, Py::Object &res) const override; + bool getPyPathValue(const ObjectIdentifier &path, Py::Object &res) const override; virtual Base::Unit getUnit() const { return Base::Unit(); } - virtual bool isSame(const Property &other) const override { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() - && getValue() == static_cast(&other)->getValue(); + && getValue() == dynamic_cast(&other)->getValue(); } private: @@ -119,7 +119,7 @@ private: class AppExport PropertyVectorDistance: public PropertyVector { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -132,20 +132,20 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyVectorDistance(); + ~PropertyVectorDistance() override; - virtual Base::Unit getUnit() const { + Base::Unit getUnit() const override { return Base::Unit::Length; } - const char* getEditorName(void) const { + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyVectorDistanceItem"; } }; class AppExport PropertyPosition: public PropertyVector { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -158,20 +158,20 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyPosition(); + ~PropertyPosition() override; - virtual Base::Unit getUnit() const { + Base::Unit getUnit() const override { return Base::Unit::Length; } - const char* getEditorName(void) const { + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyPositionItem"; } }; class AppExport PropertyDirection: public PropertyVector { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -184,13 +184,13 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyDirection(); + ~PropertyDirection() override; - virtual Base::Unit getUnit() const { + Base::Unit getUnit() const override { return Base::Unit::Length; } - const char* getEditorName(void) const { + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyDirectionItem"; } }; @@ -212,24 +212,24 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyVectorList(); + ~PropertyVectorList() override; void setValue(double x, double y, double z); using inherited::setValue; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const override; - virtual void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override; - const char* getEditorName(void) const override { + unsigned int getMemSize () const override; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyVectorListItem"; } @@ -243,7 +243,7 @@ protected: */ class AppExport PropertyMatrix: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -256,7 +256,7 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyMatrix(); + ~PropertyMatrix() override; /** Sets the property */ @@ -264,25 +264,25 @@ public: /** This method returns a string representation of the property */ - const Base::Matrix4D &getValue(void) const; - const char* getEditorName(void) const { + const Base::Matrix4D &getValue() const; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyMatrixItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const { + unsigned int getMemSize () const override { return sizeof(Base::Matrix4D); } - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -312,7 +312,7 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyPlacement(); + ~PropertyPlacement() override; /** Sets the property */ @@ -328,35 +328,35 @@ public: /** This method returns a string representation of the property */ - const Base::Placement &getValue(void) const; + const Base::Placement &getValue() const; /// Get valid paths for this property; used by auto completer void getPaths(std::vector &paths) const override; void setPathValue(const ObjectIdentifier &path, const boost::any &value) override; - virtual const boost::any getPathValue(const ObjectIdentifier &path) const override; + const boost::any getPathValue(const ObjectIdentifier &path) const override; - virtual bool getPyPathValue(const ObjectIdentifier &path, Py::Object &res) const override; + bool getPyPathValue(const ObjectIdentifier &path, Py::Object &res) const override; - const char* getEditorName(void) const override { + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyPlacementItem"; } - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override { + unsigned int getMemSize () const override { return sizeof(Base::Placement); } - virtual bool isSame(const Property &other) const override { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -374,7 +374,7 @@ private: */ class AppExport PropertyPlacementLink : public PropertyLink { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -387,14 +387,14 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyPlacementLink(); + ~PropertyPlacementLink() override; /** This method returns the linked DocumentObject */ - App::Placement * getPlacementObject(void) const; + App::Placement * getPlacementObject() const; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; }; @@ -408,20 +408,20 @@ public: */ PropertyPlacementList(); - virtual ~PropertyPlacementList(); + ~PropertyPlacementList() override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const override; - virtual void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override; + unsigned int getMemSize () const override; protected: Base::Placement getPyValue(PyObject *) const override; @@ -447,7 +447,7 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyRotation(); + ~PropertyRotation() override; /** Sets the property */ @@ -469,24 +469,24 @@ public: void setPathValue(const ObjectIdentifier &path, const boost::any &value) override; - virtual const boost::any getPathValue(const ObjectIdentifier &path) const override; + const boost::any getPathValue(const ObjectIdentifier &path) const override; - virtual bool getPyPathValue(const ObjectIdentifier &path, Py::Object &res) const override; + bool getPyPathValue(const ObjectIdentifier &path, Py::Object &res) const override; const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyRotationItem"; } - virtual PyObject *getPyObject() override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy() const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize () const override { + unsigned int getMemSize () const override { return sizeof(Base::Placement); } @@ -500,11 +500,11 @@ private: */ class AppExport PropertyGeometry : public App::Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyGeometry(); - virtual ~PropertyGeometry(); + ~PropertyGeometry() override; /** @name Modification */ //@{ @@ -524,22 +524,22 @@ public: */ class AppExport PropertyComplexGeoData : public App::PropertyGeometry { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyComplexGeoData(); - virtual ~PropertyComplexGeoData(); + ~PropertyComplexGeoData() override; /** @name Modification */ //@{ /// Applies a transformation on the real geometric data type - virtual void transformGeometry(const Base::Matrix4D &rclMat) = 0; + void transformGeometry(const Base::Matrix4D &rclMat) override = 0; //@} /** @name Getting basic geometric entities */ //@{ virtual const Data::ComplexGeoData* getComplexData() const = 0; - virtual Base::BoundBox3d getBoundingBox() const = 0; + Base::BoundBox3d getBoundingBox() const override = 0; //@} }; diff --git a/src/App/PropertyLinks.cpp b/src/App/PropertyLinks.cpp index 4616ab12bc..1bc29a722e 100644 --- a/src/App/PropertyLinks.cpp +++ b/src/App/PropertyLinks.cpp @@ -55,8 +55,7 @@ namespace bp = boost::placeholders; TYPESYSTEM_SOURCE_ABSTRACT(App::PropertyLinkBase , App::Property) static std::unordered_map > _LabelMap; -PropertyLinkBase::PropertyLinkBase() -{} +PropertyLinkBase::PropertyLinkBase() = default; PropertyLinkBase::~PropertyLinkBase() { unregisterLabelReferences(); @@ -115,7 +114,7 @@ void PropertyLinkBase::unregisterLabelReferences() void PropertyLinkBase::getLabelReferences(std::vector &subs,const char *subname) { const char *dot; - for(;(subname=strchr(subname,'$'))!=nullptr; subname=dot+1) { + for (; (subname = strchr(subname, '$')) != nullptr; subname = dot + 1) { ++subname; dot = strchr(subname,'.'); if(!dot) break; @@ -154,7 +153,7 @@ std::string PropertyLinkBase::updateLabelReference(const App::DocumentObject *pa // hierarchies, we have to search for all occurrences, and make sure the // referenced sub-object at the found hierarchy is actually the given // object. - for(const char *pos=subname; ((pos=strstr(pos,ref.c_str()))!=nullptr); pos+=ref.size()) { + for (const char *pos = subname; ((pos = strstr(pos, ref.c_str())) != nullptr); pos += ref.size()) { auto sub = std::string(subname,pos+ref.size()-subname); auto sobj = parent->getSubObject(sub.c_str()); if(sobj == obj) { @@ -216,7 +215,7 @@ void PropertyLinkBase::_registerElementReference(App::DocumentObject *obj, std:: class StringGuard { public: - StringGuard(char *c) + explicit StringGuard(char *c) :c(c) { v1 = c[0]; @@ -293,17 +292,6 @@ PropertyLinkBase::tryReplaceLink(const PropertyContainer *owner, DocumentObject if(oldObj == obj) { if(owner == parent) { - // Do not throw on sub object error yet. It's better to let - // recompute find out the error and point out the affected objects - // to user. -#if 0 - if(subname && subname[0] && !newObj->getSubObject(subname)) { - FC_THROWM(Base::RuntimeError, - "Sub-object '" << newObj->getFullName() - << '.' << subname << "' not found when replacing link in " - << owner->getFullName() << '.' << getName()); - } -#endif res.first = newObj; if(subname) res.second = subname; return res; @@ -326,14 +314,6 @@ PropertyLinkBase::tryReplaceLink(const PropertyContainer *owner, DocumentObject break; if(sobj == oldObj) { if(prev == parent) { -#if 0 - if(sub[pos] && !newObj->getSubObject(sub.c_str()+pos)) { - FC_THROWM(Base::RuntimeError, - "Sub-object '" << newObj->getFullName() - << '.' << (sub.c_str()+pos) << "' not found when replacing link in " - << owner->getFullName() << '.' << getName()); - } -#endif if(sub[prevPos] == '$') sub.replace(prevPos+1,pos-1-prevPos,newObj->Label.getValue()); else @@ -460,7 +440,7 @@ void PropertyLink::setValue(App::DocumentObject * lValue) hasSetValue(); } -App::DocumentObject * PropertyLink::getValue(void) const +App::DocumentObject * PropertyLink::getValue() const { return _pcLink; } @@ -470,7 +450,7 @@ App::DocumentObject * PropertyLink::getValue(Base::Type t) const return (_pcLink && _pcLink->getTypeId().isDerivedFrom(t)) ? _pcLink : nullptr; } -PyObject *PropertyLink::getPyObject(void) +PyObject *PropertyLink::getPyObject() { if (_pcLink) return _pcLink->getPyObject(); @@ -509,7 +489,7 @@ void PropertyLink::Restore(Base::XMLReader &reader) // Property not in a DocumentObject! assert(getContainer()->getTypeId().isDerivedFrom(App::DocumentObject::getClassTypeId()) ); - if (name != "") { + if (!name.empty()) { DocumentObject* parent = static_cast(getContainer()); App::Document* document = parent->getDocument(); @@ -534,7 +514,7 @@ void PropertyLink::Restore(Base::XMLReader &reader) } } -Property *PropertyLink::Copy(void) const +Property *PropertyLink::Copy() const { PropertyLink *p= new PropertyLink(); p->_pcLink = _pcLink; @@ -593,10 +573,7 @@ TYPESYSTEM_SOURCE(App::PropertyLinkListHidden, App::PropertyLinkList) // Construction/Destruction -PropertyLinkList::PropertyLinkList() -{ - -} +PropertyLinkList::PropertyLinkList() = default; PropertyLinkList::~PropertyLinkList() { @@ -710,7 +687,7 @@ void PropertyLinkList::setValues(const std::vector& lValue) { inherited::setValues(lValue); } -PyObject *PropertyLinkList::getPyObject(void) +PyObject *PropertyLinkList::getPyObject() { int count = getSize(); #if 0//FIXME: Should switch to tuple @@ -832,7 +809,7 @@ Property *PropertyLinkList::CopyOnLinkReplace(const App::DocumentObject *parent, return p; } -Property *PropertyLinkList::Copy(void) const +Property *PropertyLinkList::Copy() const { PropertyLinkList *p = new PropertyLinkList(); p->_lValueList = _lValueList; @@ -847,7 +824,7 @@ void PropertyLinkList::Paste(const Property &from) setValues(static_cast(from)._lValueList); } -unsigned int PropertyLinkList::getMemSize(void) const +unsigned int PropertyLinkList::getMemSize() const { return static_cast(_lValueList.size() * sizeof(App::DocumentObject *)); } @@ -982,12 +959,12 @@ void PropertyLinkSub::setValue(App::DocumentObject * lValue, hasSetValue(); } -App::DocumentObject * PropertyLinkSub::getValue(void) const +App::DocumentObject * PropertyLinkSub::getValue() const { return _pcLinkSub; } -const std::vector& PropertyLinkSub::getSubValues(void) const +const std::vector& PropertyLinkSub::getSubValues() const { return _cSubList; } @@ -996,9 +973,9 @@ static inline const std::string &getSubNameWithStyle(const std::string &subName, const PropertyLinkBase::ShadowSub &shadow, bool newStyle) { if(!newStyle) { - if(shadow.second.size()) + if(!shadow.second.empty()) return shadow.second; - }else if(shadow.first.size()) + }else if(!shadow.first.empty()) return shadow.first; return subName; } @@ -1028,7 +1005,7 @@ App::DocumentObject * PropertyLinkSub::getValue(Base::Type t) const return (_pcLinkSub && _pcLinkSub->getTypeId().isDerivedFrom(t)) ? _pcLinkSub : nullptr; } -PyObject *PropertyLinkSub::getPyObject(void) +PyObject *PropertyLinkSub::getPyObject() { Py::Tuple tup(2); Py::List list(static_cast(_cSubList.size())); @@ -1124,7 +1101,7 @@ static bool updateLinkReference(App::PropertyLinkBase *prop, if(!touched) return false; for(int idx : mapped) { - if(idx<(int)subs.size() && shadows[idx].first.size()) + if(idx<(int)subs.size() && !shadows[idx].first.empty()) subs[idx] = shadows[idx].first; } mapped.clear(); @@ -1341,16 +1318,16 @@ void PropertyLinkSub::Save (Base::Writer &writer) const if(exporting) { std::string exportName; writer.Stream() << encodeAttribute(exportSubName(exportName,_pcLinkSub,sub.c_str())); - if(shadow.second.size() && shadow.first == _cSubList[i]) + if(!shadow.second.empty() && shadow.first == _cSubList[i]) writer.Stream() << "\" " ATTR_MAPPED "=\"1"; } else { writer.Stream() << encodeAttribute(sub); - if(_cSubList[i].size()) { + if(!_cSubList[i].empty()) { if(sub!=_cSubList[i]) { // Stores the actual value that is shadowed. For new version FC, // we will restore this shadowed value instead. writer.Stream() << "\" " ATTR_SHADOWED "=\"" << encodeAttribute(_cSubList[i]); - }else if(shadow.first.size()){ + }else if(!shadow.first.empty()){ // Here means the user set value is old style element name. // We shall then store the shadow somewhere else. writer.Stream() << "\" " ATTR_SHADOW "=\"" << encodeAttribute(shadow.first); @@ -1435,7 +1412,7 @@ std::vector updateLinkSubs(const App::DocumentObject *obj, res.insert(res.end(),subs.begin(),it); } res.push_back(std::move(new_sub)); - }else if(res.size()) + }else if(!res.empty()) res.push_back(sub); } return res; @@ -1497,7 +1474,7 @@ Property *PropertyLinkSub::CopyOnLinkReplace(const App::DocumentObject *parent, return nullptr; } -Property *PropertyLinkSub::Copy(void) const +Property *PropertyLinkSub::Copy() const { PropertyLinkSub *p= new PropertyLinkSub(); p->_pcLinkSub = _pcLinkSub; @@ -1594,10 +1571,7 @@ TYPESYSTEM_SOURCE(App::PropertyLinkSubListHidden, App::PropertyLinkSubList) // Construction/Destruction -PropertyLinkSubList::PropertyLinkSubList() -{ - -} +PropertyLinkSubList::PropertyLinkSubList() = default; PropertyLinkSubList::~PropertyLinkSubList() { @@ -1640,7 +1614,7 @@ void PropertyLinkSubList::setSize(int newSize) _ShadowSubList.resize(newSize); } -int PropertyLinkSubList::getSize(void) const +int PropertyLinkSubList::getSize() const { return static_cast(_lValueList.size()); } @@ -1721,7 +1695,7 @@ void PropertyLinkSubList::setValues(const std::vector& lValue,c _lSubList.resize(lSubNames.size()); int i = 0; for (std::vector::const_iterator it = lSubNames.begin();it!=lSubNames.end();++it,++i) { - if (*it != nullptr) + if (*it) _lSubList[i] = *it; } updateElementReference(nullptr); @@ -1893,7 +1867,7 @@ const string PropertyLinkSubList::getPyReprString() const { assert(this->_lValueList.size() == this->_lSubList.size()); - if (this->_lValueList.size() == 0) + if (this->_lValueList.empty()) return std::string("None"); std::stringstream strm; @@ -1923,7 +1897,7 @@ DocumentObject *PropertyLinkSubList::getValue() const App::DocumentObject* ret = nullptr; //FIXME: cache this to avoid iterating each time, to improve speed for (std::size_t i = 0; i < this->_lValueList.size(); i++) { - if (ret == nullptr) + if (!ret) ret = this->_lValueList[i]; if (ret != this->_lValueList[i]) return nullptr; @@ -1981,13 +1955,13 @@ std::vector PropertyLinkSubList::getSubListValues(b for (std::size_t i = 0; i < _lValueList.size(); i++) { App::DocumentObject* link = _lValueList[i]; std::string sub; - if(newStyle && _ShadowSubList[i].first.size()) + if(newStyle && !_ShadowSubList[i].first.empty()) sub = _ShadowSubList[i].first; - else if(!newStyle && _ShadowSubList[i].second.size()) + else if(!newStyle && !_ShadowSubList[i].second.empty()) sub = _ShadowSubList[i].second; else sub = _lSubList[i]; - if (values.size() == 0 || values.back().first != link){ + if (values.empty() || values.back().first != link){ //new object started, start a new subset. values.emplace_back(link, std::vector()); } @@ -1996,9 +1970,8 @@ std::vector PropertyLinkSubList::getSubListValues(b return values; } -PyObject *PropertyLinkSubList::getPyObject(void) +PyObject *PropertyLinkSubList::getPyObject() { -#if 1 std::vector subLists = getSubListValues(); std::size_t count = subLists.size(); #if 0//FIXME: Should switch to tuple @@ -2021,24 +1994,6 @@ PyObject *PropertyLinkSubList::getPyObject(void) } return Py::new_reference_to(sequence); -#else - unsigned int count = getSize(); -#if 0//FIXME: Should switch to tuple - Py::Tuple sequence(count); -#else - Py::List sequence(count); -#endif - for (unsigned int i = 0; igetPyObject()); - std::string subItem; - if (_lSubList.size() > i) - subItem = _lSubList[i]; - tup[1] = Py::String(subItem); - sequence[i] = tup; - } - return Py::new_reference_to(sequence); -#endif } void PropertyLinkSubList::setPyObject(PyObject *value) @@ -2145,7 +2100,7 @@ void PropertyLinkSubList::updateElementReference(DocumentObject *feature, bool r mapped.reserve(_mapped.size()); for(int idx : _mapped) { if(idx<(int)_lSubList.size()) { - if(_ShadowSubList[idx].first.size()) + if(!_ShadowSubList[idx].first.empty()) _lSubList[idx] = _ShadowSubList[idx].first; else mapped.push_back(idx); @@ -2189,16 +2144,16 @@ void PropertyLinkSubList::Save (Base::Writer &writer) const if(exporting) { std::string exportName; writer.Stream() << encodeAttribute(exportSubName(exportName,obj,sub.c_str())); - if(shadow.second.size() && _lSubList[i]==shadow.first) + if(!shadow.second.empty() && _lSubList[i]==shadow.first) writer.Stream() << "\" " ATTR_MAPPED "=\"1"; } else { writer.Stream() << encodeAttribute(sub); - if(_lSubList[i].size()) { + if(!_lSubList[i].empty()) { if(sub!=_lSubList[i]) { // Stores the actual value that is shadowed. For new version FC, // we will restore this shadowed value instead. writer.Stream() << "\" " ATTR_SHADOWED "=\"" << encodeAttribute(_lSubList[i]); - }else if(shadow.first.size()) { + }else if(!shadow.first.empty()) { // Here means the user set value is old style element name. // We shall then store the shadow somewhere else. writer.Stream() << "\" " ATTR_SHADOW "=\"" << encodeAttribute(shadow.first); @@ -2308,7 +2263,7 @@ Property *PropertyLinkSubList::CopyOnImportExternal( auto value = *itValue; const auto &sub = *itSub; if(!value || !value->getNameInDocument()) { - if(values.size()) { + if(!values.empty()) { values.push_back(value); subs.push_back(sub); } @@ -2316,7 +2271,7 @@ Property *PropertyLinkSubList::CopyOnImportExternal( } auto linked = tryImport(owner->getDocument(),value,nameMap); auto new_sub = tryImportSubName(value,sub.c_str(),owner->getDocument(),nameMap); - if(linked!=value || new_sub.size()) { + if(linked!=value || !new_sub.empty()) { if(values.empty()) { values.reserve(_lValueList.size()); values.insert(values.end(),_lValueList.begin(),itValue); @@ -2325,7 +2280,7 @@ Property *PropertyLinkSubList::CopyOnImportExternal( } values.push_back(linked); subs.push_back(std::move(new_sub)); - }else if(values.size()) { + }else if(!values.empty()) { values.push_back(linked); subs.push_back(sub); } @@ -2351,14 +2306,14 @@ Property *PropertyLinkSubList::CopyOnLabelChange(App::DocumentObject *obj, auto value = *itValue; const auto &sub = *itSub; if(!value || !value->getNameInDocument()) { - if(values.size()) { + if(!values.empty()) { values.push_back(value); subs.push_back(sub); } continue; } auto new_sub = updateLabelReference(value,sub.c_str(),obj,ref,newLabel); - if(new_sub.size()) { + if(!new_sub.empty()) { if(values.empty()) { values.reserve(_lValueList.size()); values.insert(values.end(),_lValueList.begin(),itValue); @@ -2367,7 +2322,7 @@ Property *PropertyLinkSubList::CopyOnLabelChange(App::DocumentObject *obj, } values.push_back(value); subs.push_back(std::move(new_sub)); - }else if(values.size()) { + }else if(!values.empty()) { values.push_back(value); subs.push_back(sub); } @@ -2391,7 +2346,7 @@ Property *PropertyLinkSubList::CopyOnLinkReplace(const App::DocumentObject *pare auto value = *itValue; const auto &sub = *itSub; if(!value || !value->getNameInDocument()) { - if(values.size()) { + if(!values.empty()) { values.push_back(value); subs.push_back(sub); } @@ -2421,7 +2376,7 @@ Property *PropertyLinkSubList::CopyOnLinkReplace(const App::DocumentObject *pare } values.push_back(res.first); subs.push_back(std::move(res.second)); - }else if(values.size()) { + }else if(!values.empty()) { bool duplicate = false; if(value == newObj) { for(auto pos : positions) { @@ -2445,7 +2400,7 @@ Property *PropertyLinkSubList::CopyOnLinkReplace(const App::DocumentObject *pare return p.release(); } -Property *PropertyLinkSubList::Copy(void) const +Property *PropertyLinkSubList::Copy() const { PropertyLinkSubList *p = new PropertyLinkSubList(); p->_lValueList = _lValueList; @@ -2461,7 +2416,7 @@ void PropertyLinkSubList::Paste(const Property &from) setValues(link._lValueList, link._lSubList); } -unsigned int PropertyLinkSubList::getMemSize (void) const +unsigned int PropertyLinkSubList::getMemSize () const { unsigned int size = static_cast(_lValueList.size() * sizeof(App::DocumentObject *)); for(int i = 0;ifirst).canonicalFilePath(); return QFileInfo(myPos->first).absoluteFilePath(); } } @@ -2698,8 +2651,7 @@ public: :pcDoc(nullptr) {} - ~DocInfo() { - } + ~DocInfo() = default; void deinit() { FC_LOG("deinit " << (pcDoc?pcDoc->getName():filePath())); @@ -2832,7 +2784,6 @@ public: return; QFileInfo info(myPos->first); - // QString path(info.canonicalFilePath()); QString path(info.absoluteFilePath()); const char *filename = doc.getFileName(); QString docPath(getFullPath(filename)); @@ -2854,7 +2805,6 @@ public: tmp.swap(links); for(auto link : tmp) { auto owner = static_cast(link->getContainer()); - QString path = QString::fromUtf8(link->filePath.c_str()); // adjust file path for each PropertyXLink DocInfo::get(filename,owner->getDocument(),link,link->objectName.c_str()); } @@ -3161,7 +3111,7 @@ void PropertyXLink::setValue(std::string &&filename, std::string &&name, DocumentObject *pObject=nullptr; DocInfoPtr info; - if(filename.size()) { + if(!filename.empty()) { owner->getDocument()->signalLinkXsetValue(filename); info = DocInfo::get(filename.c_str(),owner->getDocument(),this,name.c_str()); if(info->pcDoc) @@ -3225,13 +3175,13 @@ bool PropertyXLink::upgrade(Base::XMLReader &reader, const char *typeName) { int PropertyXLink::checkRestore(std::string *msg) const { if(!docInfo) { - if(!_pcLink && objectName.size()) { + if(!_pcLink && !objectName.empty()) { // this condition means linked object not found if(msg) { std::ostringstream ss; ss << "Link not restored" << std::endl; ss << "Object: " << objectName; - if(filePath.size()) + if(!filePath.empty()) ss << std::endl << "File: " << filePath; *msg = ss.str(); } @@ -3252,7 +3202,7 @@ int PropertyXLink::checkRestore(std::string *msg) const { ss << "Linked object: " << objectName; if(docInfo->pcDoc) ss << std::endl << "Linked document: " << docInfo->pcDoc->Label.getValue(); - else if(filePath.size()) + else if(!filePath.empty()) ss << std::endl << "Linked file: " << filePath; *msg = ss.str(); } @@ -3322,14 +3272,14 @@ void PropertyXLink::Save (Base::Writer &writer) const { auto pDoc = owner->getDocument(); const char *docPath = pDoc->getFileName(); if(docPath && docPath[0]) { - if(filePath.size()) + if(!filePath.empty()) _path = DocInfo::getDocPath(filePath.c_str(),pDoc,false); else _path = docPath; }else FC_WARN("PropertyXLink export without saving the document"); } - if(_path.size()) + if(!_path.empty()) path = _path.c_str(); } writer.Stream() << writer.ind() @@ -3351,14 +3301,14 @@ void PropertyXLink::Save (Base::Writer &writer) const { std::string exportName; writer.Stream() << "\" sub=\"" << encodeAttribute(exportSubName(exportName,_pcLink,sub.c_str())); - if(shadowSub.second.size() && shadowSub.first==subName) + if(!shadowSub.second.empty() && shadowSub.first==subName) writer.Stream() << "\" " ATTR_MAPPED "=\"1"; }else{ writer.Stream() << "\" sub=\"" << encodeAttribute(sub); - if(sub.size()) { + if(!sub.empty()) { if(sub!=subName) writer.Stream() << "\" " ATTR_SHADOWED "=\"" << encodeAttribute(subName); - else if(shadowSub.first.size()) + else if(!shadowSub.first.empty()) writer.Stream() << "\" " ATTR_SHADOW "=\"" << encodeAttribute(shadowSub.first); } } @@ -3376,14 +3326,14 @@ void PropertyXLink::Save (Base::Writer &writer) const { if(exporting) { std::string exportName; writer.Stream() << encodeAttribute(exportSubName(exportName,_pcLink,sub.c_str())); - if(shadow.second.size() && shadow.first == _SubList[i]) + if(!shadow.second.empty() && shadow.first == _SubList[i]) writer.Stream() << "\" " ATTR_MAPPED "=\"1"; } else { writer.Stream() << encodeAttribute(sub); - if(_SubList[i].size()) { + if(!_SubList[i].empty()) { if(sub!=_SubList[i]) writer.Stream() << "\" " ATTR_SHADOWED "=\"" << encodeAttribute(_SubList[i]); - else if(shadow.first.size()) + else if(!shadow.first.empty()) writer.Stream() << "\" " ATTR_SHADOW "=\"" << encodeAttribute(shadow.first); } } @@ -3414,7 +3364,7 @@ void PropertyXLink::Restore(Base::XMLReader &reader) assert(getContainer()->getTypeId().isDerivedFrom(App::DocumentObject::getClassTypeId())); DocumentObject *object = nullptr; - if(name.size() && file.empty()) { + if(!name.empty() && file.empty()) { DocumentObject* parent = static_cast(getContainer()); Document *document = parent->getDocument(); object = document ? document->getObject(name.c_str()) : nullptr; @@ -3472,7 +3422,7 @@ void PropertyXLink::Restore(Base::XMLReader &reader) return; } - if(file.size() || (!object && name.size())) { + if(!file.empty() || (!object && !name.empty())) { this->stamp = stampAttr; setValue(std::move(file),std::move(name),std::move(subs),std::move(shadows)); }else @@ -3546,7 +3496,7 @@ void PropertyXLink::copyTo(PropertyXLink &other, other._Flags = _Flags; } -Property *PropertyXLink::Copy(void) const +Property *PropertyXLink::Copy() const { std::unique_ptr p(new PropertyXLink); copyTo(*p); @@ -3559,7 +3509,7 @@ void PropertyXLink::Paste(const Property &from) throw Base::TypeError("Incompatible property to paste to"); const auto &other = static_cast(from); - if(other.docName.size()) { + if(!other.docName.empty()) { auto doc = GetApplication().getDocument(other.docName.c_str()); if(!doc) { FC_WARN("Document '" << other.docName << "' not found"); @@ -3657,7 +3607,7 @@ PropertyXLink::getDocumentInList(App::Document *doc) { return ret; } -PyObject *PropertyXLink::getPyObject(void) +PyObject *PropertyXLink::getPyObject() { if(!_pcLink) Py_Return; @@ -3781,11 +3731,11 @@ void PropertyXLink::setAllowPartial(bool enable) { return; if(!App::GetApplication().isRestoring() && !owner->getDocument()->isPerformingTransaction() && - !_pcLink && docInfo && filePath.size() && objectName.size() && + !_pcLink && docInfo && !filePath.empty() && !objectName.empty() && (!docInfo->pcDoc || docInfo->pcDoc->testStatus(Document::PartialDoc))) { auto path = docInfo->getDocPath(filePath.c_str(),owner->getDocument(),false); - if(path.size()) + if(!path.empty()) App::GetApplication().openDocument(path.c_str()); } } @@ -3802,8 +3752,7 @@ PropertyXLinkSub::PropertyXLinkSub(bool allowPartial, PropertyLinkBase *parent) } -PropertyXLinkSub::~PropertyXLinkSub() { -} +PropertyXLinkSub::~PropertyXLinkSub() = default; bool PropertyXLinkSub::upgrade(Base::XMLReader &reader, const char *typeName) { if(strcmp(typeName, PropertyLinkSubGlobal::getClassTypeId().getName())==0 || @@ -3819,7 +3768,7 @@ bool PropertyXLinkSub::upgrade(Base::XMLReader &reader, const char *typeName) { return PropertyXLink::upgrade(reader,typeName); } -PyObject *PropertyXLinkSub::getPyObject(void) +PyObject *PropertyXLinkSub::getPyObject() { if(!_pcLink) Py_Return; @@ -3853,16 +3802,14 @@ PropertyXLinkSubList::PropertyXLinkSubList() setSyncSubObject(true); } -PropertyXLinkSubList::~PropertyXLinkSubList() -{ -} +PropertyXLinkSubList::~PropertyXLinkSubList() = default; void PropertyXLinkSubList::setSyncSubObject(bool enable) { _Flags.set((std::size_t)LinkSyncSubObject, enable); } -int PropertyXLinkSubList::getSize(void) const +int PropertyXLinkSubList::getSize() const { return static_cast(_Links.size()); } @@ -4053,7 +4000,7 @@ const string PropertyXLinkSubList::getPyReprString() const DocumentObject *PropertyXLinkSubList::getValue() const { - if(_Links.size()) + if(!_Links.empty()) return _Links.begin()->getValue(); return nullptr; } @@ -4075,7 +4022,7 @@ int PropertyXLinkSubList::removeValue(App::DocumentObject *lValue) return ret; } -PyObject *PropertyXLinkSubList::getPyObject(void) +PyObject *PropertyXLinkSubList::getPyObject() { Py::List list; for(auto &link : _Links) { @@ -4297,7 +4244,7 @@ Property *PropertyXLinkSubList::CopyOnLinkReplace(const App::DocumentObject *par return p.release(); } -Property *PropertyXLinkSubList::Copy(void) const +Property *PropertyXLinkSubList::Copy() const { PropertyXLinkSubList *p = new PropertyXLinkSubList(); for(auto &l : _Links) { @@ -4321,7 +4268,7 @@ void PropertyXLinkSubList::Paste(const Property &from) hasSetValue(); } -unsigned int PropertyXLinkSubList::getMemSize (void) const +unsigned int PropertyXLinkSubList::getMemSize () const { unsigned int size=0; for(auto &l : _Links) @@ -4381,7 +4328,7 @@ void PropertyXLinkSubList::getLinks(std::vector &objs, if(obj && obj->getNameInDocument()) { auto subnames = l.getSubValues(newStyle); if (subnames.empty()) - subnames.push_back(""); + subnames.emplace_back(""); for(auto &sub : subnames) { objs.push_back(obj); subs->push_back(std::move(sub)); @@ -4501,7 +4448,7 @@ void PropertyXLinkSubList::aboutToSetChildValue(Property &) { } } -std::vector PropertyXLinkSubList::getValues(void) const +std::vector PropertyXLinkSubList::getValues() const { std::vector xLinks; getLinks(xLinks); @@ -4517,15 +4464,11 @@ TYPESYSTEM_SOURCE(App::PropertyXLinkList , App::PropertyXLinkSubList) //************************************************************************** // Construction/Destruction -PropertyXLinkList::PropertyXLinkList() -{ -} +PropertyXLinkList::PropertyXLinkList() = default; -PropertyXLinkList::~PropertyXLinkList() -{ -} +PropertyXLinkList::~PropertyXLinkList() = default; -PyObject *PropertyXLinkList::getPyObject(void) +PyObject *PropertyXLinkList::getPyObject() { for(auto &link : _Links) { auto obj = link.getValue(); @@ -4569,8 +4512,7 @@ PropertyXLinkContainer::PropertyXLinkContainer() { _LinkRestored = false; } -PropertyXLinkContainer::~PropertyXLinkContainer() { -} +PropertyXLinkContainer::~PropertyXLinkContainer() = default; void PropertyXLinkContainer::afterRestore() { _DocMap.clear(); @@ -4581,7 +4523,7 @@ void PropertyXLinkContainer::afterRestore() { auto obj = info.xlink->getValue(); if(!obj) continue; - if(info.docName.size()) { + if(!info.docName.empty()) { if(info.docName != obj->getDocument()->getName()) _DocMap[info.docName] = obj->getDocument()->getName(); if(info.docLabel != obj->getDocument()->Label.getValue()) @@ -4656,7 +4598,7 @@ void PropertyXLinkContainer::Save (Base::Writer &writer) const { docSet.insert(std::make_pair(obj->getDocument(),i)); } - if(docSet.size()) + if(!docSet.empty()) writer.Stream() << "\" docs=\"" << docSet.size(); } diff --git a/src/App/PropertyLinks.h b/src/App/PropertyLinks.h index 08f508036c..133908f4d2 100644 --- a/src/App/PropertyLinks.h +++ b/src/App/PropertyLinks.h @@ -102,7 +102,7 @@ public: typedef std::pair ShadowSub; PropertyLinkBase(); - virtual ~PropertyLinkBase(); + ~PropertyLinkBase() override; friend class DocInfo; @@ -283,7 +283,7 @@ public: } //@} - virtual bool isSame(const Property &other) const override; + bool isSame(const Property &other) const override; /** Enable/disable temporary holding external object without throwing exception * @@ -546,7 +546,7 @@ public: virtual void setAllowPartial(bool enable) { (void)enable; } protected: - virtual void hasSetValue() override; + void hasSetValue() override; protected: std::bitset<32> _Flags; @@ -582,7 +582,7 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyLink(); + ~PropertyLink() override; void resetLink(); @@ -592,7 +592,7 @@ public: /** This method returns the linked DocumentObject */ - App::DocumentObject * getValue(void) const; + App::DocumentObject * getValue() const; /** Returns the link type checked */ @@ -601,33 +601,33 @@ public: /** Returns the link type checked */ template - inline _type getValue(void) const { + inline _type getValue() const { return _pcLink ? dynamic_cast<_type>(_pcLink) : 0; } - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override { + unsigned int getMemSize () const override { return sizeof(App::DocumentObject *); } - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyLinkItem"; } - virtual void getLinks(std::vector &objs, + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; + void breakLink(App::DocumentObject *obj, bool clear) override; - virtual bool adjustLink(const std::set &inList) override; + bool adjustLink(const std::set &inList) override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; protected: App::DocumentObject *_pcLink; @@ -639,7 +639,7 @@ class AppExport PropertyLinkChild : public PropertyLink { TYPESYSTEM_HEADER(); public: - PropertyLinkChild() {_pcScope = LinkScope::Child;}; + PropertyLinkChild() {_pcScope = LinkScope::Child;} }; /** The general Link Property with Global scope @@ -648,7 +648,7 @@ class AppExport PropertyLinkGlobal : public PropertyLink { TYPESYSTEM_HEADER(); public: - PropertyLinkGlobal() {_pcScope = LinkScope::Global;}; + PropertyLinkGlobal() {_pcScope = LinkScope::Global;} }; /** The general Link Property that are hidden from dependency checking @@ -657,7 +657,7 @@ class AppExport PropertyLinkHidden : public PropertyLink { TYPESYSTEM_HEADER(); public: - PropertyLinkHidden() {_pcScope = LinkScope::Hidden;}; + PropertyLinkHidden() {_pcScope = LinkScope::Hidden;} }; @@ -665,7 +665,7 @@ class AppExport PropertyLinkListBase: public PropertyLinkBase, public PropertyLi { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual void setPyObject(PyObject *obj) override { + void setPyObject(PyObject *obj) override { _setPyObject(obj); } }; @@ -687,10 +687,10 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyLinkList(); + ~PropertyLinkList() override; - virtual void setSize(int newSize) override; - virtual void setSize(int newSize, const_reference def) override; + void setSize(int newSize) override; + void setSize(int newSize, const_reference def) override; /** Sets the property */ @@ -698,26 +698,26 @@ public: void set1Value(int idx, DocumentObject * const &value) override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void Save(Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize(void) const override; - virtual const char* getEditorName(void) const override + unsigned int getMemSize() const override; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyLinkListItem"; } - virtual void getLinks(std::vector &objs, + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; + void breakLink(App::DocumentObject *obj, bool clear) override; - virtual bool adjustLink(const std::set &inList) override; + bool adjustLink(const std::set &inList) override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; DocumentObject *find(const std::string &, int *pindex=nullptr) const; @@ -739,7 +739,7 @@ class AppExport PropertyLinkListChild : public PropertyLinkList { TYPESYSTEM_HEADER(); public: - PropertyLinkListChild() {_pcScope = LinkScope::Child;}; + PropertyLinkListChild() {_pcScope = LinkScope::Child;} }; /** The general Link Property with Global scope @@ -748,7 +748,7 @@ class AppExport PropertyLinkListGlobal : public PropertyLinkList { TYPESYSTEM_HEADER(); public: - PropertyLinkListGlobal() {_pcScope = LinkScope::Global;}; + PropertyLinkListGlobal() {_pcScope = LinkScope::Global;} }; /** The general Link Property that are hidden from dependency checking @@ -757,7 +757,7 @@ class AppExport PropertyLinkListHidden : public PropertyLinkList { TYPESYSTEM_HEADER(); public: - PropertyLinkListHidden() {_pcScope = LinkScope::Hidden;}; + PropertyLinkListHidden() {_pcScope = LinkScope::Hidden;} }; /** the Link Property with sub elements @@ -781,10 +781,10 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyLinkSub(); + ~PropertyLinkSub() override; - virtual void afterRestore() override; - virtual void onContainerRestored() override; + void afterRestore() override; + void onContainerRestored() override; /** Sets the property */ @@ -795,10 +795,10 @@ public: /** This method returns the linked DocumentObject */ - App::DocumentObject * getValue(void) const; + App::DocumentObject * getValue() const; /// return the list of sub elements - const std::vector& getSubValues(void) const; + const std::vector& getSubValues() const; /// return the list of sub elements with mapped names const std::vector &getShadowSubs() const { @@ -817,46 +817,46 @@ public: /** Returns the link type checked */ template - inline _type getValue(void) const { + inline _type getValue() const { return _pcLinkSub ? dynamic_cast<_type>(_pcLinkSub) : 0; } - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyLinkItem"; } /// Return a copy of the property if any changes caused by importing external object - virtual Property *CopyOnImportExternal(const std::map &nameMap) const override; + Property *CopyOnImportExternal(const std::map &nameMap) const override; - virtual Property *CopyOnLabelChange(App::DocumentObject *obj, + Property *CopyOnLabelChange(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - virtual unsigned int getMemSize (void) const override { + unsigned int getMemSize () const override { return sizeof(App::DocumentObject *); } - virtual void updateElementReference( + void updateElementReference( DocumentObject *feature,bool reverse=false, bool notify=false) override; - virtual bool referenceChanged() const override; + bool referenceChanged() const override; - virtual void getLinks(std::vector &objs, + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; + void breakLink(App::DocumentObject *obj, bool clear) override; - virtual bool adjustLink(const std::set &inList) override; + bool adjustLink(const std::set &inList) override; void setSyncSubObject(bool enable); protected: @@ -873,7 +873,7 @@ class AppExport PropertyLinkSubChild : public PropertyLinkSub { TYPESYSTEM_HEADER(); public: - PropertyLinkSubChild() {_pcScope = LinkScope::Child;}; + PropertyLinkSubChild() {_pcScope = LinkScope::Child;} }; /** The general Link Property with Global scope @@ -882,7 +882,7 @@ class AppExport PropertyLinkSubGlobal : public PropertyLinkSub { TYPESYSTEM_HEADER(); public: - PropertyLinkSubGlobal() {_pcScope = LinkScope::Global;}; + PropertyLinkSubGlobal() {_pcScope = LinkScope::Global;} }; /** The general Link Property that are hidden from dependency checking @@ -891,7 +891,7 @@ class AppExport PropertyLinkSubHidden : public PropertyLinkSub { TYPESYSTEM_HEADER(); public: - PropertyLinkSubHidden() {_pcScope = LinkScope::Hidden;}; + PropertyLinkSubHidden() {_pcScope = LinkScope::Hidden;} }; class AppExport PropertyLinkSubList : public PropertyLinkBase @@ -910,12 +910,12 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyLinkSubList(); + ~PropertyLinkSubList() override; - virtual void afterRestore() override; - virtual void onContainerRestored() override; + void afterRestore() override; + void onContainerRestored() override; - int getSize(void) const; + int getSize() const; void setSize(int newSize); /** Sets the property. @@ -936,7 +936,7 @@ public: void addValue(App::DocumentObject *obj, const std::vector &SubList={}, bool reset = false); - const std::vector &getValues(void) const { + const std::vector &getValues() const { return _lValueList; } @@ -950,7 +950,7 @@ public: */ DocumentObject* getValue() const; - const std::vector &getSubValues(void) const { + const std::vector &getSubValues() const { return _lSubList; } @@ -969,41 +969,41 @@ public: void setSubListValues(const std::vector&); std::vector getSubListValues(bool newStyle=false) const; - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; bool upgrade(Base::XMLReader &reader, const char *typeName); - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyLinkListItem"; } /// Return a copy of the property if any changes caused by importing external object - virtual Property *CopyOnImportExternal(const std::map &nameMap) const override; + Property *CopyOnImportExternal(const std::map &nameMap) const override; - virtual Property *CopyOnLabelChange(App::DocumentObject *obj, + Property *CopyOnLabelChange(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - virtual unsigned int getMemSize (void) const override; + unsigned int getMemSize () const override; - virtual void updateElementReference( + void updateElementReference( DocumentObject *feature,bool reverse=false, bool notify=false) override; - virtual bool referenceChanged() const override; + bool referenceChanged() const override; - virtual void getLinks(std::vector &objs, + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; + void breakLink(App::DocumentObject *obj, bool clear) override; - virtual bool adjustLink(const std::set &inList) override; + bool adjustLink(const std::set &inList) override; void setSyncSubObject(bool enable); @@ -1024,7 +1024,7 @@ class AppExport PropertyLinkSubListChild : public PropertyLinkSubList { TYPESYSTEM_HEADER(); public: - PropertyLinkSubListChild() {_pcScope = LinkScope::Child;}; + PropertyLinkSubListChild() {_pcScope = LinkScope::Child;} }; /** The general Link Property with Global scope @@ -1033,7 +1033,7 @@ class AppExport PropertyLinkSubListGlobal : public PropertyLinkSubList { TYPESYSTEM_HEADER(); public: - PropertyLinkSubListGlobal() {_pcScope = LinkScope::Global;}; + PropertyLinkSubListGlobal() {_pcScope = LinkScope::Global;} }; /** The general Link Property that are hidden from dependency checking @@ -1042,7 +1042,7 @@ class AppExport PropertyLinkSubListHidden : public PropertyLinkSubList { TYPESYSTEM_HEADER(); public: - PropertyLinkSubListHidden() {_pcScope = LinkScope::Hidden;}; + PropertyLinkSubListHidden() {_pcScope = LinkScope::Hidden;} }; class PropertyXLinkSubList; @@ -1054,14 +1054,14 @@ class AppExport PropertyXLink : public PropertyLinkGlobal TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyXLink(bool allowPartial=false, PropertyLinkBase *parent=nullptr); + explicit PropertyXLink(bool allowPartial=false, PropertyLinkBase *parent=nullptr); - virtual ~PropertyXLink(); + ~PropertyXLink() override; PropertyLinkBase *parent() const { return parentProp; } - virtual void afterRestore() override; - virtual void onContainerRestored() override; + void afterRestore() override; + void onContainerRestored() override; void setValue(App::DocumentObject *) override; void setValue(App::DocumentObject *, const char *subname); @@ -1087,25 +1087,25 @@ public: const char *getDocumentPath() const; const char *getObjectName() const; - virtual int checkRestore(std::string *msg=nullptr) const override; + int checkRestore(std::string *msg=nullptr) const override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; /// Return a copy of the property if any changes caused by importing external object - virtual Property *CopyOnImportExternal(const std::map &nameMap) const override; + Property *CopyOnImportExternal(const std::map &nameMap) const override; - virtual Property *CopyOnLabelChange(App::DocumentObject *obj, + Property *CopyOnLabelChange(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; friend class DocInfo; @@ -1116,17 +1116,17 @@ public: static std::map > getDocumentInList(App::Document *doc=nullptr); static void restoreDocument(const App::Document &doc); - virtual void updateElementReference( + void updateElementReference( DocumentObject *feature,bool reverse=false, bool notify=false) override; - virtual bool referenceChanged() const override; + bool referenceChanged() const override; - virtual void getLinks(std::vector &objs, + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; - virtual bool adjustLink(const std::set &inList) override; + bool adjustLink(const std::set &inList) override; - const std::vector& getSubValues(void) const { + const std::vector& getSubValues() const { return _SubList; } const std::vector &getShadowSubs() const { @@ -1135,7 +1135,7 @@ public: std::vector getSubValues(bool newStyle) const; std::vector getSubValuesStartsWith(const char*, bool newStyle=false) const; - virtual void setAllowPartial(bool enable) override; + void setAllowPartial(bool enable) override; const char *getFilePath() const { return filePath.c_str(); @@ -1153,9 +1153,9 @@ protected: void copyTo(PropertyXLink &other, App::DocumentObject *linked=nullptr, std::vector *subs=nullptr) const; - virtual void aboutToSetValue() override; + void aboutToSetValue() override; - virtual void hasSetValue() override; + void hasSetValue() override; friend class PropertyXLinkSubList; @@ -1178,15 +1178,15 @@ class AppExport PropertyXLinkSub: public PropertyXLink { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyXLinkSub(bool allowPartial=false, PropertyLinkBase *parent=nullptr); + explicit PropertyXLinkSub(bool allowPartial=false, PropertyLinkBase *parent=nullptr); - virtual ~PropertyXLinkSub(); + ~PropertyXLinkSub() override; - virtual bool upgrade(Base::XMLReader &reader, const char *typeName) override; + bool upgrade(Base::XMLReader &reader, const char *typeName) override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyLinkItem"; } }; @@ -1203,12 +1203,12 @@ class AppExport PropertyXLinkSubList: public PropertyLinkBase public: PropertyXLinkSubList(); - virtual ~PropertyXLinkSubList(); + ~PropertyXLinkSubList() override; - virtual void afterRestore() override; - virtual void onContainerRestored() override; + void afterRestore() override; + void onContainerRestored() override; - int getSize(void) const; + int getSize() const; /** Sets the property. * setValue(0, whatever) clears the property @@ -1231,7 +1231,7 @@ public: */ void setValue(App::DocumentObject *lValue, const std::vector &SubList={}); - std::vector getValues(void) const; + std::vector getValues() const; const std::string getPyReprString() const; @@ -1255,48 +1255,48 @@ public: return _Links; } - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyLinkListItem"; } - virtual Property *CopyOnImportExternal(const std::map &nameMap) const override; + Property *CopyOnImportExternal(const std::map &nameMap) const override; - virtual Property *CopyOnLabelChange(App::DocumentObject *obj, + Property *CopyOnLabelChange(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - virtual unsigned int getMemSize (void) const override; + unsigned int getMemSize () const override; - virtual void updateElementReference( + void updateElementReference( DocumentObject *feature,bool reverse=false, bool notify=false) override; - virtual bool referenceChanged() const override; + bool referenceChanged() const override; - virtual void getLinks(std::vector &objs, + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; + void breakLink(App::DocumentObject *obj, bool clear) override; - virtual bool adjustLink(const std::set &inList) override; + bool adjustLink(const std::set &inList) override; bool upgrade(Base::XMLReader &reader, const char *typeName); - virtual int checkRestore(std::string *msg=nullptr) const override; + int checkRestore(std::string *msg=nullptr) const override; - virtual void setAllowPartial(bool enable) override; + void setAllowPartial(bool enable) override; - virtual void hasSetChildValue(Property &) override; - virtual void aboutToSetChildValue(Property &) override; + void hasSetChildValue(Property &) override; + void aboutToSetChildValue(Property &) override; void setSyncSubObject(bool enable); @@ -1316,10 +1316,10 @@ class AppExport PropertyXLinkList: public PropertyXLinkSubList { public: PropertyXLinkList(); - virtual ~PropertyXLinkList(); + ~PropertyXLinkList() override; - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; }; @@ -1331,20 +1331,20 @@ class AppExport PropertyXLinkContainer : public PropertyLinkBase { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyXLinkContainer(); - ~PropertyXLinkContainer(); + ~PropertyXLinkContainer() override; - virtual void afterRestore() override; - virtual int checkRestore(std::string *msg=nullptr) const override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; - virtual void getLinks(std::vector &objs, + void afterRestore() override; + int checkRestore(std::string *msg=nullptr) const override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; + void breakLink(App::DocumentObject *obj, bool clear) override; + void getLinks(std::vector &objs, bool all=false, std::vector *subs=nullptr, bool newStyle=true) const override; bool isLinkedToDocument(const App::Document &doc) const; protected: - virtual void aboutToSetChildValue(App::Property &prop) override; + void aboutToSetChildValue(App::Property &prop) override; virtual PropertyXLink *createXLink(); virtual void onBreakLink(App::DocumentObject *obj); virtual void onAddDep(App::DocumentObject *) {} diff --git a/src/App/PropertyPythonObject.cpp b/src/App/PropertyPythonObject.cpp index 810605ea05..604368d225 100644 --- a/src/App/PropertyPythonObject.cpp +++ b/src/App/PropertyPythonObject.cpp @@ -41,9 +41,7 @@ using namespace App; TYPESYSTEM_SOURCE(App::PropertyPythonObject , App::Property) -PropertyPythonObject::PropertyPythonObject() -{ -} +PropertyPythonObject::PropertyPythonObject() = default; PropertyPythonObject::~PropertyPythonObject() { @@ -66,7 +64,7 @@ Py::Object PropertyPythonObject::getValue() const return object; } -PyObject *PropertyPythonObject::getPyObject(void) +PyObject *PropertyPythonObject::getPyObject() { return Py::new_reference_to(this->object); } @@ -400,12 +398,12 @@ void PropertyPythonObject::RestoreDocFile(Base::Reader &reader) hasSetValue(); } -unsigned int PropertyPythonObject::getMemSize (void) const +unsigned int PropertyPythonObject::getMemSize () const { return sizeof(Py::Object); } -Property *PropertyPythonObject::Copy(void) const +Property *PropertyPythonObject::Copy() const { PropertyPythonObject *p = new PropertyPythonObject(); Base::PyGILStateLocker lock; diff --git a/src/App/PropertyPythonObject.h b/src/App/PropertyPythonObject.h index dfaea0f7bd..cf1357a234 100644 --- a/src/App/PropertyPythonObject.h +++ b/src/App/PropertyPythonObject.h @@ -44,28 +44,28 @@ namespace App */ class AppExport PropertyPythonObject : public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyPythonObject(void); - virtual ~PropertyPythonObject(); + PropertyPythonObject(); + ~PropertyPythonObject() override; void setValue(Py::Object); Py::Object getValue() const; - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; /** Use Python's pickle module to save the object */ - virtual void Save (Base::Writer &writer) const; + void Save (Base::Writer &writer) const override; /** Use Python's pickle module to restore the object */ - virtual void Restore(Base::XMLReader &reader); - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void Restore(Base::XMLReader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual unsigned int getMemSize (void) const; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + unsigned int getMemSize () const override; + Property *Copy() const override; + void Paste(const Property &from) override; std::string toString() const; void fromString(const std::string&); diff --git a/src/App/PropertyStandard.cpp b/src/App/PropertyStandard.cpp index 4246380bf4..7c18f4bad3 100644 --- a/src/App/PropertyStandard.cpp +++ b/src/App/PropertyStandard.cpp @@ -67,10 +67,7 @@ PropertyInteger::PropertyInteger() } -PropertyInteger::~PropertyInteger() -{ - -} +PropertyInteger::~PropertyInteger() = default; //************************************************************************** // Base class implementer @@ -163,15 +160,9 @@ TYPESYSTEM_SOURCE(App::PropertyPath , App::Property) //************************************************************************** // Construction/Destruction -PropertyPath::PropertyPath() -{ +PropertyPath::PropertyPath() = default; -} - -PropertyPath::~PropertyPath() -{ - -} +PropertyPath::~PropertyPath() = default; //************************************************************************** @@ -201,7 +192,7 @@ void PropertyPath::setValue(const char * Path) hasSetValue(); } -const boost::filesystem::path &PropertyPath::getValue(void) const +const boost::filesystem::path &PropertyPath::getValue() const { return _cValue; } @@ -291,10 +282,7 @@ PropertyEnumeration::PropertyEnumeration(const App::Enumeration &e) _enum = e; } -PropertyEnumeration::~PropertyEnumeration() -{ - -} +PropertyEnumeration::~PropertyEnumeration() = default; void PropertyEnumeration::setEnums(const char **plEnums) { @@ -311,19 +299,7 @@ void PropertyEnumeration::setEnums(const char **plEnums) void PropertyEnumeration::setEnums(const std::vector &Enums) { - // _enum.setEnums() will preserve old value possible, so no need to do it - // here -#if 0 - if (_enum.isValid()) { - const std::string &index = getValueAsString(); - _enum.setEnums(Enums); - setValue(index.c_str()); - } else { - _enum.setEnums(Enums); - } -#else setEnumVector(Enums); -#endif } void PropertyEnumeration::setValue(const char *value) @@ -459,13 +435,6 @@ void PropertyEnumeration::Restore(Base::XMLReader &reader) PyObject * PropertyEnumeration::getPyObject() { if (!_enum.isValid()) { - // There is legimate use case of having an empty PropertyEnumeration and - // set its enumeration items later. Returning error here cause hasattr() - // to return False even though the property exists. - // - // PyErr_SetString(PyExc_AssertionError, "The enum is empty"); - // return 0; - // Py_Return; } @@ -748,9 +717,7 @@ PropertyPercent::PropertyPercent() _ConstStruct = &percent; } -PropertyPercent::~PropertyPercent() -{ -} +PropertyPercent::~PropertyPercent() = default; //************************************************************************** //************************************************************************** @@ -763,15 +730,9 @@ TYPESYSTEM_SOURCE(App::PropertyIntegerList , App::PropertyLists) // Construction/Destruction -PropertyIntegerList::PropertyIntegerList() -{ +PropertyIntegerList::PropertyIntegerList() = default; -} - -PropertyIntegerList::~PropertyIntegerList() -{ - -} +PropertyIntegerList::~PropertyIntegerList() = default; //************************************************************************** // Base class implementer @@ -852,15 +813,9 @@ TYPESYSTEM_SOURCE(App::PropertyIntegerSet , App::Property) // Construction/Destruction -PropertyIntegerSet::PropertyIntegerSet() -{ +PropertyIntegerSet::PropertyIntegerSet() = default; -} - -PropertyIntegerSet::~PropertyIntegerSet() -{ - -} +PropertyIntegerSet::~PropertyIntegerSet() = default; //************************************************************************** @@ -984,10 +939,7 @@ PropertyFloat::PropertyFloat() _dValue = 0.0; } -PropertyFloat::~PropertyFloat() -{ - -} +PropertyFloat::~PropertyFloat() = default; //************************************************************************** // Base class implementer @@ -1223,10 +1175,7 @@ PropertyPrecision::PropertyPrecision() setConstraints(&PrecisionStandard); } -PropertyPrecision::~PropertyPrecision() -{ - -} +PropertyPrecision::~PropertyPrecision() = default; //************************************************************************** @@ -1239,15 +1188,9 @@ TYPESYSTEM_SOURCE(App::PropertyFloatList , App::PropertyLists) // Construction/Destruction -PropertyFloatList::PropertyFloatList() -{ +PropertyFloatList::PropertyFloatList() = default; -} - -PropertyFloatList::~PropertyFloatList() -{ - -} +PropertyFloatList::~PropertyFloatList() = default; //************************************************************************** // Base class implementer @@ -1362,15 +1305,9 @@ unsigned int PropertyFloatList::getMemSize () const TYPESYSTEM_SOURCE(App::PropertyString , App::Property) -PropertyString::PropertyString() -{ +PropertyString::PropertyString() = default; -} - -PropertyString::~PropertyString() -{ - -} +PropertyString::~PropertyString() = default; void PropertyString::setValue(const char* newLabel) { @@ -1470,7 +1407,7 @@ void PropertyString::setValue(const char* newLabel) propChanges = PropertyLinkBase::updateLabelReferences(obj,newLabel); } - if(propChanges.size() && !GetApplication().getActiveTransaction()) { + if(!propChanges.empty() && !GetApplication().getActiveTransaction()) { commit = true; std::ostringstream str; str << "Change " << obj->getNameInDocument() << ".Label"; @@ -1618,15 +1555,9 @@ const boost::any PropertyString::getPathValue(const ObjectIdentifier &path) cons TYPESYSTEM_SOURCE(App::PropertyUUID , App::Property) -PropertyUUID::PropertyUUID() -{ +PropertyUUID::PropertyUUID() = default; -} - -PropertyUUID::~PropertyUUID() -{ - -} +PropertyUUID::~PropertyUUID() = default; void PropertyUUID::setValue(const Base::Uuid &id) { @@ -1728,15 +1659,9 @@ unsigned int PropertyUUID::getMemSize () const TYPESYSTEM_SOURCE(App::PropertyFont , App::PropertyString) -PropertyFont::PropertyFont() -{ +PropertyFont::PropertyFont() = default; -} - -PropertyFont::~PropertyFont() -{ - -} +PropertyFont::~PropertyFont() = default; //************************************************************************** // PropertyStringList @@ -1744,15 +1669,9 @@ PropertyFont::~PropertyFont() TYPESYSTEM_SOURCE(App::PropertyStringList , App::PropertyLists) -PropertyStringList::PropertyStringList() -{ +PropertyStringList::PropertyStringList() = default; -} - -PropertyStringList::~PropertyStringList() -{ - -} +PropertyStringList::~PropertyStringList() = default; //************************************************************************** // Base class implementer @@ -1855,15 +1774,9 @@ void PropertyStringList::Paste(const Property &from) TYPESYSTEM_SOURCE(App::PropertyMap , App::Property) -PropertyMap::PropertyMap() -{ +PropertyMap::PropertyMap() = default; -} - -PropertyMap::~PropertyMap() -{ - -} +PropertyMap::~PropertyMap() = default; //************************************************************************** // Base class implementer @@ -2038,10 +1951,7 @@ PropertyBool::PropertyBool() _lValue = false; } -PropertyBool::~PropertyBool() -{ - -} +PropertyBool::~PropertyBool() = default; //************************************************************************** // Setter/getter for the property @@ -2147,15 +2057,9 @@ TYPESYSTEM_SOURCE(App::PropertyBoolList , App::PropertyLists) // Construction/Destruction -PropertyBoolList::PropertyBoolList() -{ +PropertyBoolList::PropertyBoolList() = default; -} - -PropertyBoolList::~PropertyBoolList() -{ - -} +PropertyBoolList::~PropertyBoolList() = default; //************************************************************************** // Base class implementer @@ -2245,15 +2149,9 @@ TYPESYSTEM_SOURCE(App::PropertyColor , App::Property) //************************************************************************** // Construction/Destruction -PropertyColor::PropertyColor() -{ +PropertyColor::PropertyColor() = default; -} - -PropertyColor::~PropertyColor() -{ - -} +PropertyColor::~PropertyColor() = default; //************************************************************************** // Base class implementer @@ -2394,15 +2292,9 @@ TYPESYSTEM_SOURCE(App::PropertyColorList , App::PropertyLists) //************************************************************************** // Construction/Destruction -PropertyColorList::PropertyColorList() -{ +PropertyColorList::PropertyColorList() = default; -} - -PropertyColorList::~PropertyColorList() -{ - -} +PropertyColorList::~PropertyColorList() = default; //************************************************************************** // Base class implementer @@ -2504,15 +2396,9 @@ unsigned int PropertyColorList::getMemSize () const TYPESYSTEM_SOURCE(App::PropertyMaterial , App::Property) -PropertyMaterial::PropertyMaterial() -{ +PropertyMaterial::PropertyMaterial() = default; -} - -PropertyMaterial::~PropertyMaterial() -{ - -} +PropertyMaterial::~PropertyMaterial() = default; void PropertyMaterial::setValue(const Material &mat) { @@ -2642,15 +2528,9 @@ TYPESYSTEM_SOURCE(App::PropertyMaterialList, App::PropertyLists) //************************************************************************** // Construction/Destruction -PropertyMaterialList::PropertyMaterialList() -{ +PropertyMaterialList::PropertyMaterialList() = default; -} - -PropertyMaterialList::~PropertyMaterialList() -{ - -} +PropertyMaterialList::~PropertyMaterialList() = default; //************************************************************************** // Base class implementer @@ -2767,7 +2647,7 @@ unsigned int PropertyMaterialList::getMemSize() const TYPESYSTEM_SOURCE(App::PropertyPersistentObject , App::PropertyString) -PyObject *PropertyPersistentObject::getPyObject(void){ +PyObject *PropertyPersistentObject::getPyObject(){ if(_pObject) return _pObject->getPyObject(); return inherited::getPyObject(); @@ -2793,7 +2673,7 @@ void PropertyPersistentObject::Restore(Base::XMLReader &reader){ reader.readEndElement(ELEMENT_PERSISTENT_OBJ); } -Property *PropertyPersistentObject::Copy(void) const{ +Property *PropertyPersistentObject::Copy() const{ auto *p= new PropertyPersistentObject(); p->_cValue = _cValue; p->_pObject = _pObject; diff --git a/src/App/PropertyStandard.h b/src/App/PropertyStandard.h index d4de1f6c01..4a6a9e7b76 100644 --- a/src/App/PropertyStandard.h +++ b/src/App/PropertyStandard.h @@ -50,11 +50,11 @@ namespace App */ class AppExport PropertyInteger: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyInteger(); - virtual ~PropertyInteger(); + ~PropertyInteger() override; /** Sets the property */ @@ -62,24 +62,24 @@ public: /** This method returns a string representation of the property */ - long getValue(void) const; - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyIntegerItem"; } + long getValue() const; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyIntegerItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const{return sizeof(long);} + unsigned int getMemSize () const override{return sizeof(long);} - virtual void setPathValue(const App::ObjectIdentifier & path, const boost::any & value); - virtual const boost::any getPathValue(const App::ObjectIdentifier & /*path*/) const { return _lValue; } + void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; + const boost::any getPathValue(const App::ObjectIdentifier & /*path*/) const override { return _lValue; } - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -95,12 +95,12 @@ protected: */ class AppExport PropertyPath: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyPath(); - virtual ~PropertyPath(); + ~PropertyPath() override; /** Sets the property */ @@ -112,22 +112,22 @@ public: /** This method returns a string representation of the property */ - const boost::filesystem::path &getValue(void) const; + const boost::filesystem::path &getValue() const; - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyPathItem"; } + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyPathItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const; + unsigned int getMemSize () const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -141,17 +141,17 @@ protected: /// Property wrapper around an Enumeration object. class AppExport PropertyEnumeration: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /// Standard constructor PropertyEnumeration(); /// Obvious constructor - PropertyEnumeration(const Enumeration &e); + explicit PropertyEnumeration(const Enumeration &e); /// destructor - virtual ~PropertyEnumeration(); + ~PropertyEnumeration() override; /// Enumeration methods /*! @@ -186,7 +186,7 @@ public: void setValue(const Enumeration &source); /// Returns current value of the enumeration as an integer - long getValue(void) const; + long getValue() const; /// checks if the property is set to a certain string value bool isValue(const char* value) const; @@ -195,13 +195,13 @@ public: bool isPartOf(const char* value) const; /// get the value as string - const char * getValueAsString(void) const; + const char * getValueAsString() const; /// Returns Enumeration object - const Enumeration &getEnum(void) const; + const Enumeration &getEnum() const; /// get all possible enum values as vector of strings - std::vector getEnumVector(void) const; + std::vector getEnumVector() const; /// set enum values as vector of strings void setEnumVector(const std::vector &); @@ -209,27 +209,27 @@ public: bool hasEnums() const; /// Returns true if the instance is in a usable state - bool isValid(void) const; + bool isValid() const; //@} - const char* getEditorName(void) const { return _editorTypeName.c_str(); } + const char* getEditorName() const override { return _editorTypeName.c_str(); } void setEditorName(const char* name) { _editorTypeName = name; } - virtual PyObject * getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject * getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save(Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save(Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property * Copy(void) const; - virtual void Paste(const Property &from); + Property * Copy() const override; + void Paste(const Property &from) override; - virtual void setPathValue(const App::ObjectIdentifier & path, const boost::any & value); + void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; virtual bool setPyPathValue(const App::ObjectIdentifier & path, const Py::Object &value); - virtual const boost::any getPathValue(const App::ObjectIdentifier & /*path*/) const; - virtual bool getPyPathValue(const ObjectIdentifier &path, Py::Object &r) const; + const boost::any getPathValue(const App::ObjectIdentifier & /*path*/) const override; + bool getPyPathValue(const ObjectIdentifier &path, Py::Object &r) const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -249,14 +249,14 @@ private: */ class AppExport PropertyIntegerConstraint: public PropertyInteger { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /// Standard constructor PropertyIntegerConstraint(); /// destructor - virtual ~PropertyIntegerConstraint(); + ~PropertyIntegerConstraint() override; /// Constraint methods //@{ @@ -277,9 +277,7 @@ public: , candelete(false) { } - ~Constraints() - { - } + ~Constraints() = default; void setDeletable(bool on) { candelete = on; @@ -301,15 +299,15 @@ public: */ void setConstraints(const Constraints* sConstraint); /// get the constraint struct - const Constraints* getConstraints(void) const; + const Constraints* getConstraints() const; //@} long getMinimum() const; long getMaximum() const; long getStepSize() const; - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyIntegerConstraintItem"; } - virtual void setPyObject(PyObject *); + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyIntegerConstraintItem"; } + void setPyObject(PyObject *) override; protected: const Constraints* _ConstStruct; @@ -322,14 +320,14 @@ protected: class AppExport PropertyPercent: public PropertyIntegerConstraint { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /// Standard constructor PropertyPercent(); /// destructor - virtual ~PropertyPercent(); + ~PropertyPercent() override; }; /** Integer list properties @@ -351,19 +349,19 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyIntegerList(); + ~PropertyIntegerList() override; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyIntegerListItem"; } - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; protected: long getPyValue(PyObject *item) const override; @@ -374,7 +372,7 @@ protected: */ class AppExport PropertyIntegerSet: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -388,29 +386,29 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyIntegerSet(); + ~PropertyIntegerSet() override; /** Sets the property */ void setValue(long); - void setValue(void){;} + void setValue(){;} void addValue (long value){_lValueSet.insert(value);} void setValues (const std::set& values); - const std::set &getValues(void) const{return _lValueSet;} + const std::set &getValues() const{return _lValueSet;} - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); - virtual unsigned int getMemSize (void) const; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -426,7 +424,7 @@ private: */ class AppExport PropertyMap: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: @@ -440,13 +438,13 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyMap(); + ~PropertyMap() override; - virtual int getSize(void) const; + virtual int getSize() const; /** Sets the property */ - void setValue(void){} + void setValue(){} void setValue(const std::string& key,const std::string& value); void setValues(const std::map&); @@ -455,22 +453,22 @@ public: void set1Value (const std::string& key, const std::string& value){_lValueList.operator[] (key) = value;} - const std::map &getValues(void) const{return _lValueList;} + const std::map &getValues() const{return _lValueList;} //virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyStringListItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const; + unsigned int getMemSize () const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -492,41 +490,41 @@ private: */ class AppExport PropertyFloat: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** Value Constructor * Construct with explicit Values */ - PropertyFloat(void); + PropertyFloat(); /** * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyFloat(); + ~PropertyFloat() override; void setValue(double lValue); - double getValue(void) const; + double getValue() const; - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyFloatItem"; } + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyFloatItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const{return sizeof(double);} + unsigned int getMemSize () const override{return sizeof(double);} - void setPathValue(const App::ObjectIdentifier &path, const boost::any &value); - const boost::any getPathValue(const App::ObjectIdentifier &path) const; + void setPathValue(const App::ObjectIdentifier &path, const boost::any &value) override; + const boost::any getPathValue(const App::ObjectIdentifier &path) const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -545,20 +543,20 @@ protected: */ class AppExport PropertyFloatConstraint: public PropertyFloat { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** Value Constructor * Construct with explicit Values */ - PropertyFloatConstraint(void); + PropertyFloatConstraint(); /** * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyFloatConstraint(); + ~PropertyFloatConstraint() override; /// Constraint methods @@ -580,9 +578,7 @@ public: , candelete(false) { } - ~Constraints() - { - } + ~Constraints() = default; void setDeletable(bool on) { candelete = on; @@ -604,17 +600,17 @@ public: */ void setConstraints(const Constraints* sConstrain); /// get the constraint struct - const Constraints* getConstraints(void) const; + const Constraints* getConstraints() const; //@} double getMinimum() const; double getMaximum() const; double getStepSize() const; - virtual const char* getEditorName(void) const + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyFloatConstraintItem"; } - virtual void setPyObject(PyObject *); + void setPyObject(PyObject *) override; protected: const Constraints* _ConstStruct; @@ -628,11 +624,11 @@ protected: */ class AppExport PropertyPrecision: public PropertyFloatConstraint { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyPrecision(void); - virtual ~PropertyPrecision(); - virtual const char* getEditorName(void) const + PropertyPrecision(); + ~PropertyPrecision() override; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyPrecisionItem"; } }; @@ -653,22 +649,22 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyFloatList(); + ~PropertyFloatList() override; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyFloatListItem"; } - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const override; - virtual void RestoreDocFile(Base::Reader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; protected: double getPyValue(PyObject *item) const override; @@ -680,7 +676,7 @@ protected: */ class AppExport PropertyString: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: @@ -688,36 +684,36 @@ public: * A constructor. * A more elaborate description of the constructor. */ - PropertyString(void); + PropertyString(); /** * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyString(); + ~PropertyString() override; virtual void setValue(const char* sString); void setValue(const std::string &sString); - const char* getValue(void) const; - const std::string& getStrValue(void) const + const char* getValue() const; + const std::string& getStrValue() const { return _cValue; } - bool isEmpty(void){return _cValue.empty();} + bool isEmpty(){return _cValue.empty();} - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyStringItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyStringItem"; } + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); - virtual unsigned int getMemSize (void) const; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; - void setPathValue(const App::ObjectIdentifier &path, const boost::any &value); - const boost::any getPathValue(const App::ObjectIdentifier &path) const; + void setPathValue(const App::ObjectIdentifier &path, const boost::any &value) override; + const boost::any getPathValue(const App::ObjectIdentifier &path) const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -733,7 +729,7 @@ protected: */ class AppExport PropertyUUID: public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: @@ -741,33 +737,33 @@ public: * A constructor. * A more elaborate description of the constructor. */ - PropertyUUID(void); + PropertyUUID(); /** * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyUUID(); + ~PropertyUUID() override; void setValue(const Base::Uuid &); void setValue(const char* sString); void setValue(const std::string &sString); - const std::string& getValueStr(void) const; - const Base::Uuid& getValue(void) const; + const std::string& getValueStr() const; + const Base::Uuid& getValue() const; //virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyStringItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); - virtual unsigned int getMemSize (void) const; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -783,15 +779,15 @@ private: */ class AppExport PropertyFont : public PropertyString { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyFont(void); - virtual ~PropertyFont(); - virtual const char* getEditorName(void) const + PropertyFont(); + ~PropertyFont() override; + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyFontItem"; } - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -816,23 +812,23 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyStringList(); + ~PropertyStringList() override; void setValues(const std::list&); using inherited::setValues; - virtual const char* getEditorName(void) const override + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyStringListItem"; } - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void Save (Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const override; + unsigned int getMemSize () const override; protected: std::string getPyValue(PyObject *item) const override; @@ -843,7 +839,7 @@ protected: */ class AppExport PropertyBool : public Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: @@ -851,34 +847,34 @@ public: * A constructor. * A more elaborate description of the constructor. */ - PropertyBool(void); + PropertyBool(); /** * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyBool(); + ~PropertyBool() override; void setValue(bool lValue); - bool getValue(void) const; + bool getValue() const; - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyBoolItem"; } + const char* getEditorName() const override { return "Gui::PropertyEditor::PropertyBoolItem"; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const{return sizeof(bool);} + unsigned int getMemSize () const override{return sizeof(bool);} - void setPathValue(const App::ObjectIdentifier &path, const boost::any &value); - const boost::any getPathValue(const App::ObjectIdentifier &path) const; + void setPathValue(const App::ObjectIdentifier &path, const boost::any &value) override; + const boost::any getPathValue(const App::ObjectIdentifier &path) const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -899,17 +895,17 @@ class AppExport PropertyBoolList : public PropertyListsT getObject() const { return _pObject; diff --git a/src/App/PropertyUnits.cpp b/src/App/PropertyUnits.cpp index 201cdbb331..6c422719ff 100644 --- a/src/App/PropertyUnits.cpp +++ b/src/App/PropertyUnits.cpp @@ -49,17 +49,17 @@ const PropertyQuantityConstraint::Constraints AngleStandard = {-360,360,1.0}; TYPESYSTEM_SOURCE(App::PropertyQuantity, App::PropertyFloat) -Base::Quantity PropertyQuantity::getQuantityValue(void) const +Base::Quantity PropertyQuantity::getQuantityValue() const { return Quantity(_dValue,_Unit); } -const char* PropertyQuantity::getEditorName(void) const +const char* PropertyQuantity::getEditorName() const { return "Gui::PropertyEditor::PropertyUnitItem"; } -PyObject *PropertyQuantity::getPyObject(void) +PyObject *PropertyQuantity::getPyObject() { return new QuantityPy (new Quantity(_dValue,_Unit)); } @@ -146,13 +146,13 @@ void PropertyQuantityConstraint::setConstraints(const Constraints* sConstrain) _ConstStruct = sConstrain; } -const char* PropertyQuantityConstraint::getEditorName(void) const +const char* PropertyQuantityConstraint::getEditorName() const { return "Gui::PropertyEditor::PropertyUnitConstraintItem"; } -const PropertyQuantityConstraint::Constraints* PropertyQuantityConstraint::getConstraints(void) const +const PropertyQuantityConstraint::Constraints* PropertyQuantityConstraint::getConstraints() const { return _ConstStruct; } @@ -203,42 +203,6 @@ void PropertyQuantityConstraint::setPyObject(PyObject *value) PropertyFloat::setValue(quant.getValue()); // clazy:exclude=skipped-base-method } -//************************************************************************** -//************************************************************************** -// PropertyDistance -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertyDistance, App::PropertyQuantity) - -PropertyDistance::PropertyDistance() -{ - setUnit(Base::Unit::Length); -} - -//************************************************************************** -//************************************************************************** -// PropertyFrequency -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertyFrequency, App::PropertyQuantity) - -PropertyFrequency::PropertyFrequency() -{ - setUnit(Base::Unit::Frequency); -} - -//************************************************************************** -//************************************************************************** -// PropertySpeed -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertySpeed, App::PropertyQuantity) - -PropertySpeed::PropertySpeed() -{ - setUnit(Base::Unit::Velocity); -} - //************************************************************************** //************************************************************************** // PropertyAcceleration @@ -251,45 +215,6 @@ PropertyAcceleration::PropertyAcceleration() setUnit(Base::Unit::Acceleration); } -//************************************************************************** -//************************************************************************** -// PropertyLength -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertyLength, App::PropertyQuantityConstraint) - -PropertyLength::PropertyLength() -{ - setUnit(Base::Unit::Length); - setConstraints(&LengthStandard); -} - -//************************************************************************** -//************************************************************************** -// PropertyArea -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertyArea, App::PropertyQuantityConstraint) - -PropertyArea::PropertyArea() -{ - setUnit(Base::Unit::Area); - setConstraints(&LengthStandard); -} - -//************************************************************************** -//************************************************************************** -// PropertyVolume -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertyVolume, App::PropertyQuantityConstraint) - -PropertyVolume::PropertyVolume() -{ - setUnit(Base::Unit::Volume); - setConstraints(&LengthStandard); -} - //************************************************************************** //************************************************************************** // PropertyAngle @@ -305,38 +230,27 @@ PropertyAngle::PropertyAngle() //************************************************************************** //************************************************************************** -// PropertyPressure +// PropertyArea //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TYPESYSTEM_SOURCE(App::PropertyPressure, App::PropertyQuantity) +TYPESYSTEM_SOURCE(App::PropertyArea, App::PropertyQuantityConstraint) -PropertyPressure::PropertyPressure() +PropertyArea::PropertyArea() { - setUnit(Base::Unit::Pressure); + setUnit(Base::Unit::Area); + setConstraints(&LengthStandard); } //************************************************************************** //************************************************************************** -// PropertyStiffness +// PropertyDistance //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -TYPESYSTEM_SOURCE(App::PropertyStiffness, App::PropertyQuantity) +TYPESYSTEM_SOURCE(App::PropertyDistance, App::PropertyQuantity) -PropertyStiffness::PropertyStiffness() +PropertyDistance::PropertyDistance() { - setUnit(Base::Unit::Stiffness); -} - -//************************************************************************** -//************************************************************************** -// PropertyForce -//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - -TYPESYSTEM_SOURCE(App::PropertyForce, App::PropertyQuantity) - -PropertyForce::PropertyForce() -{ - setUnit(Base::Unit::Force); + setUnit(Base::Unit::Length); } //************************************************************************** @@ -351,6 +265,80 @@ PropertyElectricPotential::PropertyElectricPotential() setUnit(Base::Unit::ElectricPotential); } +//************************************************************************** +//************************************************************************** +// PropertyFrequency +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertyFrequency, App::PropertyQuantity) + +PropertyFrequency::PropertyFrequency() +{ + setUnit(Base::Unit::Frequency); +} + +//************************************************************************** +//************************************************************************** +// PropertyForce +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertyForce, App::PropertyQuantity) + +PropertyForce::PropertyForce() +{ + setUnit(Base::Unit::Force); +} + +//************************************************************************** +//************************************************************************** +// PropertyLength +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertyLength, App::PropertyQuantityConstraint) + +PropertyLength::PropertyLength() +{ + setUnit(Base::Unit::Length); + setConstraints(&LengthStandard); +} + + +//************************************************************************** +//************************************************************************** +// PropertyPressure +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertyPressure, App::PropertyQuantity) + +PropertyPressure::PropertyPressure() +{ + setUnit(Base::Unit::Pressure); +} + +//************************************************************************** +//************************************************************************** +// PropertySpeed +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertySpeed, App::PropertyQuantity) + +PropertySpeed::PropertySpeed() +{ + setUnit(Base::Unit::Velocity); +} + +//************************************************************************** +//************************************************************************** +// PropertyStiffness +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertyStiffness, App::PropertyQuantity) + +PropertyStiffness::PropertyStiffness() +{ + setUnit(Base::Unit::Stiffness); +} + //************************************************************************** //************************************************************************** // PropertyVacuumPermittivity @@ -362,3 +350,16 @@ PropertyVacuumPermittivity::PropertyVacuumPermittivity() { setUnit(Base::Unit::VacuumPermittivity); } + +//************************************************************************** +//************************************************************************** +// PropertyVolume +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TYPESYSTEM_SOURCE(App::PropertyVolume, App::PropertyQuantityConstraint) + +PropertyVolume::PropertyVolume() +{ + setUnit(Base::Unit::Volume); + setConstraints(&LengthStandard); +} diff --git a/src/App/PropertyUnits.h b/src/App/PropertyUnits.h index e241c5e4be..4e9f5cd816 100644 --- a/src/App/PropertyUnits.h +++ b/src/App/PropertyUnits.h @@ -42,29 +42,29 @@ namespace App */ class AppExport PropertyQuantity : public PropertyFloat { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyQuantity(void){} - virtual ~PropertyQuantity(){} + PropertyQuantity() = default; + ~PropertyQuantity() override = default; - Base::Quantity getQuantityValue(void) const; + Base::Quantity getQuantityValue() const; - virtual const char* getEditorName(void) const; + const char* getEditorName() const override; - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; void setUnit(const Base::Unit &u) {_Unit = u;} - const Base::Unit &getUnit(void) const {return _Unit;} + const Base::Unit &getUnit() const {return _Unit;} void setValue(double lValue) { PropertyFloat::setValue(lValue); } - double getValue(void) const { return PropertyFloat::getValue(); } + double getValue() const { return PropertyFloat::getValue(); } - virtual void setPathValue(const App::ObjectIdentifier &path, const boost::any &value); - virtual const boost::any getPathValue(const App::ObjectIdentifier &path) const; + void setPathValue(const App::ObjectIdentifier &path, const boost::any &value) override; + const boost::any getPathValue(const App::ObjectIdentifier &path) const override; - virtual bool isSame(const Property &other) const { + bool isSame(const Property &other) const override { if (&other == this) return true; return getTypeId() == other.getTypeId() @@ -82,11 +82,11 @@ protected: */ class AppExport PropertyQuantityConstraint : public PropertyQuantity { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertyQuantityConstraint(void):_ConstStruct(nullptr){} - virtual ~PropertyQuantityConstraint(){} + PropertyQuantityConstraint():_ConstStruct(nullptr){} + ~PropertyQuantityConstraint() override = default; /// Constraint methods //@{ @@ -104,140 +104,98 @@ public: */ void setConstraints(const Constraints* sConstrain); /// get the constraint struct - const Constraints* getConstraints(void) const; + const Constraints* getConstraints() const; //@} double getMinimum() const; double getMaximum() const; double getStepSize() const; - virtual const char* getEditorName(void) const; - virtual void setPyObject(PyObject *); + const char* getEditorName() const override; + void setPyObject(PyObject *) override; protected: const Constraints* _ConstStruct; }; -/** Distance property - * This is a property for representing distances. It is basically a float - * property. On the Gui it has a quantity like m or mm. - */ -class AppExport PropertyDistance: public PropertyQuantity -{ - TYPESYSTEM_HEADER(); -public: - PropertyDistance(void); - virtual ~PropertyDistance(){} -}; - -/** Length property - * This is a property for representing lengths. It is basically a float - * property which must not be negative. On the Gui it has a quantity like m or mm. - */ -class AppExport PropertyLength : public PropertyQuantityConstraint -{ - TYPESYSTEM_HEADER(); -public: - PropertyLength(void); - virtual ~PropertyLength(){} -}; - -/** Area property - * This is a property for representing areas. It is basically a float - * property which must not be negative. On the Gui it has a quantity like m^2 or mm^2. - */ -class AppExport PropertyArea : public PropertyQuantityConstraint -{ - TYPESYSTEM_HEADER(); -public: - PropertyArea(void); - virtual ~PropertyArea(){} -}; - -/** Volume property - * This is a property for representing volumes. It is basically a float - * property which must not be negative. On the Gui it has a quantity like m^3 or mm^3. - */ -class AppExport PropertyVolume : public PropertyQuantityConstraint -{ - TYPESYSTEM_HEADER(); -public: - PropertyVolume(void); - virtual ~PropertyVolume(){} -}; - -/** Angle property - * This is a property for representing angles. It basically a float - * property. On the Gui it has a quantity like RAD. - */ -class AppExport PropertyAngle: public PropertyQuantityConstraint -{ - TYPESYSTEM_HEADER(); -public: - PropertyAngle(void); - virtual ~PropertyAngle(){} - virtual const char* getEditorName(void) const { return "Gui::PropertyEditor::PropertyAngleItem"; } -}; - -/** Frequency property - * This is a property for representing frequency. It is basically a float - * property. On the Gui it has a quantity like 1/s or Hz. - */ -class AppExport PropertyFrequency: public PropertyQuantity -{ - TYPESYSTEM_HEADER(); -public: - PropertyFrequency(void); - virtual ~PropertyFrequency(){} -}; - -/** Speed property - * This is a property for representing speed. It is basically a float - * property. On the Gui it has a quantity like m/s or km/h. - */ -class AppExport PropertySpeed: public PropertyQuantity -{ - TYPESYSTEM_HEADER(); -public: - PropertySpeed(void); - virtual ~PropertySpeed(){} -}; - /** Acceleration property * This is a property for representing acceleration. It is basically a float * property. On the Gui it has a quantity like m/s^2. */ class AppExport PropertyAcceleration: public PropertyQuantity { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - PropertyAcceleration(void); - virtual ~PropertyAcceleration(){} + PropertyAcceleration(); + ~PropertyAcceleration() override = default; }; -/** Pressure property - * This is a property for representing acceleration. It is basically a float - * property. On the Gui it has a quantity like m/s^2. +/** Angle property + * This is a property for representing angles. It basically a float + * property. On the Gui it has a quantity like RAD. */ -class AppExport PropertyPressure: public PropertyQuantity +class AppExport PropertyAngle: public PropertyQuantityConstraint { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - PropertyPressure(void); - virtual ~PropertyPressure(){} + PropertyAngle(); + ~PropertyAngle() override = default; + const char *getEditorName() const override { return "Gui::PropertyEditor::PropertyAngleItem"; } }; -/** Stiffness property - * This is a property for representing stiffness. It is basically a float - * property. On the Gui it has a quantity like m/s^2. +/** Area property + * This is a property for representing areas. It is basically a float + * property which must not be negative. On the Gui it has a quantity like m^2 or mm^2. */ -class AppExport PropertyStiffness: public PropertyQuantity +class AppExport PropertyArea: public PropertyQuantityConstraint { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - PropertyStiffness(void); - virtual ~PropertyStiffness(){} + PropertyArea(); + ~PropertyArea() override = default; +}; + +/** Distance property + * This is a property for representing distances. It is basically a float + * property. On the Gui it has a quantity like m or mm. + */ +class AppExport PropertyDistance: public PropertyQuantity +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + PropertyDistance(); + ~PropertyDistance() override = default; +}; + +/** ElectricPotential property + * This is a property for electric potentials. It is basically a float + * property. On the Gui it has a quantity of Volt. + */ +class AppExport PropertyElectricPotential: public PropertyQuantity +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + PropertyElectricPotential(); + ~PropertyElectricPotential() override = default; +}; + +/** Frequency property + * This is a property for representing frequency. It is basically a float + * property. On the Gui it has a quantity like 1/s or Hz. + */ +class AppExport PropertyFrequency: public PropertyQuantity +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + PropertyFrequency(); + ~PropertyFrequency() override = default; }; /** Force property @@ -246,22 +204,63 @@ public: */ class AppExport PropertyForce: public PropertyQuantity { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - PropertyForce(void); - virtual ~PropertyForce(){} + PropertyForce(); + ~PropertyForce() override = default; }; -/** ElectricPotential property - * This is a property for electric potentials. It is basically a float - * property. On the Gui it has a quantity of Volt. +/** Length property + * This is a property for representing lengths. It is basically a float + * property which must not be negative. On the Gui it has a quantity like m or mm. */ -class AppExport PropertyElectricPotential : public PropertyQuantity +class AppExport PropertyLength: public PropertyQuantityConstraint { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - PropertyElectricPotential(void); - virtual ~PropertyElectricPotential() {} + PropertyLength(); + ~PropertyLength() override = default; +}; + +/** Pressure property + * This is a property for representing acceleration. It is basically a float + * property. On the Gui it has a quantity like m/s^2. + */ +class AppExport PropertyPressure: public PropertyQuantity +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + PropertyPressure(); + ~PropertyPressure() override = default; +}; + +/** Speed property + * This is a property for representing speed. It is basically a float + * property. On the Gui it has a quantity like m/s or km/h. + */ +class AppExport PropertySpeed: public PropertyQuantity +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + PropertySpeed(); + ~PropertySpeed() override = default; +}; + +/** Stiffness property + * This is a property for representing stiffness. It is basically a float + * property. On the Gui it has a quantity like m/s^2. + */ +class AppExport PropertyStiffness: public PropertyQuantity +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + +public: + PropertyStiffness(); + ~PropertyStiffness() override = default; }; /** VacuumPermittivity property @@ -270,12 +269,26 @@ public: */ class AppExport PropertyVacuumPermittivity: public PropertyQuantity { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: - PropertyVacuumPermittivity(void); - virtual ~PropertyVacuumPermittivity(){} + PropertyVacuumPermittivity(); + ~PropertyVacuumPermittivity() override = default; }; -} // namespace App +/** Volume property + * This is a property for representing volumes. It is basically a float + * property which must not be negative. On the Gui it has a quantity like m^3 or mm^3. + */ +class AppExport PropertyVolume: public PropertyQuantityConstraint +{ + TYPESYSTEM_HEADER_WITH_OVERRIDE(); -#endif // APP_PROPERTYUNITS_H +public: + PropertyVolume(); + ~PropertyVolume() override = default; +}; + +}// namespace App + +#endif// APP_PROPERTYUNITS_H diff --git a/src/App/Range.cpp b/src/App/Range.cpp index 05a97294ad..25d80f2ef9 100644 --- a/src/App/Range.cpp +++ b/src/App/Range.cpp @@ -26,6 +26,8 @@ #include #include #include +#include +#include #endif #include @@ -42,9 +44,9 @@ Range::Range(const char * range, bool normalize) std::string from; std::string to; - assert(range != nullptr); + assert(range); - if (strchr(range, ':') == nullptr) { + if (!strchr(range, ':')) { from = range; to = range; } @@ -136,22 +138,33 @@ int App::decodeRow(const std::string &rowstr, bool silent) } /** - * @brief Decode a column specification into a 0-based integer. + * Assumes well-formed input. A through ZZZ. 0-based output + */ +int columnStringToNum(const std::string &colstr){ + double out {0}; + int pos {0}; + for(auto chr = colstr.crbegin(); chr != colstr.crend(); chr++){ + out += (*chr - 'A' + 1) * std::pow(26, pos++); + } + return static_cast(out - 1); +} + +/** + * @brief Decode a column name string into a 0-based integer. * - * @param colstr Column specified as a string, with "A" begin the first column. + * @param colstr input string. * * @returns The column. * */ -int App::decodeColumn(const std::string &colstr, bool silent) +int App::decodeColumn( const std::string &colstr, bool silent ) { - int col = validColumn(colstr); - - if (silent || col >= 0) - return col; - else - throw Base::IndexError("Invalid column specification"); + if(validColumn( colstr ) ) + return columnStringToNum( colstr ); + if( silent ) + return -1; + throw Base::IndexError("Invalid column specification"); } /** @@ -174,39 +187,17 @@ int App::validRow(const std::string &rowstr) } /** - * @brief Determine whether a column specification is valid or not. + * @brief Determine if a string is a valid column specification. * - * @param colstr Column specified as a string, with "A" begin the first column. + * @param colstr input string. * - * @returns 0 or positive on success, -1 on error. + * @returns true if valid, false if not. * */ -int App::validColumn(const std::string &colstr) +bool App::validColumn( const std::string &colstr ) { - int col = 0; - - if (colstr.length() == 1) { - if ((colstr[0] >= 'A' && colstr[0] <= 'Z')) - col = colstr[0] - 'A'; - else - return -1; - } - else { - col = 0; - for (std::string::const_iterator i = colstr.begin(); i != colstr.end(); ++i) { - int v; - - if ((*i >= 'A' && *i <= 'Z')) - v = *i - 'A'; - else - return -1; - - col = col * 26 + v; - } - col += 26; - } - return col; + return boost::regex_match(colstr, boost::regex("[A-Z]{1,3}")); } /** @@ -221,7 +212,7 @@ int App::validColumn(const std::string &colstr) App::CellAddress App::stringToAddress(const char * strAddress, bool silent) { - assert(strAddress != nullptr); + assert(strAddress); static boost::regex e("(\\$?[A-Z]{1,2})(\\$?[0-9]{1,5})"); boost::cmatch cm; diff --git a/src/App/Range.h b/src/App/Range.h index 17f0bb4e33..89b53d31d9 100644 --- a/src/App/Range.h +++ b/src/App/Range.h @@ -36,7 +36,7 @@ struct CellAddress; AppExport CellAddress stringToAddress(const char *strAddress, bool silent=false); AppExport int decodeColumn(const std::string &colstr, bool silent=false); AppExport int decodeRow(const std::string &rowstr, bool silent=false); -AppExport int validColumn(const std::string &colstr); +AppExport bool validColumn(const std::string &colstr); AppExport int validRow(const std::string &rowstr); struct AppExport CellAddress { @@ -49,15 +49,15 @@ struct AppExport CellAddress { ShowFull = Absolute | ShowRow | ShowColumn }; - CellAddress(int row = -1, int col = -1, bool absRow=false, bool absCol=false) + explicit CellAddress(int row = -1, int col = -1, bool absRow=false, bool absCol=false) : _row(row), _col(col), _absRow(absRow), _absCol(absCol) { } - CellAddress(const char * address) { + explicit CellAddress(const char * address) { *this = stringToAddress(address); } - CellAddress(const std::string & address) { + explicit CellAddress(const std::string & address) { *this = stringToAddress(address.c_str()); } @@ -117,7 +117,7 @@ protected: class AppExport Range { public: - Range(const char *range, bool normalize=false); + explicit Range(const char *range, bool normalize=false); Range(int _row_begin, int _col_begin, int _row_end, int _col_end, bool normalize=false); diff --git a/src/App/TextDocument.h b/src/App/TextDocument.h index b9abdf44ed..702313eb3f 100644 --- a/src/App/TextDocument.h +++ b/src/App/TextDocument.h @@ -32,7 +32,7 @@ namespace App { class AppExport TextDocument : public App::DocumentObject { - PROPERTY_HEADER(App::TextDocument); + PROPERTY_HEADER_WITH_OVERRIDE(App::TextDocument); public: using TextSignal = boost::signals2::signal; using TextSlot = TextSignal::slot_type; @@ -40,10 +40,10 @@ public: PropertyString Text; TextDocument(); - ~TextDocument() {} + ~TextDocument() override = default; - void onChanged(const Property* prop); - const char* getViewProviderName() const; + void onChanged(const Property* prop) override; + const char* getViewProviderName() const override; boost::signals2::connection connectText(const TextSlot &sub); boost::signals2::connection connectLabel(const TextSlot &sub); diff --git a/src/App/TransactionalObject.cpp b/src/App/TransactionalObject.cpp index 7235d10d44..2e4bf944e2 100644 --- a/src/App/TransactionalObject.cpp +++ b/src/App/TransactionalObject.cpp @@ -32,13 +32,9 @@ using namespace App; PROPERTY_SOURCE_ABSTRACT(App::TransactionalObject, App::ExtensionContainer) -TransactionalObject::TransactionalObject(void) -{ -} +TransactionalObject::TransactionalObject() = default; -TransactionalObject::~TransactionalObject(void) -{ -} +TransactionalObject::~TransactionalObject() = default; bool TransactionalObject::isAttachedToDocument() const { diff --git a/src/App/TransactionalObject.h b/src/App/TransactionalObject.h index bd860835e3..97d47be216 100644 --- a/src/App/TransactionalObject.h +++ b/src/App/TransactionalObject.h @@ -36,12 +36,12 @@ class TransactionObject; */ class AppExport TransactionalObject : public App::ExtensionContainer { - PROPERTY_HEADER(App::TransactionalObject); + PROPERTY_HEADER_WITH_OVERRIDE(App::TransactionalObject); public: /// Constructor - TransactionalObject(void); - virtual ~TransactionalObject(); + TransactionalObject(); + ~TransactionalObject() override; virtual bool isAttachedToDocument() const; virtual const char* detachFromDocument(); protected: diff --git a/src/App/Transactions.cpp b/src/App/Transactions.cpp index a345e375d2..4ab3334b56 100644 --- a/src/App/Transactions.cpp +++ b/src/App/Transactions.cpp @@ -99,7 +99,7 @@ static std::atomic _TransactionID; int Transaction::getNewID() { int id = ++_TransactionID; - if(id) + if(id) return id; // wrap around? really? return ++_TransactionID; @@ -109,7 +109,7 @@ int Transaction::getLastID() { return _TransactionID; } -unsigned int Transaction::getMemSize (void) const +unsigned int Transaction::getMemSize () const { return 0; } @@ -124,7 +124,7 @@ void Transaction::Restore(Base::XMLReader &/*reader*/) assert(0); } -int Transaction::getID(void) const +int Transaction::getID() const { return transID; } @@ -182,7 +182,7 @@ void Transaction::apply(Document &Doc, bool forward) }catch(...) { errMsg = "Unknown exception"; } - if(errMsg.size()) { + if(!errMsg.empty()) { FC_ERR("Exception on " << (forward?"redo":"undo") << " '" << Name << "':" << errMsg); } @@ -310,7 +310,7 @@ void TransactionObject::applyChn(Document & /*Doc*/, TransactionalObject *pcObj, // been destroies. We must prepare for the case where user removed // a dynamic property but does not recordered as transaction. auto name = pcObj->getPropertyName(prop); - if(!name || (data.name.size() && data.name != name) || data.propertyType != prop->getTypeId()) { + if(!name || (!data.name.empty() && data.name != name) || data.propertyType != prop->getTypeId()) { // Here means the original property is not found, probably removed if(data.name.empty()) { // not a dynamic property, nothing to do @@ -380,7 +380,7 @@ void TransactionObject::addOrRemoveProperty(const Property* pcProp, bool add) return; auto &data = _PropChangeMap[pcProp->getID()]; - if(data.name.size()) { + if(!data.name.empty()) { if(!add && !data.property) { // this means add and remove the same property inside a single // transaction, so they cancel each other out. @@ -404,7 +404,7 @@ void TransactionObject::addOrRemoveProperty(const Property* pcProp, bool add) } } -unsigned int TransactionObject::getMemSize (void) const +unsigned int TransactionObject::getMemSize () const { return 0; } @@ -433,17 +433,13 @@ TYPESYSTEM_SOURCE_ABSTRACT(App::TransactionDocumentObject, App::TransactionObjec * A constructor. * A more elaborate description of the constructor. */ -TransactionDocumentObject::TransactionDocumentObject() -{ -} +TransactionDocumentObject::TransactionDocumentObject() = default; /** * A destructor. * A more elaborate description of the destructor. */ -TransactionDocumentObject::~TransactionDocumentObject() -{ -} +TransactionDocumentObject::~TransactionDocumentObject() = default; void TransactionDocumentObject::applyDel(Document &Doc, TransactionalObject *pcObj) { @@ -488,7 +484,7 @@ App::TransactionFactory* App::TransactionFactory::self = nullptr; TransactionFactory& TransactionFactory::instance() { - if (self == nullptr) + if (!self) self = new TransactionFactory; return *self; } diff --git a/src/App/Transactions.h b/src/App/Transactions.h index 2eea78ee0b..0d0165a55b 100644 --- a/src/App/Transactions.h +++ b/src/App/Transactions.h @@ -44,7 +44,7 @@ class TransactionalObject; */ class AppExport Transaction : public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** Construction @@ -55,9 +55,9 @@ public: * transactions from different document, so that they can be undo/redo * together. */ - Transaction(int id = 0); + explicit Transaction(int id = 0); /// Construction - virtual ~Transaction(); + ~Transaction() override; /// apply the content to the document void apply(Document &Doc,bool forward); @@ -65,17 +65,17 @@ public: // the utf-8 name of the transaction std::string Name; - virtual unsigned int getMemSize (void) const; - virtual void Save (Base::Writer &writer) const; + unsigned int getMemSize () const override; + void Save (Base::Writer &writer) const override; /// This method is used to restore properties from an XML document. - virtual void Restore(Base::XMLReader &reader); + void Restore(Base::XMLReader &reader) override; /// Return the transaction ID - int getID(void) const; + int getID() const; /// Generate a new unique transaction ID - static int getNewID(void); - static int getLastID(void); + static int getNewID(); + static int getLastID(); /// Returns true if the transaction list is empty; otherwise returns false. bool isEmpty() const; @@ -105,13 +105,13 @@ private: */ class AppExport TransactionObject : public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /// Construction TransactionObject(); /// Destruction - virtual ~TransactionObject(); + ~TransactionObject() override; virtual void applyNew(Document &Doc, TransactionalObject *pcObj); virtual void applyDel(Document &Doc, TransactionalObject *pcObj); @@ -120,10 +120,10 @@ public: void setProperty(const Property* pcProp); void addOrRemoveProperty(const Property* pcProp, bool add); - virtual unsigned int getMemSize (void) const; - virtual void Save (Base::Writer &writer) const; + unsigned int getMemSize () const override; + void Save (Base::Writer &writer) const override; /// This method is used to restore properties from an XML document. - virtual void Restore(Base::XMLReader &reader); + void Restore(Base::XMLReader &reader) override; friend class Transaction; @@ -143,16 +143,16 @@ protected: */ class AppExport TransactionDocumentObject : public TransactionObject { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /// Construction TransactionDocumentObject(); /// Destruction - virtual ~TransactionDocumentObject(); + ~TransactionDocumentObject() override; - void applyNew(Document &Doc, TransactionalObject *pcObj); - void applyDel(Document &Doc, TransactionalObject *pcObj); + void applyNew(Document &Doc, TransactionalObject *pcObj) override; + void applyDel(Document &Doc, TransactionalObject *pcObj) override; }; class AppExport TransactionFactory @@ -168,25 +168,25 @@ private: static TransactionFactory* self; std::map producers; - TransactionFactory(){} - ~TransactionFactory(){} + TransactionFactory() = default; + ~TransactionFactory() = default; }; template class TransactionProducer : public Base::AbstractProducer { public: - TransactionProducer (const Base::Type& type) + explicit TransactionProducer (const Base::Type& type) { TransactionFactory::instance().addProducer(type, this); } - virtual ~TransactionProducer (){} + ~TransactionProducer () override = default; /** * Creates an instance of the specified transaction object. */ - virtual void* Produce () const + void* Produce () const override { return (new CLASS); } diff --git a/src/App/VRMLObject.cpp b/src/App/VRMLObject.cpp index 5994741f7b..e2cb7a8576 100644 --- a/src/App/VRMLObject.cpp +++ b/src/App/VRMLObject.cpp @@ -48,11 +48,9 @@ VRMLObject::VRMLObject() : index(0) Resources.setSize(0); } -VRMLObject::~VRMLObject() -{ -} +VRMLObject::~VRMLObject() = default; -short VRMLObject::mustExecute(void) const +short VRMLObject::mustExecute() const { return 0; } diff --git a/src/App/VRMLObject.h b/src/App/VRMLObject.h index 33d78cfb09..59ea40d9bf 100644 --- a/src/App/VRMLObject.h +++ b/src/App/VRMLObject.h @@ -33,33 +33,33 @@ namespace App class AppExport VRMLObject : public GeoFeature { - PROPERTY_HEADER(App::VRMLObject); + PROPERTY_HEADER_WITH_OVERRIDE(App::VRMLObject); public: /// Constructor - VRMLObject(void); - virtual ~VRMLObject(); + VRMLObject(); + ~VRMLObject() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "Gui::ViewProviderVRMLObject"; } - virtual DocumentObjectExecReturn *execute(void) { + DocumentObjectExecReturn *execute() override { return DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + short mustExecute() const override; + PyObject *getPyObject() override; + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; PropertyFileIncluded VrmlFile; PropertyStringList Urls; PropertyStringList Resources; protected: - void onChanged(const App::Property*); + void onChanged(const App::Property*) override; std::string getRelativePath(const std::string&, const std::string&) const; std::string fixRelativePath(const std::string&, const std::string&) const; void makeDirectories(const std::string&, const std::string&); diff --git a/src/Base/Axis.cpp b/src/Base/Axis.cpp index e1a1438b22..0f4ac79bbf 100644 --- a/src/Base/Axis.cpp +++ b/src/Base/Axis.cpp @@ -26,10 +26,7 @@ using namespace Base; -Axis::Axis() -{ - -} +Axis::Axis() = default; Axis::Axis(const Axis& that) { diff --git a/src/Base/Axis.h b/src/Base/Axis.h index 74e2058f0b..4adf3d3944 100644 --- a/src/Base/Axis.h +++ b/src/Base/Axis.h @@ -40,7 +40,7 @@ public: Axis(const Axis&); Axis(const Vector3d& Orig, const Vector3d& Dir); /// Destruction - ~Axis () {} + ~Axis () = default; const Vector3d& getBase() const {return _base;} const Vector3d& getDirection() const {return _dir;} diff --git a/src/Base/AxisPy.xml b/src/Base/AxisPy.xml index ca9d60aa86..e94b00ce53 100644 --- a/src/Base/AxisPy.xml +++ b/src/Base/AxisPy.xml @@ -1,19 +1,19 @@ - - - - Base.Axis class.\n + + + + Base.Axis class.\n An Axis defines a direction and a position (base) in 3D space.\n The following constructors are supported:\n Axis() @@ -25,46 +25,46 @@ Axis(base, direction) Define from a position and a direction. base : Base.Vector direction : Base.Vector - Axis - + Axis + > copy() -> Base.Axis\n Returns a copy of this Axis. - - - move(vector) -> None\n + + + move(vector) -> None\n Move the axis base along the given vector.\n vector : Base.Vector\n Vector by which to move the axis. - - - - - multiply(placement) -> Base.Axis\n + + + + + multiply(placement) -> Base.Axis\n Multiply this axis by a placement.\n placement : Base.Placement\n Placement by which to multiply the axis. - - - - - reversed() -> Base.Axis\n + + + + + reversed() -> Base.Axis\n Compute the reversed axis. This returns a new Base.Axis with the original direction reversed. - - - - - Base position vector of the Axis. - - - - - - Direction vector of the Axis. - - - - + + + + + Base position vector of the Axis. + + + + + + Direction vector of the Axis. + + + + diff --git a/src/Base/Base64.cpp b/src/Base/Base64.cpp index 480592babf..eb761e1eea 100644 --- a/src/Base/Base64.cpp +++ b/src/Base/Base64.cpp @@ -32,7 +32,7 @@ #include "Base64.h" - +// clazy:excludeall=non-pod-global-static static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" diff --git a/src/Base/BaseClass.cpp b/src/Base/BaseClass.cpp index a4bc2e4854..a734dfee9e 100644 --- a/src/Base/BaseClass.cpp +++ b/src/Base/BaseClass.cpp @@ -42,18 +42,13 @@ Type BaseClass::classTypeId = Base::Type::badType(); * A constructor. * A more elaborate description of the constructor. */ -BaseClass::BaseClass() -{ - -} +BaseClass::BaseClass() = default; /** * A destructor. * A more elaborate description of the destructor. */ -BaseClass::~BaseClass() -{ -} +BaseClass::~BaseClass() = default; //************************************************************************** diff --git a/src/Base/BindingManager.cpp b/src/Base/BindingManager.cpp index fa7cd4ed9c..1b3c34363d 100644 --- a/src/Base/BindingManager.cpp +++ b/src/Base/BindingManager.cpp @@ -74,9 +74,7 @@ BindingManager::BindingManager() { } -BindingManager::~BindingManager() -{ -} +BindingManager::~BindingManager() = default; bool BindingManager::hasWrapper(const void *cptr) { diff --git a/src/Base/BoundBox.h b/src/Base/BoundBox.h index c589fc9b1e..9d26961067 100644 --- a/src/Base/BoundBox.h +++ b/src/Base/BoundBox.h @@ -263,9 +263,7 @@ inline BoundBox3<_Precision>::BoundBox3 (const Vector3<_Precision> &rcVector, _P } template -inline BoundBox3<_Precision>::~BoundBox3 () -{ -} +inline BoundBox3<_Precision>::~BoundBox3 () = default; template inline BoundBox3<_Precision>& BoundBox3<_Precision>::operator = (const BoundBox3<_Precision> &rcBound) diff --git a/src/Base/BoundBoxPy.xml b/src/Base/BoundBoxPy.xml index a7244eabb4..f7917f5cce 100644 --- a/src/Base/BoundBoxPy.xml +++ b/src/Base/BoundBoxPy.xml @@ -14,246 +14,246 @@ This is the BoundBox export class - Base.BoundBox class.\n -This class represents a bounding box. -A bounding box is a rectangular cuboid which is a way to describe outer -boundaries and is obtained from a lot of 3D types. -It is often used to check if a 3D entity lies in the range of another object. -Checking for bounding interference first can save a lot of computing time! -An invalid BoundBox is represented by inconsistent values at each direction: -The maximum float value of the system at the minimum coordinates, and the -opposite value at the maximum coordinates.\n -The following constructors are supported:\n -BoundBox() -Empty constructor. Returns an invalid BoundBox.\n -BoundBox(boundBox) -Copy constructor. -boundBox : Base.BoundBox\n -BoundBox(xMin, yMin=0, zMin=0, xMax=0, yMax=0, zMax=0) -Define from the minimum and maximum values at each direction. -xMin : float\n Minimum value at x-coordinate. -yMin : float\n Minimum value at y-coordinate. -zMin : float\n Minimum value at z-coordinate. -xMax : float\n Maximum value at x-coordinate. -yMax : float\n Maximum value at y-coordinate. -zMax : float\n Maximum value at z-coordinate.\n -App.BoundBox(min, max) -Define from two containers representing the minimum and maximum values of the -coordinates in each direction. -min : Base.Vector, tuple\n Minimum values of the coordinates. -max : Base.Vector, tuple\n Maximum values of the coordinates. + Base.BoundBox class.\n +This class represents a bounding box. +A bounding box is a rectangular cuboid which is a way to describe outer +boundaries and is obtained from a lot of 3D types. +It is often used to check if a 3D entity lies in the range of another object. +Checking for bounding interference first can save a lot of computing time! +An invalid BoundBox is represented by inconsistent values at each direction: +The maximum float value of the system at the minimum coordinates, and the +opposite value at the maximum coordinates.\n +The following constructors are supported:\n +BoundBox() +Empty constructor. Returns an invalid BoundBox.\n +BoundBox(boundBox) +Copy constructor. +boundBox : Base.BoundBox\n +BoundBox(xMin, yMin=0, zMin=0, xMax=0, yMax=0, zMax=0) +Define from the minimum and maximum values at each direction. +xMin : float\n Minimum value at x-coordinate. +yMin : float\n Minimum value at y-coordinate. +zMin : float\n Minimum value at z-coordinate. +xMax : float\n Maximum value at x-coordinate. +yMax : float\n Maximum value at y-coordinate. +zMax : float\n Maximum value at z-coordinate.\n +App.BoundBox(min, max) +Define from two containers representing the minimum and maximum values of the +coordinates in each direction. +min : Base.Vector, tuple\n Minimum values of the coordinates. +max : Base.Vector, tuple\n Maximum values of the coordinates. - setVoid() -> None\n -Invalidate the bounding box. + setVoid() -> None\n +Invalidate the bounding box. - isValid() -> bool\n -Checks if the bounding box is valid. + isValid() -> bool\n +Checks if the bounding box is valid. - add(minMax) -> None -add(x, y, z) -> None\n -Increase the maximum values or decrease the minimum values of this BoundBox by -replacing the current values with the given values, so the bounding box can grow -but not shrink.\n -minMax : Base.Vector, tuple\n Values to enlarge at each direction. -x : float\n Value to enlarge at x-direction. -y : float\n Value to enlarge at y-direction. -z : float\n Value to enlarge at z-direction. + add(minMax) -> None +add(x, y, z) -> None\n +Increase the maximum values or decrease the minimum values of this BoundBox by +replacing the current values with the given values, so the bounding box can grow +but not shrink.\n +minMax : Base.Vector, tuple\n Values to enlarge at each direction. +x : float\n Value to enlarge at x-direction. +y : float\n Value to enlarge at y-direction. +z : float\n Value to enlarge at z-direction. - getPoint(index) ->Base.Vector\n -Get the point of the given index. -The index must be in the range of [0, 7].\n -index : int + getPoint(index) ->Base.Vector\n +Get the point of the given index. +The index must be in the range of [0, 7].\n +index : int - getEdge(index) -> tuple of Base.Vector\n -Get the edge points of the given index. -The index must be in the range of [0, 11].\n -index : int + getEdge(index) -> tuple of Base.Vector\n +Get the edge points of the given index. +The index must be in the range of [0, 11].\n +index : int - closestPoint(point) -> Base.Vector -closestPoint(x, y, z) -> Base.Vector\n -Get the closest point of the bounding box to the given point.\n -point : Base.Vector, tuple\n Coordinates of the given point. -x : float\n X-coordinate of the given point. -y : float\n Y-coordinate of the given point. -z : float\n Z-coordinate of the given point. + closestPoint(point) -> Base.Vector +closestPoint(x, y, z) -> Base.Vector\n +Get the closest point of the bounding box to the given point.\n +point : Base.Vector, tuple\n Coordinates of the given point. +x : float\n X-coordinate of the given point. +y : float\n Y-coordinate of the given point. +z : float\n Z-coordinate of the given point. - intersect(boundBox2) -> bool -intersect(base, dir) -> bool\n -Checks if the given object intersects with this bounding box. That can be -another bounding box or a line specified by base and direction.\n -boundBox2 : Base.BoundBox -base : Base.Vector, tuple -dir : Base.Vector, tuple - - - - - intersected(boundBox2) -> Base.BoundBox\n -Returns the intersection of this and the given bounding box.\n -boundBox2 : Base.BoundBox - - - - - united(boundBox2) -> Base.BoundBox\n -Returns the union of this and the given bounding box.\n -boundBox2 : Base.BoundBox - - - - - enlarge(variation) -> None\n -Decrease the minimum values and increase the maximum values by the given value. -A negative value shrinks the bounding box.\n -variation : float - - - - - - getIntersectionPoint(base, dir, epsilon=0.0001) -> Base.Vector\n -Calculate the intersection point of a line with the bounding box. -The base point must lie inside the bounding box, if not an exception is thrown.\n -base : Base.Vector\n Base point of the line. -dir : Base.Vector\n Direction of the line. -epsilon : float\n Bounding box size tolerance. - - - - - move(displacement) -> None -move(x, y, z) -> None\n -Move the bounding box by the given values.\n -displacement : Base.Vector, tuple\n Displacement at each direction. -x : float\n Displacement at x-direction. -y : float\n Displacement at y-direction. -z : float\n Displacement at z-direction. - - - - - scale(factor) -> None -scale(x, y, z) -> None\n -Scale the bounding box by the given values.\n -factor : Base.Vector, tuple\n Factor scale at each direction. -x : float\n Scale at x-direction. -y : float\n Scale at y-direction. -z : float\n Scale at z-direction. - - - - - transformed(matrix) -> Base.BoundBox\n -Returns a new BoundBox containing the transformed rectangular cuboid -represented by this BoundBox.\n -matrix : Base.Matrix\n Transformation matrix. - - - - - isCutPlane(base, normal) -> bool\n -Check if the plane specified by base and normal intersects (cuts) this bounding -box.\n -base : Base.Vector -normal : Base.Vector + intersect(boundBox2) -> bool +intersect(base, dir) -> bool\n +Checks if the given object intersects with this bounding box. That can be +another bounding box or a line specified by base and direction.\n +boundBox2 : Base.BoundBox +base : Base.Vector, tuple +dir : Base.Vector, tuple - - - isInside(object) -> bool -isInside(x, y, z) -> bool\n -Check if a point or a bounding box is inside this bounding box.\n -object : Base.Vector, Base.BoundBox\n Object to check if it is inside this bounding box. -x : float\n X-coordinate of the point to check. -y : float\n Y-coordinate of the point to check. -z : float\n Z-coordinate of the point to check. - - - - - Center point of the bounding box. - - - - - - The maximum x boundary position. - - - - - - The maximum y boundary position. - - - - - - The maximum z boundary position. - - - - - - The minimum x boundary position. - - - - - - The minimum y boundary position. - - - - - - The minimum z boundary position. - - - - - - Length of the bounding box in x direction. - - - - - - Length of the bounding box in y direction. - - - - - - Length of the bounding box in z direction. - - - - - - Diagonal length of the bounding box. - - - + + + intersected(boundBox2) -> Base.BoundBox\n +Returns the intersection of this and the given bounding box.\n +boundBox2 : Base.BoundBox + + + + + united(boundBox2) -> Base.BoundBox\n +Returns the union of this and the given bounding box.\n +boundBox2 : Base.BoundBox + + + + + enlarge(variation) -> None\n +Decrease the minimum values and increase the maximum values by the given value. +A negative value shrinks the bounding box.\n +variation : float + + + + + + getIntersectionPoint(base, dir, epsilon=0.0001) -> Base.Vector\n +Calculate the intersection point of a line with the bounding box. +The base point must lie inside the bounding box, if not an exception is thrown.\n +base : Base.Vector\n Base point of the line. +dir : Base.Vector\n Direction of the line. +epsilon : float\n Bounding box size tolerance. + + + + + move(displacement) -> None +move(x, y, z) -> None\n +Move the bounding box by the given values.\n +displacement : Base.Vector, tuple\n Displacement at each direction. +x : float\n Displacement at x-direction. +y : float\n Displacement at y-direction. +z : float\n Displacement at z-direction. + + + + + scale(factor) -> None +scale(x, y, z) -> None\n +Scale the bounding box by the given values.\n +factor : Base.Vector, tuple\n Factor scale at each direction. +x : float\n Scale at x-direction. +y : float\n Scale at y-direction. +z : float\n Scale at z-direction. + + + + + transformed(matrix) -> Base.BoundBox\n +Returns a new BoundBox containing the transformed rectangular cuboid +represented by this BoundBox.\n +matrix : Base.Matrix\n Transformation matrix. + + + + + isCutPlane(base, normal) -> bool\n +Check if the plane specified by base and normal intersects (cuts) this bounding +box.\n +base : Base.Vector +normal : Base.Vector + + + + + isInside(object) -> bool +isInside(x, y, z) -> bool\n +Check if a point or a bounding box is inside this bounding box.\n +object : Base.Vector, Base.BoundBox\n Object to check if it is inside this bounding box. +x : float\n X-coordinate of the point to check. +y : float\n Y-coordinate of the point to check. +z : float\n Z-coordinate of the point to check. + + + + + Center point of the bounding box. + + + + + + The maximum x boundary position. + + + + + + The maximum y boundary position. + + + + + + The maximum z boundary position. + + + + + + The minimum x boundary position. + + + + + + The minimum y boundary position. + + + + + + The minimum z boundary position. + + + + + + Length of the bounding box in x direction. + + + + + + Length of the bounding box in y direction. + + + + + + Length of the bounding box in z direction. + + + + + + Diagonal length of the bounding box. + + + - + diff --git a/src/Base/Builder3D.cpp b/src/Base/Builder3D.cpp index b08df85ec6..ba4cd430b0 100644 --- a/src/Base/Builder3D.cpp +++ b/src/Base/Builder3D.cpp @@ -24,15 +24,21 @@ #include "PreCompiled.h" #ifndef _PreComp_ +# include # include # include # include +# include +# include +# include #endif #include "Builder3D.h" #include "Console.h" #include "Exception.h" +#include "FileInfo.h" #include "Matrix.h" +#include "Stream.h" #include "Tools.h" @@ -57,9 +63,7 @@ Builder3D::Builder3D() * A destructor. * A more elaborate description of the destructor. */ -Builder3D::~Builder3D() -{ -} +Builder3D::~Builder3D() = default; //************************************************************************** @@ -304,7 +308,7 @@ void Builder3D::saveToLog() // So, we send the string directly to the observer that handles the Inventor stuff. //Console().Log("Vdbg: %s \n",result.str().c_str()); ILogger* obs = Base::Console().Get("StatusBar"); - if (obs != nullptr){ + if (obs){ obs->SendLog(result.str().c_str(), Base::LogStyle::Log); } } @@ -320,7 +324,8 @@ void Builder3D::saveToLog() void Builder3D::saveToFile(const char* FileName) { result << "} "; - std::ofstream file(FileName); + Base::FileInfo fi(FileName); + Base::ofstream file(fi); if(!file) throw FileException("Builder3D::saveToFile(): Can not open file..."); @@ -919,3 +924,194 @@ void InventorBuilder::addTransformation(const Vector3f& translation, const Vecto << " " << fAngle << std::endl; result << Base::blanks(indent) << "}" << std::endl; } + +// ----------------------------------------------------------------------------- + +template +std::vector InventorLoader::readData(const char* fieldName) const +{ + std::vector fieldValues; + std::string str; + + // search for 'fieldName' and '[' + bool found = false; + while (std::getline(inp, str)) { + std::string::size_type point = str.find(fieldName); + std::string::size_type open = str.find("["); + if (point != std::string::npos && open > point) { + str = str.substr(open); + found = true; + break; + } + } + + if (!found) + return {}; + + do { + boost::char_separator sep(" ,"); + boost::tokenizer > tokens(str, sep); + std::vector token_results; + token_results.assign(tokens.begin(),tokens.end()); + + for (const auto& it : token_results) { + try { + T value = boost::lexical_cast(it); + fieldValues.emplace_back(value); + } + catch (const boost::bad_lexical_cast&) { + } + } + + // search for ']' to finish the reading + if (str.find("]") != std::string::npos) + break; + } + while (std::getline(inp, str)); + + return fieldValues; +} + +std::vector InventorLoader::convert(const std::vector& data) const +{ + if (data.size() % 3 != 0) + throw std::string("Reading failed"); + + std::size_t len = data.size() / 3; + std::vector points; + points.reserve(len); + + for (std::size_t i = 0; i < len; i++) { + float x = data[3 * i]; + float y = data[3 * i + 1]; + float z = data[3 * i + 2]; + points.emplace_back(x, y, z); + } + + return points; +} + +std::vector InventorLoader::convert(const std::vector& data) const +{ + std::vector faces; + faces.reserve(data.size()); + int32_t coordIndex = 0; + for (const auto it : data) { + if (it == 3) { + faces.emplace_back(coordIndex, coordIndex+1, coordIndex+2); + } + else if (it == 4) { + faces.emplace_back(coordIndex, coordIndex+1, coordIndex+2); + faces.emplace_back(coordIndex, coordIndex+2, coordIndex+3); + } + coordIndex += it; + } + return faces; +} + +std::vector> InventorLoader::split(const std::vector& data) +{ + std::vector> splitdata; + std::vector::const_iterator begin = data.cbegin(); + std::vector::const_iterator it = begin; + + while ((it = std::find(begin, data.cend(), -1)) != data.cend()) { + splitdata.emplace_back(begin, it); + begin = it; + std::advance(begin, 1); + } + return splitdata; +} + +std::vector InventorLoader::convert(const std::vector>& coordIndex) const +{ + std::vector faces; + faces.reserve(coordIndex.size()); + for (const auto it : coordIndex) { + if (it.size() == 3) { + faces.emplace_back(it[0], it[1], it[2]); + } + else if (it.size() == 4) { + faces.emplace_back(it[0], it[1], it[2]); + faces.emplace_back(it[0], it[2], it[3]); + } + } + return faces; +} + +void InventorLoader::readNormals() +{ + auto data = readData("vector"); + vector = convert(data); +} + +void InventorLoader::readCoords() +{ + auto data = readData("point"); + points = convert(data); +} + +void InventorLoader::readIndexedFaceSet() +{ + auto data = readData("coordIndex"); + faces = convert(split(data)); +} + +void InventorLoader::readFaceSet() +{ + auto data = readData("numVertices"); + faces = convert(data); + isnonindexed = true; +} + +bool InventorLoader::read() +{ + if (!inp || inp.bad()) + return false; + + std::string line; + + // Verify it's an Inventor 2.1 file + std::getline(inp, line); + if (line.find("#Inventor V2.1 ascii") == std::string::npos) + return false; + + while (std::getline(inp, line)) { + // read the normals if they are defined + if (line.find("Normal {") != std::string::npos) { + readNormals(); + } + else if (line.find("Coordinate3 {") != std::string::npos) { + readCoords(); + } + else if (line.find("IndexedFaceSet {") != std::string::npos) { + readIndexedFaceSet(); + break; + } + else if (line.find("FaceSet {") != std::string::npos) { + readFaceSet(); + break; + } + } + return true; +} + +bool InventorLoader::isValid() const +{ + int32_t value{static_cast(points.size())}; + auto inRange = [value](const Face& f) { + if (f.p1 < 0 || f.p1 >= value) + return false; + if (f.p2 < 0 || f.p2 >= value) + return false; + if (f.p3 < 0 || f.p3 >= value) + return false; + return true; + }; + for (auto it : faces) { + if (!inRange(it)) + return false; + } + + return true; +} diff --git a/src/Base/Builder3D.h b/src/Base/Builder3D.h index 59161ecc00..19f949ed74 100644 --- a/src/Base/Builder3D.h +++ b/src/Base/Builder3D.h @@ -340,6 +340,69 @@ private: int indent; }; +/** + * Loads an OpenInventor file. + * @author Werner Mayer + */ +class BaseExport InventorLoader { +public: + struct Face { + Face(int32_t p1, int32_t p2, int32_t p3) + : p1(p1), p2(p2), p3(p3) {} + int32_t p1, p2, p3; + }; + + explicit InventorLoader(std::istream &inp) : inp(inp) { + } + + /// Start the read process. Returns true if successful and false otherwise. + /// The obtained data can be accessed with the appropriate getter functions. + bool read(); + + /// Checks if the loaded data are valid + bool isValid() const; + + /// Returns true if the data come from a non-indexed node as SoFaceSet. + /// This means that the read points contain duplicates. + bool isNonIndexed() const { + return isnonindexed; + } + + /// Return the vectors of an SoNormal node + const std::vector& getVector() { + return vector; + } + + /// Return the points of an SoCoordinate3 node + const std::vector& getPoints() { + return points; + } + + /// Return the faces of an SoIndexedFaceSet node + const std::vector& getFaces() { + return faces; + } + +private: + void readNormals(); + void readCoords(); + void readIndexedFaceSet(); + void readFaceSet(); + template + std::vector readData(const char*) const; + std::vector convert(const std::vector&) const; + std::vector convert(const std::vector&) const; + std::vector convert(const std::vector>&) const; + static std::vector> split(const std::vector&); + +private: + bool isnonindexed = false; + std::vector vector; + std::vector points; + std::vector faces; + std::istream &inp; +}; + } //namespace Base #endif // BASE_BUILDER3D_H diff --git a/src/Base/CMakeLists.txt b/src/Base/CMakeLists.txt index e6d59bd6e0..c51994e433 100644 --- a/src/Base/CMakeLists.txt +++ b/src/Base/CMakeLists.txt @@ -89,6 +89,7 @@ generate_from_xml(PlacementPy) generate_from_xml(AxisPy) generate_from_xml(UnitPy) generate_from_xml(QuantityPy) +generate_from_xml(PrecisionPy) generate_from_any(Parameter.xsd Parameter.inl xmlSchemeString) if(SWIG_FOUND) @@ -175,6 +176,7 @@ SET(FreeCADBase_XML_SRCS QuantityPy.xml TypePy.xml UnitPy.xml + PrecisionPy.xml ) SOURCE_GROUP("XML" FILES ${FreeCADBase_XML_SRCS}) @@ -250,6 +252,7 @@ SET(FreeCADBase_CPP_SRCS PersistencePyImp.cpp Placement.cpp PlacementPyImp.cpp + PrecisionPyImp.cpp PyExport.cpp PyObjectBase.cpp QtTools.cpp @@ -264,6 +267,7 @@ SET(FreeCADBase_CPP_SRCS TimeInfo.cpp Tools.cpp Tools2D.cpp + Tools3D.cpp Translate.cpp Type.cpp TypePyImp.cpp @@ -313,6 +317,7 @@ SET(FreeCADBase_HPP_SRCS Parameter.h Persistence.h Placement.h + Precision.h PyExport.h PyObjectBase.h QtTools.h @@ -326,6 +331,7 @@ SET(FreeCADBase_HPP_SRCS TimeInfo.h Tools.h Tools2D.h + Tools3D.h Translate.h Type.h Uuid.h diff --git a/src/Base/Console.cpp b/src/Base/Console.cpp index ba34901f3e..2185877e99 100644 --- a/src/Base/Console.cpp +++ b/src/Base/Console.cpp @@ -30,6 +30,7 @@ # include # endif # include +# include #endif #include "Console.h" @@ -54,12 +55,10 @@ public: : QEvent(QEvent::User), msgtype(type), msg(msg) { } - ~ConsoleEvent() - { - } + ~ConsoleEvent() override = default; }; -class ConsoleOutput : public QObject +class ConsoleOutput : public QObject // clazy:exclude=missing-qobject-macro { public: static ConsoleOutput* getInstance() { @@ -72,7 +71,7 @@ public: instance = nullptr; } - void customEvent(QEvent* ev) { + void customEvent(QEvent* ev) override { if (ev->type() == QEvent::User) { ConsoleEvent* ce = static_cast(ev); switch (ce->msgtype) { @@ -93,12 +92,8 @@ public: } private: - ConsoleOutput() - { - } - ~ConsoleOutput() - { - } + ConsoleOutput() = default; + ~ConsoleOutput() override = default; static ConsoleOutput* instance; }; @@ -451,134 +446,94 @@ ConsoleSingleton & ConsoleSingleton::Instance() //************************************************************************** // Python stuff -// ConsoleSingleton Methods // Methods structure +// ConsoleSingleton Methods structure PyMethodDef ConsoleSingleton::Methods[] = { {"PrintMessage", ConsoleSingleton::sPyMessage, METH_VARARGS, - "PrintMessage(string) -- Print a message to the output"}, + "PrintMessage(obj) -> None\n\n" + "Print a message to the output.\n\n" + "obj : object\n The string representation is printed."}, {"PrintLog", ConsoleSingleton::sPyLog, METH_VARARGS, - "PrintLog(string) -- Print a log message to the output"}, - {"PrintError" , ConsoleSingleton::sPyError, METH_VARARGS, - "PrintError(string) -- Print an error message to the output"}, + "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, METH_VARARGS, + "PrintError(obj) -> None\n\n" + "Print an error message to the output.\n\n" + "obj : object\n The string representation is printed."}, {"PrintWarning", ConsoleSingleton::sPyWarning, METH_VARARGS, - "PrintWarning -- Print a warning to the output"}, + "PrintWarning(obj) -> None\n\n" + "Print a warning message to the output.\n\n" + "obj : object\n The string representation is printed."}, {"SetStatus", ConsoleSingleton::sPySetStatus, METH_VARARGS, - "Set the status for either Log, Msg, Wrn or Error for an observer"}, + "SetStatus(observer, type, status) -> None\n\n" + "Set the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n\n" + "observer : str\n Logging interface name.\n" + "type : str\n Message type.\n" + "status : bool"}, {"GetStatus", ConsoleSingleton::sPyGetStatus, METH_VARARGS, - "Get the status for either Log, Msg, Wrn or Error for an observer"}, - {nullptr, nullptr, 0, nullptr} /* Sentinel */ + "GetStatus(observer, type) -> bool or None\n\n" + "Get the status for either 'Log', 'Msg', 'Wrn' or 'Error' for an observer.\n" + "Returns None if the specified observer doesn't exist.\n\n" + "observer : str\n Logging interface name.\n" + "type : str\n Message type."}, + {"GetObservers", ConsoleSingleton::sPyGetObservers, METH_VARARGS, + "GetObservers() -> list of str\n\n" + "Get the names of the current logging interfaces."}, + {nullptr, nullptr, 0, nullptr} /* Sentinel */ }; - -PyObject *ConsoleSingleton::sPyMessage(PyObject * /*self*/, PyObject *args) +namespace { +PyObject* FC_PYCONSOLE_MSG(std::function func, PyObject* args) { PyObject *output; if (!PyArg_ParseTuple(args, "O", &output)) return nullptr; - - const char* string=nullptr; - PyObject* unicode=nullptr; - if (PyUnicode_Check(output)) { - string = PyUnicode_AsUTF8(output); - } - else { - unicode = PyObject_Str(output); - if (unicode) - string = PyUnicode_AsUTF8(unicode); - } - PY_TRY { + const char* string = nullptr; + PyObject* unicode = nullptr; + if (PyUnicode_Check(output)) { + string = PyUnicode_AsUTF8(output); + } + else { + unicode = PyObject_Str(output); + if (unicode) + string = PyUnicode_AsUTF8(unicode); + } if (string) - Instance().Message("%s",string); // process message - } PY_CATCH; + func(string); /*process message*/ + Py_XDECREF(unicode); + } + PY_CATCH + Py_Return; +} +} - Py_XDECREF(unicode); - - Py_INCREF(Py_None); - return Py_None; +PyObject *ConsoleSingleton::sPyMessage(PyObject * /*self*/, PyObject *args) +{ + return FC_PYCONSOLE_MSG([](const char* msg) { + Instance().Message("%s", msg); + }, args); } PyObject *ConsoleSingleton::sPyWarning(PyObject * /*self*/, PyObject *args) { - PyObject *output; - if (!PyArg_ParseTuple(args, "O", &output)) - return nullptr; - - const char* string=nullptr; - PyObject* unicode=nullptr; - if (PyUnicode_Check(output)) { - string = PyUnicode_AsUTF8(output); - } - else { - unicode = PyObject_Str(output); - if (unicode) - string = PyUnicode_AsUTF8(unicode); - } - - PY_TRY { - if (string) - Instance().Warning("%s",string); // process message - } PY_CATCH; - - Py_XDECREF(unicode); - - Py_INCREF(Py_None); - return Py_None; + return FC_PYCONSOLE_MSG([](const char* msg) { + Instance().Warning("%s", msg); + }, args); } PyObject *ConsoleSingleton::sPyError(PyObject * /*self*/, PyObject *args) { - PyObject *output; - if (!PyArg_ParseTuple(args, "O", &output)) - return nullptr; - - const char* string=nullptr; - PyObject* unicode=nullptr; - if (PyUnicode_Check(output)) { - string = PyUnicode_AsUTF8(output); - } - else { - unicode = PyObject_Str(output); - if (unicode) - string = PyUnicode_AsUTF8(unicode); - } - - PY_TRY { - if (string) - Instance().Error("%s",string); // process message - } PY_CATCH; - - Py_XDECREF(unicode); - - Py_INCREF(Py_None); - return Py_None; + return FC_PYCONSOLE_MSG([](const char* msg) { + Instance().Error("%s", msg); + }, args); } PyObject *ConsoleSingleton::sPyLog(PyObject * /*self*/, PyObject *args) { - PyObject *output; - if (!PyArg_ParseTuple(args, "O", &output)) - return nullptr; - - const char* string=nullptr; - PyObject* unicode=nullptr; - if (PyUnicode_Check(output)) { - string = PyUnicode_AsUTF8(output); - } - else { - unicode = PyObject_Str(output); - if (unicode) - string = PyUnicode_AsUTF8(unicode); - } - - PY_TRY { - if (string) - Instance().Log("%s",string); // process message - } PY_CATCH; - - Py_XDECREF(unicode); - - Py_INCREF(Py_None); - return Py_None; + return FC_PYCONSOLE_MSG([](const char* msg) { + Instance().Log("%s", msg); + }, args); } PyObject *ConsoleSingleton::sPyGetStatus(PyObject * /*self*/, PyObject *args) @@ -592,10 +547,7 @@ PyObject *ConsoleSingleton::sPyGetStatus(PyObject * /*self*/, PyObject *args) bool b=false; ILogger *pObs = Instance().Get(pstr1); if (!pObs) - { - Py_INCREF(Py_None); - return Py_None; - } + Py_Return; if (strcmp(pstr2,"Log") == 0) b = pObs->bLog; @@ -605,43 +557,60 @@ PyObject *ConsoleSingleton::sPyGetStatus(PyObject * /*self*/, PyObject *args) b = pObs->bMsg; else if (strcmp(pstr2,"Err") == 0) b = pObs->bErr; + else + Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Msg' or 'Wrn')"); - return Py_BuildValue("i",b?1:0); - }PY_CATCH; + return PyBool_FromLong(b ? 1 : 0); + } + PY_CATCH; } PyObject *ConsoleSingleton::sPySetStatus(PyObject * /*self*/, PyObject *args) { char *pstr1; char *pstr2; - int Bool; - if (!PyArg_ParseTuple(args, "ssi", &pstr1, &pstr2,&Bool)) + PyObject* pyStatus; + if (!PyArg_ParseTuple(args, "ssO!", &pstr1, &pstr2, &PyBool_Type, &pyStatus)) return nullptr; PY_TRY{ + bool status = asBoolean(pyStatus); ILogger *pObs = Instance().Get(pstr1); - if (pObs) - { + if (pObs) { if (strcmp(pstr2,"Log") == 0) - pObs->bLog = (Bool==0)?false:true; + pObs->bLog = status; else if (strcmp(pstr2,"Wrn") == 0) - pObs->bWrn = (Bool==0)?false:true; + pObs->bWrn = status; else if (strcmp(pstr2,"Msg") == 0) - pObs->bMsg = (Bool==0)?false:true; + pObs->bMsg = status; else if (strcmp(pstr2,"Err") == 0) - pObs->bErr = (Bool==0)?false:true; + pObs->bErr = status; else - Py_Error(Base::PyExc_FC_GeneralError,"Unknown Message Type (use Log, Err, Msg or Wrn)"); + Py_Error(Base::PyExc_FC_GeneralError,"Unknown message type (use 'Log', 'Err', 'Msg' or 'Wrn')"); - Py_INCREF(Py_None); - return Py_None; + Py_Return; } else { - Py_Error(Base::PyExc_FC_GeneralError,"Unknown Console Type"); + Py_Error(Base::PyExc_FC_GeneralError,"Unknown logger type"); } - } PY_CATCH; + } + PY_CATCH; } -Base::ILogger::~ILogger() -{} +PyObject *ConsoleSingleton::sPyGetObservers(PyObject * /*self*/, PyObject *args) +{ + if (!PyArg_ParseTuple(args, "")) + return nullptr; + + PY_TRY { + Py::List list; + for (auto i : Instance()._aclObservers) + list.append(Py::String(i->Name() ? i->Name() : "")); + + return Py::new_reference_to(list); + } + PY_CATCH +} + +Base::ILogger::~ILogger() = default; diff --git a/src/Base/Console.h b/src/Base/Console.h index 6530de9f96..38d1d0de87 100644 --- a/src/Base/Console.h +++ b/src/Base/Console.h @@ -33,6 +33,7 @@ #include #include #include +#include // Python stuff typedef struct _object PyObject; @@ -596,6 +597,7 @@ protected: static PyObject *sPyError (PyObject *self,PyObject *args); static PyObject *sPySetStatus(PyObject *self,PyObject *args); static PyObject *sPyGetStatus(PyObject *self,PyObject *args); + static PyObject *sPyGetObservers(PyObject *self, PyObject *args); bool _bVerbose; bool _bCanRefresh; diff --git a/src/Base/ConsoleObserver.cpp b/src/Base/ConsoleObserver.cpp index ac564779d3..fdc23f7167 100644 --- a/src/Base/ConsoleObserver.cpp +++ b/src/Base/ConsoleObserver.cpp @@ -91,9 +91,7 @@ ConsoleObserverStd::ConsoleObserverStd() : bLog = false; } -ConsoleObserverStd::~ConsoleObserverStd() -{ -} +ConsoleObserverStd::~ConsoleObserverStd() = default; void ConsoleObserverStd::SendLog(const std::string& msg, LogStyle level) { diff --git a/src/Base/ConsoleObserver.h b/src/Base/ConsoleObserver.h index 56864d9b33..41191d2f27 100644 --- a/src/Base/ConsoleObserver.h +++ b/src/Base/ConsoleObserver.h @@ -43,7 +43,7 @@ public: ~ConsoleObserverFile() override; void SendLog(const std::string& message, LogStyle level) override; - const char* Name(void) override {return "File";} + const char* Name() override {return "File";} protected: Base::ofstream cFileStream; @@ -58,7 +58,7 @@ public: ConsoleObserverStd(); ~ConsoleObserverStd() override; void SendLog(const std::string& message, LogStyle level) override; - const char* Name(void) override {return "Console";} + const char* Name() override {return "Console";} protected: bool useColorStderr; private: @@ -113,8 +113,8 @@ public: RedirectStdOutput(); protected: - int overflow(int c = EOF); - int sync(); + int overflow(int c = EOF) override; + int sync() override; private: std::string buffer; @@ -126,8 +126,8 @@ public: RedirectStdError(); protected: - int overflow(int c = EOF); - int sync(); + int overflow(int c = EOF) override; + int sync() override; private: std::string buffer; @@ -139,8 +139,8 @@ public: RedirectStdLog(); protected: - int overflow(int c = EOF); - int sync(); + int overflow(int c = EOF) override; + int sync() override; private: std::string buffer; diff --git a/src/Base/CoordinateSystem.cpp b/src/Base/CoordinateSystem.cpp index 7914335d99..f1f6c35f7f 100644 --- a/src/Base/CoordinateSystem.cpp +++ b/src/Base/CoordinateSystem.cpp @@ -35,9 +35,7 @@ CoordinateSystem::CoordinateSystem() { } -CoordinateSystem::~CoordinateSystem() -{ -} +CoordinateSystem::~CoordinateSystem() = default; void CoordinateSystem::setAxes(const Axis& v, const Vector3d& xd) { diff --git a/src/Base/Debugger.cpp b/src/Base/Debugger.cpp index 64de00c83e..6d1f987b22 100644 --- a/src/Base/Debugger.cpp +++ b/src/Base/Debugger.cpp @@ -38,9 +38,7 @@ Debugger::Debugger(QObject* parent) { } -Debugger::~Debugger() -{ -} +Debugger::~Debugger() = default; void Debugger::attach() { diff --git a/src/Base/Debugger.h b/src/Base/Debugger.h index b85a804eea..7f312be423 100644 --- a/src/Base/Debugger.h +++ b/src/Base/Debugger.h @@ -48,7 +48,7 @@ namespace Base { btn->setText("Continue"); btn->show(); Base::Debugger dbg; - connect(btn, SIGNAL(clicked()), &dbg, SLOT(quit())); + connect(btn, &QPushButton::clicked, &dbg, &Debugger::quit); dbg.exec(); \endcode \author Werner Mayer @@ -59,11 +59,16 @@ class BaseExport Debugger : public QObject public: Debugger(QObject* parent=nullptr); - ~Debugger(); + ~Debugger() override; + + Debugger(const Debugger&) = delete; + Debugger(Debugger&&) = delete; + Debugger& operator= (const Debugger&) = delete; + Debugger& operator= (Debugger&&) = delete; void attach(); void detach(); - bool eventFilter(QObject*, QEvent*); + bool eventFilter(QObject* obj, QEvent* event) override; int exec(); public Q_SLOTS: diff --git a/src/Base/DualNumber.h b/src/Base/DualNumber.h index 48697e060f..206dae1f09 100644 --- a/src/Base/DualNumber.h +++ b/src/Base/DualNumber.h @@ -41,7 +41,7 @@ public: double re = 0.0; double du = 0.0; public: - DualNumber(){} + DualNumber() = default; DualNumber(double re, double du = 0.0) : re(re), du(du) {} diff --git a/src/Base/DualQuaternion.h b/src/Base/DualQuaternion.h index 6f4986a0f5..509a454af2 100644 --- a/src/Base/DualQuaternion.h +++ b/src/Base/DualQuaternion.h @@ -48,7 +48,7 @@ public: DualNumber w; public: ///default constructor: init with zeros - DualQuat(){} + DualQuat() = default; DualQuat(DualNumber x, DualNumber y, DualNumber z, DualNumber w) : x(x), y(y), z(z), w(w) {} DualQuat(double x,double y,double z,double w,double dx,double dy,double dz,double dw) diff --git a/src/Base/Exception.cpp b/src/Base/Exception.cpp index 3e91b74f96..bfdc7694cd 100644 --- a/src/Base/Exception.cpp +++ b/src/Base/Exception.cpp @@ -344,7 +344,7 @@ PyObject * FileException::getPyObject() void FileException::setPyObject( PyObject * pydict) { - if (pydict!=nullptr) { + if (pydict) { Exception::setPyObject(pydict); Py::Dict edict(pydict); diff --git a/src/Base/Exception.h b/src/Base/Exception.h index 044f11b935..cfb472afd6 100644 --- a/src/Base/Exception.h +++ b/src/Base/Exception.h @@ -89,10 +89,10 @@ namespace Base class BaseExport Exception : public BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~Exception() throw() {} + ~Exception() throw() override = default; Exception &operator=(const Exception &inst); @@ -121,9 +121,9 @@ public: inline void setReported(bool reported) { _isReported = reported; } /// returns a Python dictionary containing the exception data - virtual PyObject * getPyObject(); + PyObject * getPyObject() override; /// returns sets the exception data from a Python dictionary - virtual void setPyObject( PyObject * pydict); + void setPyObject( PyObject * pydict) override; /// returns the corresponding python exception type virtual PyObject * getPyExceptionType() const; @@ -165,7 +165,7 @@ public: AbortException(); /// Destruction - virtual ~AbortException() throw() {} + ~AbortException() throw() override = default; /// Description of the exception const char* what() const throw() override; /// returns the corresponding python exception type @@ -185,7 +185,7 @@ public: XMLBaseException(const std::string& sMessage); /// Destruction - virtual ~XMLBaseException() throw() {} + ~XMLBaseException() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -204,7 +204,7 @@ public: XMLParseException(); /// Destruction - virtual ~XMLParseException() throw() {} + ~XMLParseException() throw() override = default; /// Description of the exception const char* what() const throw() override; PyObject * getPyExceptionType() const override; @@ -225,7 +225,7 @@ public: XMLAttributeError(); /// Destruction - virtual ~XMLAttributeError() throw() {} + ~XMLAttributeError() throw() override = default; /// Description of the exception const char* what() const throw() override; PyObject * getPyExceptionType() const override; @@ -247,7 +247,7 @@ public: /// Construction FileException(const FileException &inst); /// Destruction - virtual ~FileException() throw() {} + ~FileException() throw() override = default; /// Assignment operator FileException &operator=(const FileException &inst); /// Description of the exception @@ -283,7 +283,7 @@ public: FileSystemError(const char * sMessage); FileSystemError(const std::string& sMessage); /// Destruction - virtual ~FileSystemError() throw() {} + ~FileSystemError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -299,7 +299,7 @@ public: BadFormatError(const char * sMessage); BadFormatError(const std::string& sMessage); /// Destruction - virtual ~BadFormatError() throw() {} + ~BadFormatError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -320,7 +320,7 @@ public: /// Construction MemoryException(const MemoryException &inst); /// Destruction - virtual ~MemoryException() throw() {} + ~MemoryException() throw() override = default; /// Assignment operator MemoryException &operator=(const MemoryException &inst); #if defined (__GNUC__) @@ -342,7 +342,7 @@ public: AccessViolation(const char * sMessage); AccessViolation(const std::string& sMessage); /// Destruction - virtual ~AccessViolation() throw() {} + ~AccessViolation() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -359,7 +359,7 @@ public: AbnormalProgramTermination(const char * sMessage); AbnormalProgramTermination(const std::string& sMessage); /// Destruction - virtual ~AbnormalProgramTermination() throw() {} + ~AbnormalProgramTermination() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -375,7 +375,7 @@ public: UnknownProgramOption(const char * sMessage); UnknownProgramOption(const std::string& sMessage); /// Destruction - virtual ~UnknownProgramOption() throw() {} + ~UnknownProgramOption() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -392,7 +392,7 @@ public: ProgramInformation(const std::string& sMessage); /// Destruction - virtual ~ProgramInformation() throw() {} + ~ProgramInformation() throw() override = default; }; /** @@ -407,7 +407,7 @@ public: TypeError(const char * sMessage); TypeError(const std::string& sMessage); /// Destruction - virtual ~TypeError() throw() {} + ~TypeError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -423,7 +423,7 @@ public: ValueError(const char * sMessage); ValueError(const std::string& sMessage); /// Destruction - virtual ~ValueError() throw() {} + ~ValueError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -439,7 +439,7 @@ public: IndexError(const char * sMessage); IndexError(const std::string& sMessage); /// Destruction - virtual ~IndexError() throw() {} + ~IndexError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -451,7 +451,7 @@ public: NameError(const char * sMessage); NameError(const std::string& sMessage); /// Destruction - virtual ~NameError() throw() {} + ~NameError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -463,7 +463,7 @@ public: ImportError(const char * sMessage); ImportError(const std::string& sMessage); /// Destruction - virtual ~ImportError() throw() {} + ~ImportError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -479,7 +479,7 @@ public: AttributeError(const char * sMessage); AttributeError(const std::string& sMessage); /// Destruction - virtual ~AttributeError() throw() {} + ~AttributeError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -495,7 +495,7 @@ public: RuntimeError(const char * sMessage); RuntimeError(const std::string& sMessage); /// Destruction - virtual ~RuntimeError() throw() {} + ~RuntimeError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -511,8 +511,8 @@ public: BadGraphError(const char * sMessage); BadGraphError(const std::string& sMessage); /// Destruction - virtual ~BadGraphError() throw() {} - PyObject * getPyExceptionType() const; + ~BadGraphError() throw() override = default; + PyObject * getPyExceptionType() const override; }; /** @@ -527,7 +527,7 @@ public: NotImplementedError(const char * sMessage); NotImplementedError(const std::string& sMessage); /// Destruction - virtual ~NotImplementedError() throw() {} + ~NotImplementedError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -543,7 +543,7 @@ public: ZeroDivisionError(const char * sMessage); ZeroDivisionError(const std::string& sMessage); /// Destruction - virtual ~ZeroDivisionError() throw() {} + ~ZeroDivisionError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -559,7 +559,7 @@ public: ReferenceError(const char * sMessage); ReferenceError(const std::string& sMessage); /// Destruction - virtual ~ReferenceError() throw() {} + ~ReferenceError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -576,7 +576,7 @@ public: ExpressionError(const char * sMessage); ExpressionError(const std::string& sMessage); /// Destruction - virtual ~ExpressionError() throw() {} + ~ExpressionError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -592,7 +592,7 @@ public: ParserError(const char * sMessage); ParserError(const std::string& sMessage); /// Destruction - virtual ~ParserError() throw() {} + ~ParserError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -608,7 +608,7 @@ public: UnicodeError(const char * sMessage); UnicodeError(const std::string& sMessage); /// Destruction - virtual ~UnicodeError() throw() {} + ~UnicodeError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -624,7 +624,7 @@ public: OverflowError(const char * sMessage); OverflowError(const std::string& sMessage); /// Destruction - virtual ~OverflowError() throw() {} + ~OverflowError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -640,7 +640,7 @@ public: UnderflowError(const char * sMessage); UnderflowError(const std::string& sMessage); /// Destruction - virtual ~UnderflowError() throw() {} + ~UnderflowError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -656,7 +656,7 @@ public: UnitsMismatchError(const char * sMessage); UnitsMismatchError(const std::string& sMessage); /// Destruction - virtual ~UnitsMismatchError() throw() {} + ~UnitsMismatchError() throw() override = default; PyObject * getPyExceptionType() const override; }; @@ -673,8 +673,8 @@ public: CADKernelError(const char * sMessage); CADKernelError(const std::string& sMessage); /// Destruction - virtual ~CADKernelError() throw() {} - PyObject * getPyExceptionType() const; + ~CADKernelError() throw() override = default; + PyObject * getPyExceptionType() const override; }; /* The RestoreError can be used to try to do a best recovery effort when an error during restoring @@ -692,7 +692,7 @@ public: RestoreError(const char * sMessage); RestoreError(const std::string& sMessage); /// Destruction - virtual ~RestoreError() throw() {} + ~RestoreError() throw() override = default; PyObject * getPyExceptionType() const override; }; diff --git a/src/Base/ExceptionFactory.cpp b/src/Base/ExceptionFactory.cpp index f574597573..40ff217394 100644 --- a/src/Base/ExceptionFactory.cpp +++ b/src/Base/ExceptionFactory.cpp @@ -32,14 +32,14 @@ ExceptionFactory* ExceptionFactory::_pcSingleton = nullptr; ExceptionFactory& ExceptionFactory::Instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) _pcSingleton = new ExceptionFactory; return *_pcSingleton; } void ExceptionFactory::Destruct () { - if (_pcSingleton != nullptr) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } diff --git a/src/Base/ExceptionFactory.h b/src/Base/ExceptionFactory.h index 5eeedd4f63..c59b354246 100644 --- a/src/Base/ExceptionFactory.h +++ b/src/Base/ExceptionFactory.h @@ -40,7 +40,7 @@ class BaseExport AbstractExceptionProducer : public AbstractProducer public: AbstractExceptionProducer () = default; // just implement it - void* Produce () const { + void* Produce () const override { return nullptr; } virtual void raiseException(PyObject * pydict) const = 0; @@ -74,9 +74,9 @@ public: ExceptionFactory::Instance().AddProducer(typeid(CLASS).name(), this); } - virtual ~ExceptionProducer (){} + ~ExceptionProducer () override = default; - void raiseException(PyObject * pydict) const + void raiseException(PyObject * pydict) const override { CLASS c; c.setPyObject(pydict); diff --git a/src/Base/Factory.cpp b/src/Base/Factory.cpp index 7864c4b367..b176bb3883 100644 --- a/src/Base/Factory.cpp +++ b/src/Base/Factory.cpp @@ -82,14 +82,14 @@ ScriptFactorySingleton* ScriptFactorySingleton::_pcSingleton = nullptr; ScriptFactorySingleton& ScriptFactorySingleton::Instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) _pcSingleton = new ScriptFactorySingleton; return *_pcSingleton; } void ScriptFactorySingleton::Destruct () { - if (_pcSingleton != nullptr) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } diff --git a/src/Base/Factory.h b/src/Base/Factory.h index 9ae760c24c..035a78b173 100644 --- a/src/Base/Factory.h +++ b/src/Base/Factory.h @@ -40,8 +40,8 @@ namespace Base class BaseExport AbstractProducer { public: - AbstractProducer() {} - virtual ~AbstractProducer() {} + AbstractProducer() = default; + virtual ~AbstractProducer() = default; /// overwritten by a concrete producer to produce the needed object virtual void* Produce () const = 0; }; @@ -69,7 +69,7 @@ protected: void* Produce (const char* sClassName) const; std::map _mpcProducers; /// construction - Factory (){} + Factory () = default; /// destruction virtual ~Factory (); }; @@ -89,8 +89,8 @@ public: private: static ScriptFactorySingleton* _pcSingleton; - ScriptFactorySingleton(){} - ~ScriptFactorySingleton(){} + ScriptFactorySingleton() = default; + ~ScriptFactorySingleton() override = default; }; inline ScriptFactorySingleton& ScriptFactory() @@ -113,10 +113,10 @@ public: ScriptFactorySingleton::Instance().AddProducer(name, this); } - virtual ~ScriptProducer (){} + ~ScriptProducer () override = default; /// Produce an instance - virtual void* Produce () const + void* Produce () const override { return const_cast(mScript); } diff --git a/src/Base/FileInfo.cpp b/src/Base/FileInfo.cpp index de13ebfe7e..1e0bc29d5b 100644 --- a/src/Base/FileInfo.cpp +++ b/src/Base/FileInfo.cpp @@ -619,12 +619,12 @@ std::vector FileInfo::getDirectoryContent() const #elif defined (FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD) DIR* dp(nullptr); struct dirent* dentry(nullptr); - if ((dp = opendir(FileName.c_str())) == nullptr) + if (!(dp = opendir(FileName.c_str()))) { return List; } - while ((dentry = readdir(dp)) != nullptr) + while ((dentry = readdir(dp))) { std::string dir = dentry->d_name; if (dir != "." && dir != "..") diff --git a/src/Base/FileTemplate.cpp b/src/Base/FileTemplate.cpp index ee4028e7a5..9114a6b800 100644 --- a/src/Base/FileTemplate.cpp +++ b/src/Base/FileTemplate.cpp @@ -48,9 +48,7 @@ ClassTemplate::ClassTemplate() * A destructor. * A more elaborate description of the destructor. */ -ClassTemplate::~ClassTemplate() -{ -} +ClassTemplate::~ClassTemplate() = default; //************************************************************************** diff --git a/src/Base/FutureWatcherProgress.cpp b/src/Base/FutureWatcherProgress.cpp index c151cd8924..574353893c 100644 --- a/src/Base/FutureWatcherProgress.cpp +++ b/src/Base/FutureWatcherProgress.cpp @@ -32,9 +32,7 @@ FutureWatcherProgress::FutureWatcherProgress(const char* text, unsigned int step { } -FutureWatcherProgress::~FutureWatcherProgress() -{ -} +FutureWatcherProgress::~FutureWatcherProgress() = default; void FutureWatcherProgress::progressValueChanged(int v) { diff --git a/src/Base/FutureWatcherProgress.h b/src/Base/FutureWatcherProgress.h index 86726fbf26..ad45a60530 100644 --- a/src/Base/FutureWatcherProgress.h +++ b/src/Base/FutureWatcherProgress.h @@ -37,10 +37,15 @@ class BaseExport FutureWatcherProgress : public QObject public: FutureWatcherProgress(const char* text, unsigned int steps); - ~FutureWatcherProgress(); + ~FutureWatcherProgress() override; + + FutureWatcherProgress(const FutureWatcherProgress&) = delete; + FutureWatcherProgress(FutureWatcherProgress&&) = delete; + FutureWatcherProgress& operator= (const FutureWatcherProgress&) = delete; + FutureWatcherProgress& operator= (FutureWatcherProgress&&) = delete; private Q_SLOTS: - void progressValueChanged(int v); + void progressValueChanged(int value); private: Base::SequencerLauncher seq; diff --git a/src/Base/GeometryPyCXX.cpp b/src/Base/GeometryPyCXX.cpp index 4e6c290519..c0a30195e5 100644 --- a/src/Base/GeometryPyCXX.cpp +++ b/src/Base/GeometryPyCXX.cpp @@ -133,9 +133,7 @@ Vector2dPy::Vector2dPy(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict v.y = y; } -Vector2dPy::~Vector2dPy() -{ -} +Vector2dPy::~Vector2dPy() = default; Py::Object Vector2dPy::repr() { @@ -227,11 +225,6 @@ Py::Object Vector2dPy::number_float() throw Py::TypeError("Not defined"); } -Py::Object Vector2dPy::number_long() -{ - throw Py::TypeError("Not defined"); -} - Py::Object Vector2dPy::number_add( const Py::Object & py) { Vector2d u(Py::toVector2d(py)); @@ -392,7 +385,7 @@ Py::Object Vector2dPy::projectToLine(const Py::Tuple& args) } PYCXX_VARARGS_METHOD_DECL(Vector2dPy, projectToLine) -void Vector2dPy::init_type(void) +void Vector2dPy::init_type() { behaviors().name( "Vector2d" ); behaviors().doc( "Vector2d class" ); diff --git a/src/Base/GeometryPyCXX.h b/src/Base/GeometryPyCXX.h index dcb3c51546..4063b24241 100644 --- a/src/Base/GeometryPyCXX.h +++ b/src/Base/GeometryPyCXX.h @@ -58,12 +58,12 @@ public: static Py::PythonClassObject create(const Vector2d&); static Py::PythonClassObject create(double x, double y); Vector2dPy(Py::PythonClassInstance *self, Py::Tuple &args, Py::Dict &kwds); - virtual ~Vector2dPy(); + ~Vector2dPy() override; static void init_type(); - Py::Object getattro(const Py::String &name_); - int setattro(const Py::String &name_, const Py::Object &value); - virtual Py::Object repr(); + Py::Object getattro(const Py::String &name_) override; + int setattro(const Py::String &name_, const Py::Object &value) override; + Py::Object repr() override; inline const Vector2d& value() const { return v; } @@ -77,24 +77,23 @@ public: /** @name methods for group handling */ //@{ - virtual Py::Object number_negative(); - virtual Py::Object number_positive(); - virtual Py::Object number_absolute(); - virtual Py::Object number_invert(); - virtual Py::Object number_int(); - virtual Py::Object number_float(); - virtual Py::Object number_long(); - virtual Py::Object number_add( const Py::Object & ); - virtual Py::Object number_subtract( const Py::Object & ); - virtual Py::Object number_multiply( const Py::Object & ); - virtual Py::Object number_remainder( const Py::Object & ); - virtual Py::Object number_divmod( const Py::Object & ); - virtual Py::Object number_lshift( const Py::Object & ); - virtual Py::Object number_rshift( const Py::Object & ); - virtual Py::Object number_and( const Py::Object & ); - virtual Py::Object number_xor( const Py::Object & ); - virtual Py::Object number_or( const Py::Object & ); - virtual Py::Object number_power( const Py::Object &, const Py::Object & ); + Py::Object number_negative() override; + Py::Object number_positive() override; + Py::Object number_absolute() override; + Py::Object number_invert() override; + Py::Object number_int() override; + Py::Object number_float() override; + Py::Object number_add( const Py::Object & ) override; + Py::Object number_subtract( const Py::Object & ) override; + Py::Object number_multiply( const Py::Object & ) override; + Py::Object number_remainder( const Py::Object & ) override; + Py::Object number_divmod( const Py::Object & ) override; + Py::Object number_lshift( const Py::Object & ) override; + Py::Object number_rshift( const Py::Object & ) override; + Py::Object number_and( const Py::Object & ) override; + Py::Object number_xor( const Py::Object & ) override; + Py::Object number_or( const Py::Object & ) override; + Py::Object number_power( const Py::Object &, const Py::Object & ) override; //@} Py::Object isNull(const Py::Tuple&); @@ -144,7 +143,7 @@ public: explicit Vector (const Base::Vector3d&); explicit Vector (const Base::Vector3f&); - virtual bool accepts (PyObject *pyob) const; + bool accepts (PyObject *pyob) const override; Vector(const Object& other): Object(other.ptr()) { validate(); @@ -203,7 +202,7 @@ public: GeometryT(const Object& other): Object(other.ptr()) { validate(); } - virtual bool accepts (PyObject *pyob) const { + bool accepts (PyObject *pyob) const override { return pyob && Geometry_TypeCheck (pyob); } GeometryT& operator= (const Object& rhs) diff --git a/src/Base/InputSource.cpp b/src/Base/InputSource.cpp index da3f49af3a..6fad8cb739 100644 --- a/src/Base/InputSource.cpp +++ b/src/Base/InputSource.cpp @@ -44,9 +44,7 @@ StdInputStream::StdInputStream( std::istream& Stream, XERCES_CPP_NAMESPACE_QUALI } -StdInputStream::~StdInputStream() -{ -} +StdInputStream::~StdInputStream() = default; // --------------------------------------------------------------------------- @@ -135,9 +133,7 @@ StdInputSource::StdInputSource ( std::istream& Stream, const char* filePath, XER } -StdInputSource::~StdInputSource() -{ -} +StdInputSource::~StdInputSource() = default; // --------------------------------------------------------------------------- diff --git a/src/Base/InputSource.h b/src/Base/InputSource.h index 51e12a8421..e281c2ff6b 100644 --- a/src/Base/InputSource.h +++ b/src/Base/InputSource.h @@ -45,7 +45,7 @@ class BaseExport StdInputStream : public XERCES_CPP_NAMESPACE_QUALIFIER BinInput { public : StdInputStream ( std::istream& Stream, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager ); - virtual ~StdInputStream(); + ~StdInputStream() override; // ----------------------------------------------------------------------- // Implementation of the input stream interface @@ -54,9 +54,9 @@ public : virtual unsigned int curPos() const; virtual unsigned int readBytes( XMLByte* const toFill, const unsigned int maxToRead ); #else - virtual XMLFilePos curPos() const; - virtual XMLSize_t readBytes( XMLByte* const toFill, const XMLSize_t maxToRead ); - virtual const XMLCh* getContentType() const {return nullptr;} + XMLFilePos curPos() const override; + XMLSize_t readBytes( XMLByte* const toFill, const XMLSize_t maxToRead ) override; + const XMLCh* getContentType() const override {return nullptr;} #endif private : @@ -83,9 +83,9 @@ class BaseExport StdInputSource : public XERCES_CPP_NAMESPACE_QUALIFIER InputSou { public : StdInputSource ( std::istream& Stream, const char* filePath, XERCES_CPP_NAMESPACE_QUALIFIER MemoryManager* const manager = XERCES_CPP_NAMESPACE_QUALIFIER XMLPlatformUtils::fgMemoryManager ); - ~StdInputSource(); + ~StdInputSource() override; - virtual XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream* makeStream() const; + XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream* makeStream() const override; private: StdInputSource(const StdInputSource&); diff --git a/src/Base/Interpreter.cpp b/src/Base/Interpreter.cpp index 5a476094b7..cfd600298a 100644 --- a/src/Base/Interpreter.cpp +++ b/src/Base/Interpreter.cpp @@ -93,9 +93,7 @@ PyException::PyException() PyErr_Clear(); // must be called to keep Python interpreter in a valid state (Werner) } -PyException::~PyException() throw() -{ -} +PyException::~PyException() throw() = default; void PyException::ThrowException() { @@ -106,7 +104,7 @@ void PyException::ThrowException() void PyException::raiseException() { PyGILStateLocker locker; - if (PP_PyDict_Object!=nullptr) { + if (PP_PyDict_Object) { // delete the Python dict upon destruction of edict Py::Dict edict(PP_PyDict_Object, true); PP_PyDict_Object = nullptr; @@ -170,7 +168,7 @@ SystemExitException::SystemExitException() if (value) { code = PyObject_GetAttrString(value, "code"); - if (code != nullptr && value != Py_None) { + if (code && value != Py_None) { Py_DECREF(value); value = code; } @@ -203,12 +201,8 @@ public: add_varargs_method("flush",&PythonStdOutput::flush,"flush()"); } - PythonStdOutput() - { - } - ~PythonStdOutput() - { - } + PythonStdOutput() = default; + ~PythonStdOutput() override = default; Py::Object write(const Py::Tuple&) { @@ -227,10 +221,7 @@ InterpreterSingleton::InterpreterSingleton() this->_global = nullptr; } -InterpreterSingleton::~InterpreterSingleton() -{ - -} +InterpreterSingleton::~InterpreterSingleton() = default; std::string InterpreterSingleton::runString(const char *sCmd) @@ -239,10 +230,10 @@ std::string InterpreterSingleton::runString(const char *sCmd) PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ - if (module == nullptr) + if (!module) throw PyException(); /* not incref'd */ dict = PyModule_GetDict(module); /* get dict namespace */ - if (dict == nullptr) + if (!dict) throw PyException(); /* not incref'd */ @@ -316,10 +307,10 @@ Py::Object InterpreterSingleton::runStringObject(const char *sCmd) PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ - if (module == nullptr) + if (!module) throw PyException(); /* not incref'd */ dict = PyModule_GetDict(module); /* get dict namespace */ - if (dict == nullptr) + if (!dict) throw PyException(); /* not incref'd */ @@ -342,7 +333,7 @@ void InterpreterSingleton::systemExit() PyErr_Fetch(&exception, &value, &tb); fflush(stdout); - if (value == nullptr || value == Py_None) + if (!value || value == Py_None) goto done; if (PyExceptionInstance_Check(value)) { /* The error code should be in the `code' attribute. */ @@ -382,10 +373,10 @@ void InterpreterSingleton::runInteractiveString(const char *sCmd) PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ - if (module == nullptr) + if (!module) throw PyException(); /* not incref'd */ dict = PyModule_GetDict(module); /* get dict namespace */ - if (dict == nullptr) + if (!dict) throw PyException(); /* not incref'd */ presult = PyRun_String(sCmd, Py_single_input, dict, dict); /* eval direct */ @@ -435,20 +426,20 @@ void InterpreterSingleton::runFile(const char*pxFileName, bool local) Py_INCREF(dict); // avoid to further distinguish between local and global dict } - if (PyDict_GetItemString(dict, "__file__") == nullptr) { - PyObject *f = PyUnicode_FromString(pxFileName); - if (f == nullptr) { + if (!PyDict_GetItemString(dict, "__file__")) { + PyObject *pyObj = PyUnicode_FromString(pxFileName); + if (!pyObj) { fclose(fp); Py_DECREF(dict); return; } - if (PyDict_SetItemString(dict, "__file__", f) < 0) { - Py_DECREF(f); + if (PyDict_SetItemString(dict, "__file__", pyObj) < 0) { + Py_DECREF(pyObj); fclose(fp); Py_DECREF(dict); return; } - Py_DECREF(f); + Py_DECREF(pyObj); } PyObject *result = PyRun_File(fp, pxFileName, Py_file_input, dict, dict); @@ -695,11 +686,11 @@ int InterpreterSingleton::runCommandLine(const char *prompt) void InterpreterSingleton::runMethodVoid(PyObject *pobject, const char *method) { PyGILStateLocker locker; - if (PP_Run_Method(pobject , // object - method, // run method - nullptr, // no return type - nullptr, // so no return object - "()") // no arguments + if (PP_Run_Method(pobject , // object + method, // run method + nullptr, // no return type + nullptr, // so no return object + "()") // no arguments != 0) throw PyException(/*"Error running InterpreterSingleton::RunMethodVoid()"*/); @@ -710,11 +701,11 @@ PyObject* InterpreterSingleton::runMethodObject(PyObject *pobject, const char *m PyObject *pcO; PyGILStateLocker locker; - if (PP_Run_Method(pobject , // object - method, // run method - "O", // return type - &pcO, // return object - "()") // no arguments + if (PP_Run_Method(pobject , // object + method, // run method + "O", // return type + &pcO, // return object + "()") // no arguments != 0) throw PyException(); @@ -731,7 +722,7 @@ void InterpreterSingleton::runMethod(PyObject *pobject, const char *method, PyGILStateLocker locker; pmeth = PyObject_GetAttrString(pobject, method); - if (pmeth == nullptr) { /* get callable object */ + if (!pmeth) { /* get callable object */ va_end(argslist); throw AttributeError("Error running InterpreterSingleton::RunMethod() method not defined"); /* bound method? has self */ } @@ -739,7 +730,7 @@ void InterpreterSingleton::runMethod(PyObject *pobject, const char *method, pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */ va_end(argslist); - if (pargs == nullptr) { + if (!pargs) { Py_DECREF(pmeth); throw TypeError("InterpreterSingleton::RunMethod() wrong arguments"); } @@ -765,10 +756,10 @@ PyObject * InterpreterSingleton::getValue(const char * key, const char * result_ PyGILStateLocker locker; module = PP_Load_Module("__main__"); /* get module, init python */ - if (module == nullptr) + if (!module) throw PyException(); /* not incref'd */ dict = PyModule_GetDict(module); /* get dict namespace */ - if (dict == nullptr) + if (!dict) throw PyException(); /* not incref'd */ diff --git a/src/Base/Interpreter.h b/src/Base/Interpreter.h index a4db52107d..e875bc7ff1 100644 --- a/src/Base/Interpreter.h +++ b/src/Base/Interpreter.h @@ -93,7 +93,7 @@ public: /// constructor does the whole job PyException(); PyException(const Py::Object &obj); - ~PyException() throw(); + ~PyException() throw() override; void raiseException(); @@ -105,10 +105,10 @@ public: /// this function returns the stack trace const std::string &getStackTrace() const {return _stackTrace;} const std::string &getErrorType() const {return _errorType;} - virtual PyObject *getPyExceptionType(void) const override {return _exceptionType;} + PyObject *getPyExceptionType() const override {return _exceptionType;} void ReportException () const override; /// Sets the Python error indicator and an error message - virtual void setPyException() const override; + void setPyException() const override; protected: std::string _stackTrace; @@ -139,7 +139,7 @@ class BaseExport SystemExitException : public Exception { public: SystemExitException(); - virtual ~SystemExitException() throw() {} + ~SystemExitException() throw() override = default; long getExitCode() const { return _exitCode;} protected: diff --git a/src/Base/Matrix.h b/src/Base/Matrix.h index afcb95d0ed..3409720510 100644 --- a/src/Base/Matrix.h +++ b/src/Base/Matrix.h @@ -72,7 +72,7 @@ public: Matrix4D (const Vector3f& rclBase, const Vector3f& rclDir, float fAngle); Matrix4D (const Vector3d& rclBase, const Vector3d& rclDir, double fAngle); /// Destruction - ~Matrix4D () {} + ~Matrix4D () = default; /** @name Operators */ //@{ @@ -287,13 +287,15 @@ inline Matrix4D Matrix4D::operator * (const Matrix4D& rclMtrx) const Matrix4D clMat; unsigned short ie, iz, is; - for (iz = 0; iz < 4; iz++) + for (iz = 0; iz < 4; iz++) { for (is = 0; is < 4; is++) { clMat.dMtrx4D[iz][is] = 0; - for (ie = 0; ie < 4; ie++) - clMat.dMtrx4D[iz][is] += dMtrx4D[iz][ie] * + for (ie = 0; ie < 4; ie++) { + clMat.dMtrx4D[iz][is] += dMtrx4D[iz][ie] * rclMtrx.dMtrx4D[ie][is]; + } } + } return clMat; } diff --git a/src/Base/MatrixPy.xml b/src/Base/MatrixPy.xml index 0e4122d010..7f53405601 100644 --- a/src/Base/MatrixPy.xml +++ b/src/Base/MatrixPy.xml @@ -1,18 +1,18 @@ + Father="PyObjectBase" + Name="MatrixPy" + Twin="Matrix" + TwinPointer="Matrix4D" + Include="Base/Matrix.h" + FatherInclude="Base/PyObjectBase.h" + Namespace="Base" + Constructor="true" + Delete="true" + NumberProtocol="true" + RichCompare="true" + FatherNamespace="Base"> This is the Matrix export class diff --git a/src/Base/Observer.h b/src/Base/Observer.h index 97bd4e464c..aa99d5b5cc 100644 --- a/src/Base/Observer.h +++ b/src/Base/Observer.h @@ -54,13 +54,13 @@ public: * A constructor. * No special function so far. */ - Observer(){} + Observer() = default; /** * A destructor. * No special function so far. */ - virtual ~Observer(){} + virtual ~Observer() = default; /** * This method need to be reimplemented from the concrete Observer @@ -108,7 +108,7 @@ public: * A constructor. * No special function so far. */ - Subject(){} + Subject() = default; /** * A destructor. diff --git a/src/Base/Parameter.cpp b/src/Base/Parameter.cpp index 98b0bc714d..00a8defdeb 100644 --- a/src/Base/Parameter.cpp +++ b/src/Base/Parameter.cpp @@ -84,17 +84,16 @@ public: fSawErrors(false) { } - ~DOMTreeErrorReporter() { - } + ~DOMTreeErrorReporter() override = default; // ----------------------------------------------------------------------- // Implementation of the error handler interface // ----------------------------------------------------------------------- - void warning(const SAXParseException& toCatch); - void error(const SAXParseException& toCatch); - void fatalError(const SAXParseException& toCatch); - void resetErrors(); + void warning(const SAXParseException& toCatch) override; + void error(const SAXParseException& toCatch) override; + void fatalError(const SAXParseException& toCatch) override; + void resetErrors() override; // ----------------------------------------------------------------------- // Getter methods @@ -156,20 +155,20 @@ public: //@{ /** @name Destructors */ - ~DOMPrintFilter() {} + ~DOMPrintFilter() override = default; //@{ /** @ interface from DOMWriterFilter */ - virtual FilterAction acceptNode(const XERCES_CPP_NAMESPACE_QUALIFIER DOMNode*) const; + FilterAction acceptNode(const XERCES_CPP_NAMESPACE_QUALIFIER DOMNode*) const override; //@{ - virtual ShowType getWhatToShow() const { + ShowType getWhatToShow() const override { return fWhatToShow; } private: // unimplemented copy ctor and assignment operator - DOMPrintFilter(const DOMPrintFilter&); + DOMPrintFilter(const DOMPrintFilter&) = delete; DOMPrintFilter & operator = (const DOMPrintFilter&); ShowType fWhatToShow; @@ -179,11 +178,11 @@ class DOMPrintErrorHandler : public DOMErrorHandler { public: - DOMPrintErrorHandler() {} - ~DOMPrintErrorHandler() {} + DOMPrintErrorHandler() = default; + ~DOMPrintErrorHandler() override = default; /** @name The error handler interface */ - bool handleError(const DOMError& domError); + bool handleError(const DOMError& domError) override; void resetErrors() {} private : @@ -222,9 +221,7 @@ ParameterGrp::ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *GroupNode, /** Destruction * complete destruction of the object */ -ParameterGrp::~ParameterGrp() -{ -} +ParameterGrp::~ParameterGrp() = default; //************************************************************************** // Access methods @@ -365,7 +362,7 @@ Base::Reference ParameterGrp::_GetGroup(const char* Name) return rParamGrp; } -std::vector > ParameterGrp::GetGroups(void) +std::vector > ParameterGrp::GetGroups() { Base::Reference rParamGrp; std::vector > vrParamGrp; @@ -390,7 +387,7 @@ std::vector > ParameterGrp::GetGroups(void) /// test if this group is empty bool ParameterGrp::IsEmpty() const { - if ( _pGroupNode->getFirstChild() ) + if (_pGroupNode->getFirstChild()) return false; else return true; @@ -399,10 +396,10 @@ bool ParameterGrp::IsEmpty() const /// test if a special sub group is in this group bool ParameterGrp::HasGroup(const char* Name) const { - if ( _GroupMap.find(Name) != _GroupMap.end() ) + if (_GroupMap.find(Name) != _GroupMap.end()) return true; - if ( FindElement(_pGroupNode,"FCParamGroup",Name) != nullptr ) + if (FindElement(_pGroupNode,"FCParamGroup",Name)) return true; return false; @@ -443,7 +440,7 @@ std::vector ParameterGrp::GetBools(const char * sFilter) const while ( pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter)!= std::string::npos) { if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),"1")) vrValues.push_back(false); else @@ -464,7 +461,7 @@ std::vector > ParameterGrp::GetBoolMap(const char * while ( pcTemp) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { if (strcmp(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),"1")) vrValues.emplace_back(Name, false); else @@ -510,7 +507,7 @@ std::vector ParameterGrp::GetInts(const char * sFilter) const while ( pcTemp ) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.push_back(atol(StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()) ); } pcTemp = FindNextElement(pcTemp,"FCInt") ; @@ -528,7 +525,7 @@ std::vector > ParameterGrp::GetIntMap(const char * s while ( pcTemp ) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.emplace_back(Name, ( atol (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()))); } @@ -572,7 +569,7 @@ std::vector ParameterGrp::GetUnsigneds(const char * sFilter) cons while ( pcTemp ) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.push_back( strtoul (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),nullptr,10) ); } pcTemp = FindNextElement(pcTemp,"FCUInt") ; @@ -590,7 +587,7 @@ std::vector > ParameterGrp::GetUnsignedMap( while ( pcTemp ) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.emplace_back(Name, ( strtoul (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str(),nullptr,10) )); } @@ -634,7 +631,7 @@ std::vector ParameterGrp::GetFloats(const char * sFilter) const while ( pcTemp ) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.push_back( atof (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()) ); } pcTemp = FindNextElement(pcTemp,"FCFloat"); @@ -652,7 +649,7 @@ std::vector > ParameterGrp::GetFloatMap(const char while ( pcTemp ) { Name = StrX(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { vrValues.emplace_back(Name, ( atof (StrX(pcTemp->getAttribute(XStr("Value").unicodeForm())).c_str()))); } @@ -700,7 +697,7 @@ std::string ParameterGrp::GetASCII(const char* Name, const char * pPreset) const DOMElement *pcElem = FindElement(_pGroupNode,"FCText",Name); // if not return preset if (!pcElem) { - if (pPreset==nullptr) + if (!pPreset) return std::string(""); else return std::string(pPreset); @@ -722,7 +719,7 @@ std::vector ParameterGrp::GetASCIIs(const char * sFilter) const while ( pcTemp ) { Name = StrXUTF8(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { // retrieve the text element DOMNode *pcElem2 = pcTemp->getFirstChild(); if (pcElem2) @@ -745,7 +742,7 @@ std::vector > ParameterGrp::GetASCIIMap(const while ( pcTemp) { Name = StrXUTF8(pcTemp->getAttribute(XStr("Name").unicodeForm())).c_str(); // check on filter condition - if (sFilter == nullptr || Name.find(sFilter)!= std::string::npos) { + if (!sFilter || Name.find(sFilter) != std::string::npos) { // retrieve the text element DOMNode *pcElem2 = pcTemp->getFirstChild(); if (pcElem2) @@ -799,9 +796,9 @@ void ParameterGrp::RemoveBlob(const char* /*Name*/) DOMElement *pcElem = FindElement(_pGroupNode,"FCGrp",Name); // if not return if(!pcElem) - return; + return; else - _pGroupNode->removeChild(pcElem); + _pGroupNode->removeChild(pcElem); */ } @@ -905,7 +902,7 @@ bool ParameterGrp::RenameGrp(const char* OldName, const char* NewName) return true; } -void ParameterGrp::Clear(void) +void ParameterGrp::Clear() { std::vector vecNodes; @@ -923,7 +920,7 @@ void ParameterGrp::Clear(void) } // remove group handles - for (auto it : removeGrp) { + for (const auto& it : removeGrp) { auto pos = _GroupMap.find(it); vecNodes.push_back(pos->second->_pGroupNode); _GroupMap.erase(pos->first); @@ -1072,9 +1069,7 @@ ParameterSerializer::ParameterSerializer(const std::string& fn) { } -ParameterSerializer::~ParameterSerializer() -{ -} +ParameterSerializer::~ParameterSerializer() = default; void ParameterSerializer::SaveDocument(const ParameterManager& mgr) { @@ -1648,10 +1643,10 @@ short DOMPrintFilter::acceptNode(const DOMNode* node) const case DOMNode::ELEMENT_NODE: { // for element whose name is "person", skip it //if (XMLString::compareString(node->getNodeName(), element_person)==0) - // return DOMNodeFilter::FILTER_SKIP; + // return DOMNodeFilter::FILTER_SKIP; // for element whose name is "line", reject it //if (XMLString::compareString(node->getNodeName(), element_link)==0) - // return DOMNodeFilter::FILTER_REJECT; + // return DOMNodeFilter::FILTER_REJECT; // for rest, accept it return DOMNodeFilter::FILTER_ACCEPT; diff --git a/src/Base/Parameter.h b/src/Base/Parameter.h index 8aa2ae55d1..481f4794ee 100644 --- a/src/Base/Parameter.h +++ b/src/Base/Parameter.h @@ -85,7 +85,7 @@ class ParameterManager; * and exporting groups of parameters and enables streaming * to a persistent medium via XML. * \par - * Its main task is making user parameter persistent, saving + * Its main task is making user parameter persistent, saving * last used values in dialog boxes, setting and retrieving all * kind of preferences and so on. * @see ParameterManager @@ -230,7 +230,7 @@ protected: /// constructor is protected (handle concept) ParameterGrp(XERCES_CPP_NAMESPACE_QUALIFIER DOMElement *GroupNode=nullptr,const char* sName=nullptr); /// destructor is protected (handle concept) - ~ParameterGrp(); + ~ParameterGrp() override; /// helper function for GetGroup Base::Reference _GetGroup(const char* Name); bool ShouldRemove() const; @@ -295,7 +295,7 @@ class BaseExport ParameterManager : public ParameterGrp { public: ParameterManager(); - ~ParameterManager(); + ~ParameterManager() override; static void Init(); static void Terminate(); diff --git a/src/Base/ParameterPy.cpp b/src/Base/ParameterPy.cpp index de7f17c2a1..d24d493306 100644 --- a/src/Base/ParameterPy.cpp +++ b/src/Base/ParameterPy.cpp @@ -52,12 +52,12 @@ public: { inst = obj; } - virtual ~ParameterGrpObserver() + ~ParameterGrpObserver() override { Base::PyGILStateLocker lock; inst = Py::None(); } - virtual void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason) + void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason) override { Base::PyGILStateLocker lock; try { @@ -93,9 +93,9 @@ public: static void init_type(); // announce properties and methods ParameterGrpPy(const Base::Reference &rcParamGrp); - ~ParameterGrpPy(); + ~ParameterGrpPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object getGroup(const Py::Tuple&); Py::Object getGroupName(const Py::Tuple&); diff --git a/src/Base/Placement.cpp b/src/Base/Placement.cpp index 0eaf2bc138..50e261c982 100644 --- a/src/Base/Placement.cpp +++ b/src/Base/Placement.cpp @@ -29,10 +29,7 @@ using namespace Base; -Placement::Placement() -{ - -} +Placement::Placement() = default; Placement::Placement(const Base::Matrix4D& matrix) { @@ -100,6 +97,18 @@ bool Placement::isIdentity() const return none; } +bool Placement::isSame(const Placement& p) const +{ + return this->_rot.isSame(p._rot) && + this->_pos.IsEqual(p._pos, 0); +} + +bool Placement::isSame(const Placement& p, double tol) const +{ + return this->_rot.isSame(p._rot, tol) && + this->_pos.IsEqual(p._pos, tol); +} + void Placement::invert() { this->_rot = this->_rot.inverse(); @@ -129,13 +138,15 @@ bool Placement::operator != (const Placement& that) const return !(*this == that); } +/*! + Let this placement be right-multiplied by \a p. Returns reference to + self. + + \sa multRight() +*/ Placement & Placement::operator*=(const Placement & p) { - Base::Vector3d tmp(p._pos); - this->_rot.multVec(tmp, tmp); - this->_pos += tmp; - this->_rot *= p._rot; - return *this; + return multRight(p); } Placement Placement::operator*(const Placement & p) const @@ -157,12 +168,46 @@ Placement Placement::pow(double t, bool shorten) const return Placement::fromDualQuaternion(this->toDualQuaternion().pow(t, shorten)); } +/*! + Let this placement be right-multiplied by \a p. Returns reference to + self. + + \sa multLeft() +*/ +Placement& Placement::multRight(const Base::Placement& p) +{ + Base::Vector3d tmp(p._pos); + this->_rot.multVec(tmp, tmp); + this->_pos += tmp; + this->_rot.multRight(p._rot); + return *this; +} + +/*! + Let this placement be left-multiplied by \a p. Returns reference to + self. + + \sa multRight() +*/ +Placement& Placement::multLeft(const Base::Placement& p) +{ + p.multVec(this->_pos, this->_pos); + this->_rot.multLeft(p._rot); + return *this; +} + void Placement::multVec(const Vector3d & src, Vector3d & dst) const { this->_rot.multVec(src, dst); dst += this->_pos; } +void Placement::multVec(const Vector3f & src, Vector3f & dst) const +{ + this->_rot.multVec(src, dst); + dst += Base::toVector(this->_pos); +} + Placement Placement::slerp(const Placement & p0, const Placement & p1, double t) { Rotation rot = Rotation::slerp(p0.getRotation(), p1.getRotation(), t); diff --git a/src/Base/Placement.h b/src/Base/Placement.h index 2020096214..7184046079 100644 --- a/src/Base/Placement.h +++ b/src/Base/Placement.h @@ -51,7 +51,7 @@ public: //@} /// Destruction - ~Placement () {} + ~Placement () = default; Matrix4D toMatrix() const; void fromMatrix(const Matrix4D& m); @@ -66,6 +66,9 @@ public: Placement inverse() const; void move(const Vector3d& MovVec); + bool isSame(const Placement&) const; + bool isSame(const Placement&, double tol) const; + /** Operators. */ //@{ Placement & operator*=(const Placement & p); @@ -75,7 +78,11 @@ public: Placement& operator = (const Placement&); Placement pow(double t, bool shorten = true) const; + Placement& multRight(const Base::Placement& p); + Placement& multLeft(const Base::Placement& p); + void multVec(const Vector3d & src, Vector3d & dst) const; + void multVec(const Vector3f & src, Vector3f & dst) const; //@} static Placement slerp(const Placement & p0, const Placement & p1, double t); diff --git a/src/Base/PlacementPy.xml b/src/Base/PlacementPy.xml index 658bd6f26a..58560ff021 100644 --- a/src/Base/PlacementPy.xml +++ b/src/Base/PlacementPy.xml @@ -1,21 +1,21 @@ - - - - Base.Placement class.\n + FatherNamespace="Base"> + + + Base.Placement class.\n A Placement defines an orientation (rotation) and a position (base) in 3D space. It is used when no scaling or other distortion is needed.\n The following constructors are supported:\n @@ -41,78 +41,83 @@ define position and rotation. base : Base.Vector axis : Base.Vector angle : float - Placement - + Placement + copy() -> Base.Placement\n Returns a copy of this placement. - - - move(vector) -> None\n + + + move(vector) -> None\n Move the placement along a vector.\n vector : Base.Vector\n Vector by which to move the placement. - - - - - translate(vector) -> None\n + + + + + translate(vector) -> None\n Alias to move(), to be compatible with TopoShape.translate().\n vector : Base.Vector\n Vector by which to move the placement. - - - + + + - rotate(center, axis, angle) -> None\n + rotate(center, axis, angle, comp) -> None\n Rotate the current placement around center and axis with the given angle. -This method is compatible with TopoShape.rotate().\n +This method is compatible with TopoShape.rotate() if the (optional) keyword +argument comp is True (default=False). + center : Base.Vector, sequence of float\n Rotation center. axis : Base.Vector, sequence of float\n Rotation axis. -angle : float\n Rotation angle in degrees. +angle : float\n Rotation angle in degrees. +comp : bool\n optional keyword only argument, if True (default=False), +behave like TopoShape.rotate() (i.e. the resulting placements are interchangeable). + - - multiply(placement) -> Base.Placement\n + + multiply(placement) -> Base.Placement\n Right multiply this placement with another placement. Also available as `*` operator.\n placement : Base.Placement\n Placement by which to multiply this placement. - - + + - - multVec(vector) -> Base.Vector\n + + multVec(vector) -> Base.Vector\n Compute the transformed vector using the placement.\n vector : Base.Vector\n Vector to be transformed. - - + + - - toMatrix() -> Base.Matrix\n + + toMatrix() -> Base.Matrix\n Compute the matrix representation of the placement. - - + + - - inverse() -> Base.Placement\n + + inverse() -> Base.Placement\n Compute the inverse placement. - - + + - - pow(t, shorten=True) -> Base.Placement\n + + pow(t, shorten=True) -> Base.Placement\n Raise this placement to real power using ScLERP interpolation. Also available as `**` operator.\n t : float\n Real power. shorten : bool\n If True, ensures rotation quaternion is net positive to make the path shorter. - - + + - - sclerp(placement2, t, shorten=True) -> Base.Placement\n + + sclerp(placement2, t, shorten=True) -> Base.Placement\n Screw Linear Interpolation (ScLERP) between this placement and `placement2`. Interpolation is a continuous motion along a helical path parametrized by `t` made of equal transforms if discretized. @@ -123,11 +128,11 @@ t : float\n Parameter of helical path. t=0 returns this placement, t=1 return `placement2`. t can also be outside of [0, 1] range for extrapolation. shorten : bool\n If True, the signs are harmonized before interpolation and the interpolation takes the shorter path. - - + + - - slerp(placement2, t) -> Base.Placement\n + + slerp(placement2, t) -> Base.Placement\n Spherical Linear Interpolation (SLERP) between this placement and `placement2`. This function performs independent interpolation of rotation and movement. Result of such interpolation might be not what application expects, thus this tool @@ -135,38 +140,45 @@ might be considered for simple cases or for interpolating between small interval For more complex cases you better use the advanced sclerp() function.\n placement2 : Base.Placement t : float\n Parameter of the path. t=0 returns this placement, t=1 returns `placement2`. - - + + - - isIdentity() -> bool\n + + isIdentity() -> bool\n Returns True if the placement has no displacement and no rotation. Matrix representation is the 4D identity matrix. - - + + + + + isSame(Base.Placement, [tol=0.0]) -> bool\n +Checks whether this and the given placement are the same. +The default tolerance is set to 0.0 + + - - Vector to the Base Position of the Placement. - - - - - - Orientation of the placement expressed as rotation. - - - - - + + Vector to the Base Position of the Placement. + + + + + + Orientation of the placement expressed as rotation. + + + + + Set/get matrix representation of the placement. - - - + + + public: PlacementPy(const Placement & pla, PyTypeObject *T = &Type) :PyObjectBase(new Placement(pla),T){} Placement value() const { return *(getPlacementPtr()); } - + diff --git a/src/Base/PlacementPyImp.cpp b/src/Base/PlacementPyImp.cpp index f7d9761492..9de81175b3 100644 --- a/src/Base/PlacementPyImp.cpp +++ b/src/Base/PlacementPyImp.cpp @@ -39,14 +39,14 @@ using namespace Base; // returns a string which represents the object e.g. when printed in python std::string PlacementPy::representation() const { - double A,B,C; + double yaw{}, pitch{}, roll{}; PlacementPy::PointerType ptr = getPlacementPtr(); std::stringstream str; - ptr->getRotation().getYawPitchRoll(A,B,C); + ptr->getRotation().getYawPitchRoll(yaw, pitch, roll); str << "Placement [Pos=("; str << ptr->getPosition().x << ","<< ptr->getPosition().y << "," << ptr->getPosition().z; - str << "), Yaw-Pitch-Roll=(" << A << "," << B << "," << C << ")]"; + str << "), Yaw-Pitch-Roll=(" << yaw << "," << pitch << "," << roll << ")]"; return str.str(); } @@ -163,22 +163,33 @@ PyObject* PlacementPy::translate(PyObject * args) return move(args); } -PyObject* PlacementPy::rotate(PyObject *args) { - PyObject *obj1, *obj2; +PyObject* PlacementPy::rotate(PyObject *args, PyObject *kwds) +{ double angle; - if (!PyArg_ParseTuple(args, "OOd", &obj1, &obj2, &angle)) + char *keywords[] = { "center", "axis", "angle", "comp", nullptr }; + Vector3d center; + Vector3d axis; + PyObject* pyComp = Py_False; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "(ddd)(ddd)d|O!", keywords, ¢er.x, ¢er.y, ¢er.z, + &axis.x, &axis.y, &axis.z, &angle, &PyBool_Type, &pyComp)) return nullptr; try { - Py::Sequence p1(obj1), p2(obj2); - Vector3d center((double)Py::Float(p1[0]), - (double)Py::Float(p1[1]), - (double)Py::Float(p1[2])); - Vector3d axis((double)Py::Float(p2[0]), - (double)Py::Float(p2[1]), - (double)Py::Float(p2[2])); - (*getPlacementPtr()) *= Placement( - Vector3d(),Rotation(axis,toRadians(angle)),center); + /* + * if comp is False, we retain the original behaviour that - contrary to the (old) documentation - generates + * Placements different from TopoShape.rotate() to ensure compatibility for existing code + */ + bool comp = Base::asBoolean(pyComp); + + if (!comp) { + getPlacementPtr()->multRight(Placement(Vector3d(), Rotation(axis, toRadians(angle)), center)); + } + else { + // multiply new Placement the same way TopoShape.rotate() does + getPlacementPtr()->multLeft(Placement(Vector3d(), Rotation(axis, toRadians(angle)), center)); + } + Py_Return; } catch (const Py::Exception&) { @@ -270,6 +281,19 @@ PyObject* PlacementPy::isIdentity(PyObject *args) return Py_BuildValue("O", (none ? Py_True : Py_False)); } +PyObject* PlacementPy::isSame(PyObject *args) +{ + PyObject* plm; + double tol = 0.0; + if (!PyArg_ParseTuple(args, "O!|d", &PlacementPy::Type, &plm, &tol)) + return nullptr; + + Base::Placement plm1 = * getPlacementPtr(); + Base::Placement plm2 = * static_cast(plm)->getPlacementPtr(); + bool same = tol > 0.0 ? plm1.isSame(plm2, tol) : plm1.isSame(plm2); + return Py_BuildValue("O", (same ? Py_True : Py_False)); +} + Py::Object PlacementPy::getBase() const { return Py::Vector(getPlacementPtr()->getPosition()); diff --git a/src/Base/PreCompiled.h b/src/Base/PreCompiled.h index 79566cc4d0..1e4bc9ef17 100644 --- a/src/Base/PreCompiled.h +++ b/src/Base/PreCompiled.h @@ -114,7 +114,10 @@ #include #include #include +#include +#include #include +#include // QtCore #include diff --git a/src/Base/Precision.h b/src/Base/Precision.h new file mode 100644 index 0000000000..6e38a9a039 --- /dev/null +++ b/src/Base/Precision.h @@ -0,0 +1,175 @@ +/*************************************************************************** + * Copyright (c) 2022 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 * + * * + ***************************************************************************/ + + +#ifndef BASE_PRECISION_H +#define BASE_PRECISION_H + +#include + +namespace Base { + +// The methods are copied from OCC's Precision class +class Precision { +public: + /*! + * \brief Angular + * Returns the recommended precision value when checking the equality of two angles (given in radians). + * \return + */ + static double Angular() { return 1.e-12; } + + /*! + * \brief Confusion + * Returns the recommended precision value when checking coincidence of two points in real space. + * \return + */ + static double Confusion() { return 1.e-7; } + + /*! + * \brief SquareConfusion + * Returns square of \ref Confusion. + * \return + */ + static double SquareConfusion() { return Confusion() * Confusion(); } + + /*! + * \brief Intersection + * Returns the precision value in real space, frequently + * used by intersection algorithms to decide that a solution is reached. + * \return + */ + static double Intersection() { return Confusion() * 0.01; } + + /*! + * \brief Approximation + * Returns the precision value in real space, frequently used + * by approximation algorithms. + * \return + */ + static double Approximation() { return Confusion() * 10.0; } + + /*! + * \brief Parametric + * Convert a real space precision to a parametric space precision. + * \param P + * \param T + * \return + */ + static double Parametric (const double P, const double T) { return P / T; } + + /*! + * \brief PConfusion + * Returns a precision value in parametric space. + * \param T + * \return + */ + static double PConfusion (const double T) { return Parametric (Confusion(), T); } + + /*! + * \brief PConfusion + * Used to test distances in parametric space on a default curve. + * \return + */ + static double PConfusion() { return Parametric (Confusion()); } + + /*! + * \brief SquarePConfusion + * Returns square of \ref PConfusion. + * \return + */ + static double SquarePConfusion() { return PConfusion() * PConfusion(); } + + /*! + * \brief PIntersection + * Returns a precision value in parametric space, which may be used by intersection algorithms, + * to decide that a solution is reached. + * \param T + * \return + */ + static double PIntersection (const double T) { return Parametric(Intersection(),T); } + + /*! + * \brief PApproximation + * Returns a precision value in parametric space, which may be used by approximation algorithms. + * \param T + * \return + */ + static double PApproximation (const double T) { return Parametric(Approximation(),T); } + + /*! + * \brief Parametric + * Convert a real space precision to a parametric space precision on a default curve. + * \param P + * \return + */ + static double Parametric (const double P) { return Parametric (P, 100.0); } + + /*! + * \brief PIntersection + * Used for Intersections in parametric space on a default curve. + * \return + */ + static double PIntersection() { return Parametric (Intersection()); } + + /*! + * \brief PApproximation + * Used for Approximations in parametric space on a default curve. + * \return + */ + static double PApproximation() { return Parametric (Approximation()); } + + /*! + * \brief IsInfinite + * Returns True if R may be considered as an infinite number. Currently Abs(R) > 1e100 + * \param R + * \return + */ + static double IsInfinite (const double R) { return std::fabs (R) >= (0.5 * Precision::Infinite()); } + + /*! + * \brief IsPositiveInfinite + * Returns True if R may be considered as a positive infinite number. Currently R > 1e100 + * \param R + * \return + */ + static double IsPositiveInfinite (const double R) { return R >= (0.5 * Precision::Infinite()); } + + /*! + * \brief IsNegativeInfinite + * Returns True if R may be considered as a negative infinite number. Currently R < -1e100 + * \param R + * \return + */ + static bool IsNegativeInfinite (const double R) { return R <= -(0.5 * Precision::Infinite()); } + + /*! + * \brief Infinite + * Returns a big number that can be considered as infinite. Use -Infinite() for a negative big number. + * \return + */ + static double Infinite() { return 2.e+100; } +}; + +} + +#endif // BASE_PRECISION_H diff --git a/src/Mod/Part/App/PrecisionPy.xml b/src/Base/PrecisionPy.xml similarity index 92% rename from src/Mod/Part/App/PrecisionPy.xml rename to src/Base/PrecisionPy.xml index 6ba4c5a80f..5c4b24726b 100644 --- a/src/Mod/Part/App/PrecisionPy.xml +++ b/src/Base/PrecisionPy.xml @@ -3,17 +3,17 @@ - This is the Type class - This is the Type class + This is the Precision class + This is the Precision class diff --git a/src/Mod/Part/App/PrecisionPyImp.cpp b/src/Base/PrecisionPyImp.cpp similarity index 98% rename from src/Mod/Part/App/PrecisionPyImp.cpp rename to src/Base/PrecisionPyImp.cpp index 3c8bf6dc5c..dd5e591922 100644 --- a/src/Mod/Part/App/PrecisionPyImp.cpp +++ b/src/Base/PrecisionPyImp.cpp @@ -26,7 +26,8 @@ #include "PrecisionPy.cpp" -using namespace Part; +using Base::Precision; +using Base::PrecisionPy; // returns a string which represents the object e.g. when printed in python diff --git a/src/Base/PyObjectBase.cpp b/src/Base/PyObjectBase.cpp index a8e1b32780..ca10b95232 100644 --- a/src/Base/PyObjectBase.cpp +++ b/src/Base/PyObjectBase.cpp @@ -107,7 +107,7 @@ static void PyBaseProxy_dealloc(PyObject* self) { /* Clear weakrefs first before calling any destructors */ - if (reinterpret_cast(self)->weakreflist != nullptr) + if (reinterpret_cast(self)->weakreflist) PyObject_ClearWeakRefs(self); Py_TYPE(self)->tp_free(self); } @@ -353,7 +353,7 @@ int PyObjectBase::__setattro(PyObject *obj, PyObject *attro, PyObject *value) //Hint: In general we don't allow to delete attributes (i.e. value=0). However, if we want to allow //we must check then in _setattr() of all subclasses whether value is 0. - if ( value==nullptr ) { + if (!value) { PyErr_Format(PyExc_AttributeError, "Cannot delete attribute: '%s'", attr); return -1; } @@ -413,7 +413,7 @@ PyObject *PyObjectBase::_getattr(const char *attr) // As fallback solution use Python's default method to get generic attributes PyObject *w, *res; w = PyUnicode_InternFromString(attr); - if (w != nullptr) { + if (w) { res = PyObject_GenericGetAttr(this, w); Py_XDECREF(w); return res; @@ -433,7 +433,7 @@ int PyObjectBase::_setattr(const char *attr, PyObject *value) PyObject *w; // As fallback solution use Python's default method to get generic attributes w = PyUnicode_InternFromString(attr); // new reference - if (w != nullptr) { + if (w) { // call methods from tp_getset if defined int res = PyObject_GenericSetAttr(this, w, value); Py_DECREF(w); diff --git a/src/Base/Quantity.h b/src/Base/Quantity.h index fc941c9249..4dbe9e7c3f 100644 --- a/src/Base/Quantity.h +++ b/src/Base/Quantity.h @@ -116,7 +116,7 @@ public: explicit Quantity(double value, const Unit& unit=Unit()); explicit Quantity(double value, const QString& unit); /// Destruction - ~Quantity () {} + ~Quantity () = default; /** Operators. */ //@{ @@ -249,7 +249,7 @@ public: static Quantity MilliNewtonPerMeter; static Quantity KiloNewtonPerMeter; static Quantity MegaNewtonPerMeter; - + static Quantity Pascal; static Quantity KiloPascal; static Quantity MegaPascal; diff --git a/src/Base/QuantityPy.xml b/src/Base/QuantityPy.xml index 7eb0edfabf..881b58a70b 100644 --- a/src/Base/QuantityPy.xml +++ b/src/Base/QuantityPy.xml @@ -1,21 +1,21 @@ - - - - Quantity + + + + Quantity defined by a value and a unit. The following constructors are supported: @@ -24,9 +24,9 @@ Quantity(Value) -- empty constructor Quantity(Value,Unit) -- empty constructor Quantity(Quantity) -- copy constructor Quantity(string) -- arbitrary mixture of numbers and chars defining a Quantity - - Quantity - + + Quantity + @@ -50,8 +50,8 @@ Quantity(string) -- arbitrary mixture of numbers and chars defining a Quantity Following parameters are allowed: getValueAs('m/s') # unit string to parse - getValueAs(2.45,1) # translatrion value and unit signature - getValueAs(FreeCAD.Units.Pascal) # predefined standard units + getValueAs(2.45,1) # translation value and unit signature + getValueAs(FreeCAD.Units.Pascal) # predefined standard units getValueAs(Qantity('N/m^2')) # a quantity getValueAs(Unit(0,1,0,0,0,0,0,0)) # a unit @@ -66,11 +66,11 @@ When an argument is passed, work like built-in round(x, ndigits). - - Numeric Value of the Quantity (in internal system mm,kg,s) - - - + + Numeric Value of the Quantity (in internal system mm,kg,s) + + + Unit of the Quantity diff --git a/src/Base/QuantityPyImp.cpp b/src/Base/QuantityPyImp.cpp index 7d0cf2eec0..84d0b4082c 100644 --- a/src/Base/QuantityPyImp.cpp +++ b/src/Base/QuantityPyImp.cpp @@ -628,15 +628,24 @@ void QuantityPy::setFormat(Py::Dict arg) } if (arg.hasKey("NumberFormat")) { - Py::Char form(arg.getItem("NumberFormat")); - std::string fmtstr = static_cast(Py::String(form)); - if (fmtstr.size() != 1) - throw Py::ValueError("Invalid format character"); + Py::Object item = arg.getItem("NumberFormat"); + if (item.isNumeric()) { + int format = static_cast(Py::Int(item)); + if (format < 0 || format > QuantityFormat::Scientific) + throw Py::ValueError("Invalid format value"); + fmt.format = static_cast(format); + } + else { + Py::Char form(item); + std::string fmtstr = static_cast(Py::String(form)); + if (fmtstr.size() != 1) + throw Py::ValueError("Invalid format character"); - bool ok; - fmt.format = Base::QuantityFormat::toFormat(fmtstr[0], &ok); - if (!ok) - throw Py::ValueError("Invalid format character"); + bool ok; + fmt.format = Base::QuantityFormat::toFormat(fmtstr[0], &ok); + if (!ok) + throw Py::ValueError("Invalid format character"); + } } if (arg.hasKey("Denominator")) { diff --git a/src/Base/Reader.h b/src/Base/Reader.h index 0627e45628..c2788c0fe9 100644 --- a/src/Base/Reader.h +++ b/src/Base/Reader.h @@ -125,7 +125,7 @@ public: }; /// open the file and read the first element XMLReader(const char* FileName, std::istream&); - ~XMLReader(); + ~XMLReader() override; bool isValid() const { return _valid; } bool isVerbose() const { return _verbose; } @@ -223,28 +223,28 @@ protected: // ----------------------------------------------------------------------- /** @name Content handler */ //@{ - virtual void startDocument(); - virtual void endDocument(); - virtual void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs); - virtual void endElement (const XMLCh* const uri, const XMLCh *const localname, const XMLCh *const qname); + void startDocument() override; + void endDocument() override; + void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) override; + void endElement (const XMLCh* const uri, const XMLCh *const localname, const XMLCh *const qname) override; #if (XERCES_VERSION_MAJOR == 2) virtual void characters (const XMLCh* const chars, const unsigned int length); virtual void ignorableWhitespace(const XMLCh* const chars, const unsigned int length); #else - virtual void characters (const XMLCh* const chars, const XMLSize_t length); - virtual void ignorableWhitespace(const XMLCh* const chars, const XMLSize_t length); + void characters (const XMLCh* const chars, const XMLSize_t length) override; + void ignorableWhitespace(const XMLCh* const chars, const XMLSize_t length) override; #endif //@} /** @name Lexical handler */ //@{ - virtual void startCDATA (); - virtual void endCDATA (); + void startCDATA () override; + void endCDATA () override; //@} /** @name Document handler */ //@{ - virtual void resetDocument(); + void resetDocument() override; //@} @@ -253,10 +253,10 @@ protected: // ----------------------------------------------------------------------- /** @name Error handler */ //@{ - void warning(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& exc); - void error(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& exc); - void fatalError(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& exc); - void resetErrors(); + void warning(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& exc) override; + void error(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& exc) override; + void fatalError(const XERCES_CPP_NAMESPACE_QUALIFIER SAXParseException& exc) override; + void resetErrors() override; //@} diff --git a/src/Base/Rotation.cpp b/src/Base/Rotation.cpp index 1326a7536a..8212956a6c 100644 --- a/src/Base/Rotation.cpp +++ b/src/Base/Rotation.cpp @@ -28,6 +28,7 @@ #include "Rotation.h" #include "Matrix.h" +#include "Precision.h" using namespace Base; @@ -350,7 +351,31 @@ Rotation Rotation::inverse() const return rot; } +/*! + Let this rotation be right-multiplied by \a q. Returns reference to + self. + + \sa multRight() +*/ Rotation & Rotation::operator*=(const Rotation & q) +{ + return multRight(q); +} + +Rotation Rotation::operator*(const Rotation & q) const +{ + Rotation quat(*this); + quat *= q; + return quat; +} + +/*! + Let this rotation be right-multiplied by \a q. Returns reference to + self. + + \sa multLeft() +*/ +Rotation& Rotation::multRight(const Base::Rotation& q) { // Taken from double x0, y0, z0, w0; @@ -365,11 +390,25 @@ Rotation & Rotation::operator*=(const Rotation & q) return *this; } -Rotation Rotation::operator*(const Rotation & q) const +/*! + Let this rotation be left-multiplied by \a q. Returns reference to + self. + + \sa multRight() +*/ +Rotation& Rotation::multLeft(const Base::Rotation& q) { - Rotation quat(*this); - quat *= q; - return quat; + // Taken from + double x0, y0, z0, w0; + q.getValue(x0, y0, z0, w0); + double x1, y1, z1, w1; + this->getValue(x1, y1, z1, w1); + + this->setValue(w0*x1 + x0*w1 + y0*z1 - z0*y1, + w0*y1 - x0*z1 + y0*w1 + z0*x1, + w0*z1 + x0*y1 - y0*x1 + z0*w1, + w0*w1 - x0*x1 - y0*y1 - z0*z1); + return *this; } bool Rotation::operator==(const Rotation & q) const @@ -444,6 +483,20 @@ void Rotation::multVec(const Vector3d & src, Vector3d & dst) const dst.z = dz; } +void Rotation::multVec(const Vector3f & src, Vector3f & dst) const +{ + Base::Vector3d srcd = Base::toVector(src); + multVec(srcd, srcd); + dst = Base::toVector(srcd); +} + +Vector3f Rotation::multVec(const Vector3f & src) const +{ + Vector3f dst; + multVec(src,dst); + return dst; +} + void Rotation::scaleAngle(const double scaleFactor) { Vector3d axis; @@ -496,7 +549,7 @@ Rotation Rotation::identity() Rotation Rotation::makeRotationByAxes(Vector3d xdir, Vector3d ydir, Vector3d zdir, const char* priorityOrder) { - const double tol = 1e-7; //equal to OCC Precision::Confusion + const double tol = Precision::Confusion(); enum dirIndex { X, Y, diff --git a/src/Base/Rotation.h b/src/Base/Rotation.h index bf08bbd481..990469e788 100644 --- a/src/Base/Rotation.h +++ b/src/Base/Rotation.h @@ -133,8 +133,13 @@ public: const double & operator [] (unsigned short usIndex) const{return quat[usIndex];} void operator = (const Rotation&); + Rotation& multRight(const Base::Rotation& q); + Rotation& multLeft(const Base::Rotation& q); + void multVec(const Vector3d & src, Vector3d & dst) const; Vector3d multVec(const Vector3d & src) const; + void multVec(const Vector3f & src, Vector3f & dst) const; + Vector3f multVec(const Vector3f & src) const; void scaleAngle(const double scaleFactor); bool isSame(const Rotation&) const; bool isSame(const Rotation&, double tol) const; diff --git a/src/Base/RotationPy.xml b/src/Base/RotationPy.xml index 572d404c52..120bd69221 100644 --- a/src/Base/RotationPy.xml +++ b/src/Base/RotationPy.xml @@ -1,22 +1,22 @@ - - - - This is the Rotation export class - Base.Rotation class.\n + FatherNamespace="Base"> + + + This is the Rotation export class + Base.Rotation class.\n A Rotation using a quaternion.\n The following constructors are supported:\n Rotation() @@ -68,13 +68,13 @@ Rotation(*coef) Define from 16 or 9 elements which represent the rotation in the 4D matrix representation or in the 3D matrix representation, respectively. coef : sequence of float - - - - invert() -> None\n + + + + invert() -> None\n Sets the rotation to its inverse. - - + + inverted() -> Base.Rotation\n @@ -91,26 +91,26 @@ tol : float\n Tolerance used to compare both rotations. - - multiply(rotation) -> Base.Rotation\n + + multiply(rotation) -> Base.Rotation\n Right multiply this rotation with another rotation.\n rotation : Base.Rotation\n Rotation by which to multiply this rotation. - - + + - - multVec(vector) -> Base.Vector\n + + multVec(vector) -> Base.Vector\n Compute the transformed vector using the rotation.\n vector : Base.Vector\n Vector to be transformed. - - + + - - slerp(rotation2, t) -> Base.Rotation\n + + slerp(rotation2, t) -> Base.Rotation\n Spherical Linear Interpolation (SLERP) of this rotation and `rotation2`.\n t : float\n Parameter of the path. t=0 returns this rotation, t=1 returns `rotation2`. - - + + setYawPitchRoll(angle1, angle2, angle3) -> None\n @@ -121,12 +121,12 @@ angle3 : float\n Angle around roll axis in degrees. - - getYawPitchRoll() -> tuple\n + + getYawPitchRoll() -> tuple\n Get the Euler angles of this rotation as yaw-pitch-roll in XY'Z'' convention. The angles are given in degrees. - - + + setEulerAngles(seq, angle1, angle2, angle3) -> None\n @@ -139,25 +139,25 @@ angle3 : float - - toEulerAngles(seq) -> list\n + + toEulerAngles(seq) -> list\n Get the Euler angles in a given sequence for this rotation.\n seq : str\n Euler sequence name. If not given, the function returns all possible values of `seq`. Optional. - - + + - - toMatrix() -> Base.Matrix\n + + toMatrix() -> Base.Matrix\n Convert the rotation to a 4D matrix representation. - - + + - - isNull() -> bool\n + + isNull() -> bool\n Returns True if all values in the quaternion representation are zero. - - + + isIdentity() -> bool\n @@ -165,35 +165,35 @@ Returns True if the rotation equals the 4D identity matrix. - - The rotation elements (as quaternion). - - - - - - The rotation axis of the quaternion. - - - - - - The rotation axis without normalization. - - - - - - The rotation angle of the quaternion. - - - - - public: - RotationPy(const Rotation & mat, PyTypeObject *T = &Type) - :PyObjectBase(new Rotation(mat),T){} - Rotation value() const - { return *(getRotationPtr()); } - - + + The rotation elements (as quaternion). + + + + + + The rotation axis of the quaternion. + + + + + + The rotation axis without normalization. + + + + + + The rotation angle of the quaternion. + + + + + public: + RotationPy(const Rotation & mat, PyTypeObject *T = &Type) + :PyObjectBase(new Rotation(mat),T){} + Rotation value() const + { return *(getRotationPtr()); } + + diff --git a/src/Base/RotationPyImp.cpp b/src/Base/RotationPyImp.cpp index 5764035beb..32b200fe1e 100644 --- a/src/Base/RotationPyImp.cpp +++ b/src/Base/RotationPyImp.cpp @@ -420,7 +420,7 @@ Py::Object RotationPy::getRawAxis() const return Py::Vector(axis); } -Py::Object RotationPy::getAxis(void) const +Py::Object RotationPy::getAxis() const { Base::Vector3d axis; double angle; this->getRotationPtr()->getValue(axis, angle); diff --git a/src/Base/Sequencer.cpp b/src/Base/Sequencer.cpp index 13b554cac9..9c0bace609 100644 --- a/src/Base/Sequencer.cpp +++ b/src/Base/Sequencer.cpp @@ -310,13 +310,9 @@ PyObject *ProgressIndicatorPy::PyMake(struct _typeobject *, PyObject *, PyObject return new ProgressIndicatorPy(); } -ProgressIndicatorPy::ProgressIndicatorPy() -{ -} +ProgressIndicatorPy::ProgressIndicatorPy() = default; -ProgressIndicatorPy::~ProgressIndicatorPy() -{ -} +ProgressIndicatorPy::~ProgressIndicatorPy() = default; Py::Object ProgressIndicatorPy::repr() { diff --git a/src/Base/Sequencer.h b/src/Base/Sequencer.h index 0b5e22f786..ae255e342d 100644 --- a/src/Base/Sequencer.h +++ b/src/Base/Sequencer.h @@ -269,15 +269,15 @@ public: protected: /** Starts the sequencer */ - void startStep(); + void startStep() override; /** Writes the current progress to the console window. */ - void nextStep(bool canAbort); + void nextStep(bool canAbort) override; private: /** Puts text to the console window */ - void setText (const char* pszTxt); + void setText (const char* pszTxt) override; /** Resets the sequencer */ - void resetData(); + void resetData() override; }; /** The SequencerLauncher class is provided for convenience. It allows you to run an instance of the @@ -390,9 +390,9 @@ public: static void init_type(); // announce properties and methods ProgressIndicatorPy(); - ~ProgressIndicatorPy(); + ~ProgressIndicatorPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object start(const Py::Tuple&); Py::Object next(const Py::Tuple&); diff --git a/src/Base/Stream.cpp b/src/Base/Stream.cpp index 134b0aa63e..c149dfafdb 100644 --- a/src/Base/Stream.cpp +++ b/src/Base/Stream.cpp @@ -44,9 +44,7 @@ Stream::Stream() : _swap(false) { } -Stream::~Stream() -{ -} +Stream::~Stream() = default; Stream::ByteOrder Stream::byteOrder() const { @@ -62,9 +60,7 @@ OutputStream::OutputStream(std::ostream &rout) : _out(rout) { } -OutputStream::~OutputStream() -{ -} +OutputStream::~OutputStream() = default; OutputStream& OutputStream::operator << (bool b) { @@ -144,9 +140,7 @@ InputStream::InputStream(std::istream &rin) : _in(rin) { } -InputStream::~InputStream() -{ -} +InputStream::~InputStream() = default; InputStream& InputStream::operator >> (bool& b) { @@ -297,9 +291,7 @@ ByteArrayIStreambuf::ByteArrayIStreambuf(const QByteArray& data) : _buffer(data) _cur = 0; } -ByteArrayIStreambuf::~ByteArrayIStreambuf() -{ -} +ByteArrayIStreambuf::~ByteArrayIStreambuf() = default; ByteArrayIStreambuf::int_type ByteArrayIStreambuf::underflow() { @@ -367,9 +359,7 @@ IODeviceOStreambuf::IODeviceOStreambuf(QIODevice* dev) : device(dev) { } -IODeviceOStreambuf::~IODeviceOStreambuf() -{ -} +IODeviceOStreambuf::~IODeviceOStreambuf() = default; std::streambuf::int_type IODeviceOStreambuf::overflow(std::streambuf::int_type c) @@ -433,9 +423,7 @@ IODeviceIStreambuf::IODeviceIStreambuf(QIODevice* dev) : device(dev), buffer{} buffer+pbSize); // end position } -IODeviceIStreambuf::~IODeviceIStreambuf() -{ -} +IODeviceIStreambuf::~IODeviceIStreambuf() = default; std::streambuf::int_type IODeviceIStreambuf::underflow() @@ -746,9 +734,7 @@ Streambuf::Streambuf(const std::string& data) _cur = _beg; } -Streambuf::~Streambuf() -{ -} +Streambuf::~Streambuf() = default; Streambuf::int_type Streambuf::underflow() { diff --git a/src/Base/Stream.h b/src/Base/Stream.h index 5ebba8999b..e4b1ec3893 100644 --- a/src/Base/Stream.h +++ b/src/Base/Stream.h @@ -67,7 +67,7 @@ class BaseExport OutputStream : public Stream { public: OutputStream(std::ostream &rout); - ~OutputStream(); + ~OutputStream() override; OutputStream& operator << (bool b); OutputStream& operator << (int8_t ch); @@ -97,7 +97,7 @@ class BaseExport InputStream : public Stream { public: InputStream(std::istream &rin); - ~InputStream(); + ~InputStream() override; InputStream& operator >> (bool& b); InputStream& operator >> (int8_t& ch); @@ -136,18 +136,18 @@ class BaseExport ByteArrayOStreambuf : public std::streambuf { public: explicit ByteArrayOStreambuf(QByteArray& ba); - ~ByteArrayOStreambuf(); + ~ByteArrayOStreambuf() override; protected: - virtual int_type overflow(std::streambuf::int_type v); - virtual std::streamsize xsputn (const char* s, std::streamsize num); - virtual pos_type seekoff(std::streambuf::off_type off, + int_type overflow(std::streambuf::int_type v) override; + std::streamsize xsputn (const char* s, std::streamsize num) override; + pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = - std::ios::in | std::ios::out); - virtual pos_type seekpos(std::streambuf::pos_type sp, + std::ios::in | std::ios::out) override; + pos_type seekpos(std::streambuf::pos_type sp, std::ios_base::openmode which = - std::ios::in | std::ios::out); + std::ios::in | std::ios::out) override; private: ByteArrayOStreambuf(const ByteArrayOStreambuf&); @@ -166,20 +166,20 @@ class BaseExport ByteArrayIStreambuf : public std::streambuf { public: explicit ByteArrayIStreambuf(const QByteArray& buf); - ~ByteArrayIStreambuf(); + ~ByteArrayIStreambuf() override; protected: - virtual int_type uflow(); - virtual int_type underflow(); - virtual int_type pbackfail(int_type ch); - virtual std::streamsize showmanyc(); - virtual pos_type seekoff(std::streambuf::off_type off, + int_type uflow() override; + int_type underflow() override; + int_type pbackfail(int_type ch) override; + std::streamsize showmanyc() override; + pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = - std::ios::in | std::ios::out); - virtual pos_type seekpos(std::streambuf::pos_type pos, + std::ios::in | std::ios::out) override; + pos_type seekpos(std::streambuf::pos_type pos, std::ios_base::openmode which = - std::ios::in | std::ios::out); + std::ios::in | std::ios::out) override; private: ByteArrayIStreambuf(const ByteArrayIStreambuf&); ByteArrayIStreambuf& operator=(const ByteArrayIStreambuf&); @@ -198,18 +198,18 @@ class BaseExport IODeviceOStreambuf : public std::streambuf { public: IODeviceOStreambuf(QIODevice* dev); - ~IODeviceOStreambuf(); + ~IODeviceOStreambuf() override; protected: - virtual int_type overflow(std::streambuf::int_type v); - virtual std::streamsize xsputn (const char* s, std::streamsize num); - virtual pos_type seekoff(std::streambuf::off_type off, + int_type overflow(std::streambuf::int_type v) override; + std::streamsize xsputn (const char* s, std::streamsize num) override; + pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = - std::ios::in | std::ios::out); - virtual pos_type seekpos(std::streambuf::pos_type sp, + std::ios::in | std::ios::out) override; + pos_type seekpos(std::streambuf::pos_type sp, std::ios_base::openmode which = - std::ios::in | std::ios::out); + std::ios::in | std::ios::out) override; private: IODeviceOStreambuf(const IODeviceOStreambuf&); IODeviceOStreambuf& operator=(const IODeviceOStreambuf&); @@ -227,17 +227,17 @@ class BaseExport IODeviceIStreambuf : public std::streambuf { public: IODeviceIStreambuf(QIODevice* dev); - ~IODeviceIStreambuf(); + ~IODeviceIStreambuf() override; protected: - virtual int_type underflow(); - virtual pos_type seekoff(std::streambuf::off_type off, + int_type underflow() override; + pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = - std::ios::in | std::ios::out); - virtual pos_type seekpos(std::streambuf::pos_type sp, + std::ios::in | std::ios::out) override; + pos_type seekpos(std::streambuf::pos_type sp, std::ios_base::openmode which = - std::ios::in | std::ios::out); + std::ios::in | std::ios::out) override; private: IODeviceIStreambuf(const IODeviceIStreambuf&); IODeviceIStreambuf& operator=(const IODeviceIStreambuf&); @@ -269,18 +269,18 @@ public: }; PyStreambuf(PyObject* o, std::size_t buf_size = 256, std::size_t put_back = 8); - virtual ~PyStreambuf(); + ~PyStreambuf() override; void setType(Type t) { type = t; } protected: - int_type underflow(); - int_type overflow(int_type c = EOF); - std::streamsize xsputn (const char* s, std::streamsize num); - int sync(); - pos_type seekoff(off_type offset, seekdir dir, openmode); - pos_type seekpos(pos_type offset, openmode mode); + int_type underflow() override; + int_type overflow(int_type c = EOF) override; + std::streamsize xsputn (const char* s, std::streamsize num) override; + int sync() override; + pos_type seekoff(off_type offset, seekdir dir, openmode) override; + pos_type seekpos(pos_type offset, openmode mode) override; private: bool flushBuffer(); @@ -301,20 +301,20 @@ class BaseExport Streambuf : public std::streambuf { public: explicit Streambuf(const std::string& data); - ~Streambuf(); + ~Streambuf() override; protected: - virtual int_type uflow(); - virtual int_type underflow(); - virtual int_type pbackfail(int_type ch); - virtual std::streamsize showmanyc(); - virtual pos_type seekoff(std::streambuf::off_type off, + int_type uflow() override; + int_type underflow() override; + int_type pbackfail(int_type ch) override; + std::streamsize showmanyc() override; + pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode which = - std::ios::in | std::ios::out); - virtual pos_type seekpos(std::streambuf::pos_type pos, + std::ios::in | std::ios::out) override; + pos_type seekpos(std::streambuf::pos_type pos, std::ios_base::openmode which = - std::ios::in | std::ios::out); + std::ios::in | std::ios::out) override; private: Streambuf(const Streambuf&); @@ -339,17 +339,22 @@ class FileInfo; class ofstream : public std::ofstream { public: + ofstream() = default; ofstream(const FileInfo& fi, ios_base::openmode mode = std::ios::out | std::ios::trunc) #ifdef _MSC_VER - : std::ofstream(fi.toStdWString().c_str(), mode) + : std::ofstream(fi.toStdWString().c_str(), mode) {} #else - : std::ofstream(fi.filePath().c_str(), mode) + : std::ofstream(fi.filePath().c_str(), mode) {} +#endif + ~ofstream() override = default; + void open(const FileInfo& fi, ios_base::openmode mode = + std::ios::out | std::ios::trunc) { +#ifdef _MSC_VER + std::ofstream::open(fi.toStdWString().c_str(), mode); +#else + std::ofstream::open(fi.filePath().c_str(), mode); #endif - { - } - virtual ~ofstream() - { } }; @@ -362,17 +367,22 @@ public: class ifstream : public std::ifstream { public: + ifstream() = default; ifstream(const FileInfo& fi, ios_base::openmode mode = std::ios::in) #ifdef _MSC_VER - : std::ifstream(fi.toStdWString().c_str(), mode) + : std::ifstream(fi.toStdWString().c_str(), mode) {} #else - : std::ifstream(fi.filePath().c_str(), mode) + : std::ifstream(fi.filePath().c_str(), mode) {} +#endif + ~ifstream() override = default; + void open(const FileInfo& fi, ios_base::openmode mode = + std::ios::in) { +#ifdef _MSC_VER + std::ifstream::open(fi.toStdWString().c_str(), mode); +#else + std::ifstream::open(fi.filePath().c_str(), mode); #endif - { - } - virtual ~ifstream() - { } }; diff --git a/src/Base/TimeInfo.cpp b/src/Base/TimeInfo.cpp index f434d9b199..9ea9c49f0a 100644 --- a/src/Base/TimeInfo.cpp +++ b/src/Base/TimeInfo.cpp @@ -50,9 +50,7 @@ TimeInfo::TimeInfo() * A destructor. * A more elaborate description of the destructor. */ -TimeInfo::~TimeInfo() -{ -} +TimeInfo::~TimeInfo() = default; //************************************************************************** diff --git a/src/Base/Tools.h b/src/Base/Tools.h index c5a6826941..cacdd37eaf 100644 --- a/src/Base/Tools.h +++ b/src/Base/Tools.h @@ -236,8 +236,7 @@ class ConnectionBlocker { public: ConnectionBlocker(Connection& c) : blocker(c) { } - ~ConnectionBlocker() { - } + ~ConnectionBlocker() = default; }; // ---------------------------------------------------------------------------- diff --git a/src/Base/Tools2D.h b/src/Base/Tools2D.h index bf937f8632..d7c56fc649 100644 --- a/src/Base/Tools2D.h +++ b/src/Base/Tools2D.h @@ -60,10 +60,10 @@ public: // operators inline Vector2d& operator= (const Vector2d &v); inline bool operator== (const Vector2d &v) const; - inline Vector2d operator+ (void) const; + inline Vector2d operator+ () const; inline Vector2d operator+ (const Vector2d &v) const; inline Vector2d& operator+= (const Vector2d &v); - inline Vector2d operator- (void) const; + inline Vector2d operator- () const; inline Vector2d operator- (const Vector2d &v) const; inline Vector2d& operator-= (const Vector2d &v); inline Vector2d operator* (double c) const; @@ -139,7 +139,7 @@ class BaseExport Line2d public: Vector2d clV1, clV2; - Line2d () {} + Line2d () = default; inline Line2d (const Line2d &rclLine); inline Line2d (const Vector2d &rclV1, const Vector2d &rclV2); @@ -167,9 +167,9 @@ public: class BaseExport Polygon2d { public: - Polygon2d () {} + Polygon2d () = default; inline Polygon2d (const Polygon2d &rclPoly); - virtual ~Polygon2d () {} + virtual ~Polygon2d () = default; inline Polygon2d& operator = (const Polygon2d &rclP); diff --git a/src/Base/Tools3D.cpp b/src/Base/Tools3D.cpp new file mode 100644 index 0000000000..eb2a842a3c --- /dev/null +++ b/src/Base/Tools3D.cpp @@ -0,0 +1,300 @@ +/*************************************************************************** + * Copyright (c) 2022 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 +# include +#endif + +#include "Tools3D.h" +#include "Vector3D.h" + +using namespace Base; + + +template +Line3::Line3(const Line3& line) + : p1(line.p1) + , p2(line.p2) +{ +} + +template +Line3::Line3(Line3&& line) +{ + *this = std::move(line); +} + +template +Line3::Line3(const Vector3& p1, const Vector3& p2) + : p1(p1) + , p2(p2) +{ +} + +template +Line3& Line3::operator= (const Line3& line) +{ + p1 = line.p1; + p2 = line.p2; + return *this; +} + +template +Line3& Line3::operator= (Line3&& line) +{ + p1 = std::move(line.p1); + p2 = std::move(line.p2); + return *this; +} + +template +bool Line3::operator== (const Line3& line) const +{ + return (p1 == line.p1 && p2 == line.p2); +} + +template +double Line3::Length() const +{ + return Base::Distance(p1, p2); +} + +template +double Line3::SqrLength() const +{ + return Base::DistanceP2(p1, p2); +} + +template +BoundBox3 Line3::CalcBoundBox() const +{ + BoundBox3 box; + box.Add(p1); + box.Add(p2); + return box; +} + +template +Vector3 Line3::GetBase() const +{ + return p1; +} + +template +Vector3 Line3::GetDirection() const +{ + return p2 - p1; +} + +template +void Line3::Transform(const Base::Matrix4D& mat) +{ + mat.multVec(p1, p1); + mat.multVec(p2, p2); +} + +template +void Line3::Transform(const Base::Placement& plm) +{ + plm.multVec(p1, p1); + plm.multVec(p2, p2); +} + +template +void Line3::Transform(const Base::Rotation& rot) +{ + rot.multVec(p1, p1); + rot.multVec(p2, p2); +} + +template +Line3 Line3::Transformed(const Base::Matrix4D& mat) const +{ + Line3 line(*this); + line.Transform(mat); + return line; +} + +template +Line3 Line3::Transformed(const Base::Placement& plm) const +{ + Line3 line(*this); + line.Transform(plm); + return line; +} + +template +Line3 Line3::Transformed(const Base::Rotation& rot) const +{ + Line3 line(*this); + line.Transform(rot); + return line; +} + +template +bool Line3::Contains(const Vector3& pt) const +{ + return Contains(pt, Vector3::epsilon()); +} + +template +bool Line3::Contains(const Vector3& pt, float_type eps) const +{ + Vector3 v1 = p1 - pt; + Vector3 v2 = p2 - pt; + Vector3 v3 = p2 - p1; + float_type dot = v1.Dot(v2); + if (dot > eps) + return false; + return v3.Cross(v1).Length() < eps; +} + +template +Vector3 Line3::FromPos(float_type distance) const +{ + Vector3 dir(p2 - p1); + dir.Normalize(); + return p1 + dir * distance; +} + +// ---------------------------------------------------------------------------- + +template +size_t Polygon3::GetSize() const +{ + return points.size(); +} + +template +void Polygon3::Add (const Vector3& p) +{ + points.push_back(p); +} + +template +const Vector3& Polygon3::operator[] (size_t pos) const +{ + return points[pos]; +} + +template +const Vector3& Polygon3::At (size_t pos) const +{ + return points.at(pos); +} + +template +Vector3& Polygon3::operator[] (size_t pos) +{ + return points[pos]; +} + +template +Vector3& Polygon3::At (size_t pos) +{ + return points.at(pos); +} + +template +bool Polygon3::Remove(size_t pos) +{ + if (pos < points.size()) { + auto it = points.begin(); + std::advance(it, pos); + points.erase(it); + return true; + } + + return false; +} + +template +void Polygon3::Clear() +{ + points.clear(); +} + +template +BoundBox3 Polygon3::CalcBoundBox() const +{ + BoundBox3 box; + for (const auto& it : points) + box.Add(it); + return box; +} + +template +void Polygon3::Transform(const Base::Matrix4D& mat) +{ + for (auto& it : points) + mat.multVec(it, it); +} + +template +void Polygon3::Transform(const Base::Placement& plm) +{ + for (auto& it : points) + plm.multVec(it, it); +} + +template +void Polygon3::Transform(const Base::Rotation& rot) +{ + for (auto& it : points) + rot.multVec(it, it); +} + +template +Polygon3 Polygon3::Transformed(const Base::Matrix4D& mat) const +{ + Polygon3 poly(*this); + poly.Transform(mat); + return poly; +} + +template +Polygon3 Polygon3::Transformed(const Base::Placement& plm) const +{ + Polygon3 poly(*this); + poly.Transform(plm); + return poly; +} + +template +Polygon3 Polygon3::Transformed(const Base::Rotation& rot) const +{ + Polygon3 poly(*this); + poly.Transform(rot); + return poly; +} + +// explicit template instantiation +namespace Base { +template class BaseExport Line3; +template class BaseExport Line3; +template class BaseExport Polygon3; +template class BaseExport Polygon3; +} diff --git a/src/Base/Tools3D.h b/src/Base/Tools3D.h new file mode 100644 index 0000000000..cc9a891d05 --- /dev/null +++ b/src/Base/Tools3D.h @@ -0,0 +1,147 @@ +/*************************************************************************** + * Copyright (c) 2022 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 * + * * + ***************************************************************************/ + + +#ifndef BASE_TOOLS3D_H +#define BASE_TOOLS3D_H + + +#include +#include +#include +#include +#include +#include + +#include +#include +#ifndef FC_GLOBAL_H +#include +#endif + +namespace Base { + +class Vector2d; +class BoundBox2d; +class Line2d; +class Polygon2d; + +/** Line3 ********************************************/ + +/** + * 3D line class. + */ +template +class Line3 +{ +public: + Vector3 p1, p2; + + Line3() = default; + ~Line3() = default; + Line3(const Line3& line); + Line3(Line3&& line); + Line3(const Vector3& p1, const Vector3& p2); + + // operators + Line3& operator= (const Line3& line); + Line3& operator= (Line3&& line); + bool operator== (const Line3& line) const; + + // methods + double Length () const; + double SqrLength () const; + BoundBox3 CalcBoundBox() const; + Vector3 GetBase() const; + Vector3 GetDirection() const; + void Transform(const Base::Matrix4D&); + void Transform(const Base::Placement&); + void Transform(const Base::Rotation&); + Line3 Transformed(const Base::Matrix4D&) const; + Line3 Transformed(const Base::Placement&) const; + Line3 Transformed(const Base::Rotation&) const; + + /*! + * \brief Contains + * Checks if the point \a p is part of the line segment. + * \param p + * \return + */ + bool Contains(const Vector3& p) const; + /*! + * \brief Contains + * Checks if the distance of point \a p to the line segment is + * less than \a eps + * \param p + * \param eps + * \return + */ + bool Contains(const Vector3& p, float_type eps) const; + Vector3 FromPos (float_type distance) const; +}; + +/** Polygon3 ********************************************/ + +/** + * 3D polygon class. + */ +template +class Polygon3 +{ +public: + Polygon3() = default; + ~Polygon3() = default; + Polygon3(const Polygon3& poly) = default; + + Polygon3& operator = (const Polygon3& poly) = default; + + size_t GetSize() const; + void Add (const Vector3& p); + const Vector3& operator[] (size_t pos) const; + const Vector3& At (size_t pos) const; + Vector3& operator[] (size_t pos); + Vector3& At (size_t pos); + bool Remove(size_t pos); + void Clear(); + + // misc + BoundBox3 CalcBoundBox() const; + void Transform(const Base::Matrix4D&); + void Transform(const Base::Placement&); + void Transform(const Base::Rotation&); + Polygon3 Transformed(const Base::Matrix4D&) const; + Polygon3 Transformed(const Base::Placement&) const; + Polygon3 Transformed(const Base::Rotation&) const; + +private: + std::vector> points; +}; + +using Line3f = Line3; +using Line3d = Line3; + +using Polygon3f = Polygon3; +using Polygon3d = Polygon3; + +} // namespace Base + +#endif // BASE_TOOLS3D_H diff --git a/src/Base/Translate.cpp b/src/Base/Translate.cpp index 0b95e2e204..9385257552 100644 --- a/src/Base/Translate.cpp +++ b/src/Base/Translate.cpp @@ -72,10 +72,7 @@ Translate::Translate() initialize("This module is the Translate module"); // register with Python } -Translate::~Translate() -{ - -} +Translate::~Translate() = default; Py::Object Translate::translate(const Py::Tuple& args) { diff --git a/src/Base/Translate.h b/src/Base/Translate.h index bb73095db8..4995689e01 100644 --- a/src/Base/Translate.h +++ b/src/Base/Translate.h @@ -40,7 +40,7 @@ class BaseExport Translate : public Py::ExtensionModule { public: Translate(); - virtual ~Translate(); + ~Translate() override; private: Py::Object translate(const Py::Tuple& args); diff --git a/src/Base/Type.cpp b/src/Base/Type.cpp index ef410857f9..f4c754b151 100644 --- a/src/Base/Type.cpp +++ b/src/Base/Type.cpp @@ -78,9 +78,7 @@ Type::Type(const Type& type) * A destructor. * A more elaborate description of the destructor. */ -Type::~Type() -{ -} +Type::~Type() = default; void *Type::createInstance() { diff --git a/src/Base/TypePyImp.cpp b/src/Base/TypePyImp.cpp index 8d335392c4..2134d077a8 100644 --- a/src/Base/TypePyImp.cpp +++ b/src/Base/TypePyImp.cpp @@ -32,7 +32,7 @@ using namespace Base; // returns a string which represent the object e.g. when printed in python -std::string TypePy::representation(void) const +std::string TypePy::representation() const { std::stringstream str; str << "getName() << "'>"; @@ -243,17 +243,17 @@ PyObject* TypePy::createInstanceByName (PyObject *args) return createPyObject(base); } -Py::String TypePy::getName(void) const +Py::String TypePy::getName() const { return Py::String(std::string(getBaseTypePtr()->getName())); } -Py::Long TypePy::getKey(void) const +Py::Long TypePy::getKey() const { return Py::Long(static_cast(getBaseTypePtr()->getKey())); } -Py::String TypePy::getModule(void) const +Py::String TypePy::getModule() const { std::string module(getBaseTypePtr()->getName()); std::string::size_type pos = module.find_first_of("::"); diff --git a/src/Base/Unit.h b/src/Base/Unit.h index 162772e1d7..50a51b8c32 100644 --- a/src/Base/Unit.h +++ b/src/Base/Unit.h @@ -64,7 +64,7 @@ public: Unit(const Unit&); explicit Unit(const QString& expr); /// Destruction - ~Unit () {} + ~Unit () = default; /** Operators. */ @@ -131,7 +131,7 @@ public: static Unit YoungsModulus; static Unit Stiffness; - + static Unit Force; static Unit Work; static Unit Power; diff --git a/src/Base/UnitPy.xml b/src/Base/UnitPy.xml index 484a9060a0..09ac932889 100644 --- a/src/Base/UnitPy.xml +++ b/src/Base/UnitPy.xml @@ -1,21 +1,21 @@ - - - - + + + + Unit defines a unit type, calculate and compare. @@ -26,14 +26,14 @@ Unit(Unit) -- copy constructor Unit(string) -- parse the string for units - Unit - - - - holds the unit type as a string, e.g. 'Area'. - - - + Unit + + + + holds the unit type as a string, e.g. 'Area'. + + + Returns the signature. diff --git a/src/Base/UnitsSchema.h b/src/Base/UnitsSchema.h index 020b323eac..112e82bb87 100644 --- a/src/Base/UnitsSchema.h +++ b/src/Base/UnitsSchema.h @@ -52,7 +52,7 @@ enum class UnitSystem { class UnitsSchema { public: - virtual ~UnitsSchema(){} + 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). diff --git a/src/Base/UnitsSchemaCentimeters.h b/src/Base/UnitsSchemaCentimeters.h index 415483b5e0..ea6ab8e043 100644 --- a/src/Base/UnitsSchemaCentimeters.h +++ b/src/Base/UnitsSchemaCentimeters.h @@ -36,7 +36,7 @@ namespace Base { class UnitsSchemaCentimeters: public UnitsSchema { public: - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; } // namespace Base diff --git a/src/Base/UnitsSchemaFemMilliMeterNewton.h b/src/Base/UnitsSchemaFemMilliMeterNewton.h index 677818c53d..c58de4b8e8 100644 --- a/src/Base/UnitsSchemaFemMilliMeterNewton.h +++ b/src/Base/UnitsSchemaFemMilliMeterNewton.h @@ -41,7 +41,7 @@ namespace Base { class UnitsSchemaFemMilliMeterNewton: public UnitsSchema { public: - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; diff --git a/src/Base/UnitsSchemaImperial1.h b/src/Base/UnitsSchemaImperial1.h index 90eccf7e81..35758f9360 100644 --- a/src/Base/UnitsSchemaImperial1.h +++ b/src/Base/UnitsSchemaImperial1.h @@ -40,7 +40,7 @@ class UnitsSchemaImperial1: public UnitsSchema public: //virtual void setSchemaUnits(void); //virtual void resetSchemaUnits(void); - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; /** The schema class for the imperial unit system @@ -52,7 +52,7 @@ class UnitsSchemaImperialDecimal: public UnitsSchema public: //virtual void setSchemaUnits(void); //virtual void resetSchemaUnits(void); - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; /** The schema class for the imperial unit system @@ -64,7 +64,7 @@ class UnitsSchemaImperialBuilding: public UnitsSchema public: //virtual void setSchemaUnits(void); //virtual void resetSchemaUnits(void); - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; /** The schema class for Civil Engineering in the imperial unit system @@ -76,7 +76,7 @@ class UnitsSchemaImperialCivil: public UnitsSchema public: //virtual void setSchemaUnits(void); //virtual void resetSchemaUnits(void); - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; diff --git a/src/Base/UnitsSchemaInternal.cpp b/src/Base/UnitsSchemaInternal.cpp index b878072f51..a5f9046fcf 100644 --- a/src/Base/UnitsSchemaInternal.cpp +++ b/src/Base/UnitsSchemaInternal.cpp @@ -29,6 +29,7 @@ #include #include "UnitsSchemaInternal.h" +#include using namespace Base; @@ -232,7 +233,6 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact else { unitString = QString::fromLatin1("MN/m"); factor = 1e6; - } } else if (unit == Unit::Force) { @@ -435,6 +435,10 @@ QString UnitsSchemaInternal::schemaTranslate(const Quantity &quant, double &fact factor = 1e6; } } + else if (unit == Unit::VacuumPermittivity) { + unitString = QString::fromLatin1("F/m"); + factor = 1e-9; + } else if (unit == Unit::Frequency) { if (UnitValue < 1e3) { unitString = QString::fromLatin1("Hz"); diff --git a/src/Base/UnitsSchemaInternal.h b/src/Base/UnitsSchemaInternal.h index 2234de20a6..c555e58b8e 100644 --- a/src/Base/UnitsSchemaInternal.h +++ b/src/Base/UnitsSchemaInternal.h @@ -39,7 +39,7 @@ namespace Base { class UnitsSchemaInternal: public UnitsSchema { public: - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; diff --git a/src/Base/UnitsSchemaMKS.cpp b/src/Base/UnitsSchemaMKS.cpp index 7e51015fed..8619816ae0 100644 --- a/src/Base/UnitsSchemaMKS.cpp +++ b/src/Base/UnitsSchemaMKS.cpp @@ -29,6 +29,7 @@ #include #include "UnitsSchemaMKS.h" +#include using namespace Base; @@ -184,7 +185,6 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q else { unitString = QString::fromLatin1("MN/m"); factor = 1e6; - } } else if (unit == Unit::ThermalConductivity) { @@ -383,6 +383,10 @@ QString UnitsSchemaMKS::schemaTranslate(const Quantity &quant, double &factor, Q factor = 1e6; } } + else if (unit == Unit::VacuumPermittivity) { + unitString = QString::fromLatin1("F/m"); + factor = 1e-9; + } else if (unit == Unit::Work) { if (UnitValue < 1.602176634e-10) { unitString = QString::fromLatin1("eV"); diff --git a/src/Base/UnitsSchemaMKS.h b/src/Base/UnitsSchemaMKS.h index 87b88c5937..e36036de81 100644 --- a/src/Base/UnitsSchemaMKS.h +++ b/src/Base/UnitsSchemaMKS.h @@ -37,7 +37,7 @@ namespace Base { class UnitsSchemaMKS: public UnitsSchema { public: - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; diff --git a/src/Base/UnitsSchemaMmMin.h b/src/Base/UnitsSchemaMmMin.h index 9974aee4f7..c2c9901bc9 100644 --- a/src/Base/UnitsSchemaMmMin.h +++ b/src/Base/UnitsSchemaMmMin.h @@ -39,7 +39,7 @@ namespace Base { class UnitsSchemaMmMin: public UnitsSchema { public: - virtual QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString); + QString schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) override; }; diff --git a/src/Base/Uuid.cpp b/src/Base/Uuid.cpp index 4968b6a328..1a800cb53f 100644 --- a/src/Base/Uuid.cpp +++ b/src/Base/Uuid.cpp @@ -51,9 +51,7 @@ Uuid::Uuid() * A destructor. * A more elaborate description of the destructor. */ -Uuid::~Uuid() -{ -} +Uuid::~Uuid() = default; //************************************************************************** //************************************************************************** diff --git a/src/Base/VectorPy.xml b/src/Base/VectorPy.xml index aed8f3c2c9..bf0bbbfa54 100644 --- a/src/Base/VectorPy.xml +++ b/src/Base/VectorPy.xml @@ -1,22 +1,22 @@ - - - - This is the Vector export class - Base.Vector class.\n + + + + This is the Vector export class + Base.Vector class.\n This class represents a 3D float vector. Useful to represent points in the 3D space.\n The following constructors are supported:\n @@ -30,7 +30,7 @@ vector : Base.Vector\n Vector(seq) Define from a sequence of float. seq : sequence of float. - + __reduce__() -> tuple\n @@ -38,77 +38,77 @@ Serialization of Vector objects. - - add(vector2) -> Base.Vector\n + + add(vector2) -> Base.Vector\n Returns the sum of this vector and `vector2`.\n vector2 : Base.Vector - - - - - sub(vector2) -> Base.Vector\n + + + + + sub(vector2) -> Base.Vector\n Returns the difference of this vector and `vector2`.\n vector2 : Base.Vector - - + + - - negative() -> Base.Vector\n + + negative() -> Base.Vector\n Returns the negative (opposite) of this vector. - - - - - scale(x, y, z) -> Base.Vector\n + + + + + scale(x, y, z) -> Base.Vector\n Scales in-place this vector by the given factor in each component.\n x : float\n x-component factor scale. y : float\n y-component factor scale. z : float\n z-component factor scale. - - - - - multiply(factor) -> Base.Vector\n + + + + + multiply(factor) -> Base.Vector\n Multiplies in-place each component of this vector by a single factor. Equivalent to scale(factor, factor, factor).\n factor : float - - - - - dot(vector2) -> float\n + + + + + dot(vector2) -> float\n Returns the scalar product (dot product) between this vector and `vector2`.\n vector2 : Base.Vector - - - - - cross(vector2) -> Base.Vector\n + + + + + cross(vector2) -> Base.Vector\n Returns the vector product (cross product) between this vector and `vector2`.\n vector2 : Base.Vector - - - - - isOnLineSegment(vector1, vector2) -> bool\n + + + + + isOnLineSegment(vector1, vector2) -> bool\n Checks if this vector is on the line segment generated by `vector1` and `vector2`.\n vector1 : Base.Vector vector2 : Base.Vector - - - - - getAngle(vector2) -> float\n + + + + + getAngle(vector2) -> float\n Returns the angle in radians between this vector and `vector2`.\n vector2 : Base.Vector - - - - - normalize() -> Base.Vector\n + + + + + normalize() -> Base.Vector\n Normalizes in-place this vector to the length of 1.0. - - + + isEqual(vector2, tol=0) -> bool\n @@ -119,8 +119,8 @@ tol : float - - projectToLine(point, dir) -> Base.Vector\n + + projectToLine(point, dir) -> Base.Vector\n Projects `point` on a line that goes through the origin with the direction `dir`. The result is the vector from `point` to the projected point. The operation is equivalent to dir_n.cross(dir_n.cross(point)), where `dir_n` is @@ -129,96 +129,96 @@ The method modifies this vector instance according to result and does not depend on the vector itself.\n point : Base.Vector dir : Base.Vector - - - - - projectToPlane(base, normal) -> Base.Vector\n + + + + + projectToPlane(base, normal) -> Base.Vector\n Projects in-place this vector on a plane defined by a base point represented by `base` and a normal defined by `normal`.\n base : Base.Vector normal : Base.Vector - - - - - distanceToPoint(point2) -> float\n + + + + + distanceToPoint(point2) -> float\n Returns the distance to another point represented by `point2`.\n. point : Base.Vector - - - - - distanceToLine(base, dir) -> float\n + + + + + distanceToLine(base, dir) -> float\n Returns the distance between the point represented by this vector and a line defined by a base point represented by `base` and a direction `dir`.\n base : Base.Vector dir : Base.Vector - - - - - distanceToLineSegment(point1, point2) -> Base.Vector\n + + + + + distanceToLineSegment(point1, point2) -> Base.Vector\n Returns the vector between the point represented by this vector and the point on the line segment with the shortest distance. The line segment is defined by `point1` and `point2`.\n point1 : Base.Vector point2 : Base.Vector - - - - - distanceToPlane(base, normal) -> float\n + + + + + distanceToPlane(base, normal) -> float\n Returns the distance between this vector and a plane defined by a base point represented by `base` and a normal defined by `normal`.\n base : Base.Vector normal : Base.Vector - - - - - Gets or sets the length of this vector. - - - - - - Gets or sets the X component of this vector. - - - - - - Gets or sets the Y component of this vector. - - - - - - Gets or sets the Z component of this vector. - - - - - - public: + + + + + Gets or sets the length of this vector. + + + + + + Gets or sets the X component of this vector. + + + + + + Gets or sets the Y component of this vector. + + + + + + Gets or sets the Z component of this vector. + + + + + + public: VectorPy(const Vector3d & vec, PyTypeObject *T = &Type) :PyObjectBase(new Vector3d(vec),T){} VectorPy(const Vector3f & vec, PyTypeObject *T = &Type) :PyObjectBase(new Vector3d(vec.x,vec.y,vec.z),T){} Vector3d value() const { return *(getVectorPtr()); } - - + + diff --git a/src/Base/ViewProj.h b/src/Base/ViewProj.h index 36891f435c..cc78cd2054 100644 --- a/src/Base/ViewProj.h +++ b/src/Base/ViewProj.h @@ -78,12 +78,12 @@ class BaseExport ViewProjMatrix : public ViewProjMethod public: ViewProjMatrix (const Matrix4D &rclMtx); - Vector3f operator()(const Vector3f &rclPt) const; - Vector3d operator()(const Vector3d &rclPt) const; - Vector3f inverse (const Vector3f &rclPt) const; - Vector3d inverse (const Vector3d &rclPt) const; + Vector3f operator()(const Vector3f &rclPt) const override; + Vector3d operator()(const Vector3d &rclPt) const override; + Vector3f inverse (const Vector3f &rclPt) const override; + Vector3d inverse (const Vector3d &rclPt) const override; - Matrix4D getProjectionMatrix () const; + Matrix4D getProjectionMatrix () const override; protected: bool isOrthographic; @@ -101,12 +101,12 @@ class BaseExport ViewOrthoProjMatrix : public ViewProjMethod public: ViewOrthoProjMatrix (const Matrix4D &rclMtx); - Vector3f operator()(const Vector3f &rclPt) const; - Vector3d operator()(const Vector3d &rclPt) const; - Vector3f inverse (const Vector3f &rclPt) const; - Vector3d inverse (const Vector3d &rclPt) const; + Vector3f operator()(const Vector3f &rclPt) const override; + Vector3d operator()(const Vector3d &rclPt) const override; + Vector3f inverse (const Vector3f &rclPt) const override; + Vector3d inverse (const Vector3d &rclPt) const override; - Matrix4D getProjectionMatrix () const; + Matrix4D getProjectionMatrix () const override; protected: Matrix4D _clMtx, _clMtxInv; diff --git a/src/Base/Writer.cpp b/src/Base/Writer.cpp index f90b68c108..c93ec383bc 100644 --- a/src/Base/Writer.cpp +++ b/src/Base/Writer.cpp @@ -53,9 +53,7 @@ Writer::Writer() indBuf[0] = '\0'; } -Writer::~Writer() -{ -} +Writer::~Writer() = default; void Writer::insertAsciiFile(const char* FileName) { @@ -286,9 +284,7 @@ FileWriter::FileWriter(const char* DirName) : DirName(DirName) { } -FileWriter::~FileWriter() -{ -} +FileWriter::~FileWriter() = default; void FileWriter::putNextEntry(const char* file) { diff --git a/src/Base/Writer.h b/src/Base/Writer.h index b280c7804d..24771cf123 100644 --- a/src/Base/Writer.h +++ b/src/Base/Writer.h @@ -152,11 +152,11 @@ class BaseExport ZipWriter : public Writer public: ZipWriter(const char* FileName); ZipWriter(std::ostream&); - virtual ~ZipWriter(); + ~ZipWriter() override; - virtual void writeFiles(); + void writeFiles() override; - virtual std::ostream &Stream(){return ZipStream;} + std::ostream &Stream() override{return ZipStream;} void setComment(const char* str){ZipStream.setComment(str);} void setLevel(int level){ZipStream.setLevel( level );} @@ -176,9 +176,9 @@ class BaseExport StringWriter : public Writer { public: - virtual std::ostream &Stream(){return StrStream;} + std::ostream &Stream() override{return StrStream;} std::string getString() const {return StrStream.str();} - virtual void writeFiles(){} + void writeFiles() override{} private: std::stringstream StrStream; @@ -193,12 +193,12 @@ class BaseExport FileWriter : public Writer { public: FileWriter(const char* DirName); - virtual ~FileWriter(); + ~FileWriter() override; void putNextEntry(const char* file); - virtual void writeFiles(); + void writeFiles() override; - virtual std::ostream &Stream(){return FileStream;} + std::ostream &Stream() override{return FileStream;} void close() {FileStream.close();} /*! This method can be re-implemented in sub-classes to avoid diff --git a/src/Base/XMLTools.h b/src/Base/XMLTools.h index 9660379685..d0dc66c876 100644 --- a/src/Base/XMLTools.h +++ b/src/Base/XMLTools.h @@ -198,9 +198,7 @@ inline XUTF8Str::XUTF8Str(const char* const fromTranscode) str = XMLTools::toXMLString(fromTranscode); } -inline XUTF8Str::~XUTF8Str() -{ -} +inline XUTF8Str::~XUTF8Str() = default; // ----------------------------------------------------------------------- diff --git a/src/Base/fdstream.hpp b/src/Base/fdstream.hpp index 2deef38d24..bf6f6d29b4 100644 --- a/src/Base/fdstream.hpp +++ b/src/Base/fdstream.hpp @@ -62,7 +62,7 @@ class fdoutbuf : public std::streambuf { } protected: // write one character - virtual int_type overflow (int_type c) { + int_type overflow (int_type c) override { if (c != EOF) { char z = c; #ifdef _MSC_VER @@ -76,9 +76,9 @@ class fdoutbuf : public std::streambuf { return c; } // write multiple characters - virtual + std::streamsize xsputn (const char* s, - std::streamsize num) { + std::streamsize num) override { #ifdef _MSC_VER return _write(fd,s,num); #else @@ -129,7 +129,7 @@ class fdinbuf : public std::streambuf { protected: // insert new characters into the buffer - virtual int_type underflow () { + int_type underflow () override { #ifndef _MSC_VER using std::memcpy; #endif diff --git a/src/Base/gzstream.cpp b/src/Base/gzstream.cpp index 3236c124ed..85f7e3fdd2 100644 --- a/src/Base/gzstream.cpp +++ b/src/Base/gzstream.cpp @@ -67,7 +67,7 @@ gzstreambuf* gzstreambuf::open( const char* name, int open_mode, int comp) *fmodeptr++ = 'b'; *fmodeptr = '\0'; file = gzopen( name, fmode); - if (file == nullptr) + if (!file) return (gzstreambuf*)nullptr; opened = 1; return this; diff --git a/src/Base/gzstream.h b/src/Base/gzstream.h index 7a098d8bf6..4f6222a54a 100644 --- a/src/Base/gzstream.h +++ b/src/Base/gzstream.h @@ -18,11 +18,11 @@ // ============================================================================ // // File : gzstream.h -// Revision : Revision: 1.5 +// Revision : Revision: 1.5 // Revision_date : Date: 2002/04/26 23:30:15 // Author(s) : Deepak Bandyopadhyay, Lutz Kettner -// -// Standard streambuf implementation following Nicolai Josuttis, "The +// +// Standard streambuf implementation following Nicolai Josuttis, "The // Standard C++ Library". // ============================================================================ @@ -31,6 +31,7 @@ #include #include +#include #ifdef _MSC_VER using std::ostream; @@ -71,11 +72,11 @@ public: int is_open() { return opened; } gzstreambuf* open( const char* name, int open_mode, int comp); gzstreambuf* close(); - ~gzstreambuf() { close(); } + ~gzstreambuf() override { close(); } - virtual int overflow( int c = EOF); - virtual int underflow(); - virtual int sync(); + int overflow( int c = EOF) override; + int underflow() override; + int sync() override; }; class BaseExport gzstreambase : virtual public std::ios { @@ -84,7 +85,7 @@ protected: public: gzstreambase() { init(&buf); } gzstreambase( const char* name, int open_mode, int comp); - ~gzstreambase(); + ~gzstreambase() override; void open( const char* name, int open_mode, int comp); void close(); gzstreambuf* rdbuf() { return &buf; } diff --git a/src/Base/swigpyrun.inl b/src/Base/swigpyrun.inl index 172198820d..42f9308b85 100644 --- a/src/Base/swigpyrun.inl +++ b/src/Base/swigpyrun.inl @@ -35,8 +35,8 @@ int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int throw Base::RuntimeError(str.str()); } - *ptr = SWIG_NewPointerObj(obj,swig_type,own); - if (*ptr == nullptr) + *ptr = SWIG_NewPointerObj(obj, swig_type, own); + if (!*ptr) throw Base::RuntimeError("Cannot convert into requested type"); // success @@ -77,13 +77,13 @@ void cleanupSWIG_T(const char* TypeName) PyObject *module, *dict; PyObject *modules = PyImport_GetModuleDict(); module = PyDict_GetItemString(modules, "__builtin__"); - if (module != nullptr && PyModule_Check(module)) { + if (module && PyModule_Check(module)) { dict = PyModule_GetDict(module); PyDict_SetItemString(dict, "_", Py_None); } module = PyDict_GetItemString(modules, "__main__"); - if (module != nullptr && PyModule_Check(module)) { + if (module && PyModule_Check(module)) { PyObject* dict = PyModule_GetDict(module); if (!dict) return; diff --git a/src/CXX/Config.hxx b/src/CXX/Config.hxx index 536e7c8820..2b728acafc 100644 --- a/src/CXX/Config.hxx +++ b/src/CXX/Config.hxx @@ -36,6 +36,13 @@ //----------------------------------------------------------------------------- #include "CXX/WrapPython.h" +#if defined( PYCXX_6_2_COMPATIBILITY ) + //typedef int PyCxx_ssize_t; + typedef Py_ssize_t PyCxx_ssize_t; +#else + typedef Py_ssize_t PyCxx_ssize_t; +#endif + #if PY_MAJOR_VERSION == 2 #include "CXX/Python2/Config.hxx" #else diff --git a/src/CXX/CxxDebug.hxx b/src/CXX/CxxDebug.hxx new file mode 100644 index 0000000000..508395f7a2 --- /dev/null +++ b/src/CXX/CxxDebug.hxx @@ -0,0 +1,41 @@ +//----------------------------------------------------------------------------- +// +// Copyright (c) 1998 - 2007, The Regents of the University of California +// Produced at the Lawrence Livermore National Laboratory +// All rights reserved. +// +// This file is part of PyCXX. For details,see http://cxx.sourceforge.net/. The +// full copyright notice is contained in the file COPYRIGHT located at the root +// of the PyCXX distribution. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// - Redistributions of source code must retain the above copyright notice, +// this list of conditions and the disclaimer below. +// - Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the disclaimer (as noted below) in the +// documentation and/or materials provided with the distribution. +// - Neither the name of the UC/LLNL nor the names of its contributors may be +// used to endorse or promote products derived from this software without +// specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OF THE UNIVERSITY OF +// CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +// DAMAGE. +// +//----------------------------------------------------------------------------- +#if PY_MAJOR_VERSION == 2 +#include "CXX/Python2/CxxDebug.hxx" +#else +#include "CXX/Python3/CxxDebug.hxx" +#endif diff --git a/src/CXX/IndirectPythonInterface.cxx b/src/CXX/IndirectPythonInterface.cxx index f6931f422b..3d810cea88 100644 --- a/src/CXX/IndirectPythonInterface.cxx +++ b/src/CXX/IndirectPythonInterface.cxx @@ -39,88 +39,72 @@ namespace Py { -PYCXX_EXPORT bool _CFunction_Check( PyObject *op ) { return op->ob_type == _CFunction_Type(); } -PYCXX_EXPORT bool _Complex_Check( PyObject *op ) { return op->ob_type == _Complex_Type(); } -PYCXX_EXPORT bool _Dict_Check( PyObject *op ) { return op->ob_type == _Dict_Type(); } -PYCXX_EXPORT bool _Float_Check( PyObject *op ) { return op->ob_type == _Float_Type(); } -PYCXX_EXPORT bool _Function_Check( PyObject *op ) { return op->ob_type == _Function_Type(); } -PYCXX_EXPORT bool _Boolean_Check( PyObject *op ) { return op->ob_type == _Bool_Type(); } -PYCXX_EXPORT bool _List_Check( PyObject *op ) { return op->ob_type == _List_Type(); } -PYCXX_EXPORT bool _Long_Check( PyObject *op ) { return op->ob_type == _Long_Type(); } -PYCXX_EXPORT bool _Method_Check( PyObject *op ) { return op->ob_type == _Method_Type(); } -PYCXX_EXPORT bool _Module_Check( PyObject *op ) { return op->ob_type == _Module_Type(); } -PYCXX_EXPORT bool _Range_Check( PyObject *op ) { return op->ob_type == _Range_Type(); } -PYCXX_EXPORT bool _Slice_Check( PyObject *op ) { return op->ob_type == _Slice_Type(); } -PYCXX_EXPORT bool _TraceBack_Check( PyObject *op ) { return op->ob_type == _TraceBack_Type(); } -PYCXX_EXPORT bool _Tuple_Check( PyObject *op ) { return op->ob_type == _Tuple_Type(); } -PYCXX_EXPORT bool _Type_Check( PyObject *op ) { return op->ob_type == _Type_Type(); } -PYCXX_EXPORT bool _Unicode_Check( PyObject *op ) { return op->ob_type == _Unicode_Type(); } +static int _IsInstance( PyObject *op, PyTypeObject *type ) +{ + return PyObject_IsInstance( op, reinterpret_cast( type ) ); +} + +PYCXX_EXPORT bool _CFunction_Check( PyObject *op ) { return _IsInstance( op, _CFunction_Type() ) > 0; } +PYCXX_EXPORT bool _Complex_Check( PyObject *op ) { return _IsInstance( op, _Complex_Type() ) > 0; } +PYCXX_EXPORT bool _Dict_Check( PyObject *op ) { return _IsInstance( op, _Dict_Type() ) > 0; } +PYCXX_EXPORT bool _Float_Check( PyObject *op ) { return _IsInstance( op, _Float_Type() ) > 0; } +#if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) +PYCXX_EXPORT bool _Function_Check( PyObject *op ) { return _IsInstance( op, _Function_Type() ) > 0; } +#endif +PYCXX_EXPORT bool _Boolean_Check( PyObject *op ) { return _IsInstance( op, _Bool_Type() ) > 0; } +PYCXX_EXPORT bool _List_Check( PyObject *op ) { return _IsInstance( op, _List_Type() ) > 0; } +PYCXX_EXPORT bool _Long_Check( PyObject *op ) { return _IsInstance( op, _Long_Type() ) > 0; } +#if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) +PYCXX_EXPORT bool _Method_Check( PyObject *op ) { return _IsInstance( op, _Method_Type() ) > 0; } +#endif +PYCXX_EXPORT bool _Module_Check( PyObject *op ) { return _IsInstance( op, _Module_Type() ) > 0; } +PYCXX_EXPORT bool _Range_Check( PyObject *op ) { return _IsInstance( op, _Range_Type() ) > 0; } +PYCXX_EXPORT bool _Slice_Check( PyObject *op ) { return _IsInstance( op, _Slice_Type() ) > 0; } +PYCXX_EXPORT bool _TraceBack_Check( PyObject *op ) { return _IsInstance( op, _TraceBack_Type() ) > 0; } +PYCXX_EXPORT bool _Tuple_Check( PyObject *op ) { return _IsInstance( op, _Tuple_Type() ) > 0; } +PYCXX_EXPORT bool _Type_Check( PyObject *op ) { return _IsInstance( op, _Type_Type() ) > 0; } +PYCXX_EXPORT bool _Unicode_Check( PyObject *op ) { return _IsInstance( op, _Unicode_Type() ) > 0; } #if PY_MAJOR_VERSION == 2 -PYCXX_EXPORT bool _String_Check( PyObject *op ) { return op->ob_type == _String_Type(); } -PYCXX_EXPORT bool _Int_Check( PyObject *op ) { return op->ob_type == _Int_Type(); } -PYCXX_EXPORT bool _CObject_Check( PyObject *op ) { return op->ob_type == _CObject_Type(); } +PYCXX_EXPORT bool _String_Check( PyObject *op ) { return _IsInstance( op, _String_Type() ) > 0; } +PYCXX_EXPORT bool _Int_Check( PyObject *op ) { return _IsInstance( op, _Int_Type() ) > 0; } +PYCXX_EXPORT bool _CObject_Check( PyObject *op ) { return _IsInstance( op, _CObject_Type() ) > 0; } #endif #if PY_MAJOR_VERSION >= 3 -PYCXX_EXPORT bool _Bytes_Check( PyObject *op ) { return op->ob_type == _Bytes_Type(); } +PYCXX_EXPORT bool _Bytes_Check( PyObject *op ) { return _IsInstance( op, _Bytes_Type() ) > 0; } #endif #if defined(PY_WIN32_DELAYLOAD_PYTHON_DLL) -#if defined(MS_WINDOWS) -#include +# if defined(MS_WINDOWS) +# include static HMODULE python_dll; -static PyObject *ptr__Exc_ArithmeticError = NULL; -static PyObject *ptr__Exc_AssertionError = NULL; -static PyObject *ptr__Exc_AttributeError = NULL; -static PyObject *ptr__Exc_EnvironmentError = NULL; -static PyObject *ptr__Exc_EOFError = NULL; -static PyObject *ptr__Exc_Exception = NULL; -static PyObject *ptr__Exc_FloatingPointError = NULL; -static PyObject *ptr__Exc_ImportError = NULL; -static PyObject *ptr__Exc_IndexError = NULL; -static PyObject *ptr__Exc_IOError = NULL; -static PyObject *ptr__Exc_KeyboardInterrupt = NULL; -static PyObject *ptr__Exc_KeyError = NULL; -static PyObject *ptr__Exc_LookupError = NULL; -static PyObject *ptr__Exc_MemoryError = NULL; -static PyObject *ptr__Exc_NameError = NULL; -static PyObject *ptr__Exc_NotImplementedError = NULL; -static PyObject *ptr__Exc_OSError = NULL; -static PyObject *ptr__Exc_OverflowError = NULL; -static PyObject *ptr__Exc_RuntimeError = NULL; -#if PY_MAJOR_VERSION == 2 -static PyObject *ptr__Exc_StandardError = NULL; -#endif -static PyObject *ptr__Exc_SyntaxError = NULL; -static PyObject *ptr__Exc_SystemError = NULL; -static PyObject *ptr__Exc_SystemExit = NULL; -static PyObject *ptr__Exc_TypeError = NULL; -static PyObject *ptr__Exc_ValueError = NULL; -static PyObject *ptr__Exc_ZeroDivisionError = NULL; +# define PYCXX_STANDARD_EXCEPTION( eclass, bclass ) \ + static PyObject *ptr_Exc_##eclass = NULL; -#ifdef MS_WINDOWS -static PyObject *ptr__Exc_WindowsError = NULL; -#endif +# if PY_MAJOR_VERSION == 2 +# include "CXX/Python2/cxx_standard_exceptions.hxx" +# else +# include "CXX/Python3/cxx_standard_exceptions.hxx" +# endif + +# undef PYCXX_STANDARD_EXCEPTION -static PyObject *ptr__Exc_IndentationError = NULL; -static PyObject *ptr__Exc_TabError = NULL; -static PyObject *ptr__Exc_UnboundLocalError = NULL; -static PyObject *ptr__Exc_UnicodeError = NULL; -static PyObject *ptr__PyNone = NULL; -static PyObject *ptr__PyFalse = NULL; -static PyObject *ptr__PyTrue = NULL; static PyTypeObject *ptr__CFunction_Type = NULL; static PyTypeObject *ptr__Complex_Type = NULL; static PyTypeObject *ptr__Dict_Type = NULL; static PyTypeObject *ptr__Float_Type = NULL; +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) static PyTypeObject *ptr__Function_Type = NULL; +# endif static PyTypeObject *ptr__Bool_Type = NULL; static PyTypeObject *ptr__List_Type = NULL; static PyTypeObject *ptr__Long_Type = NULL; +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) static PyTypeObject *ptr__Method_Type = NULL; +# endif static PyTypeObject *ptr__Module_Type = NULL; static PyTypeObject *ptr__Range_Type = NULL; static PyTypeObject *ptr__Slice_Type = NULL; @@ -128,27 +112,32 @@ static PyTypeObject *ptr__TraceBack_Type = NULL; static PyTypeObject *ptr__Tuple_Type = NULL; static PyTypeObject *ptr__Type_Type = NULL; static PyTypeObject *ptr__Unicode_Type = NULL; -#if PY_MAJOR_VERSION == 2 +# if PY_MAJOR_VERSION == 2 static PyTypeObject *ptr__Int_Type = NULL; static PyTypeObject *ptr__String_Type = NULL; static PyTypeObject *ptr__CObject_Type = NULL; -#endif -#if PY_MAJOR_VERSION >= 3 +# endif +# if PY_MAJOR_VERSION >= 3 static PyTypeObject *ptr__Bytes_Type = NULL; -#endif - +# endif +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) static int *ptr_Py_DebugFlag = NULL; static int *ptr_Py_InteractiveFlag = NULL; static int *ptr_Py_OptimizeFlag = NULL; static int *ptr_Py_NoSiteFlag = NULL; static int *ptr_Py_VerboseFlag = NULL; +# if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7 +static const char **ptr__Py_PackageContext = NULL; +# else static char **ptr__Py_PackageContext = NULL; +# endif +# endif -#ifdef Py_REF_DEBUG +# ifdef Py_REF_DEBUG int *ptr_Py_RefTotal; -#endif +# endif //-------------------------------------------------------------------------------- @@ -218,13 +207,24 @@ static char **GetCharPointer_as_CharPointerPointer( const char *name ) return (char **)addr; } +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7 +static char **GetConstCharPointer_as_ConstCharPointerPointer( const char *name ) +{ + FARPROC addr = GetProcAddress( python_dll, name ); + if( addr == NULL ) + throw GetAddressException( name ); -#ifdef _DEBUG -static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d_D.DLL"; -#else -static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d.DLL"; + return (const char **)addr; +} #endif + +# ifdef _DEBUG +static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d_D.DLL"; +# else +static const char python_dll_name_format[] = "PYTHON%1.1d%1.1d.DLL"; +# endif + //-------------------------------------------------------------------------------- bool InitialisePythonIndirectInterface() { @@ -238,69 +238,56 @@ bool InitialisePythonIndirectInterface() try { -#ifdef Py_REF_DEBUG +# ifdef Py_REF_DEBUG ptr_Py_RefTotal = GetInt_as_IntPointer( "_Py_RefTotal" ); -#endif +# endif +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) ptr_Py_DebugFlag = GetInt_as_IntPointer( "Py_DebugFlag" ); ptr_Py_InteractiveFlag = GetInt_as_IntPointer( "Py_InteractiveFlag" ); ptr_Py_OptimizeFlag = GetInt_as_IntPointer( "Py_OptimizeFlag" ); ptr_Py_NoSiteFlag = GetInt_as_IntPointer( "Py_NoSiteFlag" ); ptr_Py_VerboseFlag = GetInt_as_IntPointer( "Py_VerboseFlag" ); - ptr__Py_PackageContext = GetCharPointer_as_CharPointerPointer( "_Py_PackageContext" ); - ptr__Exc_ArithmeticError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ArithmeticError" ); - ptr__Exc_AssertionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AssertionError" ); - ptr__Exc_AttributeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_AttributeError" ); - ptr__Exc_EnvironmentError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EnvironmentError" ); - ptr__Exc_EOFError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_EOFError" ); - ptr__Exc_Exception = GetPyObjectPointer_As_PyObjectPointer( "PyExc_Exception" ); - ptr__Exc_FloatingPointError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_FloatingPointError" ); - ptr__Exc_ImportError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ImportError" ); - ptr__Exc_IndexError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndexError" ); - ptr__Exc_IOError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IOError" ); - ptr__Exc_KeyboardInterrupt = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyboardInterrupt" ); - ptr__Exc_KeyError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_KeyError" ); - ptr__Exc_LookupError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_LookupError" ); - ptr__Exc_MemoryError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_MemoryError" ); - ptr__Exc_NameError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_NameError" ); - ptr__Exc_NotImplementedError= GetPyObjectPointer_As_PyObjectPointer( "PyExc_NotImplementedError" ); - ptr__Exc_OSError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OSError" ); - ptr__Exc_OverflowError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_OverflowError" ); - ptr__Exc_RuntimeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_RuntimeError" ); -#if PY_MAJOR_VERSION == 2 - ptr__Exc_StandardError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_StandardError" ); -#endif - ptr__Exc_SyntaxError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SyntaxError" ); - ptr__Exc_SystemError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemError" ); - ptr__Exc_SystemExit = GetPyObjectPointer_As_PyObjectPointer( "PyExc_SystemExit" ); - ptr__Exc_TypeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TypeError" ); - ptr__Exc_ValueError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ValueError" ); -#ifdef MS_WINDOWS - ptr__Exc_WindowsError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_WindowsError" ); -#endif - ptr__Exc_ZeroDivisionError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_ZeroDivisionError" ); - ptr__Exc_IndentationError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_IndentationError" ); - ptr__Exc_TabError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_TabError" ); - ptr__Exc_UnboundLocalError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnboundLocalError" ); - ptr__Exc_UnicodeError = GetPyObjectPointer_As_PyObjectPointer( "PyExc_UnicodeError" ); +# if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7 + ptr__Py_PackageContext = GetConstCharPointer_as_ConstCharPointerPointer( "_Py_PackageContext" ); +# else + ptr__Py_PackageContext = GetCharPointer_as_CharPointerPointer( "_Py_PackageContext" ); +# endif +# endif + +# define PYCXX_STANDARD_EXCEPTION( eclass, bclass ) + ptr_Exc_#eclass = GetPyTypeObject_As_PyTypeObjectPointer( "PyExc_" #eclass ); + +# if PY_MAJOR_VERSION == 2 +# include "CXX/Python2/cxx_standard_exceptions.hxx" +# else +# include "CXX/Python3/cxx_standard_exceptions.hxx" +# endif + +# undef PYCXX_STANDARD_EXCEPTION + ptr__PyNone = GetPyObject_As_PyObjectPointer( "_Py_NoneStruct" ); -#if PY_MAJOR_VERSION == 2 +# if PY_MAJOR_VERSION == 2 ptr__PyFalse = GetPyObject_As_PyObjectPointer( "_Py_ZeroStruct" ); -#else +# else ptr__PyFalse = GetPyObject_As_PyObjectPointer( "_Py_FalseStruct" ); -#endif +# endif ptr__PyTrue = GetPyObject_As_PyObjectPointer( "_Py_TrueStruct" ); ptr__CFunction_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCFunction_Type" ); ptr__Complex_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyComplex_Type" ); ptr__Dict_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyDict_Type" ); ptr__Float_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFloat_Type" ); +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) ptr__Function_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyFunction_Type" ); +# endif ptr__Bool_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyBool_Type" ); ptr__List_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyList_Type" ); ptr__Long_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyLong_Type" ); +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) ptr__Method_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyMethod_Type" ); +# endif ptr__Module_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyModule_Type" ); ptr__Range_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyRange_Type" ); ptr__Slice_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PySlice_Type" ); @@ -308,14 +295,14 @@ bool InitialisePythonIndirectInterface() ptr__Tuple_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyTuple_Type" ); ptr__Type_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyType_Type" ); ptr__Unicode_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyUnicode_Type" ); -#if PY_MAJOR_VERSION == 2 +# if PY_MAJOR_VERSION == 2 ptr__String_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyString_Type" ); ptr__Int_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyInt_Type" ); ptr__CObject_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyCObject_Type" ); -#endif -#if PY_MAJOR_VERSION >= 3 +# endif +# if PY_MAJOR_VERSION >= 3 ptr__Bytes_Type = GetPyTypeObject_As_PyTypeObjectPointer( "PyBytes_Type" ); -#endif +# endif } catch( GetAddressException &e ) { @@ -352,17 +339,17 @@ PYCXX_EXPORT PyObject *_Exc_NotImplementedError() { return ptr__Exc_NotImplem PYCXX_EXPORT PyObject *_Exc_OSError() { return ptr__Exc_OSError; } PYCXX_EXPORT PyObject *_Exc_OverflowError() { return ptr__Exc_OverflowError; } PYCXX_EXPORT PyObject *_Exc_RuntimeError() { return ptr__Exc_RuntimeError; } -#if PY_MAJOR_VERSION == 2 +# if PY_MAJOR_VERSION == 2 PYCXX_EXPORT PyObject *_Exc_StandardError() { return ptr__Exc_StandardError; } -#endif +# endif PYCXX_EXPORT PyObject *_Exc_SyntaxError() { return ptr__Exc_SyntaxError; } PYCXX_EXPORT PyObject *_Exc_SystemError() { return ptr__Exc_SystemError; } PYCXX_EXPORT PyObject *_Exc_SystemExit() { return ptr__Exc_SystemExit; } PYCXX_EXPORT PyObject *_Exc_TypeError() { return ptr__Exc_TypeError; } PYCXX_EXPORT PyObject *_Exc_ValueError() { return ptr__Exc_ValueError; } -#ifdef MS_WINDOWS +# ifdef MS_WINDOWS PYCXX_EXPORT PyObject *_Exc_WindowsError() { return ptr__Exc_WindowsError; } -#endif +# endif PYCXX_EXPORT PyObject *_Exc_ZeroDivisionError() { return ptr__Exc_ZeroDivisionError; } PYCXX_EXPORT PyObject *_Exc_IndentationError() { return ptr__Exc_IndentationError; } PYCXX_EXPORT PyObject *_Exc_TabError() { return ptr__Exc_TabError; } @@ -381,11 +368,15 @@ PYCXX_EXPORT PyTypeObject *_CFunction_Type() { return ptr__CFunction_Typ PYCXX_EXPORT PyTypeObject *_Complex_Type() { return ptr__Complex_Type; } PYCXX_EXPORT PyTypeObject *_Dict_Type() { return ptr__Dict_Type; } PYCXX_EXPORT PyTypeObject *_Float_Type() { return ptr__Float_Type; } +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT PyTypeObject *_Function_Type() { return ptr__Function_Type; } +# endif PYCXX_EXPORT PyTypeObject *_Bool_Type() { return ptr__Bool_Type; } PYCXX_EXPORT PyTypeObject *_List_Type() { return ptr__List_Type; } PYCXX_EXPORT PyTypeObject *_Long_Type() { return ptr__Long_Type; } +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT PyTypeObject *_Method_Type() { return ptr__Method_Type; } +# endif PYCXX_EXPORT PyTypeObject *_Module_Type() { return ptr__Module_Type; } PYCXX_EXPORT PyTypeObject *_Range_Type() { return ptr__Range_Type; } PYCXX_EXPORT PyTypeObject *_Slice_Type() { return ptr__Slice_Type; } @@ -393,39 +384,44 @@ PYCXX_EXPORT PyTypeObject *_TraceBack_Type() { return ptr__TraceBack_Typ PYCXX_EXPORT PyTypeObject *_Tuple_Type() { return ptr__Tuple_Type; } PYCXX_EXPORT PyTypeObject *_Type_Type() { return ptr__Type_Type; } PYCXX_EXPORT PyTypeObject *_Unicode_Type() { return ptr__Unicode_Type; } -#if PY_MAJOR_VERSION == 2 +# if PY_MAJOR_VERSION == 2 PYCXX_EXPORT PyTypeObject *_String_Type() { return ptr__String_Type; } PYCXX_EXPORT PyTypeObject *_Int_Type() { return ptr__Int_Type; } PYCXX_EXPORT PyTypeObject *_CObject_Type() { return ptr__CObject_Type; } -#endif -#if PY_MAJOR_VERSION >= 3 +# endif +# if PY_MAJOR_VERSION >= 3 PYCXX_EXPORT PyTypeObject *_Bytes_Type() { return ptr__Bytes_Type; } -#endif - -PYCXX_EXPORT char *__Py_PackageContext() { return *ptr__Py_PackageContext; } - +# endif // // wrap the Python Flag variables // +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT int &_Py_DebugFlag() { return *ptr_Py_DebugFlag; } PYCXX_EXPORT int &_Py_InteractiveFlag() { return *ptr_Py_InteractiveFlag; } PYCXX_EXPORT int &_Py_OptimizeFlag() { return *ptr_Py_OptimizeFlag; } PYCXX_EXPORT int &_Py_NoSiteFlag() { return *ptr_Py_NoSiteFlag; } PYCXX_EXPORT int &_Py_VerboseFlag() { return *ptr_Py_VerboseFlag; } +# endif -#if 0 -#define Py_INCREF(op) ( \ +# if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7 +PYCXX_EXPORT const char *__Py_PackageContext() { return *ptr__Py_PackageContext; } +# else +PYCXX_EXPORT char *__Py_PackageContext() { return *ptr__Py_PackageContext; } +# endif + +# if 0 +# define Py_INCREF(op) ( \ _Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \ ((PyObject*)(op))->ob_refcnt++) -#define Py_DECREF(op) \ +# define Py_DECREF(op) \ if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \ --((PyObject*)(op))->ob_refcnt != 0) \ _Py_CHECK_REFCNT(op) \ else \ _Py_Dealloc((PyObject *)(op)) -#endif +# endif void _XINCREF( PyObject *op ) { @@ -433,9 +429,9 @@ void _XINCREF( PyObject *op ) if( op == NULL ) return; -#ifdef Py_REF_DEBUG +# ifdef Py_REF_DEBUG (*ptr_Py_RefTotal)++; -#endif +# endif (op)->ob_refcnt++; } @@ -446,18 +442,18 @@ void _XDECREF( PyObject *op ) if( op == NULL ) return; -#ifdef Py_REF_DEBUG +# ifdef Py_REF_DEBUG (*ptr_Py_RefTotal)--; -#endif +# endif if (--(op)->ob_refcnt == 0) _Py_Dealloc((PyObject *)(op)); } -#else -#error "Can only delay load under Win32" -#endif +# else +# error "Can only delay load under Win32" +# endif #else @@ -470,43 +466,16 @@ void _XDECREF( PyObject *op ) // // Wrap variables as function calls // +# define PYCXX_STANDARD_EXCEPTION( eclass, bclass ) \ + PYCXX_EXPORT PyObject *_Exc_##eclass() { return ::PyExc_##eclass; } -PYCXX_EXPORT PyObject *_Exc_ArithmeticError() { return ::PyExc_ArithmeticError; } -PYCXX_EXPORT PyObject *_Exc_AssertionError() { return ::PyExc_AssertionError; } -PYCXX_EXPORT PyObject *_Exc_AttributeError() { return ::PyExc_AttributeError; } -PYCXX_EXPORT PyObject *_Exc_EnvironmentError() { return ::PyExc_EnvironmentError; } -PYCXX_EXPORT PyObject *_Exc_EOFError() { return ::PyExc_EOFError; } -PYCXX_EXPORT PyObject *_Exc_Exception() { return ::PyExc_Exception; } -PYCXX_EXPORT PyObject *_Exc_FloatingPointError() { return ::PyExc_FloatingPointError; } -PYCXX_EXPORT PyObject *_Exc_ImportError() { return ::PyExc_ImportError; } -PYCXX_EXPORT PyObject *_Exc_IndexError() { return ::PyExc_IndexError; } -PYCXX_EXPORT PyObject *_Exc_IOError() { return ::PyExc_IOError; } -PYCXX_EXPORT PyObject *_Exc_KeyboardInterrupt() { return ::PyExc_KeyboardInterrupt; } -PYCXX_EXPORT PyObject *_Exc_KeyError() { return ::PyExc_KeyError; } -PYCXX_EXPORT PyObject *_Exc_LookupError() { return ::PyExc_LookupError; } -PYCXX_EXPORT PyObject *_Exc_MemoryError() { return ::PyExc_MemoryError; } -PYCXX_EXPORT PyObject *_Exc_NameError() { return ::PyExc_NameError; } -PYCXX_EXPORT PyObject *_Exc_NotImplementedError() { return ::PyExc_NotImplementedError; } -PYCXX_EXPORT PyObject *_Exc_OSError() { return ::PyExc_OSError; } -PYCXX_EXPORT PyObject *_Exc_OverflowError() { return ::PyExc_OverflowError; } -PYCXX_EXPORT PyObject *_Exc_RuntimeError() { return ::PyExc_RuntimeError; } -PYCXX_EXPORT PyObject *_Exc_SyntaxError() { return ::PyExc_SyntaxError; } -PYCXX_EXPORT PyObject *_Exc_SystemError() { return ::PyExc_SystemError; } -PYCXX_EXPORT PyObject *_Exc_SystemExit() { return ::PyExc_SystemExit; } -PYCXX_EXPORT PyObject *_Exc_TypeError() { return ::PyExc_TypeError; } -PYCXX_EXPORT PyObject *_Exc_ValueError() { return ::PyExc_ValueError; } -PYCXX_EXPORT PyObject *_Exc_ZeroDivisionError() { return ::PyExc_ZeroDivisionError; } -PYCXX_EXPORT PyObject *_Exc_IndentationError() { return ::PyExc_IndentationError; } -PYCXX_EXPORT PyObject *_Exc_TabError() { return ::PyExc_TabError; } -PYCXX_EXPORT PyObject *_Exc_UnboundLocalError() { return ::PyExc_UnboundLocalError; } -PYCXX_EXPORT PyObject *_Exc_UnicodeError() { return ::PyExc_UnicodeError; } - -#ifdef MS_WINDOWS -PYCXX_EXPORT PyObject *_Exc_WindowsError() { return ::PyExc_WindowsError; } -#endif - - +# if PY_MAJOR_VERSION == 2 +# include "CXX/Python2/cxx_standard_exceptions.hxx" +# else +# include "CXX/Python3/cxx_standard_exceptions.hxx" +# endif +# undef PYCXX_STANDARD_EXCEPTION // // wrap items in Object.h @@ -520,11 +489,15 @@ PYCXX_EXPORT PyTypeObject *_CFunction_Type() { return &PyCFunction_Type; PYCXX_EXPORT PyTypeObject *_Complex_Type() { return &PyComplex_Type; } PYCXX_EXPORT PyTypeObject *_Dict_Type() { return &PyDict_Type; } PYCXX_EXPORT PyTypeObject *_Float_Type() { return &PyFloat_Type; } +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT PyTypeObject *_Function_Type() { return &PyFunction_Type; } +# endif PYCXX_EXPORT PyTypeObject *_Bool_Type() { return &PyBool_Type; } PYCXX_EXPORT PyTypeObject *_List_Type() { return &PyList_Type; } PYCXX_EXPORT PyTypeObject *_Long_Type() { return &PyLong_Type; } +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT PyTypeObject *_Method_Type() { return &PyMethod_Type; } +# endif PYCXX_EXPORT PyTypeObject *_Module_Type() { return &PyModule_Type; } PYCXX_EXPORT PyTypeObject *_Range_Type() { return &PyRange_Type; } PYCXX_EXPORT PyTypeObject *_Slice_Type() { return &PySlice_Type; } @@ -532,24 +505,30 @@ PYCXX_EXPORT PyTypeObject *_TraceBack_Type() { return &PyTraceBack_Type; PYCXX_EXPORT PyTypeObject *_Tuple_Type() { return &PyTuple_Type; } PYCXX_EXPORT PyTypeObject *_Type_Type() { return &PyType_Type; } PYCXX_EXPORT PyTypeObject *_Unicode_Type() { return &PyUnicode_Type; } -#if PY_MAJOR_VERSION == 2 +# if PY_MAJOR_VERSION == 2 PYCXX_EXPORT PyTypeObject *_String_Type() { return &PyString_Type; } PYCXX_EXPORT PyTypeObject *_Int_Type() { return &PyInt_Type; } PYCXX_EXPORT PyTypeObject *_CObject_Type() { return &PyCObject_Type; } -#endif -#if PY_MAJOR_VERSION >= 3 +# endif +# if PY_MAJOR_VERSION >= 3 PYCXX_EXPORT PyTypeObject *_Bytes_Type() { return &PyBytes_Type; } -#endif +# endif // // wrap flags // +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT int &_Py_DebugFlag() { return Py_DebugFlag; } PYCXX_EXPORT int &_Py_InteractiveFlag() { return Py_InteractiveFlag; } PYCXX_EXPORT int &_Py_OptimizeFlag() { return Py_OptimizeFlag; } PYCXX_EXPORT int &_Py_NoSiteFlag() { return Py_NoSiteFlag; } PYCXX_EXPORT int &_Py_VerboseFlag() { return Py_VerboseFlag; } +# if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7 PYCXX_EXPORT const char *__Py_PackageContext() { return _Py_PackageContext; } +# else +PYCXX_EXPORT char *__Py_PackageContext() { return _Py_PackageContext; } +# endif +# endif // // Needed to keep the abstractions for delayload interface diff --git a/src/CXX/Python2/ExtensionModule.hxx b/src/CXX/Python2/ExtensionModule.hxx index bf2e49c8a6..26306b71a6 100644 --- a/src/CXX/Python2/ExtensionModule.hxx +++ b/src/CXX/Python2/ExtensionModule.hxx @@ -139,10 +139,12 @@ namespace Py args[0] = Object( self, true ); args[1] = Object( PyCObject_FromVoidPtr( method_def, do_not_dealloc ), true ); - PyObject *func = PyCFunction_New + assert( m_module != NULL ); + PyObject *func = PyCFunction_NewEx ( &method_def->ext_meth_def, - new_reference_to( args ) + new_reference_to( args ), + m_module ); method_def->py_method = Object( func, true ); diff --git a/src/CXX/Python2/ExtensionOldType.hxx b/src/CXX/Python2/ExtensionOldType.hxx index cfd2fbe6a5..570e31f612 100644 --- a/src/CXX/Python2/ExtensionOldType.hxx +++ b/src/CXX/Python2/ExtensionOldType.hxx @@ -180,7 +180,7 @@ namespace Py self[0] = Object( this ); self[1] = Object( PyCObject_FromVoidPtr( method_def, do_not_dealloc ), true ); - PyObject *func = PyCFunction_New( &method_def->ext_meth_def, self.ptr() ); + PyObject *func = PyCFunction_NewEx( &method_def->ext_meth_def, self.ptr(), NULL ); return Object(func, true); } @@ -256,7 +256,7 @@ namespace Py return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -293,7 +293,7 @@ namespace Py return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -322,7 +322,7 @@ namespace Py return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } diff --git a/src/CXX/Python3/Config.hxx b/src/CXX/Python3/Config.hxx index 339e847f2d..08aa495269 100644 --- a/src/CXX/Python3/Config.hxx +++ b/src/CXX/Python3/Config.hxx @@ -38,6 +38,10 @@ #ifndef __PyCXX_config_hh__ #define __PyCXX_config_hh__ +#if defined( Py_LIMITED_API ) && Py_LIMITED_API+0 < 0x03040000 +#error "PyCXX support for Python limited API requires version 3.4 or newer. Py_LIMITED_API=0x03040000" +#endif + // // Microsoft VC++ 6.0 has no traits // @@ -53,7 +57,7 @@ #endif // -// Assume all other compilers do +// Assume all other compilers do // #else @@ -68,14 +72,19 @@ #endif // -// Which C++ standard is in use? +// Which C++ standard is in use? // #if defined( _MSC_VER ) - +# if _MSC_VER <= 1200 +// MSVC++ 6.0 +# define PYCXX_ISO_CPP_LIB 0 +# define STR_STREAM +# define TEMPLATE_TYPENAME class +# else # define PYCXX_ISO_CPP_LIB 1 # define STR_STREAM # define TEMPLATE_TYPENAME typename - +# endif #elif defined( __GNUC__ ) # if __GNUC__ >= 3 # define PYCXX_ISO_CPP_LIB 1 diff --git a/src/CXX/Python3/Exception.hxx b/src/CXX/Python3/Exception.hxx index 1b558dc4ce..96d8ef41e2 100644 --- a/src/CXX/Python3/Exception.hxx +++ b/src/CXX/Python3/Exception.hxx @@ -54,207 +54,119 @@ namespace Py class Object; - class PYCXX_EXPORT Exception + class PYCXX_EXPORT BaseException { public: - Exception( ExtensionExceptionType &exception, const std::string &reason ); - Exception( ExtensionExceptionType &exception, Object &reason ); + BaseException( ExtensionExceptionType &exception, const std::string &reason ); + BaseException( ExtensionExceptionType &exception, Object &reason ); + BaseException( PyObject *exception, Object &reason ); + BaseException( PyObject *exception, const std::string &reason ); + explicit BaseException(); - explicit Exception () + void clear(); // clear the error + + // is the exception this specific exception 'exc' + bool matches( ExtensionExceptionType &exc ); + + Object errorType(); // get the error type of the active exception + Object errorValue();// get the error value of the active exception + }; + + // for user defined exceptions to be made know to pycxx + typedef void (*throw_exception_func_t)( void ); + void addPythonException( ExtensionExceptionType &py_exc_type, throw_exception_func_t throw_func ); + +#if defined( PYCXX_6_2_COMPATIBILITY ) + class PYCXX_EXPORT Exception : public BaseException + { + public: + Exception( ExtensionExceptionType &exception, const std::string &reason ) + : BaseException( exception, reason ) {} - - // This overloaded constructor will be removed in future PyCXX versions - //Exception (const std::string &reason) - //{ - // PyErr_SetString( Py::_Exc_RuntimeError(), reason.c_str() ); - //} - + + Exception( ExtensionExceptionType &exception, Object &reason ) + : BaseException( exception, reason ) + {} + + Exception( PyObject *exception, Object &reason ) + : BaseException( exception, reason ) + {} + Exception( PyObject *exception, const std::string &reason ) - { - PyErr_SetString( exception, reason.c_str() ); - } - - Exception( PyObject *exception, Object &reason ); + : BaseException( exception, reason ) + {} - void clear() // clear the error - // technically but not philosophically const - { - PyErr_Clear(); - } - }; - - - // Abstract - class PYCXX_EXPORT StandardError: public Exception - { - protected: - explicit StandardError() + explicit Exception() + : BaseException() {} }; - - class PYCXX_EXPORT LookupError: public StandardError - { - protected: - explicit LookupError() - {} - }; - - class PYCXX_EXPORT ArithmeticError: public StandardError - { - protected: - explicit ArithmeticError() - {} - }; - - class PYCXX_EXPORT EnvironmentError: public StandardError - { - protected: - explicit EnvironmentError() - {} - }; - - // Concrete - - class PYCXX_EXPORT TypeError: public StandardError - { - public: - TypeError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_TypeError(),reason.c_str() ); - } - }; - - class PYCXX_EXPORT IndexError: public LookupError - { - public: - IndexError (const std::string& reason) - : LookupError() - { - PyErr_SetString( Py::_Exc_IndexError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT AttributeError: public StandardError - { - public: - AttributeError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_AttributeError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT NameError: public StandardError - { - public: - NameError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_NameError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT RuntimeError: public StandardError - { - public: - RuntimeError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_RuntimeError(), reason.c_str() ); - } - }; - - class NotImplementedError: public StandardError - { - public: - NotImplementedError (const std::string& reason) - : StandardError() - { - PyErr_SetString (Py::_Exc_NotImplementedError(), reason.c_str()); - } - }; - - class PYCXX_EXPORT SystemError: public StandardError - { - public: - SystemError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_SystemError(),reason.c_str() ); - } - }; - - class PYCXX_EXPORT KeyError: public LookupError - { - public: - KeyError (const std::string& reason) - : LookupError() - { - PyErr_SetString( Py::_Exc_KeyError(),reason.c_str() ); - } - }; - - - class PYCXX_EXPORT ValueError: public StandardError - { - public: - ValueError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_ValueError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT OverflowError: public ArithmeticError - { - public: - OverflowError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString( Py::_Exc_OverflowError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT ZeroDivisionError: public ArithmeticError - { - public: - ZeroDivisionError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString( Py::_Exc_ZeroDivisionError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT FloatingPointError: public ArithmeticError - { - public: - FloatingPointError (const std::string& reason) - : ArithmeticError() - { - PyErr_SetString( Py::_Exc_FloatingPointError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT MemoryError: public StandardError - { - public: - MemoryError (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_MemoryError(), reason.c_str() ); - } - }; - - class PYCXX_EXPORT SystemExit: public StandardError - { - public: - SystemExit (const std::string& reason) - : StandardError() - { - PyErr_SetString( Py::_Exc_SystemExit(),reason.c_str() ); - } - }; +#endif + +#define PYCXX_STANDARD_EXCEPTION( eclass, bclass ) \ + class PYCXX_EXPORT eclass : public bclass \ + { \ + public: \ + eclass() {} \ + eclass( const char *reason ) { PyErr_SetString( _Exc_##eclass(), reason ); } \ + eclass( const std::string &reason ) { PyErr_SetString( _Exc_##eclass(), reason.c_str() ); } \ + ~eclass() {} \ + \ + static void throwFunc() { throw eclass(); } \ + static PyObject *exceptionType() { return _Exc_##eclass(); } \ + }; \ + +#include + +#undef PYCXX_STANDARD_EXCEPTION + +#define PYCXX_USER_EXCEPTION_STR_ARG( uclass ) \ +class PYCXX_EXPORT uclass : public Py::BaseException \ +{ \ +public: \ + uclass( const std::string &reason ) \ + : Py::BaseException( m_error, reason ) \ + { } \ + ~uclass() {} \ + static void init( Py::ExtensionModuleBase &module ) \ + { \ + m_error.init( module, #uclass ); \ + Py::addPythonException( m_error, throwFunc ); \ + Py::Dict d( module.moduleDictionary() ); \ + d[#uclass] = m_error; \ + } \ +private: \ + uclass() : Py::BaseException() {} \ + static void throwFunc() \ + { \ + throw uclass(); \ + } \ + static Py::ExtensionExceptionType m_error; \ +}; \ +Py::ExtensionExceptionType uclass::m_error; + +#define PYCXX_USER_EXCEPTION_NO_ARG( uclass ) \ +class PYCXX_EXPORT uclass : public Py::BaseException \ +{ \ +public: \ + uclass() \ + : Py::BaseException() \ + { } \ + ~uclass() {} \ + static void init( Py::ExtensionModuleBase &module ) \ + { \ + m_error.init( module, #uclass ); \ + Py::addPythonException( m_error, throwFunc ); \ + Py::Dict d( module.moduleDictionary() ); \ + d[#uclass] = m_error; \ + } \ +private: \ + static void throwFunc() \ + { \ + throw uclass(); \ + } \ + static Py::ExtensionExceptionType m_error; \ +}; \ +Py::ExtensionExceptionType uclass::m_error; }// Py diff --git a/src/CXX/Python3/ExtensionModule.hxx b/src/CXX/Python3/ExtensionModule.hxx index c2323a47bd..525f65e0b9 100644 --- a/src/CXX/Python3/ExtensionModule.hxx +++ b/src/CXX/Python3/ExtensionModule.hxx @@ -138,10 +138,12 @@ namespace Py args[0] = Object( self, true ); args[1] = Object( PyCapsule_New( method_def, NULL, NULL ), true ); - PyObject *func = PyCFunction_New + assert( m_module != NULL ); + PyObject *func = PyCFunction_NewEx ( &method_def->ext_meth_def, - new_reference_to( args ) + new_reference_to( args ), + m_module ); method_def->py_method = Object( func, true ); diff --git a/src/CXX/Python3/ExtensionOldType.hxx b/src/CXX/Python3/ExtensionOldType.hxx index 5c65e8400e..e032713b20 100644 --- a/src/CXX/Python3/ExtensionOldType.hxx +++ b/src/CXX/Python3/ExtensionOldType.hxx @@ -119,15 +119,19 @@ namespace Py { std::string name( _name ); +#if !defined( Py_LIMITED_API ) if( name == "__name__" && type_object()->tp_name != NULL ) { return Py::String( type_object()->tp_name ); } +#endif +#if !defined( Py_LIMITED_API ) if( name == "__doc__" && type_object()->tp_doc != NULL ) { return Py::String( type_object()->tp_doc ); } +#endif // trying to fake out being a class for help() // else if( name == "__bases__" ) @@ -192,7 +196,7 @@ namespace Py self[0] = Object( this ); self[1] = Object( PyCapsule_New( method_def, NULL, NULL ), true ); - PyObject *func = PyCFunction_New( &method_def->ext_meth_def, self.ptr() ); + PyObject *func = PyCFunction_NewEx( &method_def->ext_meth_def, self.ptr(), NULL ); return Object(func, true); } @@ -270,7 +274,7 @@ namespace Py return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -307,7 +311,7 @@ namespace Py return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -335,7 +339,7 @@ namespace Py return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } diff --git a/src/CXX/Python3/ExtensionType.hxx b/src/CXX/Python3/ExtensionType.hxx index 515bf4ba51..74dd2e17fb 100644 --- a/src/CXX/Python3/ExtensionType.hxx +++ b/src/CXX/Python3/ExtensionType.hxx @@ -52,7 +52,7 @@ Py::Object r( (self->NAME)() ); \ return Py::new_reference_to( r.ptr() ); \ } \ - catch( Py::Exception & ) \ + catch( Py::BaseException & ) \ { \ return 0; \ } \ @@ -68,7 +68,7 @@ Py::Object r( (self->NAME)( a ) ); \ return Py::new_reference_to( r.ptr() ); \ } \ - catch( Py::Exception & ) \ + catch( Py::BaseException & ) \ { \ return 0; \ } \ @@ -87,7 +87,7 @@ Py::Object r( (self->NAME)( a, k ) ); \ return Py::new_reference_to( r.ptr() ); \ } \ - catch( Py::Exception & ) \ + catch( Py::BaseException & ) \ { \ return 0; \ } \ @@ -111,7 +111,6 @@ namespace Py PythonExtensionBase *m_pycxx_object; }; - class PYCXX_EXPORT ExtensionClassMethodsTable { public: @@ -120,6 +119,13 @@ namespace Py , m_methods_used( 0 ) , m_methods_size( METHOD_TABLE_SIZE_INCREMENT ) { + // add the sentinel marking the table end + PyMethodDef *p = &m_methods_table[ 0 ]; + + p->ml_name = NULL; + p->ml_meth = NULL; + p->ml_flags = 0; + p->ml_doc = NULL; } ~ExtensionClassMethodsTable() @@ -194,7 +200,7 @@ namespace Py } virtual ~PythonClass() - {} + {} static ExtensionClassMethodsTable &methodTable() { @@ -212,7 +218,7 @@ namespace Py static PythonType &behaviors() { static PythonType *p; - if( p == NULL ) + if( p == NULL ) { #if defined( _CPPRTTI ) || defined( __GNUG__ ) const char *default_name = (typeid( T )).name(); @@ -240,15 +246,20 @@ namespace Py #ifdef PYCXX_DEBUG std::cout << "extension_object_new()" << std::endl; #endif - PythonClassInstance *o = reinterpret_cast( subtype->tp_alloc( subtype, 0 ) ); - if( o == NULL ) +#if defined( Py_LIMITED_API ) + PyObject *object = reinterpret_cast( PyType_GetSlot( subtype, Py_tp_alloc ) )( subtype, 0 ); +#else + PyObject *object = subtype->tp_alloc( subtype, 0 ); +#endif + if( object == NULL ) return NULL; + PythonClassInstance *o = reinterpret_cast( object ); o->m_pycxx_object = NULL; PyObject *self = reinterpret_cast( o ); #ifdef PYCXX_DEBUG - std::cout << "extension_object_new() => self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << std::endl; + std::cout << "extension_object_new() => self=0x" << std::hex << reinterpret_cast< unsigned long >( self ) << std::dec << std::endl; #endif return self; } @@ -264,26 +275,26 @@ namespace Py PythonClassInstance *self = reinterpret_cast( _self ); #ifdef PYCXX_DEBUG - std::cout << "extension_object_init( self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << " )" << std::endl; - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; + std::cout << "extension_object_init( self=0x" << std::hex << reinterpret_cast< unsigned long >( self ) << std::dec << " )" << std::endl; + std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned long >( self->m_pycxx_object ) << std::dec << std::endl; #endif if( self->m_pycxx_object == NULL ) { self->m_pycxx_object = new T( self, args, kwds ); #ifdef PYCXX_DEBUG - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; + std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned long >( self->m_pycxx_object ) << std::dec << std::endl; #endif } else { #ifdef PYCXX_DEBUG - std::cout << " reinit - self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; + std::cout << " reinit - self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned long >( self->m_pycxx_object ) << std::dec << std::endl; #endif self->m_pycxx_object->reinit( args, kwds ); } } - catch( Exception & ) + catch( BaseException & ) { return -1; } @@ -294,11 +305,16 @@ namespace Py { PythonClassInstance *self = reinterpret_cast< PythonClassInstance * >( _self ); #ifdef PYCXX_DEBUG - std::cout << "extension_object_deallocator( self=0x" << std::hex << reinterpret_cast< unsigned int >( self ) << std::dec << " )" << std::endl; - std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned int >( self->m_pycxx_object ) << std::dec << std::endl; + std::cout << "extension_object_deallocator( self=0x" << std::hex << reinterpret_cast< unsigned long >( self ) << std::dec << " )" << std::endl; + std::cout << " self->m_pycxx_object=0x" << std::hex << reinterpret_cast< unsigned long >( self->m_pycxx_object ) << std::dec << std::endl; #endif delete self->m_pycxx_object; +#ifdef Py_LIMITED_API + freefunc fn = reinterpret_cast( PyType_GetSlot( _self->ob_type, Py_tp_free ) ); + fn( _self ); +#else _self->ob_type->tp_free( _self ); +#endif } public: @@ -314,8 +330,17 @@ namespace Py static bool check( PyObject *p ) { - // is p like me? - return p->ob_type == type_object(); + // is p a me or a derived me + switch( PyObject_IsInstance( p, reinterpret_cast( type_object() ) ) ) + { + default: + case -1: + throw Exception(); + case 0: + return false; + case 1: + return true; + } } static bool check( const Object &ob ) diff --git a/src/CXX/Python3/ExtensionTypeBase.hxx b/src/CXX/Python3/ExtensionTypeBase.hxx index 2b9fa129ae..bd8d57d6dd 100644 --- a/src/CXX/Python3/ExtensionTypeBase.hxx +++ b/src/CXX/Python3/ExtensionTypeBase.hxx @@ -47,14 +47,14 @@ namespace Py // There are two ways that extension objects can get destroyed. // 1. Their reference count goes to zero // 2. Someone does an explicit delete on a pointer. - // In(1) the problem is to get the destructor called + // In(1) the problem is to get the destructor called // We register a special deallocator in the Python type object // (see behaviors()) to do this. // In(2) there is no problem, the dtor gets called. - // PythonExtension does not use the usual Python heap allocator, + // PythonExtension does not use the usual Python heap allocator, // instead using new/delete. We do the setting of the type object - // and reference count, usually done by PyObject_New, in the + // and reference count, usually done by PyObject_New, in the // base class ctor. // This special deallocator does a delete on the pointer. @@ -66,11 +66,11 @@ namespace Py virtual ~PythonExtensionBase(); public: - // object + // object virtual void reinit( Tuple &args, Dict &kwds ); // object basics -#ifdef PYCXX_PYTHON_2TO3 +#if defined( PYCXX_PYTHON_2TO3 ) && !defined( Py_LIMITED_API ) && PY_MINOR_VERSION <= 7 virtual int print( FILE *, int ); #endif virtual Object getattr( const char * ); @@ -89,15 +89,22 @@ namespace Py virtual PyObject *iternext(); // Sequence methods - virtual int sequence_length(); + virtual PyCxx_ssize_t sequence_length(); virtual Object sequence_concat( const Object & ); virtual Object sequence_repeat( Py_ssize_t ); virtual Object sequence_item( Py_ssize_t ); + virtual int sequence_ass_item( Py_ssize_t, const Object & ); + virtual Object sequence_inplace_concat( const Object & ); + virtual Object sequence_inplace_repeat( Py_ssize_t ); + + virtual int sequence_contains( const Object & ); + // Mapping - virtual int mapping_length(); + virtual PyCxx_ssize_t mapping_length(); virtual Object mapping_subscript( const Object & ); + virtual int mapping_ass_subscript( const Object &, const Object & ); // Number @@ -107,7 +114,6 @@ namespace Py virtual Object number_invert(); virtual Object number_int(); virtual Object number_float(); - virtual Object number_long(); virtual Object number_add( const Object & ); virtual Object number_subtract( const Object & ); virtual Object number_multiply( const Object & ); @@ -119,10 +125,34 @@ namespace Py virtual Object number_xor( const Object & ); virtual Object number_or( const Object & ); virtual Object number_power( const Object &, const Object & ); + virtual Object number_floor_divide( const Object & ); + virtual Object number_true_divide( const Object & ); + virtual Object number_index(); +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + virtual Object number_matrix_multiply( const Object & ); +#endif + virtual Object number_inplace_add( const Object & ); + virtual Object number_inplace_subtract( const Object & ); + virtual Object number_inplace_multiply( const Object & ); + virtual Object number_inplace_remainder( const Object & ); + virtual Object number_inplace_power( const Object &, const Object & ); + virtual Object number_inplace_lshift( const Object & ); + virtual Object number_inplace_rshift( const Object & ); + virtual Object number_inplace_and( const Object & ); + virtual Object number_inplace_xor( const Object & ); + virtual Object number_inplace_or( const Object & ); + virtual Object number_inplace_floor_divide( const Object & ); + virtual Object number_inplace_true_divide( const Object & ); +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + virtual Object number_inplace_matrix_multiply( const Object & ); +#endif + +#if !defined( Py_LIMITED_API ) // Buffer virtual int buffer_get( Py_buffer *, int flags ); virtual int buffer_release( Py_buffer *buf ); +#endif public: // helper functions to call function fn_name with 0 to 9 args diff --git a/src/CXX/Python3/Extensions.hxx b/src/CXX/Python3/Extensions.hxx index 0a181d9f07..5fcc3e3c1d 100644 --- a/src/CXX/Python3/Extensions.hxx +++ b/src/CXX/Python3/Extensions.hxx @@ -104,7 +104,7 @@ namespace Py extern "C" typedef PyObject *(*method_keyword_call_handler_t)( PyObject *_self, PyObject *_args, PyObject *_dict ); template - class MethodDefExt : public PyMethodDef + class MethodDefExt { public: typedef Object (T::*method_noargs_function_t)(); diff --git a/src/CXX/Python3/IndirectPythonInterface.hxx b/src/CXX/Python3/IndirectPythonInterface.hxx index 912fa56963..bf2c15c53f 100644 --- a/src/CXX/Python3/IndirectPythonInterface.hxx +++ b/src/CXX/Python3/IndirectPythonInterface.hxx @@ -36,9 +36,9 @@ //----------------------------------------------------------------------------- #ifndef __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ -#define __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ +# define __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ -#include "CXX/WrapPython.h" +# include "CXX/WrapPython.h" #include "CXX/Config.hxx" namespace Py @@ -48,41 +48,13 @@ bool InitialisePythonIndirectInterface(); // // Wrap Exception variables as function calls // -PYCXX_EXPORT PyObject * _Exc_Exception(); -PYCXX_EXPORT PyObject * _Exc_StandardError(); -PYCXX_EXPORT PyObject * _Exc_ArithmeticError(); -PYCXX_EXPORT PyObject * _Exc_LookupError(); +PYCXX_EXPORT PyObject * _Exc_BaseException(); -PYCXX_EXPORT PyObject * _Exc_AssertionError(); -PYCXX_EXPORT PyObject * _Exc_AttributeError(); -PYCXX_EXPORT PyObject * _Exc_EOFError(); -PYCXX_EXPORT PyObject * _Exc_FloatingPointError(); -PYCXX_EXPORT PyObject * _Exc_EnvironmentError(); -PYCXX_EXPORT PyObject * _Exc_IOError(); -PYCXX_EXPORT PyObject * _Exc_OSError(); -PYCXX_EXPORT PyObject * _Exc_ImportError(); -PYCXX_EXPORT PyObject * _Exc_IndexError(); -PYCXX_EXPORT PyObject * _Exc_KeyError(); -PYCXX_EXPORT PyObject * _Exc_KeyboardInterrupt(); -PYCXX_EXPORT PyObject * _Exc_MemoryError(); -PYCXX_EXPORT PyObject * _Exc_NameError(); -PYCXX_EXPORT PyObject * _Exc_OverflowError(); -PYCXX_EXPORT PyObject * _Exc_RuntimeError(); -PYCXX_EXPORT PyObject * _Exc_NotImplementedError(); -PYCXX_EXPORT PyObject * _Exc_SyntaxError(); -PYCXX_EXPORT PyObject * _Exc_SystemError(); -PYCXX_EXPORT PyObject * _Exc_SystemExit(); -PYCXX_EXPORT PyObject * _Exc_TypeError(); -PYCXX_EXPORT PyObject * _Exc_ValueError(); -PYCXX_EXPORT PyObject * _Exc_ZeroDivisionError(); -#ifdef MS_WINDOWS -PYCXX_EXPORT PyObject * _Exc_WindowsError(); -#endif +# define PYCXX_STANDARD_EXCEPTION( eclass, bclass ) \ + PYCXX_EXPORT PyObject * _Exc_##eclass(); -PYCXX_EXPORT PyObject * _Exc_IndentationError(); -PYCXX_EXPORT PyObject * _Exc_TabError(); -PYCXX_EXPORT PyObject * _Exc_UnboundLocalError(); -PYCXX_EXPORT PyObject * _Exc_UnicodeError(); +# include "CXX/Python3/cxx_standard_exceptions.hxx" +# undef PYCXX_STANDARD_EXCEPTION // // Wrap Object variables as function calls @@ -107,9 +79,14 @@ PYCXX_EXPORT bool _Class_Check( PyObject *op ); PYCXX_EXPORT PyTypeObject * _Instance_Type(); PYCXX_EXPORT bool _Instance_Check( PyObject *op ); +# if !defined( Py_LIMITED_API ) PYCXX_EXPORT PyTypeObject * _Method_Type(); PYCXX_EXPORT bool _Method_Check( PyObject *op ); +PYCXX_EXPORT PyTypeObject * _Function_Type(); +PYCXX_EXPORT bool _Function_Check( PyObject *op ); +# endif + PYCXX_EXPORT PyTypeObject * _Complex_Type(); PYCXX_EXPORT bool _Complex_Check( PyObject *op ); @@ -125,9 +102,6 @@ PYCXX_EXPORT bool _Float_Check( PyObject *op ); PYCXX_EXPORT PyTypeObject * _Frame_Type(); PYCXX_EXPORT bool _Frame_Check( PyObject *op ); -PYCXX_EXPORT PyTypeObject * _Function_Type(); -PYCXX_EXPORT bool _Function_Check( PyObject *op ); - PYCXX_EXPORT PyTypeObject * _Bool_Type(); PYCXX_EXPORT bool _Boolean_Check( PyObject *op ); @@ -167,18 +141,23 @@ PYCXX_EXPORT bool _TraceBack_Check( PyObject *v ); PYCXX_EXPORT PyTypeObject * _Tuple_Type(); PYCXX_EXPORT bool _Tuple_Check( PyObject *op ); +# if PY_MAJOR_VERSION == 2 || !defined( Py_LIMITED_API ) PYCXX_EXPORT int &_Py_DebugFlag(); PYCXX_EXPORT int &_Py_InteractiveFlag(); PYCXX_EXPORT int &_Py_OptimizeFlag(); PYCXX_EXPORT int &_Py_NoSiteFlag(); PYCXX_EXPORT int &_Py_TabcheckFlag(); PYCXX_EXPORT int &_Py_VerboseFlag(); -PYCXX_EXPORT int &_Py_UnicodeFlag(); + +# if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7 +PYCXX_EXPORT const char *__Py_PackageContext(); +# else +PYCXX_EXPORT char *__Py_PackageContext(); +# endif +# endif PYCXX_EXPORT void _XINCREF( PyObject *op ); PYCXX_EXPORT void _XDECREF( PyObject *op ); - -PYCXX_EXPORT const char *__Py_PackageContext(); } #endif // __CXX_INDIRECT_PYTHON_INTERFACE__HXX__ diff --git a/src/CXX/Python3/Objects.hxx b/src/CXX/Python3/Objects.hxx index 415a191ac8..38ee306688 100644 --- a/src/CXX/Python3/Objects.hxx +++ b/src/CXX/Python3/Objects.hxx @@ -51,9 +51,12 @@ #include #include #include +#include namespace Py { + PYCXX_EXPORT void ifPyErrorThrowCxxException(); + typedef Py_ssize_t sequence_index_type; // type of an index into a sequence PYCXX_EXPORT Py_ssize_t numeric_limits_max(); @@ -240,7 +243,7 @@ namespace Py // // Can pyob be used in this object's constructor? - virtual bool accepts( PyObject * /* pyob */ ) const + virtual bool accepts( PyObject * ) const { // allow any object or NULL return true; @@ -291,16 +294,6 @@ namespace Py return PyObject_IsTrue( ptr() ) != 0; } - //operator bool() const - //{ - // return as_bool(); - //} - - // int print( FILE *fp, int flags=Py_Print_RAW ) - //{ - // return PyObject_Print( p, fp, flags ); - //} - bool is( PyObject *pother ) const { // identity test return p == pother; @@ -383,7 +376,7 @@ namespace Py { if( PyObject_SetAttrString( p, const_cast( s.c_str() ), *value ) == -1 ) { - throw AttributeError( "setAttr failed." ); + ifPyErrorThrowCxxException(); } } @@ -391,7 +384,7 @@ namespace Py { if( PyObject_DelAttrString( p, const_cast( s.c_str() ) ) == -1 ) { - throw AttributeError( "delAttr failed." ); + ifPyErrorThrowCxxException(); } } @@ -402,8 +395,7 @@ namespace Py { if( PyObject_DelItem( p, *key ) == -1 ) { - // failed to link on Windows? - throw KeyError( "delItem failed." ); + ifPyErrorThrowCxxException(); } } // Equality and comparison use PyObject_Compare @@ -703,11 +695,6 @@ namespace Py } #endif - //operator bool() const - //{ - // return as_bool(); - //} - // convert to long long as_long() const { @@ -730,6 +717,7 @@ namespace Py return PyLong_AsUnsignedLong( ptr() ); } + // convert to unsigned operator unsigned long() const { return as_unsigned_long(); @@ -1022,6 +1010,8 @@ namespace Py { return pyob && Py::_Complex_Check( pyob ); } + +#if !defined( Py_LIMITED_API ) // convert to Py_complex operator Py_complex() const { @@ -1033,6 +1023,8 @@ namespace Py set( PyComplex_FromCComplex( v ), true ); return *this; } +#endif // Py_LIMITED_API + // assign from a double Complex &operator=( double v ) { @@ -1068,6 +1060,7 @@ namespace Py return PyComplex_ImagAsDouble( ptr() ); } }; + // Sequences // Sequences are here represented as sequences of items of type T. // The base class SeqBase represents that. @@ -1290,7 +1283,7 @@ namespace Py { public: // STL definitions - typedef Py_ssize_t size_type; + typedef PyCxx_ssize_t size_type; typedef seqref reference; typedef T const_reference; typedef seqref *pointer; @@ -1389,7 +1382,7 @@ namespace Py { if( PySequence_SetItem( ptr(), i, *ob ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -1453,7 +1446,7 @@ namespace Py protected: friend class SeqBase; SeqBase *seq; - size_type count; + sequence_index_type count; public: ~iterator() @@ -1464,7 +1457,7 @@ namespace Py , count( 0 ) {} - iterator( SeqBase *s, size_type where ) + iterator( SeqBase *s, Py_ssize_t where ) : seq( s ) , count( where ) {} @@ -1524,29 +1517,29 @@ namespace Py return *this; } - iterator operator+( int n ) const + iterator operator+( sequence_index_type n ) const { return iterator( seq, count + n ); } - iterator operator-( int n ) const + iterator operator-( sequence_index_type n ) const { return iterator( seq, count - n ); } - iterator &operator+=( int n ) + iterator &operator+=( sequence_index_type n ) { count = count + n; return *this; } - iterator &operator-=( int n ) + iterator &operator-=( sequence_index_type n ) { count = count - n; return *this; } - int operator-( const iterator &other ) const + sequence_index_type operator-( const iterator &other ) const { if( seq->ptr() != other.seq->ptr() ) { @@ -1623,7 +1616,7 @@ namespace Py , count( 0 ) {} - const_iterator( const SeqBase *s, size_type where ) + const_iterator( const SeqBase *s, sequence_index_type where ) : seq( s ) , count( where ) {} @@ -1653,7 +1646,7 @@ namespace Py return *this; } - const_iterator operator+( int n ) const + const_iterator operator+( sequence_index_type n ) const { return const_iterator( seq, count + n ); } @@ -1688,18 +1681,18 @@ namespace Py return count >= other.count; } - const_iterator operator-( int n ) + const_iterator operator-( sequence_index_type n ) { return const_iterator( seq, count - n ); } - const_iterator &operator+=( int n ) + const_iterator &operator+=( sequence_index_type n ) { count = count + n; return *this; } - const_iterator &operator-=( int n ) + const_iterator &operator-=( sequence_index_type n ) { count = count - n; return *this; @@ -1768,7 +1761,7 @@ namespace Py template bool operator< ( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); template bool operator> ( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); template bool operator<=( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); - template bool operator>=( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); + template bool operator>=( const EXPLICIT_TYPENAME SeqBase::const_iterator &left, const EXPLICIT_TYPENAME SeqBase::const_iterator &right ); PYCXX_EXPORT extern bool operator==( const Sequence::iterator &left, const Sequence::iterator &right ); @@ -1783,15 +1776,19 @@ namespace Py PYCXX_EXPORT extern bool operator< ( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); PYCXX_EXPORT extern bool operator> ( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); PYCXX_EXPORT extern bool operator<=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); - PYCXX_EXPORT extern bool operator>=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); + PYCXX_EXPORT extern bool operator>=( const Sequence::const_iterator &left, const Sequence::const_iterator &right ); // ================================================== // class Char // Python strings return strings as individual elements. // I'll try having a class Char which is a String of length 1 // +#if !defined(Py_LIMITED_API) typedef std::basic_string unicodestring; extern Py_UNICODE unicode_null_string[1]; +#endif + typedef std::basic_string ucs4string; + extern Py_UCS4 ucs4_null_string[1]; class PYCXX_EXPORT Byte: public Object { @@ -1800,7 +1797,7 @@ namespace Py virtual bool accepts( PyObject *pyob ) const { return pyob != NULL - && Py::_Unicode_Check( pyob ) + && Py::_Bytes_Check( pyob ) && PySequence_Length( pyob ) == 1; } @@ -1959,7 +1956,9 @@ namespace Py // Membership virtual bool accepts( PyObject *pyob ) const { - return pyob != 0 &&( Py::_Unicode_Check( pyob ) ) && PySequence_Length( pyob ) == 1; + return (pyob != 0 && + Py::_Unicode_Check( pyob ) && + PySequence_Length( pyob ) == 1); } explicit Char( PyObject *pyob, bool owned = false ) @@ -1980,17 +1979,21 @@ namespace Py validate(); } +#if !defined( Py_LIMITED_API ) Char( Py_UNICODE v ) : Object( PyUnicode_FromOrdinal( v ), true ) { validate(); } +#endif +#if !defined( Py_LIMITED_API ) Char( const unicodestring &v ) : Object( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, const_cast( v.data() ),1 ), true ) { validate(); } +#endif // Assignment acquires new ownership of pointer Char &operator=( const Object &rhs ) @@ -2005,24 +2008,56 @@ namespace Py return *this; } +#if !defined( Py_LIMITED_API ) Char &operator=( const unicodestring &v ) { set( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, const_cast( v.data() ), 1 ), true ); return *this; } +#endif +#if !defined( Py_LIMITED_API ) Char &operator=( int v_ ) { Py_UNICODE v( v_ ); set( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, &v, 1 ), true ); return *this; } +#endif +#if !defined( Py_LIMITED_API ) Char &operator=( Py_UNICODE v ) { set( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, &v, 1 ), true ); return *this; } +#endif + + long ord() + { +#if !defined( Py_LIMITED_API ) + return static_cast( PyUnicode_ReadChar( ptr(), 0 ) ); +#else + // we know that a Char() is 1 unicode code point + // that fits in 2 wchar_t on windows at worst + wchar_t buf[2]; + Py_ssize_t num_elements = PyUnicode_AsWideChar( ptr(), buf, 2 ); + + // just one wchar_t that easy + if( num_elements == 1 ) + { + return static_cast( buf[0] ); + } + // must be a pair of utf-16 surragates - convert to a code point + if( num_elements == 2 ) + { + // convert from utf-16 to a code-point + return static_cast( ((buf[0]-0xd800)*0x400) + (buf[1]-0xdc00) + 0x10000); + } + return 0; +#endif + + } // Conversion operator String() const; @@ -2082,7 +2117,7 @@ namespace Py Many of these APIs take two arguments encoding and errors. These parameters encoding and errors have the same semantics as the ones - of the builtin unicode() API. + of the builtin unicode() API. Setting encoding to NULL causes the default encoding to be used. @@ -2113,11 +2148,29 @@ namespace Py validate(); } +#if !defined( Py_LIMITED_API ) && !defined( Py_UNICODE_WIDE ) + // Need these c'tors becuase Py_UNICODE is 2 bytes + // User may use "int" or "unsigned int" as the unicode type + String( const unsigned int *s, int length ) + : SeqBase( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, reinterpret_cast( s ), length ), true ) + { + validate(); + } + + String( const int *s, int length ) + : SeqBase( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, reinterpret_cast( s ), length ), true ) + { + validate(); + } +#endif + +#if !defined( Py_LIMITED_API ) String( const Py_UNICODE *s, int length ) : SeqBase( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, s, length ), true ) { validate(); } +#endif // Assignment acquires new ownership of pointer String &operator=( const Object &rhs ) @@ -2132,35 +2185,63 @@ namespace Py return *this; } +#if !defined( Py_LIMITED_API ) String &operator=( const unicodestring &v ) { set( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, const_cast( v.data() ), v.length() ), true ); return *this; } +#endif +#if !defined( Py_UNICODE_WIDE ) && !defined( Py_LIMITED_API ) + String &operator=( const ucs4string &v ) + { + set( PyUnicode_FromKindAndData( PyUnicode_4BYTE_KIND, reinterpret_cast( v.data() ), v.length() ), true ); + return *this; + } +#endif // Encode Bytes encode( const char *encoding, const char *error="strict" ) const { return Bytes( PyUnicode_AsEncodedString( ptr(), encoding, error ), true ); } +#if !defined( Py_LIMITED_API ) // Queries virtual size_type size() const { return PyUnicode_GetLength( ptr() ); } +#endif #if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9 +#if !defined( Py_LIMITED_API ) const Py_UNICODE *unicode_data() const { return PyUnicode_AS_UNICODE( ptr() ); } +#endif +#if !defined( Py_LIMITED_API ) unicodestring as_unicodestring() const { return unicodestring( unicode_data(), PyUnicode_GetLength( ptr() ) ); } #endif +#endif + + ucs4string as_ucs4string() const + { + Py_UCS4 *buf = new Py_UCS4[ size() ]; + if( PyUnicode_AsUCS4( ptr(), buf, size(), 0 ) == NULL ) + { + ifPyErrorThrowCxxException(); + } + ucs4string ucs4( buf, size() ); + delete[] buf; + + return ucs4; + } operator std::string() const { @@ -2185,7 +2266,7 @@ namespace Py // note PyTuple_SetItem is a thief... if( PyTuple_SetItem( ptr(), offset, new_reference_to( ob ) ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2211,7 +2292,7 @@ namespace Py { if( PyTuple_SetItem( ptr(), i, new_reference_to( Py::_None() ) ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } } @@ -2227,7 +2308,7 @@ namespace Py { if( PyTuple_SetItem( ptr(), i, new_reference_to( s[i] ) ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } } @@ -2394,7 +2475,7 @@ namespace Py { if( PyList_SetItem( ptr(), i, new_reference_to( Py::_None() ) ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } } @@ -2410,7 +2491,7 @@ namespace Py { if( PyList_SetItem( ptr(), i, new_reference_to( s[i] ) ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } } @@ -2448,7 +2529,7 @@ namespace Py { if( PyList_SetSlice( ptr(), i, j, *v ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2456,7 +2537,7 @@ namespace Py { if( PyList_Append( ptr(), *ob ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2469,7 +2550,7 @@ namespace Py { if( PyList_Insert( ptr(), i, *ob ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2477,7 +2558,7 @@ namespace Py { if( PyList_Sort( ptr() ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2485,7 +2566,7 @@ namespace Py { if( PyList_Reverse( ptr() ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } }; @@ -2683,7 +2764,7 @@ namespace Py // If you assume that Python mapping is a hash_map... // hash_map::value_type is not assignable, but //( *it ).second = data must be a valid expression - typedef Py_ssize_t size_type; + typedef PyCxx_ssize_t size_type; typedef Object key_type; typedef mapref data_type; typedef std::pair< const T, T > value_type; @@ -2735,7 +2816,7 @@ namespace Py } } - virtual size_type size() const + virtual Py_ssize_t size() const { return PyMapping_Length( ptr() ); } @@ -2766,7 +2847,7 @@ namespace Py return mapref( *this, key ); } - size_type length() const + Py_ssize_t length() const { return PyMapping_Length( ptr() ); } @@ -2783,7 +2864,7 @@ namespace Py T getItem( const std::string &s ) const { - return T( asObject( PyMapping_GetItemString( ptr(),const_cast( s.c_str() ) ) ) ); + return T( asObject( PyMapping_GetItemString( ptr(), const_cast( s.c_str() ) ) ) ); } T getItem( const Object &s ) const @@ -2795,7 +2876,7 @@ namespace Py { if( PyMapping_SetItemString( ptr(), const_cast( s ), *ob ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2803,7 +2884,7 @@ namespace Py { if( PyMapping_SetItemString( ptr(), const_cast( s.c_str() ), *ob ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2811,7 +2892,7 @@ namespace Py { if( PyObject_SetItem( ptr(), s.ptr(), ob.ptr() ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2819,7 +2900,7 @@ namespace Py { if( PyMapping_DelItemString( ptr(), const_cast( s.c_str() ) ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2827,7 +2908,7 @@ namespace Py { if( PyMapping_DelItem( ptr(), *s ) == -1 ) { - throw Exception(); + ifPyErrorThrowCxxException(); } } @@ -2860,9 +2941,9 @@ namespace Py friend class MapBase; // - MapBase *map; - List keys; // for iterating over the map - size_type pos; // index into the keys + MapBase *map; + List keys; // for iterating over the map + sequence_index_type pos; // index into the keys public: ~iterator() @@ -2945,7 +3026,7 @@ namespace Py // postfix -- iterator operator--( int ) - { + { return iterator( map, keys, pos-- ); } @@ -2979,7 +3060,7 @@ namespace Py friend class MapBase; const MapBase *map; List keys; // for iterating over the map - size_type pos; // index into the keys + Py_ssize_t pos; // index into the keys public: ~const_iterator() @@ -2991,7 +3072,7 @@ namespace Py , pos() {} - const_iterator( const MapBase *m, List k, size_type p ) + const_iterator( const MapBase *m, List k, Py_ssize_t p ) : map( m ) , keys( k ) , pos( p ) @@ -3180,7 +3261,7 @@ namespace Py PyObject *result = PyObject_CallObject( ptr(), args.ptr() ); if( result == NULL ) { - throw Exception(); + ifPyErrorThrowCxxException(); } return asObject( result ); } @@ -3195,11 +3276,11 @@ namespace Py #endif if( result == NULL ) { - throw Exception(); + ifPyErrorThrowCxxException(); } return asObject( result ); } -#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 9 +#if (!defined( Py_LIMITED_API ) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 9) || (defined( Py_LIMITED_API ) && Py_LIMITED_API+0 >= 0x03090000) Object apply() const { PyObject *result = PyObject_CallNoArgs( ptr() ); @@ -3458,7 +3539,7 @@ namespace Py //------------------------------------------------------------ // type - inline Object type( const Exception &) // return the type of the error + inline Object type( const BaseException & ) // return the type of the error { PyObject *ptype, *pvalue, *ptrace; PyErr_Fetch( &ptype, &pvalue, &ptrace ); @@ -3469,7 +3550,7 @@ namespace Py return result; } - inline Object value( const Exception &) // return the value of the error + inline Object value( const BaseException & ) // return the value of the error { PyObject *ptype, *pvalue, *ptrace; PyErr_Fetch( &ptype, &pvalue, &ptrace ); @@ -3480,7 +3561,7 @@ namespace Py return result; } - inline Object trace( const Exception &) // return the traceback of the error + inline Object trace( const BaseException & ) // return the traceback of the error { PyObject *ptype, *pvalue, *ptrace; PyErr_Fetch( &ptype, &pvalue, &ptrace ); diff --git a/src/CXX/Python3/PythonType.hxx b/src/CXX/Python3/PythonType.hxx index c3b1551e16..b2bd2a32d0 100644 --- a/src/CXX/Python3/PythonType.hxx +++ b/src/CXX/Python3/PythonType.hxx @@ -38,12 +38,16 @@ #ifndef __CXX_PythonType__h #define __CXX_PythonType__h +#if defined( Py_LIMITED_API ) +#include +#endif + namespace Py { class PYCXX_EXPORT PythonType { public: - // if you define one sequence method you must define + // if you define one sequence method you must define // all of them except the assigns PythonType( size_t base_size, int itemsize, const char *default_name ); @@ -57,7 +61,7 @@ namespace Py PythonType &doc( const char *d ); PythonType &supportClass( void ); -#ifdef PYCXX_PYTHON_2TO3 +#if defined( PYCXX_PYTHON_2TO3 ) && !defined( Py_LIMITED_API ) && PY_MINOR_VERSION <= 7 PythonType &supportPrint( void ); #endif PythonType &supportGetattr( void ); @@ -72,12 +76,122 @@ namespace Py PythonType &supportStr( void ); PythonType &supportHash( void ); PythonType &supportCall( void ); - PythonType &supportIter( void ); - PythonType &supportSequenceType( void ); - PythonType &supportMappingType( void ); - PythonType &supportNumberType( void ); - PythonType &supportBufferType( void ); +#define B( n ) (1<<(n)) + enum { + support_iter_iter = B(0), + support_iter_iternext = B(1) + }; + PythonType &supportIter( int methods_to_support= + support_iter_iter | + support_iter_iternext ); + + enum { + support_sequence_length = B(0), + support_sequence_repeat = B(1), + support_sequence_item = B(2), + support_sequence_slice = B(3), + support_sequence_concat = B(4), + support_sequence_ass_item = B(5), + support_sequence_ass_slice = B(6), + support_sequence_inplace_concat = B(7), + support_sequence_inplace_repeat = B(8), + support_sequence_contains = B(9) + }; + PythonType &supportSequenceType( int methods_to_support= + support_sequence_length | + support_sequence_repeat | + support_sequence_item | + support_sequence_slice | + support_sequence_concat + ); + + enum { + support_mapping_length = B(0), + support_mapping_subscript = B(1), + support_mapping_ass_subscript = B(2) + }; + PythonType &supportMappingType( int methods_to_support= + support_mapping_length | + support_mapping_subscript + ); + + enum { + support_number_add = B(0), + support_number_subtract = B(1), + support_number_multiply = B(2), + support_number_remainder = B(3), + support_number_divmod = B(4), + support_number_power = B(5), + support_number_negative = B(6), + support_number_positive = B(7), + support_number_absolute = B(8), + support_number_invert = B(9), + support_number_lshift = B(10), + support_number_rshift = B(11), + support_number_and = B(12), + support_number_xor = B(13), + support_number_or = B(14), + support_number_int = B(15), + support_number_float = B(16), + support_number_floor_divide = B(17), + support_number_true_divide = B(18), + support_number_index = B(19), +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + support_number_matrix_multiply = B(20), +#endif + + // start a new bit mask for inplace that avoid using more then 32 bits in methods_to_support + support_number_inplace_floor_divide = B(0), + support_number_inplace_true_divide = B(1), + support_number_inplace_add = B(2), + support_number_inplace_subtract = B(3), + support_number_inplace_multiply = B(4), + support_number_inplace_remainder = B(5), + support_number_inplace_power = B(6), + support_number_inplace_lshift = B(7), + support_number_inplace_rshift = B(8), + support_number_inplace_and = B(9), + support_number_inplace_xor = B(10), + support_number_inplace_or = B(11) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + , + support_number_inplace_matrix_multiply = B(12) +#endif + }; + PythonType &supportNumberType( + int methods_to_support= + support_number_add | + support_number_subtract | + support_number_multiply | + support_number_remainder | + support_number_divmod | + support_number_power | + support_number_negative | + support_number_positive | + support_number_absolute | + support_number_invert | + support_number_lshift | + support_number_rshift | + support_number_and | + support_number_xor | + support_number_or | + support_number_int | + support_number_float, + int inplace_methods_to_support=0 + ); + +#if !defined( Py_LIMITED_API ) + enum { + support_buffer_getbuffer = B(0), + support_buffer_releasebuffer = B(1) + }; + PythonType &supportBufferType( int methods_to_support= + support_buffer_getbuffer | + support_buffer_releasebuffer + ); +#endif +#undef B PythonType &set_tp_dealloc( void (*tp_dealloc)( PyObject * ) ); PythonType &set_tp_init( int (*tp_init)( PyObject *self, PyObject *args, PyObject *kwds ) ); @@ -88,16 +202,17 @@ namespace Py bool readyType(); protected: - void init_sequence(); - void init_mapping(); - void init_number(); - void init_buffer(); - +#if defined( Py_LIMITED_API ) + std::unordered_map slots; + PyType_Spec *spec; + PyTypeObject *tp_object; +#else PyTypeObject *table; PySequenceMethods *sequence_table; PyMappingMethods *mapping_table; PyNumberMethods *number_table; PyBufferProcs *buffer_table; +#endif private: // diff --git a/src/CXX/Python3/cxx_exceptions.cxx b/src/CXX/Python3/cxx_exceptions.cxx new file mode 100644 index 0000000000..906133ac48 --- /dev/null +++ b/src/CXX/Python3/cxx_exceptions.cxx @@ -0,0 +1,72 @@ +// +// cxx_exceptions.cxx +// +#include +#include + +#include + +namespace Py +{ +typedef void (*throw_exception_func_t)( void ); + +std::map py_exc_type_to_exc_func; + +void addPythonException( ExtensionExceptionType &py_exc_type, throw_exception_func_t func ) +{ + py_exc_type_to_exc_func.insert( std::make_pair( py_exc_type.ptr(), func ) ); +} + +void addPythonException( PyObject *py_exc_type, throw_exception_func_t func ) +{ + py_exc_type_to_exc_func.insert( std::make_pair( py_exc_type, func ) ); +} + +void ifPyErrorThrowCxxException() +{ + if( PyErr_Occurred() ) + { + PyObject *ptype, *pvalue, *ptrace; + PyErr_Fetch( &ptype, &pvalue, &ptrace ); + PyErr_Restore( ptype, pvalue, ptrace ); + + Object q( ptype ); + + std::map::iterator func = py_exc_type_to_exc_func.find( ptype ); + if( func != py_exc_type_to_exc_func.end() ) + { +#ifdef PYCXX_DEBUG + std::cout << "ifPyErrorThrowCxxException found throwFunc: " << q << std::endl; +#endif + (func->second)(); + } + else + { +#ifdef PYCXX_DEBUG + std::cout << "ifPyErrorThrowCxxException no throwFunc: " << q << std::endl; +#endif + throw Exception(); + } + } +} + +void initExceptions() +{ + static bool init_done = false; + if( init_done ) + { + return; + } + +#define PYCXX_STANDARD_EXCEPTION( eclass, bclass ) \ + addPythonException( eclass::exceptionType(), eclass::throwFunc ); + +#include + +#undef PYCXX_STANDARD_EXCEPTION + + init_done = true; +} + + +} // end of namespace Py diff --git a/src/CXX/Python3/cxx_extensions.cxx b/src/CXX/Python3/cxx_extensions.cxx index 00527d059e..7371810be4 100644 --- a/src/CXX/Python3/cxx_extensions.cxx +++ b/src/CXX/Python3/cxx_extensions.cxx @@ -36,6 +36,7 @@ //----------------------------------------------------------------------------- #include "CXX/Extensions.hxx" #include "CXX/Exception.hxx" +#include "CXX/Objects.hxx" #include @@ -49,7 +50,7 @@ void bpt( void ) void printRefCount( PyObject *obj ) { - std::cout << "RefCount of 0x" << std::hex << reinterpret_cast< unsigned int >( obj ) << std::dec << " is " << Py_REFCNT( obj ) << std::endl; + std::cout << "RefCount of 0x" << std::hex << reinterpret_cast< unsigned long >( obj ) << std::dec << " is " << Py_REFCNT( obj ) << std::endl; } #endif @@ -77,10 +78,10 @@ void Object::validate() } #endif release(); - if( PyErr_Occurred() ) - { // Error message already set - throw Exception(); - } + + // If error message already set + ifPyErrorThrowCxxException(); + // Better error message if RTTI available #if defined( _CPPRTTI ) || defined( __GNUG__ ) throw TypeError( s ); @@ -151,7 +152,11 @@ PyMethodDef *MethodTable::table() //================================================================================ ExtensionModuleBase::ExtensionModuleBase( const char *name ) : m_module_name( name ) +#if defined( Py_LIMITED_API ) +, m_full_module_name( m_module_name ) +#else , m_full_module_name( __Py_PackageContext() != NULL ? std::string( __Py_PackageContext() ) : m_module_name ) +#endif , m_method_table() //m_module_def , m_module( NULL ) @@ -183,8 +188,13 @@ public: ExtensionModuleBase *module; }; +void initExceptions(); + void ExtensionModuleBase::initialize( const char *module_doc ) { + // init the exception code + initExceptions(); + memset( &m_module_def, 0, sizeof( m_module_def ) ); m_module_def.m_name = const_cast( m_module_name.c_str() ); @@ -195,12 +205,12 @@ void ExtensionModuleBase::initialize( const char *module_doc ) m_module = PyModule_Create( &m_module_def ); } -Py::Module ExtensionModuleBase::module( void ) const +Module ExtensionModuleBase::module( void ) const { return Module( m_module ); } -Py::Dict ExtensionModuleBase::moduleDictionary( void ) const +Dict ExtensionModuleBase::moduleDictionary( void ) const { return module().getDict(); } @@ -244,6 +254,11 @@ extern "C" static PyObject *sequence_item_handler( PyObject *, Py_ssize_t ); static int sequence_ass_item_handler( PyObject *, Py_ssize_t, PyObject * ); + static PyObject *sequence_inplace_concat_handler( PyObject *, PyObject * ); + static PyObject *sequence_inplace_repeat_handler( PyObject *, Py_ssize_t ); + + static int sequence_contains_handler( PyObject *, PyObject * ); + // Mapping static Py_ssize_t mapping_length_handler( PyObject * ); static PyObject *mapping_subscript_handler( PyObject *, PyObject * ); @@ -267,10 +282,34 @@ extern "C" static PyObject *number_xor_handler( PyObject *, PyObject * ); static PyObject *number_or_handler( PyObject *, PyObject * ); static PyObject *number_power_handler( PyObject *, PyObject *, PyObject * ); + static PyObject *number_floor_divide_handler( PyObject *, PyObject * ); + static PyObject *number_true_divide_handler( PyObject *, PyObject * ); + static PyObject *number_index_handler( PyObject * ); +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + static PyObject *number_matrix_multiply_handler( PyObject *, PyObject * ); +#endif + + static PyObject *number_inplace_add_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_subtract_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_multiply_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_remainder_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_power_handler( PyObject *, PyObject *, PyObject * ); + static PyObject *number_inplace_lshift_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_rshift_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_and_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_xor_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_or_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_floor_divide_handler( PyObject *, PyObject * ); + static PyObject *number_inplace_true_divide_handler( PyObject *, PyObject * ); +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + static PyObject *number_inplace_matrix_multiply_handler( PyObject *, PyObject * ); +#endif // Buffer +#if !defined( Py_LIMITED_API ) static int buffer_get_handler( PyObject *, Py_buffer *, int ); static void buffer_release_handler( PyObject *, Py_buffer * ); +#endif } extern "C" void standard_dealloc( PyObject *p ) @@ -280,88 +319,213 @@ extern "C" void standard_dealloc( PyObject *p ) bool PythonType::readyType() { +#if defined( Py_LIMITED_API ) + if( !tp_object ) + { + std::vector spec_slots( slots.size() + 1 ); + int index = 0; + + for (std::unordered_map::const_iterator i = slots.cbegin(); i != slots.cend(); i++) + { + spec_slots[ index ].slot = i->first; + spec_slots[ index ].pfunc = i->second; + index++; + } + spec_slots[ index ].slot = 0; + spec->slots = spec_slots.data(); + tp_object = reinterpret_cast( PyType_FromSpec(spec) ); + } + return tp_object != NULL; +#else return PyType_Ready( table ) >= 0; +#endif } -PythonType &PythonType::supportSequenceType() -{ - if( !sequence_table ) - { - sequence_table = new PySequenceMethods; - memset( sequence_table, 0, sizeof( PySequenceMethods ) ); // ensure new fields are 0 - table->tp_as_sequence = sequence_table; - sequence_table->sq_length = sequence_length_handler; - sequence_table->sq_concat = sequence_concat_handler; - sequence_table->sq_repeat = sequence_repeat_handler; - sequence_table->sq_item = sequence_item_handler; - - sequence_table->sq_ass_item = sequence_ass_item_handler; // BAS setup separately? - // QQQ sq_inplace_concat - // QQQ sq_inplace_repeat +#if defined( Py_LIMITED_API ) +#define FILL_SEQUENCE_SLOT(slot) \ + if( methods_to_support&support_sequence_ ## slot ) { \ + slots[ Py_sq_ ## slot ] = reinterpret_cast( sequence_ ## slot ## _handler ); \ } +#else +#define FILL_SEQUENCE_SLOT(slot) \ + if( methods_to_support&support_sequence_ ## slot ) { \ + sequence_table->sq_ ## slot = sequence_ ## slot ## _handler; \ + } +#endif + +PythonType &PythonType::supportSequenceType( int methods_to_support ) { +#if !defined( Py_LIMITED_API ) + if(sequence_table) + { + return *this; + } + sequence_table = new PySequenceMethods; + memset( sequence_table, 0, sizeof( PySequenceMethods ) ); // ensure new fields are 0 + table->tp_as_sequence = sequence_table; +#endif + + FILL_SEQUENCE_SLOT(length) + FILL_SEQUENCE_SLOT(concat) + FILL_SEQUENCE_SLOT(repeat) + FILL_SEQUENCE_SLOT(item) + FILL_SEQUENCE_SLOT(ass_item) + FILL_SEQUENCE_SLOT(inplace_concat) + FILL_SEQUENCE_SLOT(inplace_repeat) + FILL_SEQUENCE_SLOT(contains) return *this; } -PythonType &PythonType::supportMappingType() -{ - if( !mapping_table ) - { - mapping_table = new PyMappingMethods; - memset( mapping_table, 0, sizeof( PyMappingMethods ) ); // ensure new fields are 0 - table->tp_as_mapping = mapping_table; - mapping_table->mp_length = mapping_length_handler; - mapping_table->mp_subscript = mapping_subscript_handler; - mapping_table->mp_ass_subscript = mapping_ass_subscript_handler; // BAS setup separately? +#undef FILL_SEQUENCE_SLOT + +#if defined( Py_LIMITED_API ) +#define FILL_MAPPING_SLOT(slot) \ + if( methods_to_support&support_mapping_ ## slot ) { \ + slots[ Py_mp_ ## slot ] = reinterpret_cast( mapping_ ## slot ## _handler ); \ } +#else +#define FILL_MAPPING_SLOT(slot) \ + if( methods_to_support&support_mapping_ ## slot ) { \ + mapping_table->mp_ ## slot = mapping_ ## slot ## _handler; \ + } +#endif + +PythonType &PythonType::supportMappingType( int methods_to_support ) +{ +#if !defined( Py_LIMITED_API ) + if( mapping_table ) + { + return *this; + } + mapping_table = new PyMappingMethods; + memset( mapping_table, 0, sizeof( PyMappingMethods ) ); // ensure new fields are 0 + table->tp_as_mapping = mapping_table; +#endif + FILL_MAPPING_SLOT(length) + FILL_MAPPING_SLOT(subscript) + FILL_MAPPING_SLOT(ass_subscript) return *this; } -PythonType &PythonType::supportNumberType() -{ - if( !number_table ) - { - number_table = new PyNumberMethods; - memset( number_table, 0, sizeof( PyNumberMethods ) ); // ensure new fields are 0 - table->tp_as_number = number_table; - number_table->nb_add = number_add_handler; - number_table->nb_subtract = number_subtract_handler; - number_table->nb_multiply = number_multiply_handler; - number_table->nb_remainder = number_remainder_handler; - number_table->nb_divmod = number_divmod_handler; - number_table->nb_power = number_power_handler; - number_table->nb_negative = number_negative_handler; - number_table->nb_positive = number_positive_handler; - number_table->nb_absolute = number_absolute_handler; - number_table->nb_invert = number_invert_handler; - number_table->nb_lshift = number_lshift_handler; - number_table->nb_rshift = number_rshift_handler; - number_table->nb_and = number_and_handler; - number_table->nb_xor = number_xor_handler; - number_table->nb_or = number_or_handler; - number_table->nb_int = number_int_handler; - number_table->nb_float = number_float_handler; +#undef FILL_MAPPING_SLOT - // QQQ lots of new methods to add +#if defined( Py_LIMITED_API ) +#define FILL_NUMBER_SLOT(slot) \ + if( methods_to_support&support_number_ ## slot ) { \ + slots[ Py_nb_ ## slot ] = reinterpret_cast( number_ ## slot ## _handler ); \ } +#define FILL_NUMBER_INPLACE_SLOT(slot) \ + if( inplace_methods_to_support&support_number_ ## slot ) { \ + slots[ Py_nb_ ## slot ] = reinterpret_cast( number_ ## slot ## _handler ); \ + } +#else +#define FILL_NUMBER_SLOT(slot) \ + if( methods_to_support&support_number_ ## slot ) { \ + number_table->nb_ ## slot = number_ ## slot ## _handler; \ + } +#define FILL_NUMBER_INPLACE_SLOT(slot) \ + if( inplace_methods_to_support&support_number_ ## slot ) { \ + number_table->nb_ ## slot = number_ ## slot ## _handler; \ + } +#endif + +PythonType &PythonType::supportNumberType( int methods_to_support, int inplace_methods_to_support ) +{ +#if !defined( Py_LIMITED_API ) + if( number_table ) + { + return *this; + } + number_table = new PyNumberMethods; + memset( number_table, 0, sizeof( PyNumberMethods ) ); // ensure new fields are 0 + table->tp_as_number = number_table; +#endif + + FILL_NUMBER_SLOT(add) + FILL_NUMBER_SLOT(subtract) + FILL_NUMBER_SLOT(multiply) + FILL_NUMBER_SLOT(remainder) + FILL_NUMBER_SLOT(divmod) + FILL_NUMBER_SLOT(power) + FILL_NUMBER_SLOT(negative) + FILL_NUMBER_SLOT(positive) + FILL_NUMBER_SLOT(absolute) + FILL_NUMBER_SLOT(invert) + FILL_NUMBER_SLOT(lshift) + FILL_NUMBER_SLOT(rshift) + FILL_NUMBER_SLOT(and) + FILL_NUMBER_SLOT(xor) + FILL_NUMBER_SLOT(or) + FILL_NUMBER_SLOT(int) + FILL_NUMBER_SLOT(float) + FILL_NUMBER_SLOT(floor_divide) + FILL_NUMBER_SLOT(true_divide) + FILL_NUMBER_SLOT(index) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + FILL_NUMBER_SLOT(matrix_multiply) +#endif + + FILL_NUMBER_INPLACE_SLOT(inplace_add) + FILL_NUMBER_INPLACE_SLOT(inplace_subtract) + FILL_NUMBER_INPLACE_SLOT(inplace_multiply) + FILL_NUMBER_INPLACE_SLOT(inplace_remainder) + FILL_NUMBER_INPLACE_SLOT(inplace_power) + FILL_NUMBER_INPLACE_SLOT(inplace_lshift) + FILL_NUMBER_INPLACE_SLOT(inplace_rshift) + FILL_NUMBER_INPLACE_SLOT(inplace_and) + FILL_NUMBER_INPLACE_SLOT(inplace_xor) + FILL_NUMBER_INPLACE_SLOT(inplace_or) + FILL_NUMBER_INPLACE_SLOT(inplace_floor_divide) + FILL_NUMBER_INPLACE_SLOT(inplace_true_divide) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 + FILL_NUMBER_INPLACE_SLOT(inplace_matrix_multiply) +#endif + return *this; } -PythonType &PythonType::supportBufferType() +#undef FILL_NUMBER_SLOT + +#if !defined( Py_LIMITED_API ) +PythonType &PythonType::supportBufferType( int methods_to_support ) { if( !buffer_table ) { buffer_table = new PyBufferProcs; memset( buffer_table, 0, sizeof( PyBufferProcs ) ); // ensure new fields are 0 table->tp_as_buffer = buffer_table; - buffer_table->bf_getbuffer = buffer_get_handler; - buffer_table->bf_releasebuffer = buffer_release_handler; + + if( methods_to_support&support_buffer_getbuffer ) + { + buffer_table->bf_getbuffer = buffer_get_handler; + } + if( methods_to_support&support_buffer_releasebuffer ) + { + buffer_table->bf_releasebuffer = buffer_release_handler; + } } return *this; } +#endif // if you define one sequence method you must define // all of them except the assigns +#if defined( Py_LIMITED_API ) +PythonType::PythonType( size_t basic_size, int itemsize, const char *default_name ) +: spec( new PyType_Spec ) +{ + memset( spec, 0, sizeof( PyType_Spec ) ); + spec->name = const_cast( default_name ); + spec->basicsize = basic_size; + spec->itemsize = itemsize; + spec->flags = Py_TPFLAGS_DEFAULT; + + slots[ Py_tp_dealloc ] = reinterpret_cast( standard_dealloc ); + + tp_object = 0; +} + +#else PythonType::PythonType( size_t basic_size, int itemsize, const char *default_name ) : table( new PyTypeObject ) , sequence_table( NULL ) @@ -458,74 +622,126 @@ PythonType::PythonType( size_t basic_size, int itemsize, const char *default_nam table->tp_next = 0; #endif } +#endif PythonType::~PythonType() { +#if defined( Py_LIMITED_API ) + delete spec; + PyObject_Free( tp_object ); +#else delete table; delete sequence_table; delete mapping_table; delete number_table; delete buffer_table; +#endif } PyTypeObject *PythonType::type_object() const { +#if defined( Py_LIMITED_API ) + return tp_object; +#else return table; +#endif } PythonType &PythonType::name( const char *nam ) { +#if defined( Py_LIMITED_API ) + spec->name = nam; +#else table->tp_name = const_cast( nam ); +#endif return *this; } const char *PythonType::getName() const { +#if defined( Py_LIMITED_API ) + return spec->name; +#else return table->tp_name; +#endif } PythonType &PythonType::doc( const char *d ) { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_doc ] = reinterpret_cast( const_cast( d ) ); +#else table->tp_doc = const_cast( d ); +#endif return *this; } const char *PythonType::getDoc() const { +#if defined( Py_LIMITED_API ) + if( tp_object ) + return reinterpret_cast( PyType_GetSlot( tp_object, Py_tp_doc ) ); + + std::unordered_map::const_iterator slot = slots.find( Py_tp_doc ); + if( slot == slots.end() ) + return NULL; + return reinterpret_cast( slot->second ); +#else return table->tp_doc; +#endif } PythonType &PythonType::set_tp_dealloc( void (*tp_dealloc)( PyObject *self ) ) { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_dealloc ] = reinterpret_cast( tp_dealloc ); +#else table->tp_dealloc = tp_dealloc; +#endif return *this; } PythonType &PythonType::set_tp_init( int (*tp_init)( PyObject *self, PyObject *args, PyObject *kwds ) ) { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_init ] = reinterpret_cast( tp_init ); +#else table->tp_init = tp_init; +#endif return *this; } PythonType &PythonType::set_tp_new( PyObject *(*tp_new)( PyTypeObject *subtype, PyObject *args, PyObject *kwds ) ) { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_new ] = reinterpret_cast( tp_new ); +#else table->tp_new = tp_new; +#endif return *this; } PythonType &PythonType::set_methods( PyMethodDef *methods ) { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_methods ] = reinterpret_cast( methods ); +#else table->tp_methods = methods; +#endif return *this; } PythonType &PythonType::supportClass() { +#if defined( Py_LIMITED_API ) + spec->flags |= Py_TPFLAGS_BASETYPE; +#else table->tp_flags |= Py_TPFLAGS_BASETYPE; +#endif return *this; } -#ifdef PYCXX_PYTHON_2TO3 +#if defined( PYCXX_PYTHON_2TO3 ) && !defined( Py_LIMITED_API ) && PY_MINOR_VERSION <= 7 PythonType &PythonType::supportPrint() { #if PY_VERSION_HEX < 0x03080000 @@ -537,25 +753,41 @@ PythonType &PythonType::supportPrint() PythonType &PythonType::supportGetattr() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_getattr ] = reinterpret_cast( getattr_handler ); +#else table->tp_getattr = getattr_handler; +#endif return *this; } PythonType &PythonType::supportSetattr() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_setattr ] = reinterpret_cast( setattr_handler ); +#else table->tp_setattr = setattr_handler; +#endif return *this; } PythonType &PythonType::supportGetattro() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_getattro ] = reinterpret_cast( getattro_handler ); +#else table->tp_getattro = getattro_handler; +#endif return *this; } PythonType &PythonType::supportSetattro() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_setattro ] = reinterpret_cast( setattro_handler ); +#else table->tp_setattro = setattro_handler; +#endif return *this; } @@ -569,38 +801,72 @@ PythonType &PythonType::supportCompare( void ) PythonType &PythonType::supportRichCompare() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_richcompare ] = reinterpret_cast( rich_compare_handler ); +#else table->tp_richcompare = rich_compare_handler; +#endif return *this; } PythonType &PythonType::supportRepr() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_repr ] = reinterpret_cast( repr_handler ); +#else table->tp_repr = repr_handler; +#endif return *this; } PythonType &PythonType::supportStr() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_str ] = reinterpret_cast( str_handler ); +#else table->tp_str = str_handler; +#endif return *this; } PythonType &PythonType::supportHash() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_hash ] = reinterpret_cast( hash_handler ); +#else table->tp_hash = hash_handler; +#endif return *this; } PythonType &PythonType::supportCall() { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_call ] = reinterpret_cast( call_handler ); +#else table->tp_call = call_handler; +#endif return *this; } -PythonType &PythonType::supportIter() +PythonType &PythonType::supportIter( int methods_to_support ) { - table->tp_iter = iter_handler; - table->tp_iternext = iternext_handler; + if( methods_to_support&support_iter_iter ) + { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_iter ] = reinterpret_cast( iter_handler ); +#else + table->tp_iter = iter_handler; +#endif + } + if( methods_to_support&support_iter_iternext ) + { +#if defined( Py_LIMITED_API ) + slots[ Py_tp_iternext ] = reinterpret_cast( iternext_handler ); +#else + table->tp_iternext = iternext_handler; +#endif + } return *this; } @@ -611,7 +877,7 @@ PythonType &PythonType::supportIter() //-------------------------------------------------------------------------------- PythonExtensionBase *getPythonExtensionBase( PyObject *self ) { - if( self->ob_type->tp_flags&Py_TPFLAGS_BASETYPE ) + if(PyType_HasFeature(self->ob_type, Py_TPFLAGS_BASETYPE)) { PythonClassInstance *instance = reinterpret_cast( self ); return instance->m_pycxx_object; @@ -622,7 +888,7 @@ PythonExtensionBase *getPythonExtensionBase( PyObject *self ) } } -#if defined( PYCXX_PYTHON_2TO3 ) && !defined( Py_LIMITED_API ) && PY_MINOR_VERSION <= 7 +#if defined( PYCXX_PYTHON_2TO3 ) && !defined ( Py_LIMITED_API ) && PY_MINOR_VERSION <= 7 extern "C" int print_handler( PyObject *self, FILE *fp, int flags ) { try @@ -630,7 +896,7 @@ extern "C" int print_handler( PyObject *self, FILE *fp, int flags ) PythonExtensionBase *p = getPythonExtensionBase( self ); return p->print( fp, flags ); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -644,7 +910,7 @@ extern "C" PyObject *getattr_handler( PyObject *self, char *name ) PythonExtensionBase *p = getPythonExtensionBase( self ); return new_reference_to( p->getattr( name ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -655,9 +921,9 @@ extern "C" int setattr_handler( PyObject *self, char *name, PyObject *value ) try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->setattr( name, Py::Object( value ) ); + return p->setattr( name, Object( value ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -668,9 +934,9 @@ extern "C" PyObject *getattro_handler( PyObject *self, PyObject *name ) try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->getattro( Py::String( name ) ) ); + return new_reference_to( p->getattro( String( name ) ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -681,9 +947,9 @@ extern "C" int setattro_handler( PyObject *self, PyObject *name, PyObject *value try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->setattro( Py::String( name ), Py::Object( value ) ); + return p->setattro( String( name ), Object( value ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -694,9 +960,9 @@ extern "C" PyObject *rich_compare_handler( PyObject *self, PyObject *other, int try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->rich_compare( Py::Object( other ), op ) ); + return new_reference_to( p->rich_compare( Object( other ), op ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -709,7 +975,7 @@ extern "C" PyObject *repr_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return new_reference_to( p->repr() ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -722,7 +988,7 @@ extern "C" PyObject *str_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return new_reference_to( p->str() ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -735,7 +1001,7 @@ extern "C" Py_hash_t hash_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return p->hash(); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -747,11 +1013,11 @@ extern "C" PyObject *call_handler( PyObject *self, PyObject *args, PyObject *kw { PythonExtensionBase *p = getPythonExtensionBase( self ); if( kw != NULL ) - return new_reference_to( p->call( Py::Object( args ), Py::Object( kw ) ) ); + return new_reference_to( p->call( Object( args ), Object( kw ) ) ); else - return new_reference_to( p->call( Py::Object( args ), Py::Object() ) ); + return new_reference_to( p->call( Object( args ), Object() ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -764,7 +1030,7 @@ extern "C" PyObject *iter_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return new_reference_to( p->iter() ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -777,7 +1043,7 @@ extern "C" PyObject *iternext_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return p->iternext(); // might be a NULL ptr on end of iteration } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -792,7 +1058,7 @@ extern "C" Py_ssize_t sequence_length_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return p->sequence_length(); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -803,9 +1069,9 @@ extern "C" PyObject *sequence_concat_handler( PyObject *self, PyObject *other ) try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->sequence_concat( Py::Object( other ) ) ); + return new_reference_to( p->sequence_concat( Object( other ) ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -818,7 +1084,7 @@ extern "C" PyObject *sequence_repeat_handler( PyObject *self, Py_ssize_t count ) PythonExtensionBase *p = getPythonExtensionBase( self ); return new_reference_to( p->sequence_repeat( count ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -831,7 +1097,7 @@ extern "C" PyObject *sequence_item_handler( PyObject *self, Py_ssize_t index ) PythonExtensionBase *p = getPythonExtensionBase( self ); return new_reference_to( p->sequence_item( index ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -842,9 +1108,48 @@ extern "C" int sequence_ass_item_handler( PyObject *self, Py_ssize_t index, PyOb try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->sequence_ass_item( index, Py::Object( value ) ); + return p->sequence_ass_item( index, Object( value ) ); } - catch( Py::Exception & ) + catch( BaseException & ) + { + return -1; // indicate error + } +} + +extern "C" PyObject *sequence_inplace_concat_handler( PyObject *self, PyObject *o2 ) +{ + try + { + PythonExtensionBase *p = getPythonExtensionBase( self ); + return new_reference_to( p->sequence_inplace_concat( Object( o2 ) ) ); + } + catch( BaseException & ) + { + return NULL; // indicate error + } +} + +extern "C" PyObject *sequence_inplace_repeat_handler( PyObject *self, Py_ssize_t count ) +{ + try + { + PythonExtensionBase *p = getPythonExtensionBase( self ); + return new_reference_to( p->sequence_inplace_repeat( count ) ); + } + catch( BaseException & ) + { + return NULL; // indicate error + } +} + +extern "C" int sequence_contains_handler( PyObject *self, PyObject *value ) +{ + try + { + PythonExtensionBase *p = getPythonExtensionBase( self ); + return p->sequence_contains( Object( value ) ); + } + catch( BaseException & ) { return -1; // indicate error } @@ -858,7 +1163,7 @@ extern "C" Py_ssize_t mapping_length_handler( PyObject *self ) PythonExtensionBase *p = getPythonExtensionBase( self ); return p->mapping_length(); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -869,9 +1174,9 @@ extern "C" PyObject *mapping_subscript_handler( PyObject *self, PyObject *key ) try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->mapping_subscript( Py::Object( key ) ) ); + return new_reference_to( p->mapping_subscript( Object( key ) ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return NULL; // indicate error } @@ -882,237 +1187,101 @@ extern "C" int mapping_ass_subscript_handler( PyObject *self, PyObject *key, PyO try { PythonExtensionBase *p = getPythonExtensionBase( self ); - return p->mapping_ass_subscript( Py::Object( key ), Py::Object( value ) ); + return p->mapping_ass_subscript( Object( key ), Object( value ) ); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } } // Number -extern "C" PyObject *number_negative_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_negative() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } +#define NUMBER_UNARY( slot ) \ +extern "C" PyObject *number_ ## slot ## _handler( PyObject *self ) \ +{ \ + try \ + { \ + PythonExtensionBase *p = getPythonExtensionBase( self ); \ + return new_reference_to( p->number_ ## slot() ); \ + } \ + catch( BaseException & ) \ + { \ + return NULL; /* indicates error */ \ + } \ } -extern "C" PyObject *number_positive_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_positive() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } +#define NUMBER_BINARY( slot ) \ +extern "C" PyObject *number_ ## slot ## _handler( PyObject *self, PyObject *other ) \ +{ \ + try \ + { \ + PythonExtensionBase *p = getPythonExtensionBase( self ); \ + return new_reference_to( p->number_ ## slot( Object( other ) ) ); \ + } \ + catch( BaseException & ) \ + { \ + return NULL; /* indicates error */ \ + } \ +} +#define NUMBER_TERNARY( slot ) \ +extern "C" PyObject *number_ ## slot ## _handler( PyObject *self, PyObject *other1, PyObject *other2 ) \ +{ \ + try \ + { \ + PythonExtensionBase *p = getPythonExtensionBase( self ); \ + return new_reference_to( p->number_ ## slot( Object( other1 ), Object( other2 ) ) ); \ + } \ + catch( BaseException & ) \ + { \ + return NULL; /* indicates error */ \ + } \ } -extern "C" PyObject *number_absolute_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_absolute() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} +NUMBER_UNARY( negative ) +NUMBER_UNARY( positive ) +NUMBER_UNARY( absolute ) +NUMBER_UNARY( invert ) +NUMBER_UNARY( int ) +NUMBER_UNARY( float ) +NUMBER_BINARY( add ) +NUMBER_BINARY( subtract ) +NUMBER_BINARY( multiply ) +NUMBER_BINARY( remainder ) +NUMBER_BINARY( divmod ) +NUMBER_BINARY( lshift ) +NUMBER_BINARY( rshift ) +NUMBER_BINARY( and ) +NUMBER_BINARY( xor ) +NUMBER_BINARY( or ) +NUMBER_TERNARY( power ) +NUMBER_BINARY( floor_divide ) +NUMBER_BINARY( true_divide ) +NUMBER_UNARY( index ) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 +NUMBER_BINARY( matrix_multiply ) +#endif +NUMBER_BINARY( inplace_add ) +NUMBER_BINARY( inplace_subtract ) +NUMBER_BINARY( inplace_multiply ) +NUMBER_BINARY( inplace_remainder ) +NUMBER_TERNARY( inplace_power ) +NUMBER_BINARY( inplace_lshift ) +NUMBER_BINARY( inplace_rshift ) +NUMBER_BINARY( inplace_and ) +NUMBER_BINARY( inplace_xor ) +NUMBER_BINARY( inplace_or ) +NUMBER_BINARY( inplace_floor_divide ) +NUMBER_BINARY( inplace_true_divide ) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 +NUMBER_BINARY( inplace_matrix_multiply ) +#endif -extern "C" PyObject *number_invert_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_invert() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_int_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_int() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_float_handler( PyObject *self ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_float() ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_add_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_add( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_subtract_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_subtract( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_multiply_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_multiply( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_remainder_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_remainder( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_divmod_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_divmod( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_lshift_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_lshift( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_rshift_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_rshift( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_and_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_and( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_xor_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_xor( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_or_handler( PyObject *self, PyObject *other ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_or( Py::Object( other ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} - -extern "C" PyObject *number_power_handler( PyObject *self, PyObject *x1, PyObject *x2 ) -{ - try - { - PythonExtensionBase *p = getPythonExtensionBase( self ); - return new_reference_to( p->number_power( Py::Object( x1 ), Py::Object( x2 ) ) ); - } - catch( Py::Exception & ) - { - return NULL; // indicate error - } -} +#undef NUMBER_UNARY +#undef NUMBER_BINARY +#undef NUMBER_TERNARY // Buffer +#ifndef Py_LIMITED_API extern "C" int buffer_get_handler( PyObject *self, Py_buffer *buf, int flags ) { try @@ -1120,7 +1289,7 @@ extern "C" int buffer_get_handler( PyObject *self, Py_buffer *buf, int flags ) PythonExtensionBase *p = getPythonExtensionBase( self ); return p->buffer_get( buf, flags ); } - catch( Py::Exception & ) + catch( BaseException & ) { return -1; // indicate error } @@ -1132,6 +1301,7 @@ extern "C" void buffer_release_handler( PyObject *self, Py_buffer *buf ) p->buffer_release( buf ); // NOTE: No way to indicate error to Python } +#endif //================================================================================ // @@ -1151,81 +1321,81 @@ PythonExtensionBase::~PythonExtensionBase() assert( ob_refcnt == 0 ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name ) { - Py::TupleN args; + TupleN args; return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1 ) { - Py::TupleN args( arg1 ); + TupleN args( arg1 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2 ) { - Py::TupleN args( arg1, arg2 ); + TupleN args( arg1, arg2 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3 ) { - Py::TupleN args( arg1, arg2, arg3 ); + TupleN args( arg1, arg2, arg3 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3, + const Object &arg4 ) { - Py::TupleN args( arg1, arg2, arg3, arg4 ); + TupleN args( arg1, arg2, arg3, arg4 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3, + const Object &arg4, const Object &arg5 ) { - Py::TupleN args( arg1, arg2, arg3, arg4, arg5 ); + TupleN args( arg1, arg2, arg3, arg4, arg5 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3, + const Object &arg4, const Object &arg5, const Object &arg6 ) { - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6 ); + TupleN args( arg1, arg2, arg3, arg4, arg5, arg6 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3, + const Object &arg4, const Object &arg5, const Object &arg6, + const Object &arg7 ) { - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7 ); + TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7, const Py::Object &arg8 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3, + const Object &arg4, const Object &arg5, const Object &arg6, + const Object &arg7, const Object &arg8 ) { - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 ); + TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 ); return self().callMemberFunction( fn_name, args ); } -Py::Object PythonExtensionBase::callOnSelf( const std::string &fn_name, - const Py::Object &arg1, const Py::Object &arg2, const Py::Object &arg3, - const Py::Object &arg4, const Py::Object &arg5, const Py::Object &arg6, - const Py::Object &arg7, const Py::Object &arg8, const Py::Object &arg9 ) +Object PythonExtensionBase::callOnSelf( const std::string &fn_name, + const Object &arg1, const Object &arg2, const Object &arg3, + const Object &arg4, const Object &arg5, const Object &arg6, + const Object &arg7, const Object &arg8, const Object &arg9 ) { - Py::TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 ); + TupleN args( arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 ); return self().callMemberFunction( fn_name, args ); } @@ -1235,270 +1405,208 @@ void PythonExtensionBase::reinit( Tuple & /* args */, Dict & /* kwds */) } -Py::Object PythonExtensionBase::genericGetAttro( const Py::String &name ) +Object PythonExtensionBase::genericGetAttro( const String &name ) { return asObject( PyObject_GenericGetAttr( selfPtr(), name.ptr() ) ); } -int PythonExtensionBase::genericSetAttro( const Py::String &name, const Py::Object &value ) +int PythonExtensionBase::genericSetAttro( const String &name, const Object &value ) { return PyObject_GenericSetAttr( selfPtr(), name.ptr(), value.ptr() ); } -#ifdef PYCXX_PYTHON_2TO3 +#if defined( PYCXX_PYTHON_2TO3 ) && !defined( Py_LIMITED_API ) && PY_MINOR_VERSION <= 7 int PythonExtensionBase::print( FILE *, int ) { missing_method( print ); - return -1; } #endif -Py::Object PythonExtensionBase::getattr( const char * ) +Object PythonExtensionBase::getattr( const char * ) { missing_method( getattr ); - return Py::None(); } -int PythonExtensionBase::setattr( const char *, const Py::Object & ) +int PythonExtensionBase::setattr( const char *, const Object & ) { missing_method( setattr ); - return -1; } -Py::Object PythonExtensionBase::getattro( const Py::String &name ) +Object PythonExtensionBase::getattro( const String &name ) { return asObject( PyObject_GenericGetAttr( selfPtr(), name.ptr() ) ); } -int PythonExtensionBase::setattro( const Py::String &name, const Py::Object &value ) +int PythonExtensionBase::setattro( const String &name, const Object &value ) { return PyObject_GenericSetAttr( selfPtr(), name.ptr(), value.ptr() ); } -int PythonExtensionBase::compare( const Py::Object & ) +int PythonExtensionBase::compare( const Object & ) { missing_method( compare ); - return -1; } -Py::Object PythonExtensionBase::rich_compare( const Py::Object &, int ) +Object PythonExtensionBase::rich_compare( const Object &, int ) { missing_method( rich_compare ); - return Py::None(); } -Py::Object PythonExtensionBase::repr() +Object PythonExtensionBase::repr() { missing_method( repr ); - return Py::None(); } -Py::Object PythonExtensionBase::str() +Object PythonExtensionBase::str() { missing_method( str ); - return Py::None(); } long PythonExtensionBase::hash() { missing_method( hash ); - return -1; } - - -Py::Object PythonExtensionBase::call( const Py::Object &, const Py::Object & ) -{ - missing_method( call ); - return Py::None(); } -Py::Object PythonExtensionBase::iter() +Object PythonExtensionBase::call( const Object &, const Object & ) +{ + missing_method( call ); +} + +Object PythonExtensionBase::iter() { missing_method( iter ); - return Py::None(); } PyObject *PythonExtensionBase::iternext() { missing_method( iternext ); - return NULL; } - - +} // Sequence methods -int PythonExtensionBase::sequence_length() +PyCxx_ssize_t PythonExtensionBase::sequence_length() { missing_method( sequence_length ); - return -1; } +} - -Py::Object PythonExtensionBase::sequence_concat( const Py::Object & ) +Object PythonExtensionBase::sequence_concat( const Object & ) { missing_method( sequence_concat ); - return Py::None(); } -Py::Object PythonExtensionBase::sequence_repeat( Py_ssize_t ) +Object PythonExtensionBase::sequence_repeat( Py_ssize_t ) { missing_method( sequence_repeat ); - return Py::None(); } -Py::Object PythonExtensionBase::sequence_item( Py_ssize_t ) +Object PythonExtensionBase::sequence_item( Py_ssize_t ) { missing_method( sequence_item ); - return Py::None(); } -int PythonExtensionBase::sequence_ass_item( Py_ssize_t, const Py::Object & ) +int PythonExtensionBase::sequence_ass_item( Py_ssize_t, const Object & ) { missing_method( sequence_ass_item ); - return -1; } +Object PythonExtensionBase::sequence_inplace_concat( const Object & ) +{ + missing_method( sequence_inplace_concat ); +} + +Object PythonExtensionBase::sequence_inplace_repeat( Py_ssize_t ) +{ + missing_method( sequence_inplace_repeat ); +} + +int PythonExtensionBase::sequence_contains( const Object & ) +{ + missing_method( sequence_contains ); +} // Mapping -int PythonExtensionBase::mapping_length() +PyCxx_ssize_t PythonExtensionBase::mapping_length() { missing_method( mapping_length ); - return -1; } - -Py::Object PythonExtensionBase::mapping_subscript( const Py::Object & ) +Object PythonExtensionBase::mapping_subscript( const Object & ) { missing_method( mapping_subscript ); - return Py::None(); } -int PythonExtensionBase::mapping_ass_subscript( const Py::Object &, const Py::Object & ) +int PythonExtensionBase::mapping_ass_subscript( const Object &, const Object & ) { missing_method( mapping_ass_subscript ); - return -1; } -Py::Object PythonExtensionBase::number_negative() -{ - missing_method( number_negative ); - return Py::None(); -} +// Number +#define NUMBER_UNARY( slot ) Object PythonExtensionBase::number_ ## slot() \ + { missing_method( number_ ## slot ); } +#define NUMBER_BINARY( slot ) Object PythonExtensionBase::number_ ## slot( const Object & ) \ + { missing_method( number_ ## slot ); } +#define NUMBER_TERNARY( slot ) Object PythonExtensionBase::number_ ## slot( const Object &, const Object & ) \ + { missing_method( number_ ## slot ); } -Py::Object PythonExtensionBase::number_positive() -{ - missing_method( number_positive ); - return Py::None(); -} +NUMBER_UNARY( negative ) +NUMBER_UNARY( positive ) +NUMBER_UNARY( absolute ) +NUMBER_UNARY( invert ) +NUMBER_UNARY( int ) +NUMBER_UNARY( float ) +NUMBER_BINARY( add ) +NUMBER_BINARY( subtract ) +NUMBER_BINARY( multiply ) +NUMBER_BINARY( remainder ) +NUMBER_BINARY( divmod ) +NUMBER_BINARY( lshift ) +NUMBER_BINARY( rshift ) +NUMBER_BINARY( and ) +NUMBER_BINARY( xor ) +NUMBER_BINARY( or ) +NUMBER_TERNARY( power ) +NUMBER_BINARY( floor_divide ) +NUMBER_BINARY( true_divide ) +NUMBER_UNARY( index ) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 +NUMBER_BINARY( matrix_multiply ) +#endif -Py::Object PythonExtensionBase::number_absolute() -{ - missing_method( number_absolute ); - return Py::None(); -} +NUMBER_BINARY( inplace_add ) +NUMBER_BINARY( inplace_subtract ) +NUMBER_BINARY( inplace_multiply ) +NUMBER_BINARY( inplace_remainder ) +NUMBER_TERNARY( inplace_power ) +NUMBER_BINARY( inplace_lshift ) +NUMBER_BINARY( inplace_rshift ) +NUMBER_BINARY( inplace_and ) +NUMBER_BINARY( inplace_xor ) +NUMBER_BINARY( inplace_or ) +NUMBER_BINARY( inplace_floor_divide ) +NUMBER_BINARY( inplace_true_divide ) +#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5 +NUMBER_BINARY( inplace_matrix_multiply ) +#endif -Py::Object PythonExtensionBase::number_invert() -{ - missing_method( number_invert ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_int() -{ - missing_method( number_int ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_float() -{ - missing_method( number_float ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_long() -{ - missing_method( number_long ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_add( const Py::Object & ) -{ - missing_method( number_add ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_subtract( const Py::Object & ) -{ - missing_method( number_subtract ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_multiply( const Py::Object & ) -{ - missing_method( number_multiply ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_remainder( const Py::Object & ) -{ - missing_method( number_remainder ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_divmod( const Py::Object & ) -{ - missing_method( number_divmod ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_lshift( const Py::Object & ) -{ - missing_method( number_lshift ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_rshift( const Py::Object & ) -{ - missing_method( number_rshift ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_and( const Py::Object & ) -{ - missing_method( number_and ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_xor( const Py::Object & ) -{ - missing_method( number_xor ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_or( const Py::Object & ) -{ - missing_method( number_or ); - return Py::None(); -} - -Py::Object PythonExtensionBase::number_power( const Py::Object &, const Py::Object & ) -{ - missing_method( number_power ); - return Py::None(); -} +#undef NUMBER_UNARY +#undef NUMBER_BINARY +#undef NUMBER_TERNARY // Buffer -int PythonExtensionBase::buffer_get( Py_buffer * /* buf */, int /* flags */ ) +#ifndef Py_LIMITED_API +int PythonExtensionBase::buffer_get( Py_buffer * /*buf*/, int /*flags*/ ) { missing_method( buffer_get ); - return -1; } int PythonExtensionBase::buffer_release( Py_buffer * /*buf*/ ) { - /* This method is optional and only required if the buffer's - memory is dynamic. */ + // This method is optional and only required if the buffer's + // memory is dynamic. return 0; } +#endif //-------------------------------------------------------------------------------- // @@ -1525,7 +1633,7 @@ extern "C" PyObject *method_noargs_call_handler( PyObject *_self_and_name_tuple, return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -1555,7 +1663,7 @@ extern "C" PyObject *method_varargs_call_handler( PyObject *_self_and_name_tuple return new_reference_to( result.ptr() ); } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -1609,7 +1717,7 @@ extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple return new_reference_to( result.ptr() ); } } - catch( Exception & ) + catch( BaseException & ) { return 0; } @@ -1622,7 +1730,7 @@ extern "C" PyObject *method_keyword_call_handler( PyObject *_self_and_name_tuple // //-------------------------------------------------------------------------------- ExtensionExceptionType::ExtensionExceptionType() - : Py::Object() +: Object() { } @@ -1648,21 +1756,66 @@ ExtensionExceptionType::~ExtensionExceptionType() { } -Exception::Exception( ExtensionExceptionType &exception, const std::string& reason ) +BaseException::BaseException( ExtensionExceptionType &exception, const std::string& reason ) { PyErr_SetString( exception.ptr(), reason.c_str() ); } -Exception::Exception( ExtensionExceptionType &exception, Object &reason ) +BaseException::BaseException( ExtensionExceptionType &exception, Object &reason ) { PyErr_SetObject( exception.ptr(), reason.ptr() ); } -Exception::Exception( PyObject *exception, Object &reason ) +BaseException::BaseException( PyObject *exception, Object &reason ) { PyErr_SetObject( exception, reason.ptr() ); } +BaseException::BaseException( PyObject *exception, const std::string &reason ) +{ + PyErr_SetString( exception, reason.c_str() ); +} + +BaseException::BaseException() +{ +} + +void BaseException::clear() +{ + PyErr_Clear(); +} + +// is the exception this specific exception 'exc' +bool BaseException::matches( ExtensionExceptionType &exc ) +{ + return PyErr_ExceptionMatches( exc.ptr() ) != 0; +} + +Object BaseException::errorType() +{ + PyObject *type, *value, *traceback; + PyErr_Fetch( &type, &value, &traceback ); + + Object result( type ); + + PyErr_Restore( type, value, traceback ); + return result; +} + +Object BaseException::errorValue() +{ + PyObject *type, *value, *traceback; + PyErr_Fetch( &type, &value, &traceback ); + + Object result( value ); + + PyErr_Restore( type, value, traceback ); + return result; +} + + +//------------------------------------------------------------ + #if 1 //------------------------------------------------------------ // compare operators diff --git a/src/CXX/Python3/cxx_standard_exceptions.hxx b/src/CXX/Python3/cxx_standard_exceptions.hxx new file mode 100644 index 0000000000..c02bc0bad4 --- /dev/null +++ b/src/CXX/Python3/cxx_standard_exceptions.hxx @@ -0,0 +1,78 @@ +#if !defined( PYCXX_STANDARD_EXCEPTION ) +#pragma error( "define PYCXX_STANDARD_EXCEPTION before including" ) +#endif + +// taken for python3.5 documentation + +// EnvironmentError and IOError are not used in Python3 +//PYCXX_STANDARD_EXCEPTION( EnvironmentError, QQQ ) +//PYCXX_STANDARD_EXCEPTION( IOError, QQQ ) + +// 5.4 Exception hierarchy +PYCXX_STANDARD_EXCEPTION( SystemExit, BaseException ) +PYCXX_STANDARD_EXCEPTION( KeyboardInterrupt, BaseException ) +PYCXX_STANDARD_EXCEPTION( GeneratorExit, BaseException ) +#if !defined( PYCXX_6_2_COMPATIBILITY ) +PYCXX_STANDARD_EXCEPTION( Exception, BaseException ) +#endif +PYCXX_STANDARD_EXCEPTION( StopIteration, Exception ) +#if !defined(MS_WINDOWS) && ((defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x03050000 && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5) || (!defined( Py_LIMITED_API ) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5)) +PYCXX_STANDARD_EXCEPTION( StopAsyncIteration, Exception ) +#endif +// Windows builds of python 3.5 do not export the symbol PyExc_StopAsyncIteration - need atleast 3.6 +#if defined(MS_WINDOWS) && ((defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x03050000 && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 6) || (!defined( Py_LIMITED_API ) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5)) +PYCXX_STANDARD_EXCEPTION( StopAsyncIteration, Exception ) +#endif +PYCXX_STANDARD_EXCEPTION( ArithmeticError, Exception ) +PYCXX_STANDARD_EXCEPTION( FloatingPointError, ArithmeticError ) +PYCXX_STANDARD_EXCEPTION( OverflowError, ArithmeticError ) +PYCXX_STANDARD_EXCEPTION( ZeroDivisionError, ArithmeticError ) +PYCXX_STANDARD_EXCEPTION( AssertionError, Exception ) +PYCXX_STANDARD_EXCEPTION( AttributeError, Exception ) +PYCXX_STANDARD_EXCEPTION( BufferError, Exception ) +PYCXX_STANDARD_EXCEPTION( EOFError, Exception ) +PYCXX_STANDARD_EXCEPTION( ImportError, Exception ) +PYCXX_STANDARD_EXCEPTION( LookupError, Exception ) +PYCXX_STANDARD_EXCEPTION( IndexError, LookupError ) +PYCXX_STANDARD_EXCEPTION( KeyError, LookupError ) +PYCXX_STANDARD_EXCEPTION( MemoryError, Exception ) +PYCXX_STANDARD_EXCEPTION( NameError, Exception ) +PYCXX_STANDARD_EXCEPTION( UnboundLocalError, NameError ) +PYCXX_STANDARD_EXCEPTION( OSError, Exception ) +#if (defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x03060000 && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 6) || (!defined( Py_LIMITED_API ) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4) +PYCXX_STANDARD_EXCEPTION( BlockingIOError, OSError ) +PYCXX_STANDARD_EXCEPTION( ChildProcessError,OSError ) +PYCXX_STANDARD_EXCEPTION( ConnectionError, OSError ) +PYCXX_STANDARD_EXCEPTION( BrokenPipeError, ConnectionError ) +PYCXX_STANDARD_EXCEPTION( ConnectionAbortedError, ConnectionError ) +PYCXX_STANDARD_EXCEPTION( ConnectionRefusedError, ConnectionError ) +PYCXX_STANDARD_EXCEPTION( ConnectionResetError, ConnectionError ) +PYCXX_STANDARD_EXCEPTION( FileExistsError, OSError ) +PYCXX_STANDARD_EXCEPTION( FileNotFoundError, OSError ) +PYCXX_STANDARD_EXCEPTION( InterruptedError, OSError ) +PYCXX_STANDARD_EXCEPTION( IsADirectoryError, OSError ) +PYCXX_STANDARD_EXCEPTION( NotADirectoryError, OSError ) +PYCXX_STANDARD_EXCEPTION( PermissionError, OSError ) +PYCXX_STANDARD_EXCEPTION( ProcessLookupError, OSError ) +PYCXX_STANDARD_EXCEPTION( TimeoutError, OSError ) +#endif +PYCXX_STANDARD_EXCEPTION( ReferenceError, Exception ) +PYCXX_STANDARD_EXCEPTION( RuntimeError, Exception ) +PYCXX_STANDARD_EXCEPTION( NotImplementedError, RuntimeError ) +#if !defined(MS_WINDOWS) && ((defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x03050000 && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5) || (!defined( Py_LIMITED_API ) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5)) +PYCXX_STANDARD_EXCEPTION( RecursionError, RuntimeError ) +#endif +// Windows builds of python 3.5 do not export the symbol PyExc_RecursionError - need atleast 3.6 +#if defined(MS_WINDOWS) && ((defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x03050000 && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 6) || (!defined( Py_LIMITED_API ) && PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5)) +PYCXX_STANDARD_EXCEPTION( RecursionError, RuntimeError ) +#endif +PYCXX_STANDARD_EXCEPTION( SyntaxError, Exception ) +PYCXX_STANDARD_EXCEPTION( IndentationError, SyntaxError ) +PYCXX_STANDARD_EXCEPTION( TabError, IndentationError ) +PYCXX_STANDARD_EXCEPTION( SystemError, Exception ) +PYCXX_STANDARD_EXCEPTION( TypeError, Exception ) +PYCXX_STANDARD_EXCEPTION( ValueError, Exception ) +PYCXX_STANDARD_EXCEPTION( UnicodeError, ValueError ) +PYCXX_STANDARD_EXCEPTION( UnicodeDecodeError, UnicodeError ) +PYCXX_STANDARD_EXCEPTION( UnicodeEncodeError, UnicodeError ) +PYCXX_STANDARD_EXCEPTION( UnicodeTranslateError,UnicodeError ) diff --git a/src/CXX/Python3/cxxextensions.c b/src/CXX/Python3/cxxextensions.c index 7feb1e0db2..3b0f8ef7c5 100644 --- a/src/CXX/Python3/cxxextensions.c +++ b/src/CXX/Python3/cxxextensions.c @@ -38,14 +38,14 @@ #include "CXX/WrapPython.h" #ifdef __cplusplus -extern "C" +extern "C" { #endif -PyObject py_object_initializer = +PyObject py_object_initializer = { _PyObject_EXTRA_INIT - 1, + 1, NULL // type must be init'ed by user }; diff --git a/src/CXX/Python3/cxxsupport.cxx b/src/CXX/Python3/cxxsupport.cxx index aff1b04b69..a22160bd02 100644 --- a/src/CXX/Python3/cxxsupport.cxx +++ b/src/CXX/Python3/cxxsupport.cxx @@ -37,7 +37,7 @@ #include "CXX/Objects.hxx" #include -namespace Py +namespace Py { Py_ssize_t numeric_limits_max() @@ -45,10 +45,13 @@ Py_ssize_t numeric_limits_max() return std::numeric_limits::max(); } +#if !defined(Py_LIMITED_API) Py_UNICODE unicode_null_string[1] = { 0 }; +#endif +Py_UCS4 ucs4_null_string[1] = { 0 }; Type Object::type() const -{ +{ return Type( PyObject_Type( p ), true ); } @@ -58,7 +61,7 @@ String Object::str() const } String Object::repr() const -{ +{ return String( PyObject_Repr( p ), true ); } @@ -73,7 +76,7 @@ List Object::dir() const } bool Object::isType( const Type &t ) const -{ +{ return type().ptr() == t.ptr(); } @@ -91,49 +94,42 @@ String Bytes::decode( const char *encoding, const char *error ) bool operator==( const Object &o1, const Object &o2 ) { int k = PyObject_RichCompareBool( *o1, *o2, Py_EQ ); - if( PyErr_Occurred() ) - throw Exception(); + ifPyErrorThrowCxxException(); return k != 0; } bool operator!=( const Object &o1, const Object &o2 ) { int k = PyObject_RichCompareBool( *o1, *o2, Py_NE ); - if( PyErr_Occurred() ) - throw Exception(); + ifPyErrorThrowCxxException(); return k != 0; - } bool operator>=( const Object &o1, const Object &o2 ) { int k = PyObject_RichCompareBool( *o1, *o2, Py_GE ); - if( PyErr_Occurred() ) - throw Exception(); + ifPyErrorThrowCxxException(); return k != 0; } bool operator<=( const Object &o1, const Object &o2 ) { int k = PyObject_RichCompareBool( *o1, *o2, Py_LE ); - if( PyErr_Occurred() ) - throw Exception(); + ifPyErrorThrowCxxException(); return k != 0; } bool operator<( const Object &o1, const Object &o2 ) { int k = PyObject_RichCompareBool( *o1, *o2, Py_LT ); - if( PyErr_Occurred() ) - throw Exception(); + ifPyErrorThrowCxxException(); return k != 0; } bool operator>( const Object &o1, const Object &o2 ) { int k = PyObject_RichCompareBool( *o1, *o2, Py_GT ); - if( PyErr_Occurred() ) - throw Exception(); + ifPyErrorThrowCxxException(); return k != 0; } @@ -228,7 +224,7 @@ bool operator!=( const Mapping::const_iterator &left, const Mapping::const_itera std::ostream &operator<<( std::ostream &os, const Object &ob ) { return( os << static_cast( ob.str() ) ); -} +} #endif } // Py diff --git a/src/CXX/Version.hxx b/src/CXX/Version.hxx index cdca519320..e6069aad33 100644 --- a/src/CXX/Version.hxx +++ b/src/CXX/Version.hxx @@ -38,9 +38,9 @@ #ifndef __PyCXX_version_hxx__ #define __PyCXX_version_hxx__ -#define PYCXX_VERSION_MAJOR 6 -#define PYCXX_VERSION_MINOR 2 -#define PYCXX_VERSION_PATCH 8 +#define PYCXX_VERSION_MAJOR 7 +#define PYCXX_VERSION_MINOR 1 +#define PYCXX_VERSION_PATCH 7 #define PYCXX_MAKEVERSION( major, minor, patch ) ((major<<16)|(minor<<8)|(patch)) #define PYCXX_VERSION PYCXX_MAKEVERSION( PYCXX_VERSION_MAJOR, PYCXX_VERSION_MINOR, PYCXX_VERSION_PATCH ) #endif diff --git a/src/CXX/WrapPython.h b/src/CXX/WrapPython.h index b65196c4ea..00e5b966b5 100644 --- a/src/CXX/WrapPython.h +++ b/src/CXX/WrapPython.h @@ -56,18 +56,9 @@ // pull in python definitions #include -#ifdef FC_OS_MACOSX -#undef toupper -#undef tolower -#undef isupper -#undef islower -#undef isspace -#undef isalpha -#undef isalnum -#endif // fix issue with Python assuming that isspace, toupper etc are macros -#if defined(isspace) +#if defined(isspace) || defined(FC_OS_MACOSX) #undef isspace #undef isupper #undef islower diff --git a/src/CXX/cxx_exceptions.cxx b/src/CXX/cxx_exceptions.cxx new file mode 100644 index 0000000000..60e8767db9 --- /dev/null +++ b/src/CXX/cxx_exceptions.cxx @@ -0,0 +1,7 @@ +#include "CXX/WrapPython.h" + +#if PY_MAJOR_VERSION == 2 +#include "Python2/cxx_exceptions.cxx" +#else +#include "Python3/cxx_exceptions.cxx" +#endif diff --git a/src/Doc/BuildWebDoc.cfg.in b/src/Doc/BuildWebDoc.cfg.in index 7d9d9324e9..a0903907d0 100644 --- a/src/Doc/BuildWebDoc.cfg.in +++ b/src/Doc/BuildWebDoc.cfg.in @@ -1,96 +1,150 @@ -# Doxyfile 1.7.1 +# Doxyfile 1.9.4 # This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project +# doxygen (www.doxygen.org) for a project. # -# All text after a hash (#) is considered a comment and will be ignored +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. # The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" ") +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). +# +# Note: +# +# Use doxygen to compare the used configuration file with the template +# configuration file: +# doxygen -x [configFile] +# Use doxygen to compare the used configuration file with the template +# configuration file without replacing the environment variables: +# doxygen -x_noenv [configFile] #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- -# This tag specifies the encoding used for all characters in the config file -# that follow. The default is UTF-8 which is also the encoding used for all +# This tag specifies the encoding used for all characters in the configuration +# file that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See -# http://www.gnu.org/software/libiconv for the list of possible encodings. +# https://www.gnu.org/software/libiconv/ for the list of possible encodings. +# The default value is: UTF-8. DOXYFILE_ENCODING = UTF-8 -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded -# by quotes) that should identify the project. +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. PROJECT_NAME = FreeCAD -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. PROJECT_NUMBER = -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. OUTPUT_DIRECTORY = @DOXYGEN_OUTPUT_DIR@ -# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create -# 4096 sub-directories (in 2 levels) under the output directory of each output -# format and will distribute the generated files over these directories. -# Enabling this option can be useful when feeding doxygen a huge amount of -# source files, where putting all generated files in the same directory would -# otherwise cause performance problems for the file system. +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create up to 4096 +# sub-directories (in 2 levels) under the output directory of each output format +# and will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to +# control the number of sub-directories. +# The default value is: NO. CREATE_SUBDIRS = YES +# Controls the number of sub-directories that will be created when +# CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every +# level increment doubles the number of directories, resulting in 4096 +# directories at level 8 which is the default and also the maximum value. The +# sub-directories are organized in 2 levels, the first level always has a fixed +# numer of 16 directories. +# Minimum value: 0, maximum value: 8, default value: 8. +# This tag requires that the tag CREATE_SUBDIRS is set to YES. + +CREATE_SUBDIRS_LEVEL = 8 + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, -# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, -# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English -# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, -# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, -# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian, +# Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English +# (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek, +# Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with +# English messages), Korean, Korean-en (Korean with English messages), Latvian, +# Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, +# Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, +# Swedish, Turkish, Ukrainian and Vietnamese. +# The default value is: English. OUTPUT_LANGUAGE = English -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. BRIEF_MEMBER_DESC = YES -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. +# The default value is: YES. REPEAT_BRIEF = YES -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is -# used as the annotated text. Otherwise, the brief description is used as-is. -# If left blank, the following values are used ("$name" is automatically -# replaced with the name of the entity): "The $name class" "The $name widget" -# "The $name file" "is" "provides" "specifies" "contains" -# "represents" "a" "an" "the" +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. ABBREVIATE_BRIEF = # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief +# doxygen will generate a detailed section even if there is only a brief # description. +# The default value is: NO. ALWAYS_DETAILED_SEC = NO @@ -98,505 +152,778 @@ ALWAYS_DETAILED_SEC = NO # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. +# The default value is: NO. INLINE_INHERITED_MEMB = NO -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. FULL_PATH_NAMES = YES -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. The tag can be used to show relative paths in the file list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. STRIP_FROM_PATH = ../.. -# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of -# the path mentioned in the documentation of a class, which tells -# the reader which header file to include in order to use a class. -# If left blank only the name of the header file containing the class -# definition is used. Otherwise one should specify the include paths that -# are normally passed to the compiler using the -I flag. +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. STRIP_FROM_INC_PATH = -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful is your file systems -# doesn't support long names like on DOS, Mac, or CD-ROM. +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. SHORT_NAMES = NO -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like regular Qt-style comments -# (thus requiring an explicit @brief command for a brief description.) +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. JAVADOC_AUTOBRIEF = YES -# If the QT_AUTOBRIEF tag is set to YES then Doxygen will -# interpret the first line (until the first dot) of a Qt-style -# comment as the brief description. If set to NO, the comments -# will behave just like regular Qt-style comments (thus requiring -# an explicit \brief command for a brief description.) +# If the JAVADOC_BANNER tag is set to YES then doxygen will interpret a line +# such as +# /*************** +# as being the beginning of a Javadoc-style comment "banner". If set to NO, the +# Javadoc-style will behave just like regular comments and it will not be +# interpreted by doxygen. +# The default value is: NO. + +JAVADOC_BANNER = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. QT_AUTOBRIEF = NO -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. MULTILINE_CPP_IS_BRIEF = NO -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. +# By default Python docstrings are displayed as preformatted text and doxygen's +# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the +# doxygen's special commands can be used and the contents of the docstring +# documentation blocks is shown as doxygen documentation. +# The default value is: YES. + +PYTHON_DOCSTRING = YES + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. INHERIT_DOCS = YES -# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce -# a new page for each member. If set to NO, the documentation of a member will -# be part of the file/class/namespace that contains it. +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. SEPARATE_MEMBER_PAGES = NO -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. -TAB_SIZE = 8 +TAB_SIZE = 4 -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:^^" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". Note that you cannot put \n's in the value part of an alias +# to insert newlines (in the resulting output). You can put ^^ in the value part +# of an alias to insert a newline as if a physical newline was in the original +# file. When you need a literal { or } or , in the value part of an alias you +# have to escape them by means of a backslash (\), this can lead to conflicts +# with the commands \{ and \} for these it is advised to use the version @{ and +# @} or use a double escape (\\{ and \\}) ALIASES = -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C -# sources only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. OPTIMIZE_OUTPUT_FOR_C = NO -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java -# sources only. Doxygen will then generate output that is more tailored for -# Java. For instance, namespaces will be presented as packages, qualified -# scopes will look different, etc. +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. OPTIMIZE_OUTPUT_JAVA = YES # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran -# sources only. Doxygen will then generate output that is more tailored for -# Fortran. +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL -# sources. Doxygen will then generate output that is tailored for -# VHDL. +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. OPTIMIZE_OUTPUT_VHDL = NO +# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice +# sources only. Doxygen will then generate output that is more tailored for that +# language. For instance, namespaces will be presented as modules, types will be +# separated into more groups, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_SLICE = NO + # Doxygen selects the parser to use depending on the extension of the files it -# parses. With this tag you can assign which parser to use for a given extension. -# Doxygen has a built-in mapping, but you can override or extend it using this -# tag. The format is ext=language, where ext is a file extension, and language -# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, -# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make -# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C -# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions -# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, JavaScript, +# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice, +# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran: +# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser +# tries to guess whether the code is fixed or free formatted code, this is the +# default for Fortran type files). For instance to make doxygen treat .inc files +# as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. When specifying no_extension you should add +# * to the FILE_PATTERNS. +# +# Note see also the list of default file extension mappings. EXTENSION_MAPPING = +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See https://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 5. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 5 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want -# to include (a tag file for) the STL sources as input, then you should -# set this tag to YES in order to let doxygen match functions declarations and -# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. -# func(std::string) {}). This also make the inheritance and collaboration +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. +# The default value is: NO. BUILTIN_STL_SUPPORT = YES # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. +# The default value is: NO. CPP_CLI_SUPPORT = NO -# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. -# Doxygen will parse them like normal C++ but will assume all classes use public -# instead of private inheritance when no explicit protection keyword is present. +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# https://www.riverbankcomputing.com/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. SIP_SUPPORT = NO -# For Microsoft's IDL there are propget and propput attributes to indicate getter -# and setter methods for a property. Setting this option to YES (the default) -# will make doxygen to replace the get and set methods by a property in the -# documentation. This will only work if the methods are indeed getting or -# setting a simple type. If this is not the case, or you want to show the -# methods anyway, you should set this option to NO. +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first +# tag is set to YES then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. +# The default value is: NO. DISTRIBUTE_GROUP_DOC = NO -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. SUBGROUPING = YES -# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum -# is documented as struct, union, or enum with the name of the typedef. So +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, -# namespace, or class. And the struct will be named TypeS. This can typically -# be useful for C code in case the coding convention dictates that all compound +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. TYPEDEF_HIDES_STRUCT = NO -# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to -# determine which symbols to keep in memory and which to flush to disk. -# When the cache is full, less often used symbols will be written to disk. -# For small to medium size projects (<1000 input files) the default value is -# probably good enough. For larger projects a too small cache size can cause -# doxygen to be busy swapping symbols to and from disk most of the time -# causing a significant performance penalty. -# If the system has enough physical memory increasing the cache will improve the -# performance by keeping more symbols in memory. Note that the value works on -# a logarithmic scale so increasing the size by one will rougly double the -# memory usage. The cache size is given by this formula: -# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, -# corresponding to a cache size of 2^16 = 65536 symbols +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. -SYMBOL_CACHE_SIZE = 0 +LOOKUP_CACHE_SIZE = 0 + +# The NUM_PROC_THREADS specifies the number of threads doxygen is allowed to use +# during processing. When set to 0 doxygen will based this on the number of +# cores available in the system. You can set it explicitly to a value larger +# than 0 to get more control over the balance between CPU load and processing +# speed. At this moment only the input processing can be done using multiple +# threads. Since this is still an experimental feature the default is set to 1, +# which effectively disables parallel processing. Please report any issues you +# encounter. Generating dot graphs in parallel is controlled by the +# DOT_NUM_THREADS setting. +# Minimum value: 0, maximum value: 32, default value: 1. + +NUM_PROC_THREADS = 1 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. EXTRACT_ALL = YES -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. EXTRACT_PRIVATE = NO -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. +# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual +# methods of a class will be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIV_VIRTUAL = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. EXTRACT_STATIC = YES -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. EXTRACT_LOCAL_CLASSES = YES -# This flag is only useful for Objective-C code. When set to YES local -# methods, which are defined in the implementation section but not in -# the interface are included in the documentation. -# If set to NO (the default) only methods in the interface are included. +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. EXTRACT_LOCAL_METHODS = YES # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called -# 'anonymous_namespace{file}', where file will be replaced with the base -# name of the file that contains the anonymous namespace. By default -# anonymous namespace are hidden. +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. EXTRACT_ANON_NSPACES = NO -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. +# If this flag is set to YES, the name of an unnamed parameter in a declaration +# will be determined by the corresponding definition. By default unnamed +# parameters remain unnamed in the output. +# The default value is: YES. + +RESOLVE_UNNAMED_PARAMS = YES + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. HIDE_UNDOC_MEMBERS = YES -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. HIDE_UNDOC_CLASSES = YES -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# declarations. If set to NO, these declarations will be included in the # documentation. +# The default value is: NO. HIDE_FRIEND_COMPOUNDS = NO -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. HIDE_IN_BODY_DOCS = NO -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. INTERNAL_DOCS = NO -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# and Mac users are advised to set this option to NO. +# With the correct setting of option CASE_SENSE_NAMES doxygen will better be +# able to match the capabilities of the underlying filesystem. In case the +# filesystem is case sensitive (i.e. it supports files in the same directory +# whose names only differ in casing), the option must be set to YES to properly +# deal with such files in case they appear in the input. For filesystems that +# are not case sensitive the option should be set to NO to properly deal with +# output files written for symbols that only differ in casing, such as for two +# classes, one named CLASS and the other named Class, and to also support +# references to files without having to specify the exact matching casing. On +# Windows (including Cygwin) and MacOS, users should typically set this option +# to NO, whereas on Linux or other Unix flavors it should typically be set to +# YES. +# The default value is: system dependent. CASE_SENSE_NAMES = YES -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. HIDE_SCOPE_NAMES = NO -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class +# will show which file needs to be included to use the class. +# The default value is: YES. + +SHOW_HEADERFILE = YES + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. SHOW_INCLUDE_FILES = YES -# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen -# will list include files with double quotes in the documentation -# rather than with sharp brackets. +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. FORCE_LOCAL_INCLUDES = NO -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. INLINE_INFO = YES -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. SORT_MEMBER_DOCS = YES -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. SORT_BRIEF_DOCS = YES -# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen -# will sort the (brief and detailed) documentation of class members so that -# constructors and destructors are listed first. If set to NO (the default) -# the constructors will appear in the respective orders defined by -# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. -# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO -# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. SORT_MEMBERS_CTORS_1ST = NO -# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the -# hierarchy of group names into alphabetical order. If set to NO (the default) -# the group names will appear in their defined order. +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. SORT_GROUP_NAMES = NO -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. SORT_BY_SCOPE_NAME = YES -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. GENERATE_TODOLIST = NO -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. GENERATE_TESTLIST = NO -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. GENERATE_BUGLIST = NO -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. GENERATE_DEPRECATEDLIST= NO -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if sectionname ... \endif. +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. ENABLED_SECTIONS = WEB_DOCUMENTATION -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or define consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and defines in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. MAX_INITIALIZER_LINES = 30 -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the # list will mention the files that were used to generate the documentation. +# The default value is: YES. SHOW_USED_FILES = YES -# If the sources in your project are distributed over multiple directories -# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy -# in the documentation. The default is NO. - -SHOW_DIRECTORIES = NO - -# Set the SHOW_FILES tag to NO to disable the generation of the Files page. -# This will remove the Files entry from the Quick Index and from the -# Folder Tree View (if specified). The default is YES. +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. SHOW_FILES = NO -# Set the SHOW_NAMESPACES tag to NO to disable the generation of the -# Namespaces page. -# This will remove the Namespaces entry from the Quick Index -# and from the Folder Tree View (if specified). The default is YES. +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via -# popen()) the command , where is the value of -# the FILE_VERSION_FILTER tag, and is the name of an input file -# provided by doxygen. Whatever the program writes to standard output -# is used as the file version. See the manual for examples. +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated -# output files in an output format independent way. The create the layout file -# that represents doxygen's defaults, run doxygen with the -l option. -# You can optionally specify a file name after the option, if omitted -# DoxygenLayout.xml will be used as the name of the layout file. +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. See also section "Changing the +# layout of pages" for information. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. LAYOUT_FILE = @DOXYGEN_LAYOUT_FILE@ +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + #--------------------------------------------------------------------------- -# configuration options related to warning and progress messages +# Configuration options related to warning and progress messages #--------------------------------------------------------------------------- -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. WARNINGS = YES -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. WARN_IF_UNDOCUMENTED = NO -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as documenting some parameters in +# a documented function twice, or documenting parameters that don't exist or +# using markup commands wrongly. +# The default value is: YES. WARN_IF_DOC_ERROR = YES -# This WARN_NO_PARAMDOC option can be abled to get warnings for -# functions that are documented, but have no documentation for their parameters -# or return value. If set to NO (the default) doxygen will only warn about -# wrong or incomplete parameter documentation, but not about the absence of -# documentation. +# If WARN_IF_INCOMPLETE_DOC is set to YES, doxygen will warn about incomplete +# function parameter documentation. If set to NO, doxygen will accept that some +# parameters have no documentation without warning. +# The default value is: YES. + +WARN_IF_INCOMPLETE_DOC = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong parameter +# documentation, but not about the absence of documentation. If EXTRACT_ALL is +# set to YES then this flag will automatically be disabled. See also +# WARN_IF_INCOMPLETE_DOC +# The default value is: NO. WARN_NO_PARAMDOC = NO -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. Optionally the format may contain -# $version, which will be replaced by the version of the file (if it could -# be obtained via FILE_VERSION_FILTER) +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS +# then doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but +# at the end of the doxygen process doxygen will return with a non-zero status. +# Possible values are: NO, YES and FAIL_ON_WARNINGS. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# See also: WARN_LINE_FORMAT +# The default value is: $file:$line: $text. WARN_FORMAT = "$file:$line: $text" -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. +# In the $text part of the WARN_FORMAT command it is possible that a reference +# to a more specific place is given. To make it easier to jump to this place +# (outside of doxygen) the user can define a custom "cut" / "paste" string. +# Example: +# WARN_LINE_FORMAT = "'vi $file +$line'" +# See also: WARN_FORMAT +# The default value is: at line $line of file $file. + +WARN_LINE_FORMAT = "at line $line of file $file" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). In case the file specified cannot be opened for writing the +# warning and error messages are written to standard error. When as file - is +# specified the warning and error messages are written to standard output +# (stdout). WARN_LOGFILE = #--------------------------------------------------------------------------- -# configuration options related to the input files +# Configuration options related to the input files #--------------------------------------------------------------------------- -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. INPUT = @DOXYGEN_INPUT_LIST@ # This tag can be used to specify the character encoding of the source files -# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is -# also the default input encoding. Doxygen uses libiconv (or the iconv built -# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for -# the list of possible encodings. +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: +# https://www.gnu.org/software/libiconv/) for the list of possible encodings. +# The default value is: UTF-8. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx -# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# Note the list of default checked file patterns might differ from the list of +# default file extension mappings. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, +# *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be provided as doxygen C +# comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, *.f18, *.f, *.for, *.vhd, +# *.vhdl, *.ucf, *.qsf and *.ice. FILE_PATTERNS = *.h \ *.hpp \ @@ -608,29 +935,34 @@ FILE_PATTERNS = *.h \ *.py \ *.dox -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. RECURSIVE = YES -# The EXCLUDE tag can be used to specify files and/or directories that should +# The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. EXCLUDE = @DOXYGEN_EXCLUDE_LIST@ -# The EXCLUDE_SYMLINKS tag can be used select whether or not files or -# directories that are symbolic links (a Unix filesystem feature) are excluded +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded # from the input. +# The default value is: NO. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. Note that the wildcards are matched -# against the file with absolute path, so to exclude all test directories -# for example use the pattern */test/* +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* EXCLUDE_PATTERNS =*.moc.* \ moc_* \ @@ -645,7 +977,10 @@ EXCLUDE_PATTERNS =*.moc.* \ # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, -# AClass::ANamespace, ANamespace::*Test +# ANamespace::AClass, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* EXCLUDE_SYMBOLS = __init__ \ None \ @@ -660,693 +995,1247 @@ EXCLUDE_SYMBOLS = __init__ \ Py \ SIM -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. -EXAMPLE_PATTERNS = +EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. EXAMPLE_RECURSIVE = NO -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). IMAGE_PATH = @DOXYGEN_IMAGE_PATH@ # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. -# If FILTER_PATTERNS is specified, this tag will be -# ignored. +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern -# basis. -# Doxygen will compare the file name with each pattern and apply the -# filter if there is a match. -# The filters are a list of the form: -# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further -# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER -# is applied to all files. +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. FILTER_SOURCE_FILES = NO +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + #--------------------------------------------------------------------------- -# configuration options related to source browsing +# Configuration options related to source browsing #--------------------------------------------------------------------------- -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. SOURCE_BROWSER = NO -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. INLINE_SOURCES = NO -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C and C++ comments will always remain visible. +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. STRIP_CODE_COMMENTS = YES -# If the REFERENCED_BY_RELATION tag is set to YES -# then for each documented function all documented -# functions referencing it will be listed. +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# entity all documented functions referencing it will be listed. +# The default value is: NO. REFERENCED_BY_RELATION = YES -# If the REFERENCES_RELATION tag is set to YES -# then for each documented function all documented entities -# called/used by that function will be listed. +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. REFERENCES_RELATION = YES -# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) -# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from -# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will -# link to the source code. -# Otherwise they will link to the documentation. +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. -REFERENCES_LINK_SOURCE = NO +REFERENCES_LINK_SOURCE = YES -# If the USE_HTAGS tag is set to YES then the references to source code -# will point to the HTML generated by the htags(1) tool instead of doxygen -# built-in source browser. The htags tool is part of GNU's global source -# tagging system (see http://www.gnu.org/software/global/global.html). You -# will need version 4.8.6 or higher. +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = NO + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see https://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. USE_HTAGS = NO -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. VERBATIM_HEADERS = NO +# If the CLANG_ASSISTED_PARSING tag is set to YES then doxygen will use the +# clang parser (see: +# http://clang.llvm.org/) for more accurate parsing at the cost of reduced +# performance. This can be particularly helpful with template rich C++ code for +# which doxygen's built-in parser lacks the necessary type information. +# Note: The availability of this option depends on whether or not doxygen was +# generated with the -Duse_libclang=ON option for CMake. +# The default value is: NO. + +CLANG_ASSISTED_PARSING = NO + +# If the CLANG_ASSISTED_PARSING tag is set to YES and the CLANG_ADD_INC_PATHS +# tag is set to YES then doxygen will add the directory of each input to the +# include path. +# The default value is: YES. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_ADD_INC_PATHS = YES + +# If clang assisted parsing is enabled you can provide the compiler with command +# line options that you would normally use when invoking the compiler. Note that +# the include paths will already be set by doxygen for the files and directories +# specified with INPUT and INCLUDE_PATH. +# This tag requires that the tag CLANG_ASSISTED_PARSING is set to YES. + +CLANG_OPTIONS = + +# If clang assisted parsing is enabled you can provide the clang parser with the +# path to the directory containing a file called compile_commands.json. This +# file is the compilation database (see: +# http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html) containing the +# options used when the source files were built. This is equivalent to +# specifying the -p option to a clang tool, such as clang-check. These options +# will then be passed to the parser. Any options specified with CLANG_OPTIONS +# will be added as well. +# Note: The availability of this option depends on whether or not doxygen was +# generated with the -Duse_libclang=ON option for CMake. + +CLANG_DATABASE_PATH = + #--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index +# Configuration options related to the alphabetical class index #--------------------------------------------------------------------------- -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. ALPHABETICAL_INDEX = NO -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. IGNORE_PREFIX = #--------------------------------------------------------------------------- -# configuration options related to the HTML output +# Configuration options related to the HTML output #--------------------------------------------------------------------------- -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. GENERATE_HTML = YES -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_OUTPUT = html -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_FILE_EXTENSION = .html -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a # standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_HEADER = @CMAKE_CURRENT_SOURCE_DIR@/templates/header.html -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_FOOTER = @CMAKE_CURRENT_SOURCE_DIR@/templates/footer.html -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If the tag is left blank doxygen -# will generate a default style sheet. Note that doxygen will try to copy -# the style sheet file to the HTML output directory, so don't put your own -# stylesheet in the HTML output directory as well, or it will be erased! +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_STYLESHEET = +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + HTML_EXTRA_STYLESHEET = @CMAKE_CURRENT_SOURCE_DIR@/templates/customdoxygen.css +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + HTML_EXTRA_FILES = @CMAKE_CURRENT_SOURCE_DIR@/templates/doxy-boot.js -# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. -# Doxygen will adjust the colors in the stylesheet and background images -# according to this color. Hue is specified as an angle on a colorwheel, -# see http://en.wikipedia.org/wiki/Hue for more information. -# For instance the value 0 represents red, 60 is yellow, 120 is green, -# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. -# The allowed range is 0 to 359. +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a color-wheel, see +# https://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_HUE = 220 -# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of -# the colors in the HTML output. For a value of 0 the output will use -# grayscales only. A value of 255 will produce the most vivid colors. +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use gray-scales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_SAT = 100 -# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to -# the luminance component of the colors in the HTML output. Values below -# 100 gradually make the output lighter, whereas values above 100 make -# the output darker. The value divided by 100 is the actual gamma applied, -# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, -# and 100 does not change the gamma. +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML -# page will contain the date and time when the page was generated. Setting -# this to NO can help when comparing the output of multiple runs. +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_TIMESTAMP = NO -# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, -# files or namespaces will be aligned in HTML using tables. If set to -# NO a bullet list will be used. +# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML +# documentation will contain a main index with vertical navigation menus that +# are dynamically created via JavaScript. If disabled, the navigation index will +# consists of multiple levels of tabs that are statically embedded in every HTML +# page. Disable this option to support browsers that do not have JavaScript, +# like the Qt help browser. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. -HTML_ALIGN_MEMBERS = YES +HTML_DYNAMIC_MENUS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the -# page has loaded. For this to work a browser that supports -# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox -# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. HTML_DYNAMIC_SECTIONS = NO -# If the GENERATE_DOCSET tag is set to YES, additional index files -# will be generated that can be used as input for Apple's Xcode 3 -# integrated development environment, introduced with OSX 10.5 (Leopard). -# To create a documentation set, doxygen will generate a Makefile in the -# HTML output directory. Running make will produce the docset in that -# directory and running "make install" will install the docset in -# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find -# it at startup. -# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html -# for more information. +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: +# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To +# create a documentation set, doxygen will generate a Makefile in the HTML +# output directory. Running make will produce the docset in that directory and +# running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy +# genXcode/_index.html for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_DOCSET = NO -# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the -# feed. A documentation feed provides an umbrella under which multiple -# documentation sets from a single provider (such as a company or product suite) -# can be grouped. +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_FEEDNAME = "Doxygen generated docs" -# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that -# should uniquely identify the documentation set bundle. This should be a -# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen -# will append .docset to the name. +# This tag determines the URL of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDURL = + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_BUNDLE_ID = org.doxygen.Project -# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_ID = org.doxygen.Publisher -# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. DOCSET_PUBLISHER_NAME = Publisher -# If the GENERATE_HTMLHELP tag is set to YES, additional index files -# will be generated that can be used as input for tools like the -# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) -# of the generated HTML documentation. +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# on Windows. In the beginning of 2021 Microsoft took the original page, with +# a.o. the download links, offline the HTML help workshop was already many years +# in maintenance mode). You can download the HTML help workshop from the web +# archives at Installation executable (see: +# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo +# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe). +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_HTMLHELP = NO -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can -# be used to specify the file name of the resulting .chm file. You -# can add a path in front of the file if the result should not be +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be # written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_FILE = -# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can -# be used to specify the location (absolute path including file name) of -# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run -# the HTML help compiler on the generated index.hhp. +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. HHC_LOCATION = -# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag -# controls if a separate .chi index file is generated (YES) or that -# it should be included in the master .chm file (NO). +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the main .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. GENERATE_CHI = NO -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING -# is used to encode HtmlHelp index (hhk), content (hhc) and project file -# content. +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. CHM_INDEX_ENCODING = -# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag -# controls whether a binary table of contents is generated (YES) or a -# normal table of contents (NO) in the .chm file. - - - +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. BINARY_TOC = NO -# The TOC_EXPAND flag can be set to YES to add extra items for group members -# to the contents of the HTML help documentation and to the tree view. +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and -# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated -# that can be used as input for Qt's qhelpgenerator to generate a -# Qt Compressed Help (.qch) of the generated HTML documentation. +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_QHP = NO -# If the QHG_LOCATION tag is specified, the QCH_FILE tag can -# be used to specify the file name of the resulting .qch file. -# The path specified is relative to the HTML output folder. +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. QCH_FILE = FreeCADSourceDocu -# The QHP_NAMESPACE tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#namespace +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. QHP_NAMESPACE = "FreeCADSourceDocu" -# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating -# Qt Help Project output. For more information please see -# http://doc.trolltech.com/qthelpproject.html#virtual-folders +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. QHP_VIRTUAL_FOLDER = doc -# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to -# add. For more information please see -# http://doc.trolltech.com/qthelpproject.html#custom-filters +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). +# This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_NAME = -# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the -# custom filter to add. For more information please see -# -# Qt Help Project / Custom Filters. +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters). +# This tag requires that the tag GENERATE_QHP is set to YES. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this -# project's -# filter section matches. -# -# Qt Help Project / Filter Attributes. +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. QHP_SECT_FILTER_ATTRS = -# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can -# be used to specify the location of Qt's qhelpgenerator. -# If non-empty doxygen will try to run qhelpgenerator on the generated -# .qhp file. +# The QHG_LOCATION tag can be used to specify the location (absolute path +# including file name) of Qt's qhelpgenerator. If non-empty doxygen will try to +# run qhelpgenerator on the generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. QHG_LOCATION = -# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files -# will be generated, which together with the HTML files, form an Eclipse help -# plugin. To install this plugin and make it available under the help contents -# menu in Eclipse, the contents of the directory containing the HTML and XML -# files needs to be copied into the plugins directory of eclipse. The name of -# the directory within the plugins directory should be the same as -# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before -# the help appears. +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_ECLIPSEHELP = NO -# A unique identifier for the eclipse help plugin. When installing the plugin -# the directory name containing the HTML and XML files should also have -# this name. +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. ECLIPSE_DOC_ID = org.doxygen.Project -# The DISABLE_INDEX tag can be used to turn on/off the condensed index at -# top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. DISABLE_INDEX = NO -# This tag can be used to set the number of enum values (range [1..20]) -# that doxygen will group on one line in the generated HTML documentation. - -ENUM_VALUES_PER_LINE = 4 - # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index -# structure should be generated to display hierarchical information. -# If the tag value is set to YES, a side panel will be generated -# containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). -# Windows users are probably better off using the HTML help feature. +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine tune the look of the index (see "Fine-tuning the output"). As an +# example, the default style sheet generated by doxygen has an example that +# shows how to put an image at the root of the tree instead of the PROJECT_NAME. +# Since the tree basically has the same information as the tab index, you could +# consider setting DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. GENERATE_TREEVIEW = NO -# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, -# and Class Hierarchy pages using a tree view instead of an ordered list. +# When both GENERATE_TREEVIEW and DISABLE_INDEX are set to YES, then the +# FULL_SIDEBAR option determines if the side bar is limited to only the treeview +# area (value NO) or if it should extend to the full height of the window (value +# YES). Setting this to YES gives a layout similar to +# https://docs.readthedocs.io with more room for contents, but less room for the +# project logo, title, and description. If either GENERATE_TREEVIEW or +# DISABLE_INDEX is set to NO, this option has no effect. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. -USE_INLINE_TREES = NO +FULL_SIDEBAR = NO -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. TREEVIEW_WIDTH = 250 -# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open -# links to external symbols imported via tag files in a separate window. +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. EXT_LINKS_IN_WINDOW = NO -# Use this tag to change the font size of Latex formulas included -# as images in the HTML documentation. The default is 10. Note that -# when you change the font size after a successful doxygen run you need -# to manually remove any form_*.png images from the HTML output directory -# to force them to be regenerated. +# If the OBFUSCATE_EMAILS tag is set to YES, doxygen will obfuscate email +# addresses. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +OBFUSCATE_EMAILS = YES + +# If the HTML_FORMULA_FORMAT option is set to svg, doxygen will use the pdf2svg +# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see +# https://inkscape.org) to generate formulas as SVG images instead of PNGs for +# the HTML output. These images will generally look nicer at scaled resolutions. +# Possible values are: png (the default) and svg (looks nicer but requires the +# pdf2svg or inkscape tool). +# The default value is: png. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FORMULA_FORMAT = png + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_FONTSIZE = 10 -# Use the FORMULA_TRANPARENT tag to determine whether or not the images -# generated for formulas are transparent PNGs. Transparent PNGs are -# not supported properly for IE 6.0, but are supported on all modern browsers. -# Note that when changing this option you need to delete any form_*.png files -# in the HTML output before the changes have effect. +# Use the FORMULA_TRANSPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. FORMULA_TRANSPARENT = YES -# When the SEARCHENGINE tag is enabled doxygen will generate a search box -# for the HTML output. The underlying search engine uses javascript -# and DHTML and should work on any modern browser. Note that when using -# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets -# (GENERATE_DOCSET) there is already a search function so this one should -# typically be disabled. For large projects the javascript based search engine -# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. +# The FORMULA_MACROFILE can contain LaTeX \newcommand and \renewcommand commands +# to create new LaTeX commands to be used in formulas as building blocks. See +# the section "Including formulas" for details. -SEARCHENGINE = NO +FORMULA_MACROFILE = + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# https://www.mathjax.org) which uses client side JavaScript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# With MATHJAX_VERSION it is possible to specify the MathJax version to be used. +# Note that the different versions of MathJax have different requirements with +# regards to the different settings, so it is possible that also other MathJax +# settings have to be changed when switching between the different MathJax +# versions. +# Possible values are: MathJax_2 and MathJax_3. +# The default value is: MathJax_2. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_VERSION = MathJax_2 + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. For more details about the output format see MathJax +# version 2 (see: +# http://docs.mathjax.org/en/v2.7-latest/output.html) and MathJax version 3 +# (see: +# http://docs.mathjax.org/en/latest/web/components/output.html). +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility. This is the name for Mathjax version 2, for MathJax version 3 +# this will be translated into chtml), NativeMML (i.e. MathML. Only supported +# for NathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This +# is the name for Mathjax version 3, for MathJax version 2 this will be +# translated into HTML-CSS) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from https://www.mathjax.org before deployment. The default value is: +# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2 +# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3 +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# for MathJax version 2 (see https://docs.mathjax.org/en/v2.7-latest/tex.html +# #tex-and-latex-extensions): +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# For example for MathJax version 3 (see +# http://docs.mathjax.org/en/latest/input/tex/extensions/index.html): +# MATHJAX_EXTENSIONS = ams +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: +# http://docs.mathjax.org/en/v2.7-latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /

'); - $('body').append('
'); - $('body').append('
'); + $('wrapper').append('
'); + $('wrapper').append('
'); + $('wrapper').append('
'); searchBox.searchLabel = ''; searchBox.DOMSearchField = function() { diff --git a/src/Doc/templates/footer.html b/src/Doc/templates/footer.html index bd51dade56..8e62d09085 100644 --- a/src/Doc/templates/footer.html +++ b/src/Doc/templates/footer.html @@ -1,32 +1,18 @@ - + + - - - - - - +
diff --git a/src/Doc/templates/header.html b/src/Doc/templates/header.html index 20b6f64717..6cf526d782 100644 --- a/src/Doc/templates/header.html +++ b/src/Doc/templates/header.html @@ -1,20 +1,20 @@ - - + + - - - - - - - - - - $projectname: $title - $title + + + + + + $projectname: $title + + + $title + + $treeview $search $mathjax @@ -25,22 +25,18 @@ - - - -
-
-
-
-
-
+ +
+ + +
diff --git a/src/Ext/freecad/CMakeLists.txt b/src/Ext/freecad/CMakeLists.txt index 3dbb5a00ea..6803c7b5e8 100644 --- a/src/Ext/freecad/CMakeLists.txt +++ b/src/Ext/freecad/CMakeLists.txt @@ -10,7 +10,8 @@ if (WIN32) REALPATH BASE_DIR "${CMAKE_INSTALL_PREFIX}") set( ${CMAKE_INSTALL_BINDIR}) else() - set(FREECAD_LIBRARY_INSTALL_DIR ${CMAKE_INSTALL_LIBDIR}) + get_filename_component(FREECAD_LIBRARY_INSTALL_DIR "${CMAKE_INSTALL_LIBDIR}" + REALPATH BASE_DIR "${CMAKE_INSTALL_PREFIX}") endif() configure_file(__init__.py.template ${NAMESPACE_INIT}) diff --git a/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h b/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h index 4040e931fe..5321dd9621 100644 --- a/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h +++ b/src/Gui/3Dconnexion/GuiAbstractNativeEvent.h @@ -36,8 +36,8 @@ namespace Gui { Q_OBJECT public: - GuiAbstractNativeEvent(GUIApplicationNativeEventAware *app); - virtual ~GuiAbstractNativeEvent()=0; + explicit GuiAbstractNativeEvent(GUIApplicationNativeEventAware *app); + ~GuiAbstractNativeEvent() override =0; virtual void initSpaceball(QMainWindow *window)=0; private: GuiAbstractNativeEvent(); diff --git a/src/Gui/3Dconnexion/GuiNativeEventMac.h b/src/Gui/3Dconnexion/GuiNativeEventMac.h index 809e668088..2bfda80bea 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventMac.h +++ b/src/Gui/3Dconnexion/GuiNativeEventMac.h @@ -61,9 +61,9 @@ namespace Gui { Q_OBJECT public: - GuiNativeEvent(GUIApplicationNativeEventAware *app); + explicit GuiNativeEvent(GUIApplicationNativeEventAware *app); ~GuiNativeEvent() override; - void initSpaceball(QMainWindow *window) override final; + void initSpaceball(QMainWindow *window) final; private: GuiNativeEvent(); GuiNativeEvent(const GuiNativeEvent&); diff --git a/src/Gui/3Dconnexion/GuiNativeEventWin32.h b/src/Gui/3Dconnexion/GuiNativeEventWin32.h index 59602e5cb1..c8c8006d0b 100644 --- a/src/Gui/3Dconnexion/GuiNativeEventWin32.h +++ b/src/Gui/3Dconnexion/GuiNativeEventWin32.h @@ -29,7 +29,6 @@ #include -//#define _WIN32_WINNT 0x0501 //target at least windows XP #include #include "GuiRawInputEventFilter.h" diff --git a/src/Gui/Action.cpp b/src/Gui/Action.cpp index 431a491446..f80458abef 100644 --- a/src/Gui/Action.cpp +++ b/src/Gui/Action.cpp @@ -33,6 +33,7 @@ # include # include # include +# include #endif #include @@ -359,23 +360,6 @@ void ActionGroup::onActivated (QAction* a) { int index = _group->actions().indexOf(a); - // Calling QToolButton::setIcon() etc. has no effect if it has QAction set. - // We have to change the QAction icon instead -#if 0 - QList widgets = a->associatedWidgets(); - for (QList::iterator it = widgets.begin(); it != widgets.end(); ++it) { - QMenu* menu = qobject_cast(*it); - if (menu) { - QToolButton* button = qobject_cast(menu->parent()); - if (button) { - button->setIcon(a->icon()); - button->setText(a->text()); - button->setToolTip(a->toolTip()); - this->setProperty("defaultAction", QVariant(index)); - } - } - } -#endif this->setIcon(a->icon()); if (!this->_isMode) this->setToolTip(a->toolTip()); this->setProperty("defaultAction", QVariant(index)); @@ -384,7 +368,7 @@ void ActionGroup::onActivated (QAction* a) void ActionGroup::onHovered (QAction *a) { - Gui::ToolTip::showText(QCursor::pos(), a->toolTip()); + QToolTip::showText(QCursor::pos(), a->toolTip()); } @@ -400,10 +384,10 @@ namespace Gui { class WorkbenchActionEvent : public QEvent { public: - WorkbenchActionEvent(QAction* a) + explicit WorkbenchActionEvent(QAction* a) : QEvent(QEvent::User), act(a) { } - ~WorkbenchActionEvent() + ~WorkbenchActionEvent() override { } QAction* action() const { return act; } @@ -696,12 +680,12 @@ public: handle->Attach(this); } - virtual ~Private() + ~Private() override { handle->Detach(this); } - void OnChange(Base::Subject &, const char *reason) + void OnChange(Base::Subject &, const char *reason) override { if (!updating && reason && strcmp(reason, "RecentFiles")==0) { Base::StateLocker guard(updating); @@ -931,7 +915,7 @@ void RecentMacrosAction::setFiles(const QStringList& files) if (check) { recentFiles[index]->setShortcut(QKeySequence()); auto msg = QStringLiteral("Recent macros : keyboard shortcut %1 disabled because conflicting with %2") - .arg(accel_tmp).arg(QLatin1String(check->getName())); + .arg(accel_tmp, QLatin1String(check->getName())); Base::Console().Warning("%s\n", qPrintable(msg)); } else { @@ -939,7 +923,7 @@ void RecentMacrosAction::setFiles(const QStringList& files) recentFiles[index]->setShortcut(accel); } } - recentFiles[index]->setStatusTip(tr("Run macro %1 (Shift+click to edit) keyboard shortcut: %2").arg(files[index]).arg(accel)); + recentFiles[index]->setStatusTip(tr("Run macro %1 (Shift+click to edit) keyboard shortcut: %2").arg(files[index], accel)); recentFiles[index]->setVisible(true); } diff --git a/src/Gui/ActionFunction.h b/src/Gui/ActionFunction.h index d015451258..04927e6290 100644 --- a/src/Gui/ActionFunction.h +++ b/src/Gui/ActionFunction.h @@ -68,7 +68,7 @@ class GuiExport ActionFunction : public QObject public: /// Constructor ActionFunction(QObject*); - virtual ~ActionFunction(); + ~ActionFunction() override; /*! Connects the QAction's triggered() signal with the function \a func @@ -97,7 +97,7 @@ class GuiExport TimerFunction : public QObject public: /// Constructor TimerFunction(QObject* = nullptr); - virtual ~TimerFunction(); + ~TimerFunction() override; void setFunction(std::function func); void setFunction(std::function func, QObject* args); diff --git a/src/Gui/ActiveObjectList.h b/src/Gui/ActiveObjectList.h index b7d021a8e2..e392c97337 100644 --- a/src/Gui/ActiveObjectList.h +++ b/src/Gui/ActiveObjectList.h @@ -27,7 +27,9 @@ #define GUI_ActiveObjectList_H #include +#include #include +#include namespace App { @@ -39,17 +41,17 @@ namespace Gui class Document; class ViewProviderDocumentObject; - /** List of active or special objects - * This class holds a list of objects with a special name. - * Its mainly used to points to something like the active Body or Part in a edit session. - * The class is used the viewer (editor) of a document. - * @see Gui::MDIViewer - * @author Jürgen Riegel - */ + /** List of active or special objects + * This class holds a list of objects with a special name. + * Its mainly used to points to something like the active Body or Part in a edit session. + * The class is used the viewer (editor) of a document. + * @see Gui::MDIViewer + * @author Jürgen Riegel + */ class GuiExport ActiveObjectList { public: - ActiveObjectList(Document *doc) + explicit ActiveObjectList(Document *doc) :_Doc(doc) {} diff --git a/src/Gui/Application.cpp b/src/Gui/Application.cpp index 57173b4c56..2220dbbd2e 100644 --- a/src/Gui/Application.cpp +++ b/src/Gui/Application.cpp @@ -160,7 +160,7 @@ public: // Pimpl class struct ApplicationP { - ApplicationP(bool GUIenabled) : + explicit ApplicationP(bool GUIenabled) : activeDocument(nullptr), editDocument(nullptr), isClosing(false), @@ -360,14 +360,6 @@ Application::Application(bool GUIenabled) throw Base::RuntimeError("Invalid system settings"); } #endif -#if 0 // QuantitySpinBox and InputField try to handle the group separator now - // http://forum.freecadweb.org/viewtopic.php?f=10&t=6910 - // A workaround is to disable the group separator for double-to-string conversion, i.e. - // setting the flag 'OmitGroupSeparator'. - QLocale loc; - loc.setNumberOptions(QLocale::OmitGroupSeparator); - QLocale::setDefault(loc); -#endif // setting up Python binding Base::PyGILStateLocker lock; @@ -451,7 +443,7 @@ Application::Application(bool GUIenabled) for (; meth->ml_name != nullptr; meth++) { PyObject *descr; descr = PyCFunction_NewEx(meth,nullptr,nullptr); - if (descr == nullptr) + if (!descr) break; if (PyDict_SetItemString(dict, meth->ml_name, descr) != 0) break; @@ -500,25 +492,8 @@ Application::~Application() WidgetFactorySupplier::destruct(); BitmapFactoryInst::destruct(); -#if 0 - // we must run the garbage collector before shutting down the SoDB - // subsystem because we may reference some class objects of them in Python - Base::Interpreter().cleanupSWIG("SoBase *"); - // finish also Inventor subsystem - SoFCDB::finish(); - -#if (COIN_MAJOR_VERSION >= 2) && (COIN_MINOR_VERSION >= 4) - SoDB::finish(); -#elif (COIN_MAJOR_VERSION >= 3) - SoDB::finish(); -#else - SoDB::cleanup(); -#endif -#endif - { Base::PyGILStateLocker lock; Py_DECREF(_pcWorkbenchDictionary); - } // save macros try { @@ -527,7 +502,6 @@ Application::~Application() catch (const Base::Exception& e) { std::cerr << "Saving macros failed: " << e.what() << std::endl; } - //App::GetApplication().Detach(this); delete d; Instance = nullptr; @@ -556,7 +530,7 @@ void Application::open(const char* FileName, const char* Module) qApp->processEvents(); // an update is needed otherwise the new view isn't shown } - if (Module != nullptr) { + if (Module) { try { if (File.hasExtension("FCStd")) { bool handled = false; @@ -618,7 +592,7 @@ void Application::importFrom(const char* FileName, const char* DocName, const ch string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str()); unicodepath = Base::Tools::escapeEncodeFilename(unicodepath); - if (Module != nullptr) { + if (Module) { try { // issue module loading Command::doCommand(Command::App, "import %s", Module); @@ -709,7 +683,7 @@ void Application::exportTo(const char* FileName, const char* DocName, const char string unicodepath = Base::Tools::escapedUnicodeFromUtf8(File.filePath().c_str()); unicodepath = Base::Tools::escapeEncodeFilename(unicodepath); - if (Module != nullptr) { + if (Module) { try { std::vector sel = Gui::Selection().getObjectsOfType (App::DocumentObject::getClassTypeId(),DocName); @@ -940,7 +914,7 @@ void Application::onLastWindowClosed(Gui::Document* pcDoc) if (!d->isClosing && pcDoc) { // Call the closing mechanism from Python. This also checks whether pcDoc is the last open document. Command::doCommand(Command::Doc, "App.closeDocument(\"%s\")", pcDoc->getDocument()->getName()); - if (!d->activeDocument && d->documents.size()) { + if (!d->activeDocument && !d->documents.empty()) { Document *gdoc = nullptr; for(auto &v : d->documents) { if (v.second->getDocument()->testStatus(App::Document::TempDoc)) @@ -1022,7 +996,7 @@ bool Application::sendHasMsgToFocusView(const char* pMsg) return false; } -Gui::MDIView* Application::activeView(void) const +Gui::MDIView* Application::activeView() const { if (activeDocument()) return activeDocument()->getActiveView(); @@ -1054,12 +1028,12 @@ void Application::activateView(const Base::Type& type, bool create) } /// Getter for the active view -Gui::Document* Application::activeDocument(void) const +Gui::Document* Application::activeDocument() const { return d->activeDocument; } -Gui::Document* Application::editDocument(void) const +Gui::Document* Application::editDocument() const { return d->editDocument; } @@ -1193,7 +1167,7 @@ void Application::detachView(Gui::BaseView* pcView) d->passive.remove(pcView); } -void Application::onUpdate(void) +void Application::onUpdate() { // update all documents std::map::iterator It; @@ -1223,7 +1197,7 @@ void Application::viewActivated(MDIView* pcView) } -void Application::updateActive(void) +void Application::updateActive() { activeDocument()->onUpdate(); } @@ -1574,7 +1548,7 @@ QString Application::workbenchMenuText(const QString& wb) const return QString(); } -QStringList Application::workbenches(void) const +QStringList Application::workbenches() const { // If neither 'HiddenWorkbench' nor 'ExtraWorkbench' is set then all workbenches are returned. const std::map& config = App::Application::Config(); @@ -1664,22 +1638,22 @@ void Application::setupContextMenu(const char* recipient, MenuItem* items) const } } -bool Application::isClosing(void) +bool Application::isClosing() { return d->isClosing; } -MacroManager *Application::macroManager(void) +MacroManager *Application::macroManager() { return d->macroMngr; } -CommandManager &Application::commandManager(void) +CommandManager &Application::commandManager() { return d->commandManager; } -Gui::PreferencePackManager* Application::prefPackManager(void) +Gui::PreferencePackManager* Application::prefPackManager() { return d->prefPackManager; } @@ -1761,7 +1735,7 @@ static void init_resources() Q_INIT_RESOURCE(translation); } -void Application::initApplication(void) +void Application::initApplication() { static bool init = false; if (init) { @@ -1783,7 +1757,7 @@ void Application::initApplication(void) } } -void Application::initTypes(void) +void Application::initTypes() { // views Gui::BaseView ::init(); @@ -1853,7 +1827,7 @@ void Application::initTypes(void) (ViewProviderDocumentObject::getClassTypeId()); } -void Application::initOpenInventor(void) +void Application::initOpenInventor() { // init the Inventor subsystem SoDB::init(); @@ -1861,12 +1835,12 @@ void Application::initOpenInventor(void) SoFCDB::init(); } -void Application::runInitGuiScript(void) +void Application::runInitGuiScript() { Base::Interpreter().runString(Base::ScriptFactory().ProduceScript("FreeCADGuiInit")); } -void Application::runApplication(void) +void Application::runApplication() { const std::map& cfg = App::Application::Config(); std::map::const_iterator it; @@ -2464,7 +2438,7 @@ App::Document *Application::reopen(App::Document *doc) { for(auto d : doc->getDependentDocuments(true)) { if(d->testStatus(App::Document::PartialDoc) || d->testStatus(App::Document::PartialRestore) ) - docs.push_back(d->FileName.getValue()); + docs.emplace_back(d->FileName.getValue()); } if(docs.empty()) { diff --git a/src/Gui/Application.h b/src/Gui/Application.h index 6a740791a1..4ad59f9f3f 100644 --- a/src/Gui/Application.h +++ b/src/Gui/Application.h @@ -55,7 +55,7 @@ class GuiExport Application { public: /// construction - Application(bool GUIenabled); + explicit Application(bool GUIenabled); /// destruction ~Application(); @@ -89,9 +89,9 @@ public: /// get called if a view gets activated, this manage the whole activation scheme void viewActivated(Gui::MDIView* pcView); /// call update to all documents and all views (costly!) - void onUpdate(void); + void onUpdate(); /// call update to all views of the active document - void updateActive(void); + void updateActive(); /// call update to all command actions void updateActions(bool delay = false); //@} @@ -160,11 +160,11 @@ public: /// message when a GuiDocument is about to vanish void onLastWindowClosed(Gui::Document* pcDoc); /// Getter for the active document - Gui::Document* activeDocument(void) const; + Gui::Document* activeDocument() const; /// Set the active document void setActiveDocument(Gui::Document* pcDocument); /// Getter for the editing document - Gui::Document* editDocument(void) const; + Gui::Document* editDocument() const; Gui::MDIView* editViewOfNode(SoNode *node) const; /// Set editing document, which will reset editing of all other document void setEditDocument(Gui::Document* pcDocument); @@ -177,7 +177,7 @@ public: */ Gui::Document* getDocument(const App::Document* pDoc) const; /// Getter for the active view of the active document or null - Gui::MDIView* activeView(void) const; + Gui::MDIView* activeView() const; /// Activate a view of the given type of the active document void activateView(const Base::Type&, bool create=false); /// Shows the associated view provider of the given object @@ -189,7 +189,7 @@ public: //@} /// true when the application shutting down - bool isClosing(void); + bool isClosing(); void checkForPreviousCrashes(); /** @name workbench handling */ @@ -199,7 +199,7 @@ public: QPixmap workbenchIcon(const QString&) const; QString workbenchToolTip(const QString&) const; QString workbenchMenuText(const QString&) const; - QStringList workbenches(void) const; + QStringList workbenches() const; void setupContextMenu(const char* recipient, MenuItem*) const; //@} @@ -212,24 +212,24 @@ public: /** @name User Commands */ //@{ /// Get macro manager - Gui::MacroManager *macroManager(void); + Gui::MacroManager *macroManager(); /// Reference to the command manager - Gui::CommandManager &commandManager(void); + Gui::CommandManager &commandManager(); /// helper which create the commands void createStandardOperations(); //@} - Gui::PreferencePackManager* prefPackManager(void); + Gui::PreferencePackManager* prefPackManager(); /** @name Init, Destruct an Access methods */ //@{ /// some kind of singleton static Application* Instance; - static void initApplication(void); - static void initTypes(void); - static void initOpenInventor(void); - static void runInitGuiScript(void); - static void runApplication(void); + static void initApplication(); + static void initTypes(); + static void initOpenInventor(); + static void runInitGuiScript(); + static void runApplication(); void tryClose( QCloseEvent * e ); //@} diff --git a/src/Gui/Assistant.h b/src/Gui/Assistant.h index f6541bc01c..9ce2469f03 100644 --- a/src/Gui/Assistant.h +++ b/src/Gui/Assistant.h @@ -36,7 +36,7 @@ class Assistant : public QObject public: Assistant(); - ~Assistant(); + ~Assistant() override; void showDocumentation(const QString &file); private Q_SLOTS: diff --git a/src/Gui/AutoSaver.cpp b/src/Gui/AutoSaver.cpp index 6f3d7336da..634664f52a 100644 --- a/src/Gui/AutoSaver.cpp +++ b/src/Gui/AutoSaver.cpp @@ -360,11 +360,8 @@ private: } -void RecoveryWriter::writeFiles(void) +void RecoveryWriter::writeFiles() { -#if 0 - FileWriter::writeFiles(); -#else // use a while loop because it is possible that while // processing the files new ones can be added size_t index = 0; @@ -397,7 +394,6 @@ void RecoveryWriter::writeFiles(void) index++; } -#endif } diff --git a/src/Gui/AutoSaver.h b/src/Gui/AutoSaver.h index 41944c91c1..2e851e71b9 100644 --- a/src/Gui/AutoSaver.h +++ b/src/Gui/AutoSaver.h @@ -70,7 +70,7 @@ class AutoSaver : public QObject private: static AutoSaver* self; AutoSaver(QObject* parent); - virtual ~AutoSaver(); + ~AutoSaver() override; public: static AutoSaver* instance(); @@ -86,7 +86,7 @@ public: protected: void slotCreateDocument(const App::Document& Doc); void slotDeleteDocument(const App::Document& Doc); - void timerEvent(QTimerEvent * event); + void timerEvent(QTimerEvent * event) override; void saveDocument(const std::string&, AutoSaveProperty&); public Q_SLOTS: @@ -102,15 +102,15 @@ class RecoveryWriter : public Base::FileWriter { public: RecoveryWriter(AutoSaveProperty&); - virtual ~RecoveryWriter(); + ~RecoveryWriter() override; /*! This method can be re-implemented in sub-classes to avoid to write out certain objects. The default implementation always returns true. */ - virtual bool shouldWrite(const std::string&, const Base::Persistence *) const; - virtual void writeFiles(void); + bool shouldWrite(const std::string&, const Base::Persistence *) const override; + void writeFiles() override; private: AutoSaveProperty& saver; diff --git a/src/Gui/AxisOriginPyImp.cpp b/src/Gui/AxisOriginPyImp.cpp index c3aa997fa0..78d7f2345e 100644 --- a/src/Gui/AxisOriginPyImp.cpp +++ b/src/Gui/AxisOriginPyImp.cpp @@ -45,7 +45,7 @@ int AxisOriginPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) // returns a string which represent the object e.g. when printed in python -std::string AxisOriginPy::representation(void) const +std::string AxisOriginPy::representation() const { return ""; } @@ -175,7 +175,7 @@ void AxisOriginPy::setLabels(Py::Dict dict) getAxisOriginPtr()->setLabels(labels); } -Py::Object AxisOriginPy::getNode(void) const +Py::Object AxisOriginPy::getNode() const { SoGroup* node = getAxisOriginPtr()->getNode(); PyObject* Ptr = Base::Interpreter().createSWIGPointerObj("pivy.coin","SoGroup *", node, 1); diff --git a/src/Gui/BitmapFactory.cpp b/src/Gui/BitmapFactory.cpp index 7e6d1fd9bb..0d9519c109 100644 --- a/src/Gui/BitmapFactory.cpp +++ b/src/Gui/BitmapFactory.cpp @@ -89,9 +89,9 @@ public: BitmapFactoryInst* BitmapFactoryInst::_pcSingleton = nullptr; -BitmapFactoryInst& BitmapFactoryInst::instance(void) +BitmapFactoryInst& BitmapFactoryInst::instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) { _pcSingleton = new BitmapFactoryInst; std::map::const_iterator it; @@ -113,9 +113,9 @@ BitmapFactoryInst& BitmapFactoryInst::instance(void) return *_pcSingleton; } -void BitmapFactoryInst::destruct (void) +void BitmapFactoryInst::destruct () { - if (_pcSingleton != nullptr) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } @@ -204,7 +204,7 @@ bool BitmapFactoryInst::findPixmapInCache(const char* name, QPixmap& px) const QIcon BitmapFactoryInst::iconFromTheme(const char* name, const QIcon& fallback) { - QString iconName = QString::fromLatin1(name); + QString iconName = QString::fromUtf8(name); QIcon icon = QIcon::fromTheme(iconName, fallback); if (icon.isNull()) { QPixmap px = pixmap(name); diff --git a/src/Gui/BitmapFactory.h b/src/Gui/BitmapFactory.h index d4b2e9d003..4f71b3659c 100644 --- a/src/Gui/BitmapFactory.h +++ b/src/Gui/BitmapFactory.h @@ -52,8 +52,8 @@ public: BottomRight /**< Place to the bottom right corner */ }; - static BitmapFactoryInst& instance(void); - static void destruct (void); + static BitmapFactoryInst& instance(); + static void destruct (); /// Adds a path where pixmaps can be found void addPath(const QString& path); @@ -143,13 +143,13 @@ private: static BitmapFactoryInst* _pcSingleton; BitmapFactoryInst(); - ~BitmapFactoryInst(); + ~BitmapFactoryInst() override; BitmapFactoryInstP* d; }; /// Get the global instance -inline BitmapFactoryInst& BitmapFactory(void) +inline BitmapFactoryInst& BitmapFactory() { return BitmapFactoryInst::instance(); } diff --git a/src/Gui/CADNavigationStyle.cpp b/src/Gui/CADNavigationStyle.cpp index 7cd4002ced..f6abc32ae8 100644 --- a/src/Gui/CADNavigationStyle.cpp +++ b/src/Gui/CADNavigationStyle.cpp @@ -65,18 +65,9 @@ const char* CADNavigationStyle::mouseButtons(ViewerMode mode) SbBool CADNavigationStyle::processSoEvent(const SoEvent * const ev) { -#if 0 - // Events when in "ready-to-seek" mode are ignored, except those - // which influence the seek mode itself -- these are handled further - // up the inheritance hierarchy. - if (this->isSeekMode()) { - return inherited::processSoEvent(ev); - } -#else // Switch off viewing mode (Bug #0000911) if (!this->isSeekMode() && !this->isAnimating() && this->isViewing()) this->setViewing(false); // by default disable viewing mode to render the scene -#endif const SoType type(ev->getTypeId()); diff --git a/src/Gui/CallTips.cpp b/src/Gui/CallTips.cpp index 0cb4792452..fb51c3ff5c 100644 --- a/src/Gui/CallTips.cpp +++ b/src/Gui/CallTips.cpp @@ -214,19 +214,6 @@ QMap CallTipsList::extractTips(const QString& context) const items.pop_front(); if (!dict.hasKey(std::string(modname.toLatin1()))) return tips; // unknown object -#if 0 - // get the Python object we need - Py::Object obj = dict.getItem(std::string(modname.toLatin1())); - while (!items.isEmpty()) { - QByteArray name = items.front().toLatin1(); - std::string attr = name.constData(); - items.pop_front(); - if (obj.hasAttr(attr)) - obj = obj.getAttr(attr); - else - return tips; - } -#else // Don't use hasattr & getattr because if a property is bound to a method this will be executed twice. PyObject* code = Py_CompileString(static_cast(context.toLatin1()), "", Py_eval_input); if (!code) { @@ -244,7 +231,6 @@ QMap CallTipsList::extractTips(const QString& context) const return tips; } Py::Object obj(eval, true); -#endif // Checks whether the type is a subclass of PyObjectBase because to get the doc string // of a member we must get it by its type instead of its instance otherwise we get the diff --git a/src/Gui/CallTips.h b/src/Gui/CallTips.h index 5853408145..259a2708b0 100644 --- a/src/Gui/CallTips.h +++ b/src/Gui/CallTips.h @@ -56,16 +56,16 @@ public: /// Construction CallTipsList(QPlainTextEdit* parent); /// Destruction - ~CallTipsList(); + ~CallTipsList() override; - void keyboardSearch (const QString&); + void keyboardSearch (const QString&) override; void showTips(const QString&); void validateCursor(); protected: - bool eventFilter(QObject *, QEvent *); - void showEvent(QShowEvent*); - void hideEvent(QHideEvent*); + bool eventFilter(QObject *, QEvent *) override; + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; private Q_SLOTS: void callTipItemActivated(QListWidgetItem *item); diff --git a/src/Gui/CoinRiftWidget.h b/src/Gui/CoinRiftWidget.h index 2664ca9cdc..2dd1880d85 100644 --- a/src/Gui/CoinRiftWidget.h +++ b/src/Gui/CoinRiftWidget.h @@ -38,7 +38,6 @@ // defines which method to use to render #define USE_SO_OFFSCREEN_RENDERER -//#define USE_FRAMEBUFFER #ifdef USE_SO_OFFSCREEN_RENDERER # ifdef USE_FRAMEBUFFER @@ -66,7 +65,6 @@ #include #include #include -//#include #include <../Src/OVR_CAPI_GL.h> #include <../Src/CAPI/GL/CAPI_GL_Util.h> // For framebuffer functions. @@ -75,8 +73,6 @@ class CoinRiftWidget : public QGLWidget { ovrHmd hmd; - //ovrHmdDesc hmdDesc; - //ovrEyeType eyes[2]; ovrEyeRenderDesc eyeRenderDesc[2]; ovrTexture eyeTexture[2]; diff --git a/src/Gui/ComboView.h b/src/Gui/ComboView.h index 408d199368..195790314d 100644 --- a/src/Gui/ComboView.h +++ b/src/Gui/ComboView.h @@ -74,9 +74,9 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~ComboView(); + ~ComboView() override; - Gui::TaskView::TaskView *getTaskPanel(void){return taskPanel;} + Gui::TaskView::TaskView *getTaskPanel(){return taskPanel;} QTabWidget* getTabPanel() const { return tabs;} @@ -92,7 +92,7 @@ protected: void showDialog(Gui::TaskView::TaskDialog *dlg); void closeDialog(); void closedDialog(); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: int oldTabIndex; diff --git a/src/Gui/Command.cpp b/src/Gui/Command.cpp index 07194c422c..e04d1e3d14 100644 --- a/src/Gui/Command.cpp +++ b/src/Gui/Command.cpp @@ -265,12 +265,12 @@ void Command::addToGroup(ActionGroup* group) group->addAction(_pcAction->findChild()); } -Application *Command::getGuiApplication(void) +Application *Command::getGuiApplication() { return Application::Instance; } -Gui::Document* Command::getActiveGuiDocument(void) const +Gui::Document* Command::getActiveGuiDocument() const { return getGuiApplication()->activeDocument(); } @@ -475,7 +475,7 @@ void Command::_invoke(int id, bool disablelog) #endif } -void Command::testActive(void) +void Command::testActive() { if (!_pcAction) return; @@ -498,7 +498,8 @@ void Command::testActive(void) Gui::ActionGroup* pcAction = qobject_cast(_pcAction); if(pcAction) { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); - for(auto action : pcAction->actions()) { + const auto actions = pcAction->actions(); + for(auto action : actions) { auto name = action->property("CommandName").toByteArray(); if(!name.size()) continue; @@ -524,7 +525,7 @@ void Command::setEnabled(bool on) // Helper methods //-------------------------------------------------------------------------- -bool Command::hasActiveDocument(void) const +bool Command::hasActiveDocument() const { return getActiveGuiDocument() != nullptr; } @@ -534,7 +535,7 @@ bool Command::hasObject(const char* Name) return getDocument() != nullptr && getDocument()->getObject(Name) != nullptr; } -Gui::SelectionSingleton& Command::getSelection(void) +Gui::SelectionSingleton& Command::getSelection() { return Gui::Selection(); } @@ -606,17 +607,17 @@ void Command::openCommand(const char* sCmdName) App::GetApplication().setActiveTransaction(sCmdName); } -void Command::commitCommand(void) +void Command::commitCommand() { App::GetApplication().closeActiveTransaction(); } -void Command::abortCommand(void) +void Command::abortCommand() { App::GetApplication().closeActiveTransaction(true); } -bool Command::hasPendingCommand(void) +bool Command::hasPendingCommand() { return !!App::GetApplication().getActiveTransaction(); } @@ -818,13 +819,13 @@ const std::string Command::strToPython(const char* Str) } /// Updates the (active) document (propagate changes) -void Command::updateActive(void) +void Command::updateActive() { WaitCursor wc; doCommand(App,"App.ActiveDocument.recompute()"); } -bool Command::isActiveObjectValid(void) +bool Command::isActiveObjectValid() { Gui::Document* active = Gui::Application::Instance->activeDocument(); assert(active); @@ -837,7 +838,7 @@ bool Command::isActiveObjectValid(void) /// Updates the (all or listed) documents (propagate changes) void Command::updateAll(std::list cList) { - if (cList.size()>0) { + if (!cList.empty()) { for (std::list::iterator It= cList.begin();It!=cList.end();++It) (*It)->onUpdate(); } @@ -851,7 +852,7 @@ void Command::updateAll(std::list cList) //-------------------------------------------------------------------------- /// returns the begin of a online help page -const char * Command::beginCmdHelp(void) +const char * Command::beginCmdHelp() { return "\n" "\n" @@ -863,7 +864,7 @@ const char * Command::beginCmdHelp(void) } /// returns the end of a online help page -const char * Command::endCmdHelp(void) +const char * Command::endCmdHelp() { return "\n\n"; } @@ -982,7 +983,7 @@ void Command::printConflictingAccelerators() const Base::Console().Warning("Accelerator conflict between %s (%s) and %s (%s)\n", sName, sAccel, cmd->sName, cmd->sAccel); } -Action * Command::createAction(void) +Action * Command::createAction() { Action *pcAction; pcAction = new Action(this,getMainWindow()); @@ -1029,7 +1030,7 @@ Command *GroupCommand::addCommand(const char *name) { return cmd; } -Action * GroupCommand::createAction(void) { +Action * GroupCommand::createAction() { ActionGroup* pcAction = new ActionGroup(this, getMainWindow()); pcAction->setMenuRole(QAction::NoRole); pcAction->setDropDownMenu(true); @@ -1144,7 +1145,7 @@ void MacroCommand::activated(int iMsg) } } -Action * MacroCommand::createAction(void) +Action * MacroCommand::createAction() { Action *pcAction; pcAction = new Action(this,getMainWindow()); @@ -1211,7 +1212,7 @@ void MacroCommand::save() hGrp->Clear(); std::vector macros = Application::Instance->commandManager().getGroupCommands("Macros"); - if ( macros.size() > 0 ) { + if ( !macros.empty() ) { for (std::vector::iterator it = macros.begin(); it!=macros.end(); ++it ) { MacroCommand* macro = (MacroCommand*)(*it); ParameterGrp::handle hMacro = hGrp->GetGroup(macro->getName()); @@ -1314,7 +1315,7 @@ void PythonCommand::activated(int iMsg) } } -bool PythonCommand::isActive(void) +bool PythonCommand::isActive() { try { Base::PyGILStateLocker lock; @@ -1344,7 +1345,7 @@ void PythonCommand::languageChange() } } -const char* PythonCommand::getHelpUrl(void) const +const char* PythonCommand::getHelpUrl() const { PyObject* pcTemp; pcTemp = Interpreter().runMethodObject(_pcPyCommand, "CmdHelpURL"); @@ -1355,7 +1356,7 @@ const char* PythonCommand::getHelpUrl(void) const return PyUnicode_AsUTF8(pcTemp); } -Action * PythonCommand::createAction(void) +Action * PythonCommand::createAction() { QAction* qtAction = new QAction(nullptr); Action *pcAction; @@ -1513,14 +1514,6 @@ void PythonGroupCommand::activated(int iMsg) } } - // It is better to let ActionGroup::onActivated() to handle icon and - // text change. The net effect is that the GUI won't change by user - // inovking command through runCommandByName() -#if 0 - // Since the default icon is reset when enabling/disabling the command we have - // to explicitly set the icon of the used command. - pcAction->setIcon(a[iMsg]->icon()); -#endif } catch(Py::Exception&) { Base::PyGILStateLocker lock; @@ -1530,7 +1523,7 @@ void PythonGroupCommand::activated(int iMsg) } } -bool PythonGroupCommand::isActive(void) +bool PythonGroupCommand::isActive() { try { Base::PyGILStateLocker lock; @@ -1554,7 +1547,7 @@ bool PythonGroupCommand::isActive(void) return true; } -Action * PythonGroupCommand::createAction(void) +Action * PythonGroupCommand::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(hasDropDownMenu()); @@ -1664,7 +1657,7 @@ void PythonGroupCommand::languageChange() } } -const char* PythonGroupCommand::getHelpUrl(void) const +const char* PythonGroupCommand::getHelpUrl() const { return ""; } @@ -1841,7 +1834,7 @@ std::vector CommandManager::getModuleCommands(const char *sModName) c return vCmds; } -std::vector CommandManager::getAllCommands(void) const +std::vector CommandManager::getAllCommands() const { std::vector vCmds; @@ -1878,7 +1871,7 @@ void CommandManager::runCommandByName (const char* sName) const pCmd->invoke(0); } -void CommandManager::testActive(void) +void CommandManager::testActive() { for ( std::map::iterator It= _sCommands.begin();It!=_sCommands.end();++It) { It->second->testActive(); diff --git a/src/Gui/Command.h b/src/Gui/Command.h index c24b641551..7d7ba18409 100644 --- a/src/Gui/Command.h +++ b/src/Gui/Command.h @@ -213,15 +213,15 @@ class SelectionSingleton; class MDIView; -void CreateStdCommands(void); -void CreateDocCommands(void); -void CreateFeatCommands(void); -void CreateMacroCommands(void); -void CreateViewStdCommands(void); -void CreateWindowStdCommands(void); -void CreateStructureCommands(void); -void CreateTestCommands(void); -void CreateLinkCommands(void); +void CreateStdCommands(); +void CreateDocCommands(); +void CreateFeatCommands(); +void CreateMacroCommands(); +void CreateViewStdCommands(); +void CreateWindowStdCommands(); +void CreateStructureCommands(); +void CreateTestCommands(); +void CreateLinkCommands(); /** The CommandBase class @@ -232,7 +232,7 @@ void CreateLinkCommands(void); class GuiExport CommandBase { protected: - CommandBase(const char* sMenu, const char* sToolTip=nullptr, const char* sWhat=nullptr, + explicit CommandBase(const char* sMenu, const char* sToolTip=nullptr, const char* sWhat=nullptr, const char* sStatus=nullptr, const char* sPixmap=nullptr, const char* sAccel=nullptr); virtual ~CommandBase(); @@ -246,7 +246,7 @@ public: //@{ protected: /// Creates the used Action when adding to a widget. The default implementation does nothing. - virtual Action * createAction(void); + virtual Action * createAction(); public: /// Reassigns QAction stuff after the language has changed. @@ -313,8 +313,8 @@ protected: class GuiExport Command : public CommandBase { protected: - Command(const char* name); - virtual ~Command(); + explicit Command(const char* name); + ~Command() override; protected: /** @name Methods to override when creating a new command @@ -323,7 +323,7 @@ protected: /// Methods which gets called when activated, needs to be reimplemented! virtual void activated(int iMsg)=0; /// Creates the used Action - virtual Action * createAction(void); + Action * createAction() override; /// Applies the menu text, tool and status tip to the passed action object void applyCommandData(const char* context, Action* ); const char* keySequenceToAccel(int) const; @@ -336,9 +336,9 @@ public: /// CommandManager is a friend friend class CommandManager; /// Override this method if your Cmd is not always active - virtual bool isActive(void){return true;} + virtual bool isActive(){return true;} /// Get somtile called to check the state of the command - void testActive(void); + void testActive(); /// Enables or disables the command void setEnabled(bool); /// (Re)Create the text for the tooltip (for example, when the shortcut is changed) @@ -372,11 +372,11 @@ public: /** @name Helper methods to get important classes */ //@{ /// Get pointer to the Application Window - static Application* getGuiApplication(void); + static Application* getGuiApplication(); /// Get a reference to the selection - static Gui::SelectionSingleton& getSelection(void); + static Gui::SelectionSingleton& getSelection(); /// Get pointer to the active gui document - Gui::Document* getActiveGuiDocument(void) const; + Gui::Document* getActiveGuiDocument() const; /** Get pointer to the named or active App document * Returns a pointer to the named document or the active * document when no name is given. NULL is returned @@ -407,21 +407,21 @@ public: /// Open a new Undo transaction on the active document static void openCommand(const char* sName=nullptr); /// Commit the Undo transaction on the active document - static void commitCommand(void); + static void commitCommand(); /// Abort the Undo transaction on the active document - static void abortCommand(void); + static void abortCommand(); /// Check if an Undo transaction is open on the active document - static bool hasPendingCommand(void); + static bool hasPendingCommand(); /// Updates the (active) document (propagate changes) - static void updateActive(void); + static void updateActive(); /// Updates the (all or listed) documents (propagate changes) static void updateAll(std::list cList); /// Checks if the active object of the active document is valid - static bool isActiveObjectValid(void); + static bool isActiveObjectValid(); /// Translate command - void languageChange(); + void languageChange() override; /// Updates the QAction with respect to the passed mode. - void updateAction(int mode); + void updateAction(int mode) override; /// Setup checkable actions based on current TriggerSource void setupCheckable(int iMsg); //@} @@ -539,17 +539,17 @@ public: /** @name Helper methods to generate help pages */ //@{ /// returns the begin of a online help page - const char * beginCmdHelp(void); + const char * beginCmdHelp(); /// returns the end of a online help page - const char * endCmdHelp(void); + const char * endCmdHelp(); /// Get the help URL - virtual const char* getHelpUrl(void) const { return sHelpUrl; } + virtual const char* getHelpUrl() const { return sHelpUrl; } //@} /** @name Helper methods for the Active tests */ //@{ /// true when there is a document - bool hasActiveDocument(void) const; + bool hasActiveDocument() const; /// true when there is a document and a Feature with Name bool hasObject(const char* Name); //@} @@ -557,7 +557,7 @@ public: /** @name checking of internal state */ //@{ /// returns the name to which the command belongs - const char* getAppModuleName(void) const {return sAppModule;} + const char* getAppModuleName() const {return sAppModule;} void setAppModuleName(const char*); /// Get the command name const char* getName() const { return sName; } @@ -627,7 +627,7 @@ private: class GuiExport GroupCommand : public Command { public: /// Constructor - GroupCommand(const char *name); + explicit GroupCommand(const char *name); /** Add child command * @param cmd: child command. Pass null pointer to add a separator. @@ -642,9 +642,9 @@ public: Command *addCommand(const char *cmdName); protected: - virtual void activated(int iMsg); - virtual Gui::Action * createAction(void); - virtual void languageChange(); + void activated(int iMsg) override; + Gui::Action * createAction() override; + void languageChange() override; void setup(Action *); @@ -665,34 +665,34 @@ class PythonCommand: public Command { public: PythonCommand(const char* name, PyObject * pcPyCommand, const char* pActivationString); - virtual ~PythonCommand(); + ~PythonCommand() override; protected: /** @name Methods reimplemented for Command Framework */ //@{ /// Method which gets called when activated - virtual void activated(int iMsg); + void activated(int iMsg) override; /// if the command is not always active - virtual bool isActive(void); + bool isActive() override; /// Get the help URL - const char* getHelpUrl(void) const; + const char* getHelpUrl() const override; /// Creates the used Action - virtual Action * createAction(void); + Action * createAction() override; //@} public: /** @name Methods to get the properties of the command */ //@{ /// Reassigns QAction stuff after the language has changed. - void languageChange(); - const char* className() const + void languageChange() override; + const char* className() const override { return "PythonCommand"; } - const char* getWhatsThis () const; - const char* getMenuText () const; - const char* getToolTipText() const; - const char* getStatusTip () const; - const char* getPixmap () const; - const char* getAccel () const; + const char* getWhatsThis () const override; + const char* getMenuText () const override; + const char* getToolTipText() const override; + const char* getStatusTip () const override; + const char* getPixmap () const override; + const char* getAccel () const override; bool isCheckable () const; bool isChecked () const; //@} @@ -716,34 +716,34 @@ class PythonGroupCommand: public Command { public: PythonGroupCommand(const char* name, PyObject * pcPyCommand); - virtual ~PythonGroupCommand(); + ~PythonGroupCommand() override; protected: /** @name Methods reimplemented for Command Framework */ //@{ /// Method which gets called when activated - virtual void activated(int iMsg); + void activated(int iMsg) override; /// if the command is not always active - virtual bool isActive(void); + bool isActive() override; /// Get the help URL - const char* getHelpUrl(void) const; + const char* getHelpUrl() const override; /// Creates the used Action - virtual Action * createAction(void); + Action * createAction() override; //@} public: /** @name Methods to get the properties of the command */ //@{ /// Reassigns QAction stuff after the language has changed. - void languageChange(); - const char* className() const + void languageChange() override; + const char* className() const override { return "PythonGroupCommand"; } - const char* getWhatsThis () const; - const char* getMenuText () const; - const char* getToolTipText() const; - const char* getStatusTip () const; - const char* getPixmap () const; - const char* getAccel () const; + const char* getWhatsThis () const override; + const char* getMenuText () const override; + const char* getToolTipText() const override; + const char* getStatusTip () const override; + const char* getPixmap () const override; + const char* getAccel () const override; bool isExclusive () const; bool hasDropDownMenu () const; //@} @@ -770,24 +770,24 @@ protected: class MacroCommand: public Command { public: - MacroCommand(const char* name, bool system = false); - virtual ~MacroCommand(); + explicit MacroCommand(const char* name, bool system = false); + ~MacroCommand() override; protected: /** @name methods reimplemented for Command Framework */ //@{ /// Method which get called when activated - void activated(int iMsg); + void activated(int iMsg) override; /// Creates the used Action - Action * createAction(void); + Action * createAction() override; //@} public: /// Returns the script name const char* getScriptName () const { return sScriptName; } /// Ignore when language has changed. - void languageChange() {} - const char* className() const + void languageChange() override {} + const char* className() const override { return "Gui::MacroCommand"; } /** @name Methods to set the properties of the Script Command */ @@ -845,7 +845,7 @@ public: * of a special app module use GetModuleCommands() * @see Command */ - std::vector getAllCommands(void) const; + std::vector getAllCommands() const; /** Returns all commands of a group * delivers a vector of all commands in the given group. @@ -866,7 +866,7 @@ public: /// method is OBSOLETE use GetModuleCommands() or GetAllCommands() const std::map& getCommands() const { return _sCommands; } /// get frequently called by the AppWnd to check the commands are active. - void testActive(void); + void testActive(); void addCommandMode(const char* sContext, const char* sName); void updateCommands(const char* sContext, int mode); diff --git a/src/Gui/CommandDoc.cpp b/src/Gui/CommandDoc.cpp index cd7de66d52..33e607d639 100644 --- a/src/Gui/CommandDoc.cpp +++ b/src/Gui/CommandDoc.cpp @@ -242,7 +242,7 @@ void StdCmdImport::activated(int iMsg) } } -bool StdCmdImport::isActive(void) +bool StdCmdImport::isActive() { return (getActiveGuiDocument() ? true : false); } @@ -398,7 +398,7 @@ void StdCmdExport::activated(int iMsg) static QString lastExportFilterUsed = QString(); auto selection = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(Gui::getMainWindow(), QString::fromUtf8(QT_TR_NOOP("No selection")), QString::fromUtf8(QT_TR_NOOP("Select the objects to export before choosing Export."))); @@ -490,7 +490,7 @@ void StdCmdExport::activated(int iMsg) } } -bool StdCmdExport::isActive(void) +bool StdCmdExport::isActive() { return (getActiveGuiDocument() ? true : false); } @@ -543,7 +543,7 @@ void StdCmdMergeProjects::activated(int iMsg) } } -bool StdCmdMergeProjects::isActive(void) +bool StdCmdMergeProjects::isActive() { return this->hasActiveDocument(); } @@ -576,7 +576,7 @@ void StdCmdDependencyGraph::activated(int iMsg) getMainWindow()->addWindow(view); } -bool StdCmdDependencyGraph::isActive(void) +bool StdCmdDependencyGraph::isActive() { return (getActiveGuiDocument() ? true : false); } @@ -634,22 +634,11 @@ StdCmdSave::StdCmdSave() void StdCmdSave::activated(int iMsg) { Q_UNUSED(iMsg); -#if 0 - Gui::Document* pActiveDoc = getActiveGuiDocument(); - if ( pActiveDoc ) - pActiveDoc->save(); - else -#endif doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Save\")"); } -bool StdCmdSave::isActive(void) +bool StdCmdSave::isActive() { -#if 0 - if( getActiveGuiDocument() ) - return true; - else -#endif return getGuiApplication()->sendHasMsgToActiveView("Save"); } @@ -674,22 +663,11 @@ StdCmdSaveAs::StdCmdSaveAs() void StdCmdSaveAs::activated(int iMsg) { Q_UNUSED(iMsg); -#if 0 - Gui::Document* pActiveDoc = getActiveGuiDocument(); - if ( pActiveDoc ) - pActiveDoc->saveAs(); - else -#endif doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"SaveAs\")"); } -bool StdCmdSaveAs::isActive(void) +bool StdCmdSaveAs::isActive() { -#if 0 - if( getActiveGuiDocument() ) - return true; - else -#endif return getGuiApplication()->sendHasMsgToActiveView("SaveAs"); } @@ -712,16 +690,10 @@ StdCmdSaveCopy::StdCmdSaveCopy() void StdCmdSaveCopy::activated(int iMsg) { Q_UNUSED(iMsg); -#if 0 - Gui::Document* pActiveDoc = getActiveGuiDocument(); - if ( pActiveDoc ) - pActiveDoc->saveCopy(); - else -#endif doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"SaveCopy\")"); } -bool StdCmdSaveCopy::isActive(void) +bool StdCmdSaveCopy::isActive() { return ( getActiveGuiDocument() ? true : false ); } @@ -748,7 +720,7 @@ void StdCmdSaveAll::activated(int iMsg) Gui::Document::saveAll(); } -bool StdCmdSaveAll::isActive(void) +bool StdCmdSaveAll::isActive() { return ( getActiveGuiDocument() ? true : false ); } @@ -786,7 +758,7 @@ void StdCmdRevert::activated(int iMsg) doCommand(Command::App,"App.ActiveDocument.restore()"); } -bool StdCmdRevert::isActive(void) +bool StdCmdRevert::isActive() { return ( getActiveGuiDocument() ? true : false ); } @@ -816,7 +788,7 @@ void StdCmdProjectInfo::activated(int iMsg) dlg.exec(); } -bool StdCmdProjectInfo::isActive(void) +bool StdCmdProjectInfo::isActive() { return ( getActiveGuiDocument() ? true : false ); } @@ -846,7 +818,7 @@ void StdCmdProjectUtil::activated(int iMsg) dlg.exec(); } -bool StdCmdProjectUtil::isActive(void) +bool StdCmdProjectUtil::isActive() { return true; } @@ -878,7 +850,7 @@ void StdCmdPrint::activated(int iMsg) } } -bool StdCmdPrint::isActive(void) +bool StdCmdPrint::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Print"); } @@ -908,7 +880,7 @@ void StdCmdPrintPreview::activated(int iMsg) } } -bool StdCmdPrintPreview::isActive(void) +bool StdCmdPrintPreview::isActive() { return getGuiApplication()->sendHasMsgToActiveView("PrintPreview"); } @@ -939,7 +911,7 @@ void StdCmdPrintPdf::activated(int iMsg) } } -bool StdCmdPrintPdf::isActive(void) +bool StdCmdPrintPdf::isActive() { return getGuiApplication()->sendHasMsgToActiveView("PrintPdf"); } @@ -996,12 +968,12 @@ void StdCmdUndo::activated(int iMsg) getGuiApplication()->sendMsgToActiveView("Undo"); } -bool StdCmdUndo::isActive(void) +bool StdCmdUndo::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Undo"); } -Action * StdCmdUndo::createAction(void) +Action * StdCmdUndo::createAction() { Action *pcAction; @@ -1040,12 +1012,12 @@ void StdCmdRedo::activated(int iMsg) getGuiApplication()->sendMsgToActiveView("Redo"); } -bool StdCmdRedo::isActive(void) +bool StdCmdRedo::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Redo"); } -Action * StdCmdRedo::createAction(void) +Action * StdCmdRedo::createAction() { Action *pcAction; @@ -1081,7 +1053,7 @@ void StdCmdCut::activated(int iMsg) getGuiApplication()->sendMsgToActiveView("Cut"); } -bool StdCmdCut::isActive(void) +bool StdCmdCut::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Cut"); } @@ -1114,7 +1086,7 @@ void StdCmdCopy::activated(int iMsg) } } -bool StdCmdCopy::isActive(void) +bool StdCmdCopy::isActive() { if (getGuiApplication()->sendHasMsgToFocusView("Copy")) return true; @@ -1152,7 +1124,7 @@ void StdCmdPaste::activated(int iMsg) } } -bool StdCmdPaste::isActive(void) +bool StdCmdPaste::isActive() { if (getGuiApplication()->sendHasMsgToFocusView("Paste")) return true; @@ -1203,7 +1175,7 @@ void StdCmdDuplicateSelection::activated(int iMsg) } std::vector unsaved; hasXLink = App::PropertyXLink::hasXLink(sel,&unsaved); - if(unsaved.size()) { + if(!unsaved.empty()) { QMessageBox::critical(getMainWindow(), QObject::tr("Unsaved document"), QObject::tr("The exported object contains external link. Please save the document" "at least once before exporting.")); @@ -1243,7 +1215,7 @@ void StdCmdDuplicateSelection::activated(int iMsg) fi.deleteFile(); } -bool StdCmdDuplicateSelection::isActive(void) +bool StdCmdDuplicateSelection::isActive() { return Gui::Selection().hasSelection(); } @@ -1275,7 +1247,7 @@ void StdCmdSelectAll::activated(int iMsg) rSel.setSelection(doc->getName(), objs); } -bool StdCmdSelectAll::isActive(void) +bool StdCmdSelectAll::isActive() { return App::GetApplication().getActiveDocument() != nullptr; } @@ -1359,23 +1331,6 @@ void StdCmdDelete::activated(int iMsg) break; } - // The check below is not needed because we now only get selection - // from the active document -#if 0 - //check for inactive objects in selection Mantis #3477 - std::set inactiveLabels; - App::Application& app = App::GetApplication(); - App::Document* actDoc = app.getActiveDocument(); - for (std::vector::iterator ft = sels.begin(); ft != sels.end(); ++ft) { - App::DocumentObject* obj = ft->getObject(); - App::Document* objDoc = obj->getDocument(); - if (actDoc != objDoc) { - inactiveLabels.insert(QString::fromUtf8(obj->Label.getValue())); - autoDeletion = false; - } - } -#endif - if (!autoDeletion) { QString bodyMessage; QTextStream bodyMessageStream(&bodyMessage); @@ -1386,19 +1341,6 @@ void StdCmdDelete::activated(int iMsg) bodyMessageStream << '\n' << currentLabel; if(more) bodyMessageStream << "\n..."; -#if 0 - //message for inactive items - if (!inactiveLabels.empty()) { - if (!affectedLabels.empty()) { - bodyMessageStream << "\n"; - } - std::string thisDoc = pGuiDoc->getDocument()->getName(); - bodyMessageStream << qApp->translate("Std_Delete", - "These items are selected for deletion, but are not in the active document."); - for (const auto ¤tLabel : inactiveLabels) - bodyMessageStream << currentLabel << " / " << Base::Tools::fromStdString(thisDoc) << '\n'; - } -#endif int ret = QMessageBox::warning(Gui::getMainWindow(), qApp->translate("Std_Delete", "Object dependencies"), bodyMessage, @@ -1420,7 +1362,7 @@ void StdCmdDelete::activated(int iMsg) } } } - if(docs.size()) { + if(!docs.empty()) { const auto &outList = App::PropertyXLink::getDocumentOutList(); for(auto it=docs.begin();it!=docs.end();++it) { auto itd = outList.find(*it); @@ -1448,9 +1390,9 @@ void StdCmdDelete::activated(int iMsg) Gui::getMainWindow()->update(); } -bool StdCmdDelete::isActive(void) +bool StdCmdDelete::isActive() { - return Selection().getCompleteSelection().size() > 0; + return !Selection().getCompleteSelection().empty(); } //=========================================================================== @@ -1502,7 +1444,7 @@ void StdCmdRefresh::activated(int iMsg) } } -bool StdCmdRefresh::isActive(void) +bool StdCmdRefresh::isActive() { return this->getDocument() && this->getDocument()->mustExecute(); } @@ -1528,9 +1470,9 @@ void StdCmdTransform::activated(int iMsg) Gui::Control().showDialog(new Gui::Dialog::TaskTransform()); } -bool StdCmdTransform::isActive(void) +bool StdCmdTransform::isActive() { - return (Gui::Control().activeDialog()==nullptr); + return (Gui::Control().activeDialog() == nullptr); } //=========================================================================== @@ -1562,7 +1504,7 @@ void StdCmdPlacement::activated(int iMsg) Gui::Control().showDialog(plm); } -bool StdCmdPlacement::isActive(void) +bool StdCmdPlacement::isActive() { return Gui::Selection().countObjectsOfType(App::GeoFeature::getClassTypeId()) >= 1; } @@ -1596,7 +1538,7 @@ void StdCmdTransformManip::activated(int iMsg) getActiveGuiDocument()->setEdit(vp, Gui::ViewProvider::Transform); } -bool StdCmdTransformManip::isActive(void) +bool StdCmdTransformManip::isActive() { return Gui::Selection().countObjectsOfType(App::GeoFeature::getClassTypeId()) == 1; } @@ -1664,7 +1606,7 @@ void StdCmdAlignment::activated(int iMsg) Gui::Selection().clearSelection(); } -bool StdCmdAlignment::isActive(void) +bool StdCmdAlignment::isActive() { if (ManualAlignment::hasInstance()) return false; @@ -1698,7 +1640,7 @@ void StdCmdEdit::activated(int iMsg) if (viewer->isEditingViewProvider()) { doCommand(Command::Gui,"Gui.activeDocument().resetEdit()"); } else { - if (Selection().getCompleteSelection().size() > 0) { + if (!Selection().getCompleteSelection().empty()) { SelectionSingleton::SelObj obj = Selection().getCompleteSelection()[0]; doCommand(Command::Gui,"Gui.activeDocument().setEdit(\"%s\",0)",obj.FeatName); } @@ -1706,9 +1648,9 @@ void StdCmdEdit::activated(int iMsg) } } -bool StdCmdEdit::isActive(void) +bool StdCmdEdit::isActive() { - return (Selection().getCompleteSelection().size() > 0) || (Gui::Control().activeDialog() != nullptr); + return (!Selection().getCompleteSelection().empty()) || (Gui::Control().activeDialog() != nullptr); } //====================================================================== @@ -1731,10 +1673,10 @@ public: eType = ForEdit; } - virtual const char* className() const {return "StdCmdExpression";} + const char* className() const override {return "StdCmdExpression";} protected: - virtual void activated(int iMsg) { + void activated(int iMsg) override { std::map > objs; switch(iMsg) { case 0: @@ -1763,7 +1705,7 @@ protected: copyExpressions(objs); } - virtual Gui::Action * createAction(void) { + Gui::Action * createAction() override { ActionGroup* pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); applyCommandData(this->className(), pcAction); @@ -1791,7 +1733,7 @@ protected: << obj->getFullName() << '.' << p->getName() << " (" << obj->Label.getValue() << ')' << std::endl; ss << "##@@"; - if(v.second->comment.size()) { + if(!v.second->comment.empty()) { if(v.second->comment[0] == '&' || v.second->comment.find('\n') != std::string::npos || v.second->comment.find('\r') != std::string::npos) @@ -1860,7 +1802,7 @@ protected: size_t len = (found?m2[0].first:tend) - m[0].second; try { App::ExpressionPtr expr(App::Expression::parse(obj,std::string(m[0].second,len))); - if(expr && comment.size()) { + if(expr && !comment.empty()) { if(comment[0] == '&') { expr->comment = comment.c_str()+1; boost::replace_all(expr->comment,"&","&"); @@ -1894,7 +1836,7 @@ protected: if(iter != old.end() && it->second->isSame(*iter->second)) expressions.erase(it); } - if(expressions.size()) + if(!expressions.empty()) v2.first->setExpressions(std::move(expressions)); } } @@ -1907,7 +1849,7 @@ protected: } } - bool isActive() { + bool isActive() override { if(!App::GetApplication().getActiveDocument()) { pcActionCopyAll->setEnabled(false); pcActionCopySel->setEnabled(false); @@ -1932,7 +1874,7 @@ protected: namespace Gui { -void CreateDocCommands(void) +void CreateDocCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); diff --git a/src/Gui/CommandFeat.cpp b/src/Gui/CommandFeat.cpp index 25e8648ea3..79f7a0bef7 100644 --- a/src/Gui/CommandFeat.cpp +++ b/src/Gui/CommandFeat.cpp @@ -110,7 +110,7 @@ void StdCmdRandomColor::activated(int iMsg) } } -bool StdCmdRandomColor::isActive(void) +bool StdCmdRandomColor::isActive() { return (Gui::Selection().size() != 0); } @@ -135,7 +135,7 @@ StdCmdSendToPythonConsole::StdCmdSendToPythonConsole() sAccel = "Ctrl+Shift+P"; } -bool StdCmdSendToPythonConsole::isActive(void) +bool StdCmdSendToPythonConsole::isActive() { //active only if either 1 object is selected or multiple subobjects from the same object return Gui::Selection().getSelectionEx().size() == 1; @@ -211,7 +211,7 @@ void StdCmdSendToPythonConsole::activated(int iMsg) namespace Gui { -void CreateFeatCommands(void) +void CreateFeatCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); diff --git a/src/Gui/CommandLink.cpp b/src/Gui/CommandLink.cpp index 89d4be14c4..4bfc0f13df 100644 --- a/src/Gui/CommandLink.cpp +++ b/src/Gui/CommandLink.cpp @@ -60,14 +60,14 @@ class StdCmdLinkMakeGroup : public Gui::Command { public: StdCmdLinkMakeGroup(); - const char* className() const + const char* className() const override { return "StdCmdLinkMakeGroup"; } protected: - virtual void activated(int iMsg); - virtual bool isActive(void); - virtual Action * createAction(void); - virtual void languageChange(); + void activated(int iMsg) override; + bool isActive() override; + Action * createAction() override; + void languageChange() override; }; StdCmdLinkMakeGroup::StdCmdLinkMakeGroup() @@ -86,7 +86,7 @@ bool StdCmdLinkMakeGroup::isActive() { return !!App::GetApplication().getActiveDocument(); } -Action * StdCmdLinkMakeGroup::createAction(void) +Action * StdCmdLinkMakeGroup::createAction() { ActionGroup* pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); @@ -356,7 +356,7 @@ static void linkConvert(bool unlink) { // PropertyLinkBase::CopyOnLinkReplace(). std::map, Info> infos; - for(auto sel : TreeWidget::getSelection()) { + for(const auto& sel : TreeWidget::getSelection()) { auto obj = sel.vp->getObject(); auto parent = sel.parentVp; if(!parent) { @@ -423,7 +423,7 @@ static void linkConvert(bool unlink) { replaceObj = link; } - // adjust subname for the the new object + // adjust subname for the new object auto pos = info.subname.rfind('.'); if(pos==std::string::npos && pos) info.subname.clear(); @@ -450,7 +450,7 @@ static void linkConvert(bool unlink) { if(obj) recomputes.push_back(obj); } - if(recomputes.size()) + if(!recomputes.empty()) recomputes.front()->getDocument()->recompute(recomputes); Command::commitCommand(); @@ -726,7 +726,7 @@ static App::DocumentObject *getSelectedLink(bool finalLink, std::string *subname if(found) { linked = sels[0].pObject; - *subname = prefix.size()?prefix:prefix2 + *subname; + *subname = !prefix.empty()?prefix:prefix2 + *subname; } } @@ -734,7 +734,7 @@ static App::DocumentObject *getSelectedLink(bool finalLink, std::string *subname } bool StdCmdLinkSelectLinked::isActive() { - return getSelectedLink(false)!=nullptr; + return getSelectedLink(false) != nullptr; } void StdCmdLinkSelectLinked::activated(int) @@ -747,7 +747,7 @@ void StdCmdLinkSelectLinked::activated(int) } Selection().selStackPush(); Selection().clearCompleteSelection(); - if(subname.size()) { + if(!subname.empty()) { Selection().addSelection(linked->getDocument()->getName(),linked->getNameInDocument(),subname.c_str()); auto doc = Application::Instance->getDocument(linked->getDocument()); if(doc) { @@ -755,7 +755,8 @@ void StdCmdLinkSelectLinked::activated(int) doc->setActiveView(vp); } } else { - for(auto tree : getMainWindow()->findChildren()) + const auto trees = getMainWindow()->findChildren(); + for(auto tree : trees) tree->selectLinkedObject(linked); } Selection().selStackPush(); @@ -779,7 +780,7 @@ StdCmdLinkSelectLinkedFinal::StdCmdLinkSelectLinkedFinal() } bool StdCmdLinkSelectLinkedFinal::isActive() { - return getSelectedLink(true)!=nullptr; + return getSelectedLink(true) != nullptr; } void StdCmdLinkSelectLinkedFinal::activated(int) { @@ -790,7 +791,8 @@ void StdCmdLinkSelectLinkedFinal::activated(int) { } Selection().selStackPush(); Selection().clearCompleteSelection(); - for(auto tree : getMainWindow()->findChildren()) + const auto trees = getMainWindow()->findChildren(); + for(auto tree : trees) tree->selectLinkedObject(linked); Selection().selStackPush(); } @@ -825,7 +827,8 @@ void StdCmdLinkSelectAllLinks::activated(int) return; Selection().selStackPush(); Selection().clearCompleteSelection(); - for(auto tree : getMainWindow()->findChildren()) + const auto trees = getMainWindow()->findChildren(); + for(auto tree : trees) tree->selectAllLinks(sels[0].pObject); Selection().selStackPush(); } @@ -854,7 +857,7 @@ public: addCommand(new StdCmdLinkSelectAllLinks()); } - virtual const char* className() const {return "StdCmdLinkSelectActions";} + const char* className() const override {return "StdCmdLinkSelectActions";} }; //====================================================================== @@ -882,7 +885,7 @@ public: addCommand(new StdCmdLinkImportAll()); } - virtual const char* className() const {return "StdCmdLinkActions";} + const char* className() const override {return "StdCmdLinkActions";} }; //=========================================================================== @@ -892,7 +895,7 @@ public: namespace Gui { -void CreateLinkCommands(void) +void CreateLinkCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdLinkMake()); diff --git a/src/Gui/CommandMacro.cpp b/src/Gui/CommandMacro.cpp index 8f15186f3d..9313191e55 100644 --- a/src/Gui/CommandMacro.cpp +++ b/src/Gui/CommandMacro.cpp @@ -58,7 +58,7 @@ void StdCmdDlgMacroRecord::activated(int iMsg) cDlg.exec(); } -bool StdCmdDlgMacroRecord::isActive(void) +bool StdCmdDlgMacroRecord::isActive() { return ! (getGuiApplication()->macroManager()->isOpen()); } @@ -86,7 +86,7 @@ void StdCmdMacroStopRecord::activated(int iMsg) getGuiApplication()->macroManager()->commit(); } -bool StdCmdMacroStopRecord::isActive(void) +bool StdCmdMacroStopRecord::isActive() { return getGuiApplication()->macroManager()->isOpen(); } @@ -115,7 +115,7 @@ void StdCmdDlgMacroExecute::activated(int iMsg) cDlg.exec(); } -bool StdCmdDlgMacroExecute::isActive(void) +bool StdCmdDlgMacroExecute::isActive() { return ! (getGuiApplication()->macroManager()->isOpen()); } @@ -144,7 +144,7 @@ void StdCmdDlgMacroExecuteDirect::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Run\")"); } -bool StdCmdDlgMacroExecuteDirect::isActive(void) +bool StdCmdDlgMacroExecuteDirect::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Run"); } @@ -169,7 +169,7 @@ void StdCmdMacroAttachDebugger::activated(int iMsg) "RemoteDebugger.attachToRemoteDebugger()"); } -bool StdCmdMacroAttachDebugger::isActive(void) +bool StdCmdMacroAttachDebugger::isActive() { return true; } @@ -199,7 +199,7 @@ void StdCmdMacroStartDebug::activated(int iMsg) dbg->stepRun(); } -bool StdCmdMacroStartDebug::isActive(void) +bool StdCmdMacroStartDebug::isActive() { return getGuiApplication()->sendHasMsgToActiveView("StartDebug"); } @@ -225,7 +225,7 @@ void StdCmdMacroStopDebug::activated(int iMsg) Application::Instance->macroManager()->debugger()->tryStop(); } -bool StdCmdMacroStopDebug::isActive(void) +bool StdCmdMacroStopDebug::isActive() { static PythonDebugger* dbg = Application::Instance->macroManager()->debugger(); return dbg->isRunning(); @@ -252,7 +252,7 @@ void StdCmdMacroStepOver::activated(int iMsg) Application::Instance->macroManager()->debugger()->stepOver(); } -bool StdCmdMacroStepOver::isActive(void) +bool StdCmdMacroStepOver::isActive() { static PythonDebugger* dbg = Application::Instance->macroManager()->debugger(); return dbg->isRunning(); @@ -279,7 +279,7 @@ void StdCmdMacroStepInto::activated(int iMsg) Application::Instance->macroManager()->debugger()->stepInto(); } -bool StdCmdMacroStepInto::isActive(void) +bool StdCmdMacroStepInto::isActive() { static PythonDebugger* dbg = Application::Instance->macroManager()->debugger(); return dbg->isRunning(); @@ -306,14 +306,14 @@ void StdCmdToggleBreakpoint::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ToggleBreakpoint\")"); } -bool StdCmdToggleBreakpoint::isActive(void) +bool StdCmdToggleBreakpoint::isActive() { return getGuiApplication()->sendHasMsgToActiveView("ToggleBreakpoint"); } namespace Gui { -void CreateMacroCommands(void) +void CreateMacroCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); rcCmdMgr.addCommand(new StdCmdDlgMacroRecord()); diff --git a/src/Gui/CommandPyImp.cpp b/src/Gui/CommandPyImp.cpp index 0070a4a807..22e6c5bb81 100644 --- a/src/Gui/CommandPyImp.cpp +++ b/src/Gui/CommandPyImp.cpp @@ -39,7 +39,7 @@ // returns a string which represents the object e.g. when printed in python -std::string CommandPy::representation(void) const +std::string CommandPy::representation() const { return std::string(""); } @@ -106,19 +106,19 @@ PyObject* CommandPy::listByShortcut(PyObject *args) } if (re.indexIn(action->shortcut().toString().remove(spc).toUpper()) != -1) { - matches.push_back(c->getName()); + matches.emplace_back(c->getName()); } } else if (action->shortcut().toString().remove(spc).toUpper() == QString::fromLatin1(shortcut_to_find).remove(spc).toUpper()) { - matches.push_back(c->getName()); + matches.emplace_back(c->getName()); } } } PyObject* pyList = PyList_New(matches.size()); int i=0; - for (std::string match : matches) { + for (const std::string& match : matches) { PyObject* str = PyUnicode_FromString(match.c_str()); PyList_SetItem(pyList, i++, str); } @@ -268,7 +268,7 @@ PyObject* CommandPy::getInfo(PyObject *args) const char* whatsThisTxt = cmd->getWhatsThis(); const char* statustipTxt = cmd->getStatusTip(); const char* pixMapTxt = cmd->getPixmap(); - std::string shortcutTxt = ""; + std::string shortcutTxt; if (action) shortcutTxt = action->shortcut().toString().toStdString(); @@ -309,7 +309,8 @@ PyObject* CommandPy::getAction(PyObject *args) Py::List list; if (group) { - for (auto a : group->actions()) + const auto actions = group->actions(); + for (auto a : actions) list.append(wrap.fromQObject(a)); } else if (action) { diff --git a/src/Gui/CommandStd.cpp b/src/Gui/CommandStd.cpp index bf4a844336..db5c4b9e4b 100644 --- a/src/Gui/CommandStd.cpp +++ b/src/Gui/CommandStd.cpp @@ -102,12 +102,12 @@ void StdCmdWorkbench::activated(int i) } } -bool StdCmdWorkbench::isActive(void) +bool StdCmdWorkbench::isActive() { return true; } -Action * StdCmdWorkbench::createAction(void) +Action * StdCmdWorkbench::createAction() { Action *pcAction; @@ -152,7 +152,7 @@ void StdCmdRecentFiles::activated(int iMsg) /** * Creates the QAction object containing the recent files. */ -Action * StdCmdRecentFiles::createAction(void) +Action * StdCmdRecentFiles::createAction() { RecentFilesAction* pcAction = new RecentFilesAction(this, getMainWindow()); pcAction->setObjectName(QLatin1String("recentFiles")); @@ -192,7 +192,7 @@ void StdCmdRecentMacros::activated(int iMsg) /** * Creates the QAction object containing the recent macros. */ -Action * StdCmdRecentMacros::createAction(void) +Action * StdCmdRecentMacros::createAction() { RecentMacrosAction* pcAction = new RecentMacrosAction(this, getMainWindow()); pcAction->setObjectName(QLatin1String("recentMacros")); @@ -218,7 +218,7 @@ StdCmdAbout::StdCmdAbout() eType = 0; } -Action * StdCmdAbout::createAction(void) +Action * StdCmdAbout::createAction() { Action *pcAction; @@ -356,7 +356,7 @@ StdCmdDlgPreferences::StdCmdDlgPreferences() eType = 0; } -Action * StdCmdDlgPreferences::createAction(void) +Action * StdCmdDlgPreferences::createAction() { Action *pcAction = Command::createAction(); pcAction->setMenuRole(QAction::PreferencesRole); @@ -803,7 +803,7 @@ void StdCmdTextDocument::activated(int iMsg) commitCommand(); } -bool StdCmdTextDocument::isActive(void) +bool StdCmdTextDocument::isActive() { return hasActiveDocument(); } @@ -839,14 +839,14 @@ class StdCmdUserEditMode : public Gui::Command { public: StdCmdUserEditMode(); - virtual ~StdCmdUserEditMode(){} - virtual void languageChange(); - virtual const char* className() const {return "StdCmdUserEditMode";} + ~StdCmdUserEditMode() override{} + void languageChange() override; + const char* className() const override {return "StdCmdUserEditMode";} void updateIcon(int mode); protected: - virtual void activated(int iMsg); - virtual bool isActive(void); - virtual Gui::Action * createAction(void); + void activated(int iMsg) override; + bool isActive() override; + Gui::Action * createAction() override; }; StdCmdUserEditMode::StdCmdUserEditMode() @@ -863,7 +863,7 @@ StdCmdUserEditMode::StdCmdUserEditMode() this->getGuiApplication()->signalUserEditModeChanged.connect(boost::bind(&StdCmdUserEditMode::updateIcon, this, bp::_1)); } -Gui::Action * StdCmdUserEditMode::createAction(void) +Gui::Action * StdCmdUserEditMode::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -928,14 +928,14 @@ void StdCmdUserEditMode::activated(int iMsg) Gui::Application::Instance->setUserEditMode(iMsg); } -bool StdCmdUserEditMode::isActive(void) +bool StdCmdUserEditMode::isActive() { return true; } namespace Gui { -void CreateStdCommands(void) +void CreateStdCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); diff --git a/src/Gui/CommandStructure.cpp b/src/Gui/CommandStructure.cpp index a00c0ed26d..70dcff97eb 100644 --- a/src/Gui/CommandStructure.cpp +++ b/src/Gui/CommandStructure.cpp @@ -75,7 +75,7 @@ void StdCmdPart::activated(int iMsg) updateActive(); } -bool StdCmdPart::isActive(void) +bool StdCmdPart::isActive() { return hasActiveDocument(); } @@ -117,14 +117,14 @@ void StdCmdGroup::activated(int iMsg) gui->signalScrollToObject(*static_cast(vp)); } -bool StdCmdGroup::isActive(void) +bool StdCmdGroup::isActive() { return hasActiveDocument(); } namespace Gui { -void CreateStructureCommands(void) +void CreateStructureCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); diff --git a/src/Gui/CommandTest.cpp b/src/Gui/CommandTest.cpp index 3e745de98f..d0a7a7c6c1 100644 --- a/src/Gui/CommandTest.cpp +++ b/src/Gui/CommandTest.cpp @@ -132,7 +132,7 @@ void FCCmdTest1::activated(int iMsg) Q_UNUSED(iMsg); } -bool FCCmdTest1::isActive(void) +bool FCCmdTest1::isActive() { //return (GetActiveOCCDocument()!=NULL); return true; @@ -160,9 +160,9 @@ void FCCmdTest2::activated(int iMsg) Q_UNUSED(iMsg); } -bool FCCmdTest2::isActive(void) +bool FCCmdTest2::isActive() { - return (getDocument()!=nullptr); + return (getDocument() != nullptr); } //=========================================================================== @@ -190,9 +190,9 @@ void FCCmdTest3::activated(int iMsg) } -bool FCCmdTest3::isActive(void) +bool FCCmdTest3::isActive() { - return (getDocument()!=nullptr); + return (getDocument() != nullptr); } //=========================================================================== @@ -221,9 +221,9 @@ void FCCmdTest4::activated(int iMsg) } -bool FCCmdTest4::isActive(void) +bool FCCmdTest4::isActive() { - return (getDocument()!=nullptr); + return (getDocument() != nullptr); } //=========================================================================== @@ -250,9 +250,9 @@ void FCCmdTest5::activated(int iMsg) return; } -bool FCCmdTest5::isActive(void) +bool FCCmdTest5::isActive() { - return (getDocument()!=nullptr); + return (getDocument() != nullptr); } @@ -280,9 +280,9 @@ void FCCmdTest6::activated(int iMsg) return; } -bool FCCmdTest6::isActive(void) +bool FCCmdTest6::isActive() { - return (getDocument()!=nullptr); + return (getDocument() != nullptr); } //=========================================================================== @@ -330,9 +330,9 @@ void CmdTestCmdFuncs::activated(int iMsg) Gui::copyVisualT(objName.c_str(), "DisplayMode", objName.c_str()); } -bool CmdTestCmdFuncs::isActive(void) +bool CmdTestCmdFuncs::isActive() { - return (getDocument()!=nullptr); + return (getDocument() != nullptr); } //=========================================================================== @@ -372,7 +372,7 @@ void CmdTestProgress1::activated(int iMsg) } } -bool CmdTestProgress1::isActive(void) +bool CmdTestProgress1::isActive() { return (!Base::Sequencer().isRunning()); } @@ -415,7 +415,7 @@ void CmdTestProgress2::activated(int iMsg) } } -bool CmdTestProgress2::isActive(void) +bool CmdTestProgress2::isActive() { return ( !Base::Sequencer().isRunning() ); } @@ -485,7 +485,7 @@ void CmdTestProgress3::activated(int iMsg) } } -bool CmdTestProgress3::isActive(void) +bool CmdTestProgress3::isActive() { return ( !Base::Sequencer().isRunning() ); } @@ -540,7 +540,7 @@ void CmdTestProgress4::activated(int iMsg) } } -bool CmdTestProgress4::isActive(void) +bool CmdTestProgress4::isActive() { return (!Base::Sequencer().isRunning()); } @@ -564,13 +564,13 @@ CmdTestProgress5::CmdTestProgress5() class BarThread : public QThread { public: - BarThread(unsigned long s) : steps(s) + explicit BarThread(unsigned long s) : steps(s) { } - ~BarThread() + ~BarThread() override { } - void run() + void run() override { QMutex mutex; QMutexLocker ml(&mutex); @@ -620,7 +620,7 @@ void CmdTestProgress5::activated(int iMsg) thr3->start(); } -bool CmdTestProgress5::isActive(void) +bool CmdTestProgress5::isActive() { return (!Base::Sequencer().isRunning()); } @@ -647,7 +647,7 @@ void CmdTestMDI1::activated(int iMsg) getMainWindow()->removeWindow(mdi); } -bool CmdTestMDI1::isActive(void) +bool CmdTestMDI1::isActive() { return getMainWindow()->activeWindow(); } @@ -675,7 +675,7 @@ void CmdTestMDI2::activated(int iMsg) } } -bool CmdTestMDI2::isActive(void) +bool CmdTestMDI2::isActive() { return getMainWindow()->activeWindow(); } @@ -703,7 +703,7 @@ void CmdTestMDI3::activated(int iMsg) mdi->show(); } -bool CmdTestMDI3::isActive(void) +bool CmdTestMDI3::isActive() { return getMainWindow()->activeWindow(); } @@ -728,7 +728,7 @@ public: TestConsoleObserver() : matchMsg(0), matchWrn(0), matchErr(0), matchLog(0) { } - void SendLog(const std::string& msg, Base::LogStyle level){ + void SendLog(const std::string& msg, Base::LogStyle level) override{ QMutexLocker ml(&mutex); @@ -752,7 +752,7 @@ public: class ConsoleMessageTask : public QRunnable { public: - void run() + void run() override { for (int i=0; i<10; i++) Base::Console().Message("Write a message to the console output.\n"); @@ -762,7 +762,7 @@ public: class ConsoleWarningTask : public QRunnable { public: - void run() + void run() override { for (int i=0; i<10; i++) Base::Console().Warning("Write a warning to the console output.\n"); @@ -772,7 +772,7 @@ public: class ConsoleErrorTask : public QRunnable { public: - void run() + void run() override { for (int i=0; i<10; i++) Base::Console().Error("Write an error to the console output.\n"); @@ -782,7 +782,7 @@ public: class ConsoleLogTask : public QRunnable { public: - void run() + void run() override { for (int i=0; i<10; i++) Base::Console().Log("Write a log to the console output.\n"); @@ -811,7 +811,7 @@ void CmdTestConsoleOutput::activated(int iMsg) namespace Gui { -void CreateTestCommands(void) +void CreateTestCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); diff --git a/src/Gui/CommandView.cpp b/src/Gui/CommandView.cpp index 64241c21ee..6084e17e08 100644 --- a/src/Gui/CommandView.cpp +++ b/src/Gui/CommandView.cpp @@ -114,7 +114,7 @@ void StdOrthographicCamera::activated(int iMsg) } } -bool StdOrthographicCamera::isActive(void) +bool StdOrthographicCamera::isActive() { View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); if (view) { @@ -131,7 +131,7 @@ bool StdOrthographicCamera::isActive(void) return false; } -Action * StdOrthographicCamera::createAction(void) +Action * StdOrthographicCamera::createAction() { Action *pcAction = Command::createAction(); pcAction->setCheckable(true); @@ -164,7 +164,7 @@ void StdPerspectiveCamera::activated(int iMsg) } } -bool StdPerspectiveCamera::isActive(void) +bool StdPerspectiveCamera::isActive() { View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); if (view) { @@ -182,7 +182,7 @@ bool StdPerspectiveCamera::isActive(void) return false; } -Action * StdPerspectiveCamera::createAction(void) +Action * StdPerspectiveCamera::createAction() { Action *pcAction = Command::createAction(); pcAction->setCheckable(true); @@ -254,15 +254,15 @@ class StdCmdFreezeViews : public Gui::Command { public: StdCmdFreezeViews(); - virtual ~StdCmdFreezeViews(){} - const char* className() const + ~StdCmdFreezeViews() override{} + const char* className() const override { return "StdCmdFreezeViews"; } protected: - virtual void activated(int iMsg); - virtual bool isActive(void); - virtual Action * createAction(void); - virtual void languageChange(); + void activated(int iMsg) override; + bool isActive() override; + Action * createAction() override; + void languageChange() override; private: void onSaveViews(); @@ -297,7 +297,7 @@ StdCmdFreezeViews::StdCmdFreezeViews() eType = Alter3DView; } -Action * StdCmdFreezeViews::createAction(void) +Action * StdCmdFreezeViews::createAction() { ActionGroup* pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); @@ -499,7 +499,7 @@ void StdCmdFreezeViews::onRestoreViews() } } -bool StdCmdFreezeViews::isActive(void) +bool StdCmdFreezeViews::isActive() { View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); if (view) { @@ -556,27 +556,15 @@ StdCmdToggleClipPlane::StdCmdToggleClipPlane() eType = Alter3DView; } -Action * StdCmdToggleClipPlane::createAction(void) +Action * StdCmdToggleClipPlane::createAction() { Action *pcAction = (Action*)Command::createAction(); -#if 0 - pcAction->setCheckable(true); -#endif return pcAction; } void StdCmdToggleClipPlane::activated(int iMsg) { Q_UNUSED(iMsg); -#if 0 - View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); - if (view) { - if (iMsg > 0 && !view->hasClippingPlane()) - view->toggleClippingPlane(); - else if (iMsg == 0 && view->hasClippingPlane()) - view->toggleClippingPlane(); - } -#else static QPointer clipping = nullptr; if (!clipping) { View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); @@ -584,29 +572,12 @@ void StdCmdToggleClipPlane::activated(int iMsg) clipping = Gui::Dialog::Clipping::makeDockWidget(view); } } -#endif } -bool StdCmdToggleClipPlane::isActive(void) +bool StdCmdToggleClipPlane::isActive() { -#if 0 - View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); - if (view) { - Action* action = qobject_cast(_pcAction); - if (action->isChecked() != view->hasClippingPlane()) - action->setChecked(view->hasClippingPlane()); - return true; - } - else { - Action* action = qobject_cast(_pcAction); - if (action->isChecked()) - action->setChecked(false); - return false; - } -#else View3DInventor* view = qobject_cast(getMainWindow()->activeWindow()); return view ? true : false; -#endif } //=========================================================================== @@ -616,14 +587,14 @@ class StdCmdDrawStyle : public Gui::Command { public: StdCmdDrawStyle(); - virtual ~StdCmdDrawStyle(){} - virtual void languageChange(); - virtual const char* className() const {return "StdCmdDrawStyle";} + ~StdCmdDrawStyle() override{} + void languageChange() override; + const char* className() const override {return "StdCmdDrawStyle";} void updateIcon(const Gui::MDIView* view); protected: - virtual void activated(int iMsg); - virtual bool isActive(void); - virtual Gui::Action * createAction(void); + void activated(int iMsg) override; + bool isActive() override; + Gui::Action * createAction() override; }; StdCmdDrawStyle::StdCmdDrawStyle() @@ -640,7 +611,7 @@ StdCmdDrawStyle::StdCmdDrawStyle() this->getGuiApplication()->signalActivateView.connect(boost::bind(&StdCmdDrawStyle::updateIcon, this, bp::_1)); } -Gui::Action * StdCmdDrawStyle::createAction(void) +Gui::Action * StdCmdDrawStyle::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -691,7 +662,6 @@ Gui::Action * StdCmdDrawStyle::createAction(void) a6->setShortcut(QKeySequence(QString::fromUtf8("V,7"))); a6->setWhatsThis(QString::fromLatin1(getWhatsThis())); - pcAction->setIcon(a0->icon()); _pcAction = pcAction; @@ -835,7 +805,7 @@ void StdCmdDrawStyle::activated(int iMsg) } } -bool StdCmdDrawStyle::isActive(void) +bool StdCmdDrawStyle::isActive() { return Gui::Application::Instance->activeDocument(); } @@ -865,7 +835,7 @@ void StdCmdToggleVisibility::activated(int iMsg) Selection().setVisible(SelectionSingleton::VisToggle); } -bool StdCmdToggleVisibility::isActive(void) +bool StdCmdToggleVisibility::isActive() { return (Gui::Selection().size() != 0); } @@ -912,7 +882,7 @@ void StdCmdToggleSelectability::activated(int iMsg) } } -bool StdCmdToggleSelectability::isActive(void) +bool StdCmdToggleSelectability::isActive() { return (Gui::Selection().size() != 0); } @@ -940,7 +910,7 @@ void StdCmdShowSelection::activated(int iMsg) Selection().setVisible(SelectionSingleton::VisShow); } -bool StdCmdShowSelection::isActive(void) +bool StdCmdShowSelection::isActive() { return (Gui::Selection().size() != 0); } @@ -968,7 +938,7 @@ void StdCmdHideSelection::activated(int iMsg) Selection().setVisible(SelectionSingleton::VisHide); } -bool StdCmdHideSelection::isActive(void) +bool StdCmdHideSelection::isActive() { return (Gui::Selection().size() != 0); } @@ -1010,7 +980,7 @@ void StdCmdSelectVisibleObjects::activated(int iMsg) rSel.setSelection(app->getName(), visible); } -bool StdCmdSelectVisibleObjects::isActive(void) +bool StdCmdSelectVisibleObjects::isActive() { return App::GetApplication().getActiveDocument(); } @@ -1051,7 +1021,7 @@ void StdCmdToggleObjects::activated(int iMsg) } } -bool StdCmdToggleObjects::isActive(void) +bool StdCmdToggleObjects::isActive() { return App::GetApplication().getActiveDocument(); } @@ -1088,7 +1058,7 @@ void StdCmdShowObjects::activated(int iMsg) } } -bool StdCmdShowObjects::isActive(void) +bool StdCmdShowObjects::isActive() { return App::GetApplication().getActiveDocument(); } @@ -1125,7 +1095,7 @@ void StdCmdHideObjects::activated(int iMsg) } } -bool StdCmdHideObjects::isActive(void) +bool StdCmdHideObjects::isActive() { return App::GetApplication().getActiveDocument(); } @@ -1151,26 +1121,13 @@ StdCmdSetAppearance::StdCmdSetAppearance() void StdCmdSetAppearance::activated(int iMsg) { Q_UNUSED(iMsg); -#if 0 - static QPointer dlg = 0; - if (!dlg) - dlg = new Gui::Dialog::DlgDisplayPropertiesImp(true, getMainWindow()); - dlg->setModal(false); - dlg->setAttribute(Qt::WA_DeleteOnClose); - dlg->show(); -#else Gui::Control().showDialog(new Gui::Dialog::TaskDisplayProperties()); -#endif } -bool StdCmdSetAppearance::isActive(void) +bool StdCmdSetAppearance::isActive() { -#if 0 - return Gui::Selection().size() != 0; -#else return (Gui::Control().activeDialog() == nullptr) && (Gui::Selection().size() != 0); -#endif } //=========================================================================== @@ -1490,7 +1447,7 @@ void StdCmdViewFitAll::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewFit\")"); } -bool StdCmdViewFitAll::isActive(void) +bool StdCmdViewFitAll::isActive() { //return isViewOfType(Gui::View3DInventor::getClassTypeId()); return getGuiApplication()->sendHasMsgToActiveView("ViewFit"); @@ -1517,13 +1474,11 @@ StdCmdViewFitSelection::StdCmdViewFitSelection() void StdCmdViewFitSelection::activated(int iMsg) { Q_UNUSED(iMsg); - //doCommand(Command::Gui,"Gui.activeDocument().activeView().fitAll()"); doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewSelection\")"); } -bool StdCmdViewFitSelection::isActive(void) +bool StdCmdViewFitSelection::isActive() { - //return isViewOfType(Gui::View3DInventor::getClassTypeId()); return getGuiApplication()->sendHasMsgToActiveView("ViewSelection"); } @@ -1550,7 +1505,7 @@ void StdViewDock::activated(int iMsg) Q_UNUSED(iMsg); } -bool StdViewDock::isActive(void) +bool StdViewDock::isActive() { MDIView* view = getMainWindow()->activeWindow(); return (qobject_cast(view) ? true : false); @@ -1579,7 +1534,7 @@ void StdViewUndock::activated(int iMsg) Q_UNUSED(iMsg); } -bool StdViewUndock::isActive(void) +bool StdViewUndock::isActive() { MDIView* view = getMainWindow()->activeWindow(); return (qobject_cast(view) ? true : false); @@ -1641,7 +1596,7 @@ void StdViewFullscreen::activated(int iMsg) Q_UNUSED(iMsg); } -bool StdViewFullscreen::isActive(void) +bool StdViewFullscreen::isActive() { MDIView* view = getMainWindow()->activeWindow(); return (qobject_cast(view) ? true : false); @@ -1668,7 +1623,7 @@ StdViewDockUndockFullscreen::StdViewDockUndockFullscreen() rcCmdMgr.addCommand(new StdViewFullscreen()); } -Action * StdViewDockUndockFullscreen::createAction(void) +Action * StdViewDockUndockFullscreen::createAction() { ActionGroup* pcAction = new ActionGroup(this, getMainWindow()); pcAction->setDropDownMenu(true); @@ -1733,13 +1688,12 @@ void StdViewDockUndockFullscreen::activated(int iMsg) else clone->setCurrentViewMode(MDIView::FullScreen); } - // destroy the old view view->deleteSelf(); } } -bool StdViewDockUndockFullscreen::isActive(void) +bool StdViewDockUndockFullscreen::isActive() { MDIView* view = getMainWindow()->activeWindow(); if (qobject_cast(view)) { @@ -1779,12 +1733,11 @@ StdCmdViewVR::StdCmdViewVR() void StdCmdViewVR::activated(int iMsg) { - Q_UNUSED(iMsg); - //doCommand(Command::Gui,"Gui.activeDocument().activeView().fitAll()"); + Q_UNUSED(iMsg); doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"ViewVR\")"); } -bool StdCmdViewVR::isActive(void) +bool StdCmdViewVR::isActive() { return getGuiApplication()->sendHasMsgToActiveView("ViewVR"); } @@ -1861,7 +1814,7 @@ void StdViewScreenShot::activated(int iMsg) if (fd.exec() == QDialog::Accepted) { selFilter = fd.selectedNameFilter(); - QString fn = fd.selectedFiles().front(); + QString fn = fd.selectedFiles().constFirst(); // We must convert '\' path separators to '/' before otherwise // Python would interpret them as escape sequences. fn.replace(QLatin1Char('\\'), QLatin1Char('/')); @@ -1957,7 +1910,7 @@ void StdViewScreenShot::activated(int iMsg) } } -bool StdViewScreenShot::isActive(void) +bool StdViewScreenShot::isActive() { return isViewOfType(Gui::View3DInventor::getClassTypeId()); } @@ -1987,9 +1940,9 @@ void StdCmdViewCreate::activated(int iMsg) getActiveGuiDocument()->getActiveView()->viewAll(); } -bool StdCmdViewCreate::isActive(void) +bool StdCmdViewCreate::isActive() { - return (getActiveGuiDocument()!=nullptr); + return (getActiveGuiDocument() != nullptr); } //=========================================================================== @@ -2022,7 +1975,7 @@ void StdCmdToggleNavigation::activated(int iMsg) } } -bool StdCmdToggleNavigation::isActive(void) +bool StdCmdToggleNavigation::isActive() { //#0001087: Inventor Navigation continues with released Mouse Button //This happens because 'Esc' is also used to close the task dialog. @@ -2040,95 +1993,7 @@ bool StdCmdToggleNavigation::isActive(void) -#if 0 // old Axis command -// Command to show/hide axis cross -class StdCmdAxisCross : public Gui::Command -{ -private: - SoShapeScale* axisCross; - SoGroup* axisGroup; -public: - StdCmdAxisCross() : Command("Std_AxisCross"), axisCross(0), axisGroup(0) - { - sGroup = "Standard-View"; - sMenuText = QT_TR_NOOP("Toggle axis cross"); - sToolTipText = QT_TR_NOOP("Toggle axis cross"); - sStatusTip = QT_TR_NOOP("Toggle axis cross"); - sWhatsThis = "Std_AxisCross"; - sPixmap = "Std_AxisCross"; - } - ~StdCmdAxisCross() - { - if (axisGroup) - axisGroup->unref(); - if (axisCross) - axisCross->unref(); - } - const char* className() const - { return "StdCmdAxisCross"; } - Action * createAction(void) - { - axisCross = new Gui::SoShapeScale; - axisCross->ref(); - Gui::SoAxisCrossKit* axisKit = new Gui::SoAxisCrossKit(); - axisKit->set("xAxis.appearance.drawStyle", "lineWidth 2"); - axisKit->set("yAxis.appearance.drawStyle", "lineWidth 2"); - axisKit->set("zAxis.appearance.drawStyle", "lineWidth 2"); - axisCross->setPart("shape", axisKit); - axisGroup = new SoSkipBoundingGroup; - axisGroup->ref(); - axisGroup->addChild(axisCross); - - Action *pcAction = Gui::Command::createAction(); - pcAction->setCheckable(true); - return pcAction; - } - -protected: - void activated(int iMsg) - { - float scale = 1.0f; - - Gui::View3DInventor* view = qobject_cast - (getMainWindow()->activeWindow()); - if (view) { - SoNode* scene = view->getViewer()->getSceneGraph(); - SoSeparator* sep = static_cast(scene); - bool hasaxis = (sep->findChild(axisGroup) != -1); - if (iMsg > 0 && !hasaxis) { - axisCross->scaleFactor = scale; - sep->addChild(axisGroup); - } - else if (iMsg == 0 && hasaxis) { - sep->removeChild(axisGroup); - } - } - } - - bool isActive(void) - { - Gui::View3DInventor* view = qobject_cast(Gui::getMainWindow()->activeWindow()); - if (view) { - Gui::View3DInventorViewer* viewer = view->getViewer(); - if (!viewer) - return false; // no active viewer - SoGroup* group = dynamic_cast(viewer->getSceneGraph()); - if (!group) - return false; // empty scene graph - bool hasaxis = group->findChild(axisGroup) != -1; - if (_pcAction->isChecked() != hasaxis) - _pcAction->setChecked(hasaxis); - return true; - } - else { - if (_pcAction->isChecked()) - _pcAction->setChecked(false); - return false; - } - } -}; -#else //=========================================================================== // Std_ViewExample1 //=========================================================================== @@ -2158,7 +2023,7 @@ void StdCmdAxisCross::activated(int iMsg) } } -bool StdCmdAxisCross::isActive(void) +bool StdCmdAxisCross::isActive() { Gui::View3DInventor* view = qobject_cast(Gui::getMainWindow()->activeWindow()); if (view && view->getViewer()->hasAxisCross()) { @@ -2175,8 +2040,6 @@ bool StdCmdAxisCross::isActive(void) } -#endif - //=========================================================================== // Std_ViewExample1 //=========================================================================== @@ -2200,7 +2063,7 @@ void StdCmdViewExample1::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Example1\")"); } -bool StdCmdViewExample1::isActive(void) +bool StdCmdViewExample1::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Example1"); } @@ -2228,7 +2091,7 @@ void StdCmdViewExample2::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Example2\")"); } -bool StdCmdViewExample2::isActive(void) +bool StdCmdViewExample2::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Example2"); } @@ -2256,7 +2119,7 @@ void StdCmdViewExample3::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView(\"Example3\")"); } -bool StdCmdViewExample3::isActive(void) +bool StdCmdViewExample3::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Example3"); } @@ -2285,7 +2148,7 @@ void StdCmdViewIvStereoOff::activated(int iMsg) doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"Mono\")"); } -bool StdCmdViewIvStereoOff::isActive(void) +bool StdCmdViewIvStereoOff::isActive() { return getGuiApplication()->sendHasMsgToActiveView("SetStereoOff"); } @@ -2314,7 +2177,7 @@ void StdCmdViewIvStereoRedGreen::activated(int iMsg) doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"Anaglyph\")"); } -bool StdCmdViewIvStereoRedGreen::isActive(void) +bool StdCmdViewIvStereoRedGreen::isActive() { return getGuiApplication()->sendHasMsgToActiveView("SetStereoRedGreen"); } @@ -2342,7 +2205,7 @@ void StdCmdViewIvStereoQuadBuff::activated(int iMsg) doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"QuadBuffer\")"); } -bool StdCmdViewIvStereoQuadBuff::isActive(void) +bool StdCmdViewIvStereoQuadBuff::isActive() { return getGuiApplication()->sendHasMsgToActiveView("SetStereoQuadBuff"); } @@ -2370,7 +2233,7 @@ void StdCmdViewIvStereoInterleavedRows::activated(int iMsg) doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"InterleavedRows\")"); } -bool StdCmdViewIvStereoInterleavedRows::isActive(void) +bool StdCmdViewIvStereoInterleavedRows::isActive() { return getGuiApplication()->sendHasMsgToActiveView("SetStereoInterleavedRows"); } @@ -2398,7 +2261,7 @@ void StdCmdViewIvStereoInterleavedColumns::activated(int iMsg) doCommand(Command::Gui,"Gui.activeDocument().activeView().setStereoType(\"InterleavedColumns\")"); } -bool StdCmdViewIvStereoInterleavedColumns::isActive(void) +bool StdCmdViewIvStereoInterleavedColumns::isActive() { return getGuiApplication()->sendHasMsgToActiveView("SetStereoInterleavedColumns"); } @@ -2448,7 +2311,7 @@ void StdCmdViewIvIssueCamPos::activated(int iMsg) getGuiApplication()->macroManager()->addLine(MacroManager::Gui,Temp.c_str()); } -bool StdCmdViewIvIssueCamPos::isActive(void) +bool StdCmdViewIvIssueCamPos::isActive() { return getGuiApplication()->sendHasMsgToActiveView("GetCamera"); } @@ -2482,7 +2345,7 @@ void StdViewZoomIn::activated(int iMsg) } } -bool StdViewZoomIn::isActive(void) +bool StdViewZoomIn::isActive() { return (qobject_cast(getMainWindow()->activeWindow())); } @@ -2515,7 +2378,7 @@ void StdViewZoomOut::activated(int iMsg) } } -bool StdViewZoomOut::isActive(void) +bool StdViewZoomOut::isActive() { return (qobject_cast(getMainWindow()->activeWindow())); } @@ -2858,7 +2721,7 @@ static std::vector getBoxSelection( continue; const auto &sels = getBoxSelection(svp,mode,selectElement,proj,polygon,smat,false,depth+1); - if(sels.size()==1 && sels[0] == "") + if(sels.size()==1 && sels[0].empty()) ++count; for(auto &sel : sels) ret.emplace_back(sub+sel); @@ -3123,7 +2986,7 @@ StdCmdTreeSelectAllInstances::StdCmdTreeSelectAllInstances() eType = AlterSelection; } -bool StdCmdTreeSelectAllInstances::isActive(void) +bool StdCmdTreeSelectAllInstances::isActive() { const auto &sels = Selection().getSelectionEx("*",App::DocumentObject::getClassTypeId(), ResolveMode::OldStyleElement, true); if(sels.empty()) @@ -3132,7 +2995,7 @@ bool StdCmdTreeSelectAllInstances::isActive(void) if(!obj || !obj->getNameInDocument()) return false; return dynamic_cast( - Application::Instance->getViewProvider(obj))!=nullptr; + Application::Instance->getViewProvider(obj)) != nullptr; } void StdCmdTreeSelectAllInstances::activated(int iMsg) @@ -3150,7 +3013,8 @@ void StdCmdTreeSelectAllInstances::activated(int iMsg) return; Selection().selStackPush(); Selection().clearCompleteSelection(); - for(auto tree : getMainWindow()->findChildren()) + const auto trees = getMainWindow()->findChildren(); + for(auto tree : trees) tree->selectAllInstances(*vpd); Selection().selStackPush(); } @@ -3230,7 +3094,7 @@ void StdCmdMeasureDistance::activated(int iMsg) } } -bool StdCmdMeasureDistance::isActive(void) +bool StdCmdMeasureDistance::isActive() { App::Document* doc = App::GetApplication().getActiveDocument(); if (!doc || doc->countObjectsOfType(App::GeoFeature::getClassTypeId()) == 0) @@ -3303,11 +3167,11 @@ void StdCmdTextureMapping::activated(int iMsg) Gui::Control().showDialog(new Gui::Dialog::TaskTextureMapping); } -bool StdCmdTextureMapping::isActive(void) +bool StdCmdTextureMapping::isActive() { Gui::MDIView* view = getMainWindow()->activeWindow(); return view && view->isDerivedFrom(Gui::View3DInventor::getClassTypeId()) - && (Gui::Control().activeDialog()==nullptr); + && (Gui::Control().activeDialog() == nullptr); } DEF_STD_CMD(StdCmdDemoMode) @@ -3418,7 +3282,7 @@ void StdCmdSelBack::activated(int iMsg) Selection().selStackGoBack(); } -bool StdCmdSelBack::isActive(void) +bool StdCmdSelBack::isActive() { return Selection().selStackBackSize()>1; } @@ -3448,7 +3312,7 @@ void StdCmdSelForward::activated(int iMsg) Selection().selStackGoForward(); } -bool StdCmdSelForward::isActive(void) +bool StdCmdSelForward::isActive() { return !!Selection().selStackForwardSize(); } @@ -3658,7 +3522,8 @@ StdTreeDrag::StdTreeDrag() void StdTreeDrag::activated(int) { if(Gui::Selection().hasSelection()) { - for(auto tree : getMainWindow()->findChildren()) { + const auto trees = getMainWindow()->findChildren(); + for(auto tree : trees) { if(tree->isVisible()) { tree->startDragging(); break; @@ -3699,10 +3564,10 @@ public: addCommand(); - addCommand(new StdTreeDrag(),cmds.size()); - addCommand(new StdTreeSelection(),cmds.size()); + addCommand(new StdTreeDrag(),!cmds.empty()); + addCommand(new StdTreeSelection(),!cmds.empty()); }; - virtual const char* className() const {return "StdCmdTreeViewActions";} + const char* className() const override {return "StdCmdTreeViewActions";} }; @@ -3733,7 +3598,7 @@ void StdCmdSelBoundingBox::activated(int iMsg) } } -bool StdCmdSelBoundingBox::isActive(void) +bool StdCmdSelBoundingBox::isActive() { if(_pcAction) { bool checked = _pcAction->isChecked(); @@ -3743,7 +3608,7 @@ bool StdCmdSelBoundingBox::isActive(void) return true; } -Action * StdCmdSelBoundingBox::createAction(void) +Action * StdCmdSelBoundingBox::createAction() { Action *pcAction = Command::createAction(); pcAction->setCheckable(true); @@ -3757,7 +3622,7 @@ Action * StdCmdSelBoundingBox::createAction(void) namespace Gui { -void CreateViewStdCommands(void) +void CreateViewStdCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); @@ -3831,7 +3696,6 @@ void CreateViewStdCommands(void) rcCmdMgr.addCommand(new StdCmdSelForward()); rcCmdMgr.addCommand(new StdCmdTreeViewActions()); - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); if(hGrp->GetASCII("GestureRollFwdCommand").empty()) hGrp->SetASCII("GestureRollFwdCommand","Std_SelForward"); diff --git a/src/Gui/CommandWindow.cpp b/src/Gui/CommandWindow.cpp index 196ce99130..e592a70642 100644 --- a/src/Gui/CommandWindow.cpp +++ b/src/Gui/CommandWindow.cpp @@ -65,7 +65,7 @@ void StdCmdArrangeIcons::activated(int iMsg) getMainWindow()->arrangeIcons (); } -bool StdCmdArrangeIcons::isActive(void) +bool StdCmdArrangeIcons::isActive() { return !(getMainWindow()->windows().isEmpty()); } @@ -93,7 +93,7 @@ void StdCmdTileWindows::activated(int iMsg) getMainWindow()->tile(); } -bool StdCmdTileWindows::isActive(void) +bool StdCmdTileWindows::isActive() { return !(getMainWindow()->windows().isEmpty()); } @@ -121,7 +121,7 @@ void StdCmdCascadeWindows::activated(int iMsg) getMainWindow()->cascade(); } -bool StdCmdCascadeWindows::isActive(void) +bool StdCmdCascadeWindows::isActive() { return !(getMainWindow()->windows().isEmpty()); } @@ -153,7 +153,7 @@ void StdCmdCloseActiveWindow::activated(int iMsg) getMainWindow()->closeActiveWindow(); } -bool StdCmdCloseActiveWindow::isActive(void) +bool StdCmdCloseActiveWindow::isActive() { return !(getMainWindow()->windows().isEmpty()); } @@ -181,9 +181,9 @@ void StdCmdCloseAllWindows::activated(int iMsg) getMainWindow()->closeAllDocuments(); } -bool StdCmdCloseAllWindows::isActive(void) +bool StdCmdCloseAllWindows::isActive() { - return !(getMainWindow()->windows().isEmpty()) || App::GetApplication().getDocuments().size(); + return !(getMainWindow()->windows().isEmpty()) || !App::GetApplication().getDocuments().empty(); } //=========================================================================== @@ -210,7 +210,7 @@ void StdCmdActivateNextWindow::activated(int iMsg) getMainWindow()->activateNextWindow(); } -bool StdCmdActivateNextWindow::isActive(void) +bool StdCmdActivateNextWindow::isActive() { return !(getMainWindow()->windows().isEmpty()); } @@ -239,7 +239,7 @@ void StdCmdActivatePrevWindow::activated(int iMsg) getMainWindow()->activatePreviousWindow(); } -bool StdCmdActivatePrevWindow::isActive(void) +bool StdCmdActivatePrevWindow::isActive() { return !(getMainWindow()->windows().isEmpty()); } @@ -312,12 +312,12 @@ void StdCmdDockViewMenu::activated(int iMsg) Q_UNUSED(iMsg); } -bool StdCmdDockViewMenu::isActive(void) +bool StdCmdDockViewMenu::isActive() { return true; } -Action * StdCmdDockViewMenu::createAction(void) +Action * StdCmdDockViewMenu::createAction() { Action *pcAction; pcAction = new DockWidgetAction(this, getMainWindow()); @@ -348,12 +348,12 @@ void StdCmdToolBarMenu::activated(int iMsg) Q_UNUSED(iMsg); } -bool StdCmdToolBarMenu::isActive(void) +bool StdCmdToolBarMenu::isActive() { return true; } -Action * StdCmdToolBarMenu::createAction(void) +Action * StdCmdToolBarMenu::createAction() { Action *pcAction; pcAction = new ToolBarAction(this, getMainWindow()); @@ -374,9 +374,9 @@ public: // virtual ~FilterStatusBar() {} protected: Action * action; - bool eventFilter(QObject *obj, QEvent *event) + bool eventFilter(QObject *obj, QEvent *event) override { - if (getMainWindow()->findChild() != nullptr && obj == getMainWindow()->statusBar() && ((event->type() == QEvent::Hide) || (event->type() == QEvent::Show))) { + if (getMainWindow()->findChild() && obj == getMainWindow()->statusBar() && ((event->type() == QEvent::Hide) || (event->type() == QEvent::Show))) { this->action->setChecked(getMainWindow()->statusBar()->isVisible()); } return false; @@ -396,7 +396,7 @@ StdCmdStatusBar::StdCmdStatusBar() eType = 0; } -Action * StdCmdStatusBar::createAction(void) +Action * StdCmdStatusBar::createAction() { Action *pcAction = Command::createAction(); pcAction->setCheckable(true); @@ -448,12 +448,12 @@ void StdCmdWindowsMenu::activated(int iMsg) Q_UNUSED(iMsg); } -bool StdCmdWindowsMenu::isActive(void) +bool StdCmdWindowsMenu::isActive() { return true; } -Action * StdCmdWindowsMenu::createAction(void) +Action * StdCmdWindowsMenu::createAction() { // Allow to show 10 menu items in the 'Window' menu and one separator. // If we have more windows then the user can use the 'Windows...' item. @@ -483,7 +483,7 @@ Action * StdCmdWindowsMenu::createAction(void) namespace Gui { -void CreateWindowStdCommands(void) +void CreateWindowStdCommands() { CommandManager &rcCmdMgr = Application::Instance->commandManager(); diff --git a/src/Gui/Control.cpp b/src/Gui/Control.cpp index 38eb27e7ed..85ed4d3aac 100644 --- a/src/Gui/Control.cpp +++ b/src/Gui/Control.cpp @@ -230,7 +230,7 @@ void ControlSingleton::closedDialog() | QDockWidget::DockWidgetFloatable); } -bool ControlSingleton::isAllowedAlterDocument(void) const +bool ControlSingleton::isAllowedAlterDocument() const { if (ActiveDialog) return ActiveDialog->isAllowedAlterDocument(); @@ -238,14 +238,14 @@ bool ControlSingleton::isAllowedAlterDocument(void) const } -bool ControlSingleton::isAllowedAlterView(void) const +bool ControlSingleton::isAllowedAlterView() const { if (ActiveDialog) return ActiveDialog->isAllowedAlterView(); return true; } -bool ControlSingleton::isAllowedAlterSelection(void) const +bool ControlSingleton::isAllowedAlterSelection() const { if (ActiveDialog) return ActiveDialog->isAllowedAlterSelection(); @@ -254,16 +254,16 @@ bool ControlSingleton::isAllowedAlterSelection(void) const // ------------------------------------------- -ControlSingleton& ControlSingleton::instance(void) +ControlSingleton& ControlSingleton::instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) _pcSingleton = new ControlSingleton; return *_pcSingleton; } -void ControlSingleton::destruct (void) +void ControlSingleton::destruct () { - if (_pcSingleton != nullptr) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } diff --git a/src/Gui/Control.h b/src/Gui/Control.h index 169ce37bf5..7da5098ce3 100644 --- a/src/Gui/Control.h +++ b/src/Gui/Control.h @@ -56,8 +56,8 @@ class GuiExport ControlSingleton : public QObject Q_OBJECT public: - static ControlSingleton& instance(void); - static void destruct (void); + static ControlSingleton& instance(); + static void destruct (); /** @name dialog handling * These methods are used to control the TaskDialog stuff. @@ -83,17 +83,17 @@ public: If a task dialog is open then it indicates whether this task dialog allows other commands to modify the document while it is open. If no task dialog is open true is returned. */ - bool isAllowedAlterDocument(void) const; + bool isAllowedAlterDocument() const; /*! If a task dialog is open then it indicates whether this task dialog allows other commands to modify the 3d view while it is open. If no task dialog is open true is returned. */ - bool isAllowedAlterView(void) const; + bool isAllowedAlterView() const; /*! If a task dialog is open then it indicates whether this task dialog allows other commands to modify the selection while it is open. If no task dialog is open true is returned. */ - bool isAllowedAlterSelection(void) const; + bool isAllowedAlterSelection() const; public Q_SLOTS: void accept(); @@ -122,13 +122,13 @@ private: /// Construction ControlSingleton(); /// Destruction - virtual ~ControlSingleton(); + ~ControlSingleton() override; static ControlSingleton* _pcSingleton; }; /// Get the global instance -inline ControlSingleton& Control(void) +inline ControlSingleton& Control() { return ControlSingleton::instance(); } diff --git a/src/Gui/DAGView/DAGFilter.h b/src/Gui/DAGView/DAGFilter.h index 0ceb90aae8..4a71408d0c 100644 --- a/src/Gui/DAGView/DAGFilter.h +++ b/src/Gui/DAGView/DAGFilter.h @@ -56,7 +56,7 @@ namespace Gui { public: FilterOrigin(); - virtual bool goFilter(const Vertex &vertexIn, const Graph &graphIn, const GraphLinkContainer &linkIn) const override; + bool goFilter(const Vertex &vertexIn, const Graph &graphIn, const GraphLinkContainer &linkIn) const override; }; /*! Hide nodes of type*/ @@ -65,7 +65,7 @@ namespace Gui public: explicit FilterTyped(const std::string &typeIn); std::string type; - virtual bool goFilter(const Vertex &vertexIn, const Graph &graphIn, const GraphLinkContainer &linkIn) const override; + bool goFilter(const Vertex &vertexIn, const Graph &graphIn, const GraphLinkContainer &linkIn) const override; }; } } diff --git a/src/Gui/DAGView/DAGModel.cpp b/src/Gui/DAGView/DAGModel.cpp index 7eb0821964..75509c1d18 100644 --- a/src/Gui/DAGView/DAGModel.cpp +++ b/src/Gui/DAGView/DAGModel.cpp @@ -1095,7 +1095,7 @@ void Model::contextMenuEvent(QGraphicsSceneContextMenuEvent* event) void Model::onRenameSlot() { - assert(proxy == nullptr); + assert(!proxy); std::vector selections = getAllSelected(); assert(selections.size() == 1); diff --git a/src/Gui/DAGView/DAGModel.h b/src/Gui/DAGView/DAGModel.h index 80dc4d8645..e29eb03e9e 100644 --- a/src/Gui/DAGView/DAGModel.h +++ b/src/Gui/DAGView/DAGModel.h @@ -52,12 +52,12 @@ namespace Gui { Q_OBJECT public: - LineEdit(QWidget *parentIn = nullptr); + explicit LineEdit(QWidget *parentIn = nullptr); Q_SIGNALS: void acceptedSignal(); void rejectedSignal(); protected: - virtual void keyPressEvent(QKeyEvent*); + void keyPressEvent(QKeyEvent*) override; }; class Model : public QGraphicsScene @@ -65,15 +65,15 @@ namespace Gui Q_OBJECT public: Model(QObject *parentIn, const Gui::Document &documentIn); - virtual ~Model() override; + ~Model() override; void awake(); //!< hooked up to event dispatcher for update when idle. void selectionChanged(const SelectionChanges& msg); protected: - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; - virtual void mousePressEvent(QGraphicsSceneMouseEvent* event) override; - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; - virtual void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent* event) override; + void mousePressEvent(QGraphicsSceneMouseEvent* event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; + void contextMenuEvent(QGraphicsSceneContextMenuEvent* event) override; private Q_SLOTS: void updateSlot(); diff --git a/src/Gui/DAGView/DAGModelGraph.h b/src/Gui/DAGView/DAGModelGraph.h index e6174652e2..166a797176 100644 --- a/src/Gui/DAGView/DAGModelGraph.h +++ b/src/Gui/DAGView/DAGModelGraph.h @@ -134,7 +134,7 @@ namespace Gui template class Edge_writer { public: - Edge_writer(const GraphEW &graphEWIn) : graphEW(graphEWIn) {} + explicit Edge_writer(const GraphEW &graphEWIn) : graphEW(graphEWIn) {} template void operator()(std::ostream& out, const EdgeW& /*edgeW*/) const { @@ -149,7 +149,7 @@ namespace Gui template class Vertex_writer { public: - Vertex_writer(const GraphVW &graphVWIn) : graphVW(graphVWIn) {} + explicit Vertex_writer(const GraphVW &graphVWIn) : graphVW(graphVWIn) {} template void operator()(std::ostream& out, const VertexW& vertexW) const { @@ -176,7 +176,7 @@ namespace Gui typedef boost::graph_traits::vertex_descriptor GraphInVertex; typedef std::vector GraphInVertices; public: - RakeLeaves(const GraphIn &graphIn) : graph(graphIn) {} + explicit RakeLeaves(const GraphIn &graphIn) : graph(graphIn) {} GraphInVertices operator()() const { GraphInVertices out; @@ -198,7 +198,7 @@ namespace Gui typedef boost::graph_traits::vertex_descriptor GraphInVertex; typedef std::vector GraphInVertices; public: - DigRoots(const GraphIn &graphIn) : graph(graphIn) {} + explicit DigRoots(const GraphIn &graphIn) : graph(graphIn) {} GraphInVertices operator()() const { GraphInVertices out; @@ -218,7 +218,7 @@ namespace Gui class ConnectionVisitor : public boost::default_bfs_visitor { public: - ConnectionVisitor(std::vector &verticesIn) : vertices(verticesIn){} + explicit ConnectionVisitor(std::vector &verticesIn) : vertices(verticesIn){} template void discover_vertex(TVertex vertex, TGraph &graph) diff --git a/src/Gui/DAGView/DAGRectItem.h b/src/Gui/DAGView/DAGRectItem.h index 9537e1df19..fe88a15945 100644 --- a/src/Gui/DAGView/DAGRectItem.h +++ b/src/Gui/DAGView/DAGRectItem.h @@ -37,7 +37,7 @@ namespace Gui class RectItem : public QGraphicsRectItem { public: - RectItem(QGraphicsItem* parent = nullptr); + explicit RectItem(QGraphicsItem* parent = nullptr); void setBackgroundBrush(const QBrush &brushIn){backgroundBrush = brushIn;} void setEditingBrush(const QBrush &brushIn){editBrush = brushIn;} void preHighlightOn(){preSelected = true;} @@ -50,7 +50,7 @@ namespace Gui void editingFinished(){editing = false;} bool isEditing(){return editing;} protected: - virtual void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr); + void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget = nullptr) override; private: QBrush backgroundBrush; //!< brush used for background. not used yet. QBrush editBrush; //!< brush used when object is in edit mode. diff --git a/src/Gui/DAGView/DAGView.h b/src/Gui/DAGView/DAGView.h index f6329e8d08..efd1d145be 100644 --- a/src/Gui/DAGView/DAGView.h +++ b/src/Gui/DAGView/DAGView.h @@ -43,14 +43,14 @@ namespace Gui { Q_OBJECT public: - View(QWidget *parentIn = nullptr); - virtual ~View() override; + explicit View(QWidget *parentIn = nullptr); + ~View() override; public Q_SLOTS: void awakeSlot(); //!< hooked up to event dispatcher for update when idle. private: - virtual void onSelectionChanged(const SelectionChanges& msg) override; + void onSelectionChanged(const SelectionChanges& msg) override; void slotActiveDocument(const Gui::Document &documentIn); void slotDeleteDocument(const Gui::Document &documentIn); @@ -66,8 +66,8 @@ namespace Gui { Q_OBJECT public: - DockWindow(Gui::Document* gDocumentIn = nullptr, QWidget *parent = nullptr); - ~DockWindow(){} + explicit DockWindow(Gui::Document* gDocumentIn = nullptr, QWidget *parent = nullptr); + ~DockWindow() override{} private: View *dagView; diff --git a/src/Gui/DlgActionsImp.h b/src/Gui/DlgActionsImp.h index 6770fb5a05..53e01a7925 100644 --- a/src/Gui/DlgActionsImp.h +++ b/src/Gui/DlgActionsImp.h @@ -53,8 +53,8 @@ class DlgCustomActionsImp : public CustomizeActionPage Q_OBJECT public: - DlgCustomActionsImp( QWidget* parent = nullptr ); - ~DlgCustomActionsImp(); + explicit DlgCustomActionsImp( QWidget* parent = nullptr ); + ~DlgCustomActionsImp() override; Q_SIGNALS: void addMacroAction( const QByteArray& ); @@ -63,8 +63,8 @@ Q_SIGNALS: protected: /** Trigger for reparent event. */ - bool event(QEvent* e); - void changeEvent(QEvent *e); + bool event(QEvent* e) override; + void changeEvent(QEvent *e) override; protected Q_SLOTS: /** Enables/disables buttons for deletion */ @@ -77,9 +77,9 @@ protected Q_SLOTS: void on_buttonRemoveAction_clicked(); /** Shows the setup of the action */ void on_buttonReplaceAction_clicked(); - void onAddMacroAction(const QByteArray&); - void onRemoveMacroAction(const QByteArray&); - void onModifyMacroAction(const QByteArray&); + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; private: /** Shows all actions and their pixmaps if available */ @@ -96,9 +96,9 @@ class IconDialog : public QDialog Q_OBJECT public: - IconDialog(QWidget* parent); - ~IconDialog(); - void resizeEvent(QResizeEvent*); + explicit IconDialog(QWidget* parent); + ~IconDialog() override; + void resizeEvent(QResizeEvent*) override; QListWidgetItem* currentItem() const; private Q_SLOTS: @@ -114,7 +114,7 @@ class IconFolders : public QDialog public: IconFolders(const QStringList&, QWidget* parent); - ~IconFolders(); + ~IconFolders() override; QStringList getPaths() const; private Q_SLOTS: diff --git a/src/Gui/DlgActivateWindowImp.h b/src/Gui/DlgActivateWindowImp.h index 33537dc43b..6cdb3f4097 100644 --- a/src/Gui/DlgActivateWindowImp.h +++ b/src/Gui/DlgActivateWindowImp.h @@ -40,11 +40,11 @@ class DlgActivateWindowImp : public QDialog Q_OBJECT public: - DlgActivateWindowImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgActivateWindowImp(); + explicit DlgActivateWindowImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgActivateWindowImp() override; protected: - void accept(); + void accept() override; private: Ui_DlgActivateWindow* ui; diff --git a/src/Gui/DlgAddProperty.cpp b/src/Gui/DlgAddProperty.cpp index f97f38b87f..2fe4d34065 100644 --- a/src/Gui/DlgAddProperty.cpp +++ b/src/Gui/DlgAddProperty.cpp @@ -56,7 +56,7 @@ DlgAddProperty::DlgAddProperty(QWidget* parent, std::vector types; Base::Type::getAllDerivedFrom(Base::Type::fromName("App::Property"),types); - for(auto type : types) { + for(const auto& type : types) { ui->comboType->addItem(QString::fromLatin1(type.getName())); if(type == defType) ui->comboType->setCurrentIndex(ui->comboType->count()-1); diff --git a/src/Gui/DlgCheckableMessageBox.h b/src/Gui/DlgCheckableMessageBox.h index 7556fda1b2..f20978eccc 100644 --- a/src/Gui/DlgCheckableMessageBox.h +++ b/src/Gui/DlgCheckableMessageBox.h @@ -33,6 +33,7 @@ #include #include #include +#include namespace Gui { namespace Dialog { @@ -46,13 +47,13 @@ struct DlgCheckableMessageBoxPrivate; class GuiExport DlgCheckableMessageBox : public QDialog { Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText) - Q_PROPERTY(QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap) - Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) + Q_PROPERTY(QString text READ text WRITE setText) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QPixmap iconPixmap READ iconPixmap WRITE setIconPixmap) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool isChecked READ isChecked WRITE setChecked) // clazy:exclude=qproperty-without-notify //Q_PROPERTY(QString prefEntry WRITE setPrefEntry) // Must have a READ accessor! - Q_PROPERTY(QString checkBoxText READ checkBoxText WRITE setCheckBoxText) - Q_PROPERTY(QDialogButtonBox::StandardButtons buttons READ standardButtons WRITE setStandardButtons) - Q_PROPERTY(QDialogButtonBox::StandardButton defaultButton READ defaultButton WRITE setDefaultButton) + Q_PROPERTY(QString checkBoxText READ checkBoxText WRITE setCheckBoxText) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QDialogButtonBox::StandardButtons buttons READ standardButtons WRITE setStandardButtons) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QDialogButtonBox::StandardButton defaultButton READ defaultButton WRITE setDefaultButton) // clazy:exclude=qproperty-without-notify public: explicit DlgCheckableMessageBox(QWidget *parent); virtual ~DlgCheckableMessageBox(); @@ -82,40 +83,40 @@ public: QString checkBoxText() const; void setCheckBoxText(const QString &); - QDialogButtonBox::StandardButtons standardButtons() const; - void setStandardButtons(QDialogButtonBox::StandardButtons s); + QDialogButtonBox::StandardButtons standardButtons() const; + void setStandardButtons(QDialogButtonBox::StandardButtons s); - QDialogButtonBox::StandardButton defaultButton() const; - void setDefaultButton(QDialogButtonBox::StandardButton s); + QDialogButtonBox::StandardButton defaultButton() const; + void setDefaultButton(QDialogButtonBox::StandardButton s); // see static QMessageBox::standardPixmap() QPixmap iconPixmap() const; void setIconPixmap (const QPixmap &p); - // Query the result - QAbstractButton *clickedButton() const; - QDialogButtonBox::StandardButton clickedStandardButton() const; + // Query the result + QAbstractButton *clickedButton() const; + QDialogButtonBox::StandardButton clickedStandardButton() const; - // Conversion convenience - static QMessageBox::StandardButton dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton); + // Conversion convenience + static QMessageBox::StandardButton dialogButtonBoxToMessageBoxButton(QDialogButtonBox::StandardButton); - /// convenient show method - /// It shows a dialog with header and message provided and a checkbox in check state with the message provided. - /// It uses a parameter in path "User parameter:BaseApp/CheckMessages" derived from the header test, defaulting to false, - /// to store the status of the checkbox, when the user exits the modal dialog. - static void showMessage(const QString& header, const QString& message, bool check = false, const QString& checkText = QString::fromLatin1("Don't show me again")); + /// convenient show method + /// It shows a dialog with header and message provided and a checkbox in check state with the message provided. + /// It uses a parameter in path "User parameter:BaseApp/CheckMessages" derived from the header test, defaulting to false, + /// to store the status of the checkbox, when the user exits the modal dialog. + static void showMessage(const QString& header, const QString& message, bool check = false, const QString& checkText = QString::fromLatin1("Don't show me again")); - /// Same as showMessage above, but it checks the specific preference path and parameter provided, defaulting to entryDefault value if the parameter is not present. - static void showMessage(const QString& header, const QString& message, const QString& prefPath, const QString& paramEntry, bool entryDefault = false, - bool check = false, const QString& checkText = QString::fromLatin1("Don't show me again")); + /// Same as showMessage above, but it checks the specific preference path and parameter provided, defaulting to entryDefault value if the parameter is not present. + static void showMessage(const QString& header, const QString& message, const QString& prefPath, const QString& paramEntry, bool entryDefault = false, + bool check = false, const QString& checkText = QString::fromLatin1("Don't show me again")); private Q_SLOTS: - void slotClicked(QAbstractButton *b); + void slotClicked(QAbstractButton *b); private: - DlgCheckableMessageBoxPrivate *m_d; - QByteArray paramEntry; - QString prefPath; + DlgCheckableMessageBoxPrivate *m_d; + QByteArray paramEntry; + QString prefPath; }; } // namespace Dialog diff --git a/src/Gui/DlgCommandsImp.cpp b/src/Gui/DlgCommandsImp.cpp index b73166104f..ad3462b841 100644 --- a/src/Gui/DlgCommandsImp.cpp +++ b/src/Gui/DlgCommandsImp.cpp @@ -43,7 +43,7 @@ typedef std::vector< std::pair > GroupMap; struct GroupMap_find { const QLatin1String& item; - GroupMap_find(const QLatin1String& item) : item(item) {} + explicit GroupMap_find(const QLatin1String& item) : item(item) {} bool operator () (const std::pair& elem) const { return elem.first == item; diff --git a/src/Gui/DlgCommandsImp.h b/src/Gui/DlgCommandsImp.h index b7b2a07207..a3b79dfd89 100644 --- a/src/Gui/DlgCommandsImp.h +++ b/src/Gui/DlgCommandsImp.h @@ -46,18 +46,18 @@ class DlgCustomCommandsImp : public CustomizeActionPage Q_OBJECT public: - DlgCustomCommandsImp(QWidget* parent = nullptr); - ~DlgCustomCommandsImp(); + explicit DlgCustomCommandsImp(QWidget* parent = nullptr); + ~DlgCustomCommandsImp() override; protected Q_SLOTS: void onGroupActivated(QTreeWidgetItem *i); void onDescription(QTreeWidgetItem *i); - void onAddMacroAction(const QByteArray&); - void onRemoveMacroAction(const QByteArray&); - void onModifyMacroAction(const QByteArray&); + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgCreateNewPreferencePackImp.h b/src/Gui/DlgCreateNewPreferencePackImp.h index b6d0caf705..d154d31808 100644 --- a/src/Gui/DlgCreateNewPreferencePackImp.h +++ b/src/Gui/DlgCreateNewPreferencePackImp.h @@ -51,8 +51,8 @@ class GuiExport DlgCreateNewPreferencePackImp : public QDialog public: - DlgCreateNewPreferencePackImp(QWidget* parent = nullptr); - ~DlgCreateNewPreferencePackImp(); + explicit DlgCreateNewPreferencePackImp(QWidget* parent = nullptr); + ~DlgCreateNewPreferencePackImp() override; void setPreferencePackTemplates(const std::vector &availableTemplates); void setPreferencePackNames(const std::vector& usedNames); diff --git a/src/Gui/DlgCustomizeImp.h b/src/Gui/DlgCustomizeImp.h index a12f372b71..320ca849cb 100644 --- a/src/Gui/DlgCustomizeImp.h +++ b/src/Gui/DlgCustomizeImp.h @@ -51,8 +51,8 @@ class DlgCustomizeImp : public QDialog Q_OBJECT public: - DlgCustomizeImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgCustomizeImp(); + explicit DlgCustomizeImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgCustomizeImp() override; static void addPage(const char* className); void addPage (QWidget* w); @@ -63,7 +63,7 @@ Q_SIGNALS: void modifyMacroAction(const QByteArray&); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: /** @name for internal use only */ diff --git a/src/Gui/DlgCustomizeSpNavSettings.h b/src/Gui/DlgCustomizeSpNavSettings.h index 7a74ffcef5..7ed6d8a751 100644 --- a/src/Gui/DlgCustomizeSpNavSettings.h +++ b/src/Gui/DlgCustomizeSpNavSettings.h @@ -40,12 +40,12 @@ namespace Gui public: explicit DlgCustomizeSpNavSettings(QWidget *parent = nullptr); - ~DlgCustomizeSpNavSettings(); + ~DlgCustomizeSpNavSettings() override; protected Q_SLOTS: - void onAddMacroAction(const QByteArray&); - void onRemoveMacroAction(const QByteArray&); - void onModifyMacroAction(const QByteArray&); + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; void on_CBDominant_clicked(); void on_CBFlipYZ_clicked(); void on_CBRotations_clicked(); @@ -73,7 +73,7 @@ namespace Gui void on_ButtonCalibrate_clicked(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: ParameterGrp::handle spaceballMotionGroup() const; diff --git a/src/Gui/DlgCustomizeSpaceball.cpp b/src/Gui/DlgCustomizeSpaceball.cpp index dc258e50d4..28f797b885 100644 --- a/src/Gui/DlgCustomizeSpaceball.cpp +++ b/src/Gui/DlgCustomizeSpaceball.cpp @@ -282,7 +282,7 @@ QString ButtonModel::getLabel(const int &number) const GetGroup(numberString.toLatin1())-> GetASCII("Description","")); if (desc.length()) - desc = tr(" \"") + desc + tr("\""); + desc = QString::fromUtf8(" \"") + desc + QString::fromUtf8("\""); return tr("Button %1").arg(number + 1) + desc; } else return tr("Out Of Range"); @@ -316,7 +316,7 @@ void CommandView::goChangeCommandSelection(const QString& commandName) return; QModelIndexList index(this->model()->match(this->model()->index(0,0), Qt::UserRole, QVariant(commandName), 1, Qt::MatchWrap | Qt::MatchRecursive)); - if (index.size() < 1) + if (index.empty()) return; this->expand(index.at(0)); this->setCurrentIndex(index.at(0)); @@ -421,7 +421,7 @@ QVariant CommandModel::data(const QModelIndex &index, int role) const return QVariant(qApp->translate(node->aCommand->className(), node->aCommand->getMenuText())); if (node->nodeType == CommandNode::GroupType) { - if (node->children.size() < 1) + if (node->children.empty()) return QVariant(); CommandNode *childNode = node->children.at(0); return QVariant(childNode->aCommand->translatedGroupName()); @@ -446,7 +446,7 @@ QVariant CommandModel::data(const QModelIndex &index, int role) const return QVariant(QString::fromLatin1(node->aCommand->getName())); if (node->nodeType == CommandNode::GroupType) { - if (node->children.size() < 1) + if (node->children.empty()) return QVariant(); CommandNode *childNode = node->children.at(0); return QVariant(QString::fromLatin1(childNode->aCommand->getGroupName())); @@ -490,7 +490,7 @@ void CommandModel::goAddMacro(const QByteArray ¯oName) QModelIndexList indexList(this->match(this->index(0,0), Qt::UserRole, QVariant(QString::fromLatin1("Macros")), 1, Qt::MatchWrap | Qt::MatchRecursive)); QModelIndex macrosIndex; - if (indexList.size() < 1) + if (indexList.empty()) { //this is the first macro and we have to add the Macros item. //figure out where to insert it. Should be in the command groups now. diff --git a/src/Gui/DlgCustomizeSpaceball.h b/src/Gui/DlgCustomizeSpaceball.h index 3bede9957a..d3950b6c95 100644 --- a/src/Gui/DlgCustomizeSpaceball.h +++ b/src/Gui/DlgCustomizeSpaceball.h @@ -44,7 +44,7 @@ namespace Gui { Q_OBJECT public: - ButtonView(QWidget *parent = nullptr); + explicit ButtonView(QWidget *parent = nullptr); void selectButton(int number); Q_SIGNALS: void changeCommandSelection(const QString& commandName); @@ -59,9 +59,9 @@ namespace Gui { Q_OBJECT public: - ButtonModel(QObject *parent); - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; + explicit ButtonModel(QObject *parent); + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; void insertButtonRows(int number); void setCommand(int row, QString command); void goButtonPress(int number); @@ -79,7 +79,7 @@ namespace Gui { Q_OBJECT public: - CommandView(QWidget *parent = nullptr); + explicit CommandView(QWidget *parent = nullptr); public Q_SLOTS: void goChangeCommandSelection(const QString& commandName); private Q_SLOTS: @@ -93,7 +93,7 @@ namespace Gui public: enum NodeType {RootType, GroupType, CommandType}; - CommandNode(NodeType typeIn); + explicit CommandNode(NodeType typeIn); ~CommandNode(); NodeType nodeType; @@ -107,15 +107,15 @@ namespace Gui { Q_OBJECT public: - CommandModel(QObject *parent = nullptr); - ~CommandModel(); - virtual QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; - virtual QModelIndex parent(const QModelIndex &index) const; - virtual int rowCount(const QModelIndex &parent) const; - virtual int columnCount(const QModelIndex &parent) const; - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - virtual Qt::ItemFlags flags (const QModelIndex &index) const; + explicit CommandModel(QObject *parent = nullptr); + ~CommandModel() override; + QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override; + QModelIndex parent(const QModelIndex &index) const override; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + Qt::ItemFlags flags (const QModelIndex &index) const override; void goAddMacro(const QByteArray ¯oName); void goRemoveMacro(const QByteArray ¯oName); private: @@ -131,10 +131,10 @@ namespace Gui Q_OBJECT public: PrintModel(QObject *parent, ButtonModel *buttonModelIn, CommandModel *commandModelIn); - virtual int rowCount(const QModelIndex &parent) const; - virtual int columnCount(const QModelIndex &parent) const; - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; private: ButtonModel *buttonModel; CommandModel *commandModel; @@ -144,18 +144,18 @@ namespace Gui { Q_OBJECT public: - DlgCustomizeSpaceball(QWidget *parent = nullptr); - virtual ~DlgCustomizeSpaceball(); + explicit DlgCustomizeSpaceball(QWidget *parent = nullptr); + ~DlgCustomizeSpaceball() override; protected: - void changeEvent(QEvent *e); - virtual bool event(QEvent *event); - virtual void hideEvent(QHideEvent *event); - virtual void showEvent (QShowEvent *event); + void changeEvent(QEvent *e) override; + bool event(QEvent *event) override; + void hideEvent(QHideEvent *event) override; + void showEvent (QShowEvent *event) override; protected Q_SLOTS: - void onAddMacroAction(const QByteArray ¯oName); - void onRemoveMacroAction(const QByteArray ¯oName); - void onModifyMacroAction(const QByteArray ¯oName); + void onAddMacroAction(const QByteArray ¯oName) override; + void onRemoveMacroAction(const QByteArray ¯oName) override; + void onModifyMacroAction(const QByteArray ¯oName) override; private Q_SLOTS: void goClear(); diff --git a/src/Gui/DlgDisplayPropertiesImp.h b/src/Gui/DlgDisplayPropertiesImp.h index 78c607604f..a634ac121d 100644 --- a/src/Gui/DlgDisplayPropertiesImp.h +++ b/src/Gui/DlgDisplayPropertiesImp.h @@ -56,13 +56,13 @@ class DlgDisplayPropertiesImp : public QDialog, Q_OBJECT public: - DlgDisplayPropertiesImp(bool floating, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgDisplayPropertiesImp(); + explicit DlgDisplayPropertiesImp(bool floating, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgDisplayPropertiesImp() override; /// Observer message from the Selection void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason); + Gui::SelectionSingleton::MessageType Reason) override; void showDefaultButtons(bool); - void reject(); + void reject() override; private Q_SLOTS: void on_changeMaterial_activated(int); @@ -78,7 +78,7 @@ private Q_SLOTS: void on_buttonColorPlot_clicked(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: void slotChangedObject(const Gui::ViewProvider&, const App::Property& Prop); @@ -105,18 +105,18 @@ class TaskDisplayProperties : public Gui::TaskView::TaskDialog public: TaskDisplayProperties(); - ~TaskDisplayProperties(); + ~TaskDisplayProperties() override; public: - bool reject(); + bool reject() override; - bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return true; } - bool isAllowedAlterView(void) const + bool isAllowedAlterView() const override { return true; } - bool isAllowedAlterSelection(void) const + bool isAllowedAlterSelection() const override { return true; } - QDialogButtonBox::StandardButtons getStandardButtons() const; + QDialogButtonBox::StandardButtons getStandardButtons() const override; private: DlgDisplayPropertiesImp* widget; diff --git a/src/Gui/DlgEditFileIncludePropertyExternal.cpp b/src/Gui/DlgEditFileIncludePropertyExternal.cpp index e7b38383f1..3dc581571c 100644 --- a/src/Gui/DlgEditFileIncludePropertyExternal.cpp +++ b/src/Gui/DlgEditFileIncludePropertyExternal.cpp @@ -55,7 +55,7 @@ DlgEditFileIncludePropertyExternal::~DlgEditFileIncludePropertyExternal() } -int DlgEditFileIncludePropertyExternal::Do(void) +int DlgEditFileIncludePropertyExternal::Do() { QFileInfo file = QString::fromUtf8(Prop.getValue()); assert(file.exists()); diff --git a/src/Gui/DlgEditFileIncludePropertyExternal.h b/src/Gui/DlgEditFileIncludePropertyExternal.h index a31b7c6f0e..6c1737fb57 100644 --- a/src/Gui/DlgEditFileIncludePropertyExternal.h +++ b/src/Gui/DlgEditFileIncludePropertyExternal.h @@ -40,9 +40,9 @@ class GuiExport DlgEditFileIncludePropertyExternal : public DlgRunExternal public: DlgEditFileIncludePropertyExternal( App::PropertyFileIncluded& Prop, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - virtual ~DlgEditFileIncludePropertyExternal(); + ~DlgEditFileIncludePropertyExternal() override; - int Do(void); + int Do(); protected Q_SLOTS: protected: diff --git a/src/Gui/DlgEditorImp.h b/src/Gui/DlgEditorImp.h index bf747c7e5b..199e2ce085 100644 --- a/src/Gui/DlgEditorImp.h +++ b/src/Gui/DlgEditorImp.h @@ -45,12 +45,12 @@ class DlgSettingsEditorImp : public PreferencePage Q_OBJECT public: - DlgSettingsEditorImp( QWidget* parent = nullptr ); - ~DlgSettingsEditorImp(); + explicit DlgSettingsEditorImp( QWidget* parent = nullptr ); + ~DlgSettingsEditorImp() override; public: - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected Q_SLOTS: void on_displayItems_currentItemChanged(QTreeWidgetItem *i); @@ -59,7 +59,7 @@ protected Q_SLOTS: void on_fontSize_valueChanged(const QString&); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void setEditorTabWidth(int); private: diff --git a/src/Gui/DlgExpressionInput.cpp b/src/Gui/DlgExpressionInput.cpp index b0c28e23cb..e342ad7022 100644 --- a/src/Gui/DlgExpressionInput.cpp +++ b/src/Gui/DlgExpressionInput.cpp @@ -51,7 +51,7 @@ DlgExpressionInput::DlgExpressionInput(const App::ObjectIdentifier & _path, , impliedUnit(_impliedUnit) , minimumWidth(10) { - assert(path.getDocumentObject() != nullptr); + assert(path.getDocumentObject()); // Setup UI ui->setupUi(this); @@ -144,7 +144,7 @@ void DlgExpressionInput::textChanged(const QString &text) if (expr) { std::string error = path.getDocumentObject()->ExpressionEngine.validateExpression(path, expr); - if (error.size() > 0) + if (!error.empty()) throw Base::RuntimeError(error.c_str()); std::unique_ptr result(expr->eval()); @@ -214,53 +214,13 @@ void DlgExpressionInput::setExpressionInputSize(int width, int height) void DlgExpressionInput::mouseReleaseEvent(QMouseEvent* ev) { -#if 0//defined(Q_OS_WIN) - if (QWidget::mouseGrabber() == this) { - QList childs = this->findChildren(); - for (QList::iterator it = childs.begin(); it != childs.end(); ++it) { - QPoint pos = (*it)->mapFromGlobal(ev->globalPos()); - if ((*it)->rect().contains(pos)) { - // Create new mouse event with the correct local position - QMouseEvent me(ev->type(), pos, ev->globalPos(), ev->button(), ev->buttons(), ev->modifiers()); - QObject* obj = *it; - obj->event(&me); - if (me.isAccepted()) { - break; - } - } - } - } -#else Q_UNUSED(ev); -#endif } void DlgExpressionInput::mousePressEvent(QMouseEvent* ev) { -#if 0//defined(Q_OS_WIN) - bool handled = false; - if (QWidget::mouseGrabber() == this) { - QList childs = this->findChildren(); - for (QList::iterator it = childs.begin(); it != childs.end(); ++it) { - QPoint pos = (*it)->mapFromGlobal(ev->globalPos()); - if ((*it)->rect().contains(pos)) { - // Create new mouse event with the correct local position - QMouseEvent me(ev->type(), pos, ev->globalPos(), ev->button(), ev->buttons(), ev->modifiers()); - QObject* obj = *it; - obj->event(&me); - if (me.isAccepted()) { - handled = true; - break; - } - } - } - } - - if (handled) - return; -#else Q_UNUSED(ev); -#endif + // The 'FramelessWindowHint' is also set when the background is transparent. if (windowFlags() & Qt::FramelessWindowHint) { //we need to reject the dialog when clicked on the background. As the background is transparent @@ -281,17 +241,6 @@ void DlgExpressionInput::show() void DlgExpressionInput::showEvent(QShowEvent* ev) { QDialog::showEvent(ev); - -#if 0//defined(Q_OS_WIN) - // This way we can fetch click events outside modal dialogs - QWidget* widget = QApplication::activeModalWidget(); - if (widget) { - QList childs = widget->findChildren(); - if (childs.contains(this)) { - this->grabMouse(); - } - } -#endif } bool DlgExpressionInput::eventFilter(QObject *obj, QEvent *ev) @@ -315,7 +264,6 @@ bool DlgExpressionInput::eventFilter(QObject *obj, QEvent *ev) } } } - return false; } diff --git a/src/Gui/DlgExpressionInput.h b/src/Gui/DlgExpressionInput.h index 7fbb85ba62..e11081bb64 100644 --- a/src/Gui/DlgExpressionInput.h +++ b/src/Gui/DlgExpressionInput.h @@ -52,7 +52,7 @@ class GuiExport DlgExpressionInput : public QDialog public: explicit DlgExpressionInput(const App::ObjectIdentifier & _path, std::shared_ptr _expression, const Base::Unit &_impliedUnit, QWidget *parent = nullptr); - ~DlgExpressionInput(); + ~DlgExpressionInput() override; std::shared_ptr getExpression() const { return expression; } @@ -61,15 +61,15 @@ public: QPoint expressionPosition() const; void setExpressionInputSize(int width, int height); - bool eventFilter(QObject *obj, QEvent *event); + bool eventFilter(QObject *obj, QEvent *event) override; public Q_SLOTS: void show(); protected: - void showEvent(QShowEvent*); - void mouseReleaseEvent(QMouseEvent*); - void mousePressEvent(QMouseEvent*); + void showEvent(QShowEvent*) override; + void mouseReleaseEvent(QMouseEvent*) override; + void mousePressEvent(QMouseEvent*) override; private Q_SLOTS: void textChanged(const QString & text); diff --git a/src/Gui/DlgGeneralImp.cpp b/src/Gui/DlgGeneralImp.cpp index 2583b59241..174f7300c0 100644 --- a/src/Gui/DlgGeneralImp.cpp +++ b/src/Gui/DlgGeneralImp.cpp @@ -259,6 +259,8 @@ void DlgGeneralImp::loadSettings() model->sort(0); int current = getMainWindow()->iconSize().width(); + current = hGrp->GetInt("ToolbarIconSize", current); + ui->toolbarIconSize->clear(); ui->toolbarIconSize->addItem(tr("Small (%1px)").arg(16), QVariant((int)16)); ui->toolbarIconSize->addItem(tr("Medium (%1px)").arg(24), QVariant((int)24)); ui->toolbarIconSize->addItem(tr("Large (%1px)").arg(32), QVariant((int)32)); @@ -270,6 +272,7 @@ void DlgGeneralImp::loadSettings() } ui->toolbarIconSize->setCurrentIndex(index); + ui->treeMode->clear(); ui->treeMode->addItem(tr("Combo View")); ui->treeMode->addItem(tr("TreeView and PropertyView")); ui->treeMode->addItem(tr("Both")); @@ -308,6 +311,7 @@ void DlgGeneralImp::loadSettings() } // now add all unique items + ui->StyleSheets->clear(); ui->StyleSheets->addItem(tr("No style sheet"), QString::fromLatin1("")); for (QMap::iterator it = cssFiles.begin(); it != cssFiles.end(); ++it) { ui->StyleSheets->addItem(it.key(), it.value()); @@ -333,7 +337,8 @@ void DlgGeneralImp::loadSettings() } } - if (index > -1) ui->StyleSheets->setCurrentIndex(index); + if (index > -1) + ui->StyleSheets->setCurrentIndex(index); } void DlgGeneralImp::changeEvent(QEvent *e) diff --git a/src/Gui/DlgGeneralImp.h b/src/Gui/DlgGeneralImp.h index 7ea991d203..0652e39fe6 100644 --- a/src/Gui/DlgGeneralImp.h +++ b/src/Gui/DlgGeneralImp.h @@ -46,13 +46,13 @@ class DlgGeneralImp : public PreferencePage public: DlgGeneralImp( QWidget* parent = nullptr ); - ~DlgGeneralImp(); + ~DlgGeneralImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; protected Q_SLOTS: void onLoadPreferencePackClicked(const std::string &packName); diff --git a/src/Gui/DlgKeyboardImp.cpp b/src/Gui/DlgKeyboardImp.cpp index 3f3db30503..ba3aa265a5 100644 --- a/src/Gui/DlgKeyboardImp.cpp +++ b/src/Gui/DlgKeyboardImp.cpp @@ -46,7 +46,7 @@ typedef std::vector< std::pair > GroupMap; struct GroupMap_find { const QLatin1String& item; - GroupMap_find(const QLatin1String& item) : item(item) {} + explicit GroupMap_find(const QLatin1String& item) : item(item) {} bool operator () (const std::pair& elem) const { return elem.first == item; diff --git a/src/Gui/DlgKeyboardImp.h b/src/Gui/DlgKeyboardImp.h index 8626c8996e..e66162e829 100644 --- a/src/Gui/DlgKeyboardImp.h +++ b/src/Gui/DlgKeyboardImp.h @@ -45,11 +45,11 @@ class DlgCustomKeyboardImp : public CustomizeActionPage Q_OBJECT public: - DlgCustomKeyboardImp( QWidget* parent = nullptr ); - ~DlgCustomKeyboardImp(); + explicit DlgCustomKeyboardImp( QWidget* parent = nullptr ); + ~DlgCustomKeyboardImp() override; protected: - void showEvent(QShowEvent* e); + void showEvent(QShowEvent* e) override; protected Q_SLOTS: void on_categoryBox_activated(int index); @@ -59,12 +59,12 @@ protected Q_SLOTS: void on_buttonReset_clicked(); void on_buttonResetAll_clicked(); void on_editShortcut_textChanged(const QString&); - void onAddMacroAction(const QByteArray&); - void onRemoveMacroAction(const QByteArray&); - void onModifyMacroAction(const QByteArray&); + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void setShortcutOfCurrentAction(const QString&); private: diff --git a/src/Gui/DlgMacroExecuteImp.cpp b/src/Gui/DlgMacroExecuteImp.cpp index 14430ddf07..5fed71d093 100644 --- a/src/Gui/DlgMacroExecuteImp.cpp +++ b/src/Gui/DlgMacroExecuteImp.cpp @@ -58,7 +58,7 @@ namespace Gui { : QTreeWidgetItem(widget), systemWide(systemwide){} - ~MacroItem(){} + ~MacroItem() override{} bool systemWide; }; @@ -110,7 +110,7 @@ DlgMacroExecuteImp::~DlgMacroExecuteImp() /** * Fills up the list with all macro files found in the specified location. */ -void DlgMacroExecuteImp::fillUpList(void) +void DlgMacroExecuteImp::fillUpList() { // lists all files in macro path QDir dir(this->macroPath, QLatin1String("*.FCMacro *.py")); diff --git a/src/Gui/DlgMacroExecuteImp.h b/src/Gui/DlgMacroExecuteImp.h index 5d92c6ce1a..568d13120c 100644 --- a/src/Gui/DlgMacroExecuteImp.h +++ b/src/Gui/DlgMacroExecuteImp.h @@ -44,10 +44,10 @@ class DlgMacroExecuteImp : public QDialog, public Gui::WindowParameter Q_OBJECT public: - DlgMacroExecuteImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgMacroExecuteImp(); + explicit DlgMacroExecuteImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgMacroExecuteImp() override; - void accept(); + void accept() override; public Q_SLOTS: void on_fileChooser_fileNameChanged(const QString&); @@ -65,7 +65,7 @@ protected Q_SLOTS: void on_tabMacroWidget_currentChanged(int index); protected: - void fillUpList(void); + void fillUpList(); protected: QString macroPath; diff --git a/src/Gui/DlgMacroRecordImp.h b/src/Gui/DlgMacroRecordImp.h index 349751b064..82bb6b8e8c 100644 --- a/src/Gui/DlgMacroRecordImp.h +++ b/src/Gui/DlgMacroRecordImp.h @@ -42,8 +42,8 @@ class DlgMacroRecordImp : public QDialog, public Gui::WindowParameter Q_OBJECT public: - DlgMacroRecordImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - virtual ~DlgMacroRecordImp(); + explicit DlgMacroRecordImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + ~DlgMacroRecordImp() override; protected Q_SLOTS: void on_buttonStart_clicked(); diff --git a/src/Gui/DlgMaterialPropertiesImp.cpp b/src/Gui/DlgMaterialPropertiesImp.cpp index 3a2d48defb..abe0f4b361 100644 --- a/src/Gui/DlgMaterialPropertiesImp.cpp +++ b/src/Gui/DlgMaterialPropertiesImp.cpp @@ -52,12 +52,10 @@ DlgMaterialPropertiesImp::DlgMaterialPropertiesImp(const std::string& mat, QWidg ui->diffuseColor->hide(); } -//#if !defined(Q_OS_MAC) ui->ambientColor->setAutoChangeColor(true); ui->diffuseColor->setAutoChangeColor(true); ui->emissiveColor->setAutoChangeColor(true); ui->specularColor->setAutoChangeColor(true); -//#endif } /** diff --git a/src/Gui/DlgMaterialPropertiesImp.h b/src/Gui/DlgMaterialPropertiesImp.h index 5ef5273fcf..dd94d88bdc 100644 --- a/src/Gui/DlgMaterialPropertiesImp.h +++ b/src/Gui/DlgMaterialPropertiesImp.h @@ -39,8 +39,8 @@ class DlgMaterialPropertiesImp : public QDialog Q_OBJECT public: - DlgMaterialPropertiesImp(const std::string& mat, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgMaterialPropertiesImp(); + explicit DlgMaterialPropertiesImp(const std::string& mat, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgMaterialPropertiesImp() override; void setViewProviders(const std::vector&); QColor diffuseColor() const; diff --git a/src/Gui/DlgObjectSelection.cpp b/src/Gui/DlgObjectSelection.cpp index efe75080c1..3aec2b367c 100644 --- a/src/Gui/DlgObjectSelection.cpp +++ b/src/Gui/DlgObjectSelection.cpp @@ -186,7 +186,7 @@ QTreeWidgetItem *DlgObjectSelection::getItem(App::DocumentObject *obj, *pitems = &items; QTreeWidgetItem *item; if (!parent) { - if (items.size()) + if (!items.empty()) return items[0]; item = new QTreeWidgetItem(ui->treeWidget); auto vp = Base::freecad_dynamic_cast( @@ -204,7 +204,7 @@ QTreeWidgetItem *DlgObjectSelection::getItem(App::DocumentObject *obj, item->setData(0, Qt::UserRole, QVariant::fromValue(objT)); item->setChildIndicatorPolicy(obj->getOutList().empty() ? QTreeWidgetItem::DontShowIndicator : QTreeWidgetItem::ShowIndicator); - } else if (items.size()) { + } else if (!items.empty()) { item = new QTreeWidgetItem(parent); item->setIcon(0, items[0]->icon(0)); item->setText(0, items[0]->text(0)); @@ -365,7 +365,8 @@ void DlgObjectSelection::onDepItemChanged(QTreeWidgetItem * depItem, int column) QSignalBlocker blocker3(ui->treeWidget); auto state = depItem->checkState(0); if (depItem->isSelected()) { - for (auto item : depItem->treeWidget()->selectedItems()) { + const auto items = depItem->treeWidget()->selectedItems(); + for (auto item : items) { auto objT = qvariant_cast(item->data(0, Qt::UserRole)); auto it = itemMap.find(objT); if (it == itemMap.end()) @@ -437,7 +438,8 @@ void DlgObjectSelection::onObjItemChanged(QTreeWidgetItem * objItem, int column) onItemSelectionChanged(); } else { - for (auto item : ui->treeWidget->selectedItems()) { + const auto items = ui->treeWidget->selectedItems(); + for (auto item : items) { setCheckState(item, state); itemChanged[qvariant_cast(item->data(0, Qt::UserRole))] = state; } @@ -484,7 +486,7 @@ void DlgObjectSelection::checkItemChanged() { } } - if (unchecked.size()) { + if (!unchecked.empty()) { // When some item is unchecked by the user, we need to re-check the // recursive outlist of the initially selected object, excluding all // currently unchecked object. And then uncheck any item that does not @@ -552,7 +554,8 @@ void DlgObjectSelection::onItemSelectionChanged() { inMap.clear(); std::vector sels; - for (auto item : ui->treeWidget->selectedItems()) { + const auto items = ui->treeWidget->selectedItems(); + for (auto item : items) { if (item == allItem) { sels.clear(); break; @@ -563,7 +566,7 @@ void DlgObjectSelection::onItemSelectionChanged() { } std::vector _deps; - if (sels.size()) { + if (!sels.empty()) { std::sort(sels.begin(), sels.end()); for (auto dep : App::Document::getDependencyList(sels, App::Document::DepSort)) { if (!std::binary_search(sels.begin(), sels.end(), dep)) @@ -581,7 +584,7 @@ void DlgObjectSelection::onItemSelectionChanged() { { QSignalBlocker blocker(ui->depList); - auto &objs = sels.size() ? _deps : deps; + auto &objs = !sels.empty() ? _deps : deps; for (auto it = objs.rbegin(); it != objs.rend(); ++it) createDepItem(ui->depList, *it); } diff --git a/src/Gui/DlgObjectSelection.h b/src/Gui/DlgObjectSelection.h index 037287882d..cb7ade0e1c 100644 --- a/src/Gui/DlgObjectSelection.h +++ b/src/Gui/DlgObjectSelection.h @@ -71,7 +71,7 @@ public: QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); /// Destructor - ~DlgObjectSelection(); + ~DlgObjectSelection() override; /// Options for getSelections() enum class SelectionOptions { @@ -91,8 +91,8 @@ public: /// Override the prompt message void setMessage(const QString &); - void accept(); - void reject(); + void accept() override; + void reject() override; private Q_SLOTS: void onDepItemChanged(QTreeWidgetItem * item, int); diff --git a/src/Gui/DlgOnlineHelpImp.h b/src/Gui/DlgOnlineHelpImp.h index ac3e4dea6f..6a7c4a4e70 100644 --- a/src/Gui/DlgOnlineHelpImp.h +++ b/src/Gui/DlgOnlineHelpImp.h @@ -42,15 +42,15 @@ class DlgOnlineHelpImp : public PreferencePage public: DlgOnlineHelpImp( QWidget* parent = nullptr ); - ~DlgOnlineHelpImp(); + ~DlgOnlineHelpImp() override; static QString getStartpage(); - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; protected: void on_lineEditDownload_fileNameSelected(const QString&); diff --git a/src/Gui/DlgParameterImp.cpp b/src/Gui/DlgParameterImp.cpp index 543ad7376a..f64f84e0c1 100644 --- a/src/Gui/DlgParameterImp.cpp +++ b/src/Gui/DlgParameterImp.cpp @@ -144,8 +144,8 @@ void DlgParameterImp::on_findGroupLE_textChanged(const QString &SearchStr) QTreeWidgetItem* ExpandItem; // at first reset all items to the default font and expand state - if (foundList.size() > 0) { - for (QTreeWidgetItem* item : foundList) { + if (!foundList.empty()) { + for (QTreeWidgetItem* item : qAsConst(foundList)) { item->setFont(0, defaultFont); item->setForeground(0, defaultColor); ExpandItem = item; @@ -172,11 +172,11 @@ void DlgParameterImp::on_findGroupLE_textChanged(const QString &SearchStr) // search the tree widget foundList = paramGroup->findItems(SearchStr, Qt::MatchContains | Qt::MatchRecursive); - if (foundList.size() > 0) { + if (!foundList.empty()) { // reset background style sheet if (!ui->findGroupLE->styleSheet().isEmpty()) ui->findGroupLE->setStyleSheet(QString()); - for (QTreeWidgetItem* item : foundList) { + for (QTreeWidgetItem* item : qAsConst(foundList)) { item->setFont(0, boldFont); item->setForeground(0, Qt::red); // expand its parent to see the item @@ -937,7 +937,7 @@ ParameterGroupItem::~ParameterGroupItem() _hcGrp->ClearObserver(); } -void ParameterGroupItem::fillUp(void) +void ParameterGroupItem::fillUp() { // filling up groups std::vector > vhcParamGrp = _hcGrp->GetGroups(); diff --git a/src/Gui/DlgParameterImp.h b/src/Gui/DlgParameterImp.h index 339c898018..9150e69021 100644 --- a/src/Gui/DlgParameterImp.h +++ b/src/Gui/DlgParameterImp.h @@ -47,11 +47,11 @@ class GuiExport DlgParameterImp : public QDialog Q_OBJECT public: - DlgParameterImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgParameterImp(); + explicit DlgParameterImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + ~DlgParameterImp() override; - void accept(); - void reject(); + void accept() override; + void reject() override; void activateParameterSet(const char*); @@ -66,9 +66,9 @@ protected Q_SLOTS: void on_checkSort_toggled(bool); protected: - void changeEvent(QEvent *e); - void showEvent(QShowEvent*); - void closeEvent(QCloseEvent*); + void changeEvent(QEvent *e) override; + void showEvent(QShowEvent*) override; + void closeEvent(QCloseEvent*) override; protected: QTreeWidget* paramGroup; @@ -95,14 +95,14 @@ class ParameterGroup : public QTreeWidget Q_OBJECT public: - ParameterGroup( QWidget * parent = nullptr ); - virtual ~ParameterGroup(); + explicit ParameterGroup( QWidget * parent = nullptr ); + ~ParameterGroup() override; protected: /** Shows the context menu. */ - void contextMenuEvent ( QContextMenuEvent* event ); + void contextMenuEvent ( QContextMenuEvent* event ) override; /** Triggers the "Del" key. */ - void keyPressEvent (QKeyEvent* event); + void keyPressEvent (QKeyEvent* event) override; protected Q_SLOTS: /** Removes the underlying parameter group and its sub-groups from the @@ -123,7 +123,7 @@ protected Q_SLOTS: void onRenameSelectedItem(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: QMenu* menuEdit; @@ -147,8 +147,8 @@ class ParameterValue : public QTreeWidget Q_OBJECT public: - ParameterValue( QWidget * parent = nullptr ); - virtual ~ParameterValue(); + explicit ParameterValue( QWidget * parent = nullptr ); + ~ParameterValue() override; /** Sets the current parameter group that is displayed. */ void setCurrentGroup( const Base::Reference& _hcGrp ); @@ -157,10 +157,10 @@ public: protected: /** Shows the context menu. */ - void contextMenuEvent ( QContextMenuEvent* event ); + void contextMenuEvent ( QContextMenuEvent* event ) override; /** Invokes onDeleteSelectedItem() if the "Del" key was pressed. */ - void keyPressEvent (QKeyEvent* event); - void resizeEvent(QResizeEvent*); + void keyPressEvent (QKeyEvent* event) override; + void resizeEvent(QResizeEvent*) override; protected Q_SLOTS: /** Changes the value of the leaf of the selected item. */ @@ -186,7 +186,7 @@ protected Q_SLOTS: * @note We need to reimplement this method as QTreeWidgetItem::flags() * doesn't have an int parameter. */ - bool edit ( const QModelIndex & index, EditTrigger trigger, QEvent * event ); + bool edit ( const QModelIndex & index, QAbstractItemView::EditTrigger trigger, QEvent * event ) override; private: QMenu* menuEdit; @@ -215,12 +215,12 @@ public: /// Constructor ParameterGroupItem( ParameterGroupItem * parent, const Base::Reference &hcGrp ); ParameterGroupItem( QTreeWidget* parent, const Base::Reference &hcGrp); - ~ParameterGroupItem(); + ~ParameterGroupItem() override; - void setData ( int column, int role, const QVariant & value ); - QVariant data ( int column, int role ) const; + void setData ( int column, int role, const QVariant & value ) override; + QVariant data ( int column, int role ) const override; - void fillUp(void); + void fillUp(); Base::Reference _hcGrp; }; @@ -238,10 +238,10 @@ class ParameterValueItem : public QTreeWidgetItem public: /// Constructor ParameterValueItem ( QTreeWidget* parent, const Base::Reference &hcGrp); - virtual ~ParameterValueItem(); + ~ParameterValueItem() override; /** If the name of the item has changed replace() is invoked. */ - virtual void setData ( int column, int role, const QVariant & value ); + void setData ( int column, int role, const QVariant & value ) override; /** Opens an input dialog to change the value. */ virtual void changeValue() = 0; /** Append this item as leaf to the parameter group. */ @@ -266,14 +266,14 @@ class ParameterText : public ParameterValueItem public: /// Constructor ParameterText ( QTreeWidget * parent, QString label1, const char* value, const Base::Reference &hcGrp); - ~ParameterText(); + ~ParameterText() override; - void changeValue(); - void appendToGroup(); - void removeFromGroup(); + void changeValue() override; + void appendToGroup() override; + void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ); + void replace( const QString& oldName, const QString& newName ) override; }; /** @@ -285,14 +285,14 @@ class ParameterInt : public ParameterValueItem public: /// Constructor ParameterInt ( QTreeWidget * parent, QString label1, long value, const Base::Reference &hcGrp); - ~ParameterInt(); + ~ParameterInt() override; - void changeValue(); - void appendToGroup(); - void removeFromGroup(); + void changeValue() override; + void appendToGroup() override; + void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ); + void replace( const QString& oldName, const QString& newName ) override; }; /** @@ -304,14 +304,14 @@ class ParameterUInt : public ParameterValueItem public: /// Constructor ParameterUInt ( QTreeWidget * parent, QString label1, unsigned long value, const Base::Reference &hcGrp); - ~ParameterUInt(); + ~ParameterUInt() override; - void changeValue(); - void appendToGroup(); - void removeFromGroup(); + void changeValue() override; + void appendToGroup() override; + void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ); + void replace( const QString& oldName, const QString& newName ) override; }; /** @@ -323,14 +323,14 @@ class ParameterFloat : public ParameterValueItem public: /// Constructor ParameterFloat ( QTreeWidget * parent, QString label1, double value, const Base::Reference &hcGrp); - ~ParameterFloat(); + ~ParameterFloat() override; - void changeValue(); - void appendToGroup(); - void removeFromGroup(); + void changeValue() override; + void appendToGroup() override; + void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ); + void replace( const QString& oldName, const QString& newName ) override; }; /** @@ -342,14 +342,14 @@ class ParameterBool : public ParameterValueItem public: /// Constructor ParameterBool ( QTreeWidget * parent, QString label1, bool value, const Base::Reference &hcGrp); - ~ParameterBool(); + ~ParameterBool() override; - void changeValue(); - void appendToGroup(); - void removeFromGroup(); + void changeValue() override; + void appendToGroup() override; + void removeFromGroup() override; protected: - void replace( const QString& oldName, const QString& newName ); + void replace( const QString& oldName, const QString& newName ) override; }; } // namespace Dialog diff --git a/src/Gui/DlgPreferencePackManagementImp.cpp b/src/Gui/DlgPreferencePackManagementImp.cpp index 6134266424..dde897ca7d 100644 --- a/src/Gui/DlgPreferencePackManagementImp.cpp +++ b/src/Gui/DlgPreferencePackManagementImp.cpp @@ -182,7 +182,7 @@ void DlgPreferencePackManagementImp::deleteUserPack(const std::string& name) if (result == QMessageBox::Yes) { Application::Instance->prefPackManager()->deleteUserPack(name); showEvent(nullptr); - packVisibilityChanged(); + Q_EMIT packVisibilityChanged(); } } @@ -190,14 +190,14 @@ void DlgPreferencePackManagementImp::hideBuiltInPack(const std::string& prefPack { Application::Instance->prefPackManager()->toggleVisibility("##BUILT_IN##", prefPackName); showEvent(nullptr); - packVisibilityChanged(); + Q_EMIT packVisibilityChanged(); } void DlgPreferencePackManagementImp::hideInstalledPack(const std::string& addonName, const std::string& prefPackName) { Application::Instance->prefPackManager()->toggleVisibility(addonName, prefPackName); showEvent(nullptr); - packVisibilityChanged(); + Q_EMIT packVisibilityChanged(); } void DlgPreferencePackManagementImp::showAddonManager() diff --git a/src/Gui/DlgPreferencesImp.cpp b/src/Gui/DlgPreferencesImp.cpp index 64c3818033..6309950a2d 100644 --- a/src/Gui/DlgPreferencesImp.cpp +++ b/src/Gui/DlgPreferencesImp.cpp @@ -37,11 +37,13 @@ #include #include #include +#include #include "DlgPreferencesImp.h" #include "ui_DlgPreferences.h" #include "BitmapFactory.h" #include "MainWindow.h" +#include "Tools.h" #include "WidgetFactory.h" @@ -52,6 +54,8 @@ const int DlgPreferencesImp::GroupNameRole = Qt::UserRole; /* TRANSLATOR Gui::Dialog::DlgPreferencesImp */ std::list DlgPreferencesImp::_pages; +std::map DlgPreferencesImp::_groupMap; + DlgPreferencesImp* DlgPreferencesImp::_activeDialog = nullptr; /** @@ -66,7 +70,9 @@ DlgPreferencesImp::DlgPreferencesImp(QWidget* parent, Qt::WindowFlags fl) invalidParameter(false), canEmbedScrollArea(true) { ui->setupUi(this); - ui->listBox->setFixedWidth(108); + QFontMetrics fm(font()); + int length = QtTools::horizontalAdvance(fm, longestGroupName()); + ui->listBox->setFixedWidth(Base::clamp(length + 20, 108, 120)); ui->listBox->setGridSize(QSize(108, 75)); connect(ui->buttonBox, SIGNAL (helpRequested()), @@ -107,6 +113,17 @@ void DlgPreferencesImp::setupPages() ui->listBox->setCurrentRow(0); } +QString DlgPreferencesImp::longestGroupName() const +{ + std::string name; + for (const auto &group : _pages) { + if (group.first.size() > name.size()) + name = group.first; + } + + return QString::fromStdString(name); +} + /** * Create the necessary widgets for a new group named \a groupName. Returns a * pointer to the group's QTabWidget: that widget's lifetime is managed by the @@ -116,6 +133,10 @@ QTabWidget* DlgPreferencesImp::createTabForGroup(const std::string &groupName) { QString groupNameQString = QString::fromStdString(groupName); + std::string fileName = groupName; + QString tooltip; + getGroupData(groupName, fileName, tooltip); + QTabWidget* tabWidget = new QTabWidget; ui->tabWidgetStack->addWidget(tabWidget); tabWidget->setProperty("GroupName", QVariant(groupNameQString)); @@ -123,15 +144,8 @@ QTabWidget* DlgPreferencesImp::createTabForGroup(const std::string &groupName) QListWidgetItem* item = new QListWidgetItem(ui->listBox); item->setData(GroupNameRole, QVariant(groupNameQString)); item->setText(QObject::tr(groupNameQString.toLatin1())); - // for Part/PD we need another tooltip since this group is for 2 WBs - if (groupName.compare("Part/Part Design") == 0) - item->setToolTip(QObject::tr(QString::fromStdString("Part and Part Design workbench").toLatin1())); - else - item->setToolTip(QObject::tr(groupNameQString.toLatin1())); - std::string fileName = groupName; - // for Part/PD the filename cannot be groupName since this group is for 2 WBs - if (groupName.compare("Part/Part Design") == 0) - fileName = "Part design"; + item->setToolTip(tooltip); + for (auto &ch : fileName) { if (ch == ' ') ch = '_'; @@ -206,10 +220,10 @@ void DlgPreferencesImp::addPage(const std::string& className, const std::string& // This is a new group: create it, with its one page std::list pages; pages.push_back(className); - _pages.push_back(std::make_pair(group, pages)); + _pages.emplace_back(group, pages); } - if (DlgPreferencesImp::_activeDialog != nullptr) { + if (DlgPreferencesImp::_activeDialog) { // If the dialog is currently showing, tell it to insert the new page _activeDialog->reloadPages(); } @@ -238,6 +252,36 @@ void DlgPreferencesImp::removePage(const std::string& className, const std::stri } } +/** + * Sets a custom icon name or tool tip for a given group. + */ +void DlgPreferencesImp::setGroupData(const std::string& name, const std::string& icon, const QString& tip) +{ + Group group; + group.iconName = icon; + group.tooltip = tip; + _groupMap[name] = group; +} + +/** + * Gets the icon name or tool tip for a given group. If no custom name or tool tip is given + * they are determined from the group name. + */ +void DlgPreferencesImp::getGroupData(const std::string& group, std::string& icon, QString& tip) +{ + auto it = _groupMap.find(group); + if (it != _groupMap.end()) { + icon = it->second.iconName; + tip = it->second.tooltip; + } + + if (icon.empty()) + icon = group; + + if (tip.isEmpty()) + tip = QObject::tr(group.c_str()); +} + /** * Activates the page at position \a index of the group with name \a group. */ @@ -292,14 +336,7 @@ void DlgPreferencesImp::restoreDefaults() App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")-> SetBool("SaveUserParameter", saveParameter); -#if 0 - QList pages = this->findChildren(); - for (QList::iterator it = pages.begin(); it != pages.end(); ++it) { - (*it)->loadSettings(); - } -#else reject(); -#endif } } @@ -406,7 +443,6 @@ void DlgPreferencesImp::applyChanges() void DlgPreferencesImp::showEvent(QShowEvent* ev) { - //canEmbedScrollArea = false; this->adjustSize(); QDialog::showEvent(ev); } diff --git a/src/Gui/DlgPreferencesImp.h b/src/Gui/DlgPreferencesImp.h index c7aa1e44d2..4e85d26a7b 100644 --- a/src/Gui/DlgPreferencesImp.h +++ b/src/Gui/DlgPreferencesImp.h @@ -114,19 +114,21 @@ class GuiExport DlgPreferencesImp : public QDialog public: static void addPage(const std::string& className, const std::string& group); static void removePage(const std::string& className, const std::string& group); + static void setGroupData(const std::string& group, const std::string& icon, const QString& tip); + static void getGroupData(const std::string& group, std::string& icon, QString& tip); static void reloadSettings(); - DlgPreferencesImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgPreferencesImp(); + explicit DlgPreferencesImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgPreferencesImp() override; - void accept(); + void accept() override; void reload(); void activateGroupPage(const QString& group, int id); protected: - void changeEvent(QEvent *e); - void showEvent(QShowEvent*); - void resizeEvent(QResizeEvent*); + void changeEvent(QEvent *e) override; + void showEvent(QShowEvent*) override; + void resizeEvent(QResizeEvent*) override; protected Q_SLOTS: @@ -143,11 +145,17 @@ private: void createPageInGroup(QTabWidget* tabWidget, const std::string& pageName); void applyChanges(); void restoreDefaults(); + QString longestGroupName() const; //@} private: typedef std::pair> TGroupPages; static std::list _pages; /**< Name of all registered preference pages */ + struct Group { + std::string iconName; + QString tooltip; + }; + static std::map _groupMap; std::unique_ptr ui; bool invalidParameter; bool canEmbedScrollArea; diff --git a/src/Gui/DlgProjectInformationImp.h b/src/Gui/DlgProjectInformationImp.h index c068f91526..235d8f0fc2 100644 --- a/src/Gui/DlgProjectInformationImp.h +++ b/src/Gui/DlgProjectInformationImp.h @@ -41,8 +41,8 @@ class DlgProjectInformationImp : public QDialog public: DlgProjectInformationImp(App::Document* doc, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgProjectInformationImp(); - void accept(); + ~DlgProjectInformationImp() override; + void accept() override; private Q_SLOTS: void open_url(); diff --git a/src/Gui/DlgProjectUtility.h b/src/Gui/DlgProjectUtility.h index 3a44c86186..6bac75fedb 100644 --- a/src/Gui/DlgProjectUtility.h +++ b/src/Gui/DlgProjectUtility.h @@ -36,7 +36,7 @@ class DlgProjectUtility : public QDialog public: DlgProjectUtility(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgProjectUtility(); + ~DlgProjectUtility() override; private Q_SLOTS: void on_extractButton_clicked(); diff --git a/src/Gui/DlgPropertyLink.cpp b/src/Gui/DlgPropertyLink.cpp index 63bd12a3f4..830e4dbcfe 100644 --- a/src/Gui/DlgPropertyLink.cpp +++ b/src/Gui/DlgPropertyLink.cpp @@ -52,10 +52,10 @@ using namespace Gui::Dialog; class ItemDelegate: public QStyledItemDelegate { public: - ItemDelegate(QObject* parent=nullptr): QStyledItemDelegate(parent) {} + explicit ItemDelegate(QObject* parent=nullptr): QStyledItemDelegate(parent) {} - virtual QWidget* createEditor(QWidget *parent, - const QStyleOptionViewItem &option, const QModelIndex &index) const + QWidget* createEditor(QWidget *parent, + const QStyleOptionViewItem &option, const QModelIndex &index) const override { if(index.column() != 1) return nullptr; @@ -161,9 +161,9 @@ QString DlgPropertyLink::formatObject(App::Document *ownerDoc, App::DocumentObje QString::fromUtf8(sobj->Label.getValue())); } -static inline bool isLinkSub(QList links) +static inline bool isLinkSub(const QList& links) { - for(auto &link : links) { + for(const auto &link : links) { if(&link == &links.front()) continue; if(link.getDocumentName() != links.front().getDocumentName() @@ -353,7 +353,7 @@ void DlgPropertyLink::init(const App::DocumentObjectT &prop, bool tryFilter) { // For link list type property, try to auto filter type if(tryFilter && isLinkList) { Base::Type objType; - for(auto link : oldLinks) { + for(const auto& link : qAsConst(oldLinks)) { auto obj = link.getSubObject(); if(!obj) continue; @@ -466,7 +466,7 @@ void DlgPropertyLink::detachObserver() { detachSelection(); auto view = qobject_cast(parentView.data()); - if(view && savedSelections.size()) { + if(view && !savedSelections.empty()) { try { Gui::Selection().clearSelection(); } @@ -501,7 +501,7 @@ void DlgPropertyLink::onItemSelectionChanged() selections = newSelections; auto sobjs = getLinkFromItem(newSelections.back()); - App::DocumentObject *obj = sobjs.size()?sobjs.front().getObject():nullptr; + App::DocumentObject *obj = !sobjs.empty()?sobjs.front().getObject():nullptr; if(!obj) { Gui::Selection().clearSelection(); return; @@ -534,7 +534,8 @@ void DlgPropertyLink::onItemSelectionChanged() // Enforce single parent if(singleParent && currentObj && currentObj!=obj) { ui->treeWidget->blockSignals(true); - for(auto item : ui->treeWidget->selectedItems()) { + const auto items = ui->treeWidget->selectedItems(); + for(auto item : items) { if(item != selections.back()) item->setSelected(false); } @@ -671,8 +672,8 @@ void DlgPropertyLink::accept() static QTreeWidgetItem *_getLinkFromItem(std::ostringstream &ss, QTreeWidgetItem *item, const char *objName) { auto parent = item->parent(); assert(parent); - const char *nextName = parent->data(0, Qt::UserRole).toByteArray().constData(); - if(!nextName[0]) + QByteArray nextName = parent->data(0, Qt::UserRole).toByteArray(); + if (nextName.isEmpty()) return item; item = _getLinkFromItem(ss, parent, nextName); @@ -707,7 +708,8 @@ DlgPropertyLink::getLinkFromItem(QTreeWidgetItem *item, bool needSubName) const return res; } - for(const QString &element : elements.split(QLatin1Char(','))) { + const auto split = elements.split(QLatin1Char(',')); + for(const QString &element : split) { res.append(App::SubObjectT()); res.last() = App::SubObjectT(sobj.getDocumentName().c_str(), sobj.getObjectName().c_str(), @@ -745,7 +747,7 @@ QList DlgPropertyLink::originalLinks() const return oldLinks; } -QString DlgPropertyLink::linksToPython(QList links) { +QString DlgPropertyLink::linksToPython(const QList& links) { if(links.isEmpty()) return QLatin1String("None"); @@ -756,15 +758,15 @@ QString DlgPropertyLink::linksToPython(QList links) { if(isLinkSub(links)) { ss << '(' << links.front().getObjectPython() << ", ["; - for(auto link : links) { + for(const auto& link : links) { const auto &sub = link.getSubName(); - if(sub.size()) + if(!sub.empty()) ss << "u'" << Base::Tools::escapedUnicodeFromUtf8(sub.c_str()) << "',"; } ss << "])"; } else { ss << '['; - for(auto link : links) + for(const auto& link : links) ss << link.getSubObjectPython(false) << ','; ss << ']'; } @@ -898,7 +900,7 @@ QTreeWidgetItem *DlgPropertyLink::createItem( item->setData(0, Qt::UserRole+1, QByteArray(obj->getDocument()->getName())); if(allowSubObject) { - item->setChildIndicatorPolicy(obj->getLinkedObject(true)->getOutList().size()? + item->setChildIndicatorPolicy(!obj->getLinkedObject(true)->getOutList().empty()? QTreeWidgetItem::ShowIndicator:QTreeWidgetItem::DontShowIndicator); item->setFlags(item->flags() | Qt::ItemIsEditable | Qt::ItemIsUserCheckable); } @@ -1014,13 +1016,13 @@ void DlgPropertyLink::onItemExpanded(QTreeWidgetItem * item) { if(item->childCount()) return; - const char *docName = item->data(0, Qt::UserRole+1).toByteArray().constData(); + QByteArray docName = item->data(0, Qt::UserRole+1).toByteArray(); auto doc = App::GetApplication().getDocument(docName); - if(!doc) + if (!doc) return; - const char *objName = item->data(0, Qt::UserRole).toByteArray().constData(); - if(!objName[0]) { + QByteArray objName = item->data(0, Qt::UserRole).toByteArray(); + if (objName.isEmpty()) { for(auto obj : doc->getObjects()) { auto newItem = createItem(obj,item); if(newItem) @@ -1052,7 +1054,8 @@ void DlgPropertyLink::on_checkObjectType_toggled(bool on) void DlgPropertyLink::on_typeTree_itemSelectionChanged() { selectedTypes.clear(); - for(auto item : ui->typeTree->selectedItems()) + const auto items = ui->typeTree->selectedItems(); + for(auto item : items) selectedTypes.insert(item->data(0, Qt::UserRole).toByteArray()); if(ui->checkObjectType->isChecked()) diff --git a/src/Gui/DlgPropertyLink.h b/src/Gui/DlgPropertyLink.h index 42b7362901..6548cacdfc 100644 --- a/src/Gui/DlgPropertyLink.h +++ b/src/Gui/DlgPropertyLink.h @@ -40,16 +40,16 @@ class DlgPropertyLink : public QDialog, public Gui::SelectionObserver public: DlgPropertyLink(QWidget* parent = nullptr); - ~DlgPropertyLink(); + ~DlgPropertyLink() override; - void accept(); + void accept() override; QList currentLinks() const; QList originalLinks() const; void init(const App::DocumentObjectT &prop, bool tryFilter=true); - static QString linksToPython(QList links); + static QString linksToPython(const QList& links); static QList getLinksFromProperty(const App::PropertyLinkBase *prop); @@ -62,17 +62,17 @@ public: static QString formatLinks(App::Document *ownerDoc, QList links); protected: - void showEvent(QShowEvent *); - void hideEvent(QHideEvent *); - void closeEvent (QCloseEvent * e); - void leaveEvent(QEvent *); - bool eventFilter(QObject *obj, QEvent *ev); - void keyPressEvent(QKeyEvent *ev); + void showEvent(QShowEvent *) override; + void hideEvent(QHideEvent *) override; + void closeEvent (QCloseEvent * e) override; + void leaveEvent(QEvent *) override; + bool eventFilter(QObject *obj, QEvent *ev) override; + void keyPressEvent(QKeyEvent *ev) override; void detachObserver(); void attachObserver(); - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private Q_SLOTS: void on_checkObjectType_toggled(bool); diff --git a/src/Gui/DlgReportViewImp.h b/src/Gui/DlgReportViewImp.h index d2af172577..ebecb65fdb 100644 --- a/src/Gui/DlgReportViewImp.h +++ b/src/Gui/DlgReportViewImp.h @@ -40,14 +40,14 @@ class DlgReportViewImp : public PreferencePage Q_OBJECT public: - DlgReportViewImp( QWidget* parent = nullptr ); - ~DlgReportViewImp(); + explicit DlgReportViewImp( QWidget* parent = nullptr ); + ~DlgReportViewImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgRevertToBackupConfigImp.h b/src/Gui/DlgRevertToBackupConfigImp.h index cf42a7504c..0728304014 100644 --- a/src/Gui/DlgRevertToBackupConfigImp.h +++ b/src/Gui/DlgRevertToBackupConfigImp.h @@ -39,8 +39,8 @@ class DlgRevertToBackupConfigImp : public QDialog Q_OBJECT public: - DlgRevertToBackupConfigImp( QWidget* parent = nullptr ); - ~DlgRevertToBackupConfigImp(); + explicit DlgRevertToBackupConfigImp( QWidget* parent = nullptr ); + ~DlgRevertToBackupConfigImp() override; public Q_SLOTS: void accept() override; diff --git a/src/Gui/DlgRunExternal.cpp b/src/Gui/DlgRunExternal.cpp index 1ddac4ee2b..42fb48fa0b 100644 --- a/src/Gui/DlgRunExternal.cpp +++ b/src/Gui/DlgRunExternal.cpp @@ -66,7 +66,7 @@ DlgRunExternal::~DlgRunExternal() delete ui; } -int DlgRunExternal::Do(void) +int DlgRunExternal::Do() { QFileInfo ifo (ProcName); @@ -79,23 +79,23 @@ int DlgRunExternal::Do(void) return exec(); } -void DlgRunExternal::reject (void) +void DlgRunExternal::reject () { QDialog::reject(); } -void DlgRunExternal::accept (void) +void DlgRunExternal::accept () { QDialog::accept(); } -void DlgRunExternal::abort (void) +void DlgRunExternal::abort () { process.terminate(); DlgRunExternal::reject(); } -void DlgRunExternal::advanced (void) +void DlgRunExternal::advanced () { if (advancedHidden){ ui->extensionWidget->show(); diff --git a/src/Gui/DlgRunExternal.h b/src/Gui/DlgRunExternal.h index 8fd7033908..2dbbd03372 100644 --- a/src/Gui/DlgRunExternal.h +++ b/src/Gui/DlgRunExternal.h @@ -25,6 +25,7 @@ #include #include +#include namespace Gui { namespace Dialog { @@ -40,19 +41,19 @@ class GuiExport DlgRunExternal : public QDialog Q_OBJECT public: - DlgRunExternal(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - virtual ~DlgRunExternal(); + explicit DlgRunExternal(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgRunExternal() override; - int Do(void); + int Do(); QString ProcName; QStringList arguments; protected Q_SLOTS: - virtual void reject(void); - virtual void accept(void); - virtual void abort(void); - virtual void advanced(void); + void reject() override; + void accept() override; + virtual void abort(); + virtual void advanced(); void finished (int exitCode, QProcess::ExitStatus exitStatus); void on_chooseProgram_clicked(); diff --git a/src/Gui/DlgSettings3DViewImp.h b/src/Gui/DlgSettings3DViewImp.h index 76451c572c..5c8ade7c74 100644 --- a/src/Gui/DlgSettings3DViewImp.h +++ b/src/Gui/DlgSettings3DViewImp.h @@ -43,17 +43,17 @@ class DlgSettings3DViewImp : public PreferencePage Q_OBJECT public: - DlgSettings3DViewImp(QWidget* parent = nullptr); - ~DlgSettings3DViewImp(); + explicit DlgSettings3DViewImp(QWidget* parent = nullptr); + ~DlgSettings3DViewImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; private Q_SLOTS: void onAliasingChanged(int); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgSettingsCacheDirectory.cpp b/src/Gui/DlgSettingsCacheDirectory.cpp index 82faa4ba94..eda5e9f2cb 100644 --- a/src/Gui/DlgSettingsCacheDirectory.cpp +++ b/src/Gui/DlgSettingsCacheDirectory.cpp @@ -264,21 +264,8 @@ bool ApplicationCache::performAction(qint64 total) */ qint64 ApplicationCache::size() const { - // QDirIterator lists some directories twice -#if 0 - QDir cache = QString::fromStdString(App::Application::getUserCachePath()); - QDirIterator it(cache, QDirIterator::Subdirectories); - qint64 total = 0; - while (it.hasNext()) { - it.next(); - total += it.fileInfo().size(); - } - - return total; -#else qint64 total = dirSize(QString::fromStdString(App::Application::getUserCachePath())); return total; -#endif } /*! @@ -314,14 +301,16 @@ qint64 ApplicationCache::dirSize(QString dirPath) const QDir dir(dirPath); QDir::Filters fileFilters = QDir::Files; - for (QString filePath : dir.entryList(fileFilters)) { + const auto& files = dir.entryList(fileFilters); + for (const QString& filePath : files) { QFileInfo fi(dir, filePath); total += fi.size(); } // traverse sub-directories recursively QDir::Filters dirFilters = QDir::Dirs | QDir::NoDotAndDotDot; - for (QString subDirPath : dir.entryList(dirFilters)) + const auto& dirs = dir.entryList(dirFilters); + for (const QString& subDirPath : dirs) total += dirSize(dirPath + QDir::separator() + subDirPath); return total; } diff --git a/src/Gui/DlgSettingsCacheDirectory.h b/src/Gui/DlgSettingsCacheDirectory.h index 6701bf3801..19fcf17ab4 100644 --- a/src/Gui/DlgSettingsCacheDirectory.h +++ b/src/Gui/DlgSettingsCacheDirectory.h @@ -41,14 +41,14 @@ class DlgSettingsCacheDirectory : public PreferencePage Q_OBJECT public: - DlgSettingsCacheDirectory(QWidget* parent = nullptr); - ~DlgSettingsCacheDirectory(); + explicit DlgSettingsCacheDirectory(QWidget* parent = nullptr); + ~DlgSettingsCacheDirectory() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: void runCheck(); diff --git a/src/Gui/DlgSettingsColorGradientImp.h b/src/Gui/DlgSettingsColorGradientImp.h index 0cba4c09d0..3f39463738 100644 --- a/src/Gui/DlgSettingsColorGradientImp.h +++ b/src/Gui/DlgSettingsColorGradientImp.h @@ -44,12 +44,12 @@ class DlgSettingsColorGradientImp : public QDialog Q_OBJECT public: - DlgSettingsColorGradientImp(const App::ColorGradient& cg, + explicit DlgSettingsColorGradientImp(const App::ColorGradient& cg, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgSettingsColorGradientImp(); + ~DlgSettingsColorGradientImp() override; - void accept(); + void accept() override; /** @name Color profile */ //@{ diff --git a/src/Gui/DlgSettingsDocumentImp.h b/src/Gui/DlgSettingsDocumentImp.h index 78663d1729..71c922b6f5 100644 --- a/src/Gui/DlgSettingsDocumentImp.h +++ b/src/Gui/DlgSettingsDocumentImp.h @@ -41,17 +41,17 @@ class DlgSettingsDocumentImp : public PreferencePage Q_OBJECT public: - DlgSettingsDocumentImp( QWidget* parent = nullptr ); - ~DlgSettingsDocumentImp(); + explicit DlgSettingsDocumentImp( QWidget* parent = nullptr ); + ~DlgSettingsDocumentImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected Q_SLOTS: void onLicenseTypeChanged(int index); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgSettingsImageImp.h b/src/Gui/DlgSettingsImageImp.h index 67c8176122..d9fb73a200 100644 --- a/src/Gui/DlgSettingsImageImp.h +++ b/src/Gui/DlgSettingsImageImp.h @@ -43,8 +43,8 @@ class DlgSettingsImageImp : public QWidget Q_OBJECT public: - DlgSettingsImageImp( QWidget* parent = nullptr ); - ~DlgSettingsImageImp(); + explicit DlgSettingsImageImp( QWidget* parent = nullptr ); + ~DlgSettingsImageImp() override; /** @name Image dimensions */ //@{ @@ -79,7 +79,7 @@ protected Q_SLOTS: protected: // helper to force an aspect ratio void adjustImageSize(float fRatio); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: diff --git a/src/Gui/DlgSettingsLazyLoadedImp.h b/src/Gui/DlgSettingsLazyLoadedImp.h index ce52286423..a81a21ec91 100644 --- a/src/Gui/DlgSettingsLazyLoadedImp.h +++ b/src/Gui/DlgSettingsLazyLoadedImp.h @@ -44,18 +44,18 @@ class DlgSettingsLazyLoadedImp : public PreferencePage Q_OBJECT public: - DlgSettingsLazyLoadedImp( QWidget* parent = nullptr ); - ~DlgSettingsLazyLoadedImp(); + explicit DlgSettingsLazyLoadedImp( QWidget* parent = nullptr ); + ~DlgSettingsLazyLoadedImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected Q_SLOTS: void onLoadClicked(const QString& wbName); protected: void buildUnloadedWorkbenchList(); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgSettingsMacroImp.h b/src/Gui/DlgSettingsMacroImp.h index 08febd279a..cff2bbdfa3 100644 --- a/src/Gui/DlgSettingsMacroImp.h +++ b/src/Gui/DlgSettingsMacroImp.h @@ -41,14 +41,14 @@ class DlgSettingsMacroImp : public PreferencePage Q_OBJECT public: - DlgSettingsMacroImp( QWidget* parent = nullptr ); - ~DlgSettingsMacroImp(); + explicit DlgSettingsMacroImp( QWidget* parent = nullptr ); + ~DlgSettingsMacroImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgSettingsNavigation.cpp b/src/Gui/DlgSettingsNavigation.cpp index bae79fd0e0..a2a7f27fcf 100644 --- a/src/Gui/DlgSettingsNavigation.cpp +++ b/src/Gui/DlgSettingsNavigation.cpp @@ -77,10 +77,6 @@ void DlgSettingsNavigation::saveSettings() int index = ui->comboOrbitStyle->currentIndex(); hGrp->SetInt("OrbitStyle", index); - - index = ui->naviCubeCorner->currentIndex(); - hGrp->SetInt("CornerNaviCube", index); - index = ui->comboRotationMode->currentIndex(); hGrp->SetInt("RotationMode", index); @@ -91,6 +87,7 @@ void DlgSettingsNavigation::saveSettings() ui->checkBoxUseAutoRotation->onSave(); ui->qspinNewDocScale->onSave(); ui->prefStepByTurn->onSave(); + ui->naviCubeCorner->onSave(); ui->naviCubeToNearest->onSave(); ui->prefCubeSize->onSave(); @@ -117,6 +114,7 @@ void DlgSettingsNavigation::loadSettings() ui->checkBoxUseAutoRotation->onRestore(); ui->qspinNewDocScale->onRestore(); ui->prefStepByTurn->onRestore(); + ui->naviCubeCorner->onRestore(); ui->naviCubeToNearest->onRestore(); ui->prefCubeSize->onRestore(); @@ -130,9 +128,6 @@ void DlgSettingsNavigation::loadSettings() index = Base::clamp(index, 0, ui->comboOrbitStyle->count()-1); ui->comboOrbitStyle->setCurrentIndex(index); - index = hGrp->GetInt("CornerNaviCube", 1); - ui->naviCubeCorner->setCurrentIndex(index); - index = hGrp->GetInt("RotationMode", 1); ui->comboRotationMode->setCurrentIndex(index); diff --git a/src/Gui/DlgSettingsNavigation.h b/src/Gui/DlgSettingsNavigation.h index 6090b3db6d..bedb578d9e 100644 --- a/src/Gui/DlgSettingsNavigation.h +++ b/src/Gui/DlgSettingsNavigation.h @@ -44,18 +44,18 @@ class DlgSettingsNavigation : public PreferencePage Q_OBJECT public: - DlgSettingsNavigation(QWidget* parent = nullptr); - ~DlgSettingsNavigation(); + explicit DlgSettingsNavigation(QWidget* parent = nullptr); + ~DlgSettingsNavigation() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; private Q_SLOTS: void on_mouseButton_clicked(); void onNewDocViewChanged(int); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void retranslate(); private: @@ -68,8 +68,8 @@ class CameraDialog : public QDialog Q_OBJECT public: - CameraDialog(QWidget* parent=nullptr); - ~CameraDialog(); + explicit CameraDialog(QWidget* parent=nullptr); + ~CameraDialog() override; void setValues(double q0, double q1, double q2, double q3); void getValues(double& q0, double& q1, double& q2, double& q3) const; diff --git a/src/Gui/DlgSettingsNavigation.ui b/src/Gui/DlgSettingsNavigation.ui index ced2092983..76132d0422 100644 --- a/src/Gui/DlgSettingsNavigation.ui +++ b/src/Gui/DlgSettingsNavigation.ui @@ -51,7 +51,7 @@ NaviStepByTurn - View + NaviCube @@ -82,13 +82,19 @@ - + Corner where navigation cube is shown 1 + + CornerNaviCube + + + NaviCube + Top left @@ -577,6 +583,11 @@ Mouse tilting is not disabled by this setting. QCheckBox
Gui/PrefWidgets.h
+ + Gui::PrefComboBox + QComboBox +
Gui/PrefWidgets.h
+
Gui::PrefDoubleSpinBox QDoubleSpinBox diff --git a/src/Gui/DlgSettingsPythonConsole.h b/src/Gui/DlgSettingsPythonConsole.h index 84b507a3b2..4afaebf92e 100644 --- a/src/Gui/DlgSettingsPythonConsole.h +++ b/src/Gui/DlgSettingsPythonConsole.h @@ -41,14 +41,14 @@ class DlgSettingsPythonConsole : public PreferencePage Q_OBJECT public: - DlgSettingsPythonConsole(QWidget* parent = nullptr); - ~DlgSettingsPythonConsole(); + explicit DlgSettingsPythonConsole(QWidget* parent = nullptr); + ~DlgSettingsPythonConsole() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgSettingsSelection.h b/src/Gui/DlgSettingsSelection.h index b58846a6a5..fd56ced3e9 100644 --- a/src/Gui/DlgSettingsSelection.h +++ b/src/Gui/DlgSettingsSelection.h @@ -44,13 +44,13 @@ class DlgSettingsSelection : public PreferencePage public: DlgSettingsSelection(QWidget* parent = nullptr); - ~DlgSettingsSelection(); + ~DlgSettingsSelection() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Gui/DlgSettingsUnitsImp.cpp b/src/Gui/DlgSettingsUnitsImp.cpp index d7391b52c4..7ee25c36b2 100644 --- a/src/Gui/DlgSettingsUnitsImp.cpp +++ b/src/Gui/DlgSettingsUnitsImp.cpp @@ -49,7 +49,7 @@ using namespace Base; qApp->translate("Gui::Dialog::DlgSettingsUnits", "Building US (ft-in/sqft/cft)"); qApp->translate("Gui::Dialog::DlgSettingsUnits", "Metric small parts & CNC(mm, mm/min)"); qApp->translate("Gui::Dialog::DlgSettingsUnits", "Imperial for Civil Eng (ft, ft/sec)"); - qApp->translate("Gui::Dialog::DlgSettingsUnits", "FEM (mm, N, sec)"); + qApp->translate("Gui::Dialog::DlgSettingsUnits", "FEM (mm, N, s)"); #endif /** @@ -68,7 +68,6 @@ DlgSettingsUnitsImp::DlgSettingsUnitsImp(QWidget* parent) ui->comboBox_ViewSystem->addItem(item, i); } - //fillUpListBox(); ui->tableWidget->setVisible(false); // // Enable/disable the fractional inch option depending on system diff --git a/src/Gui/DlgSettingsUnitsImp.h b/src/Gui/DlgSettingsUnitsImp.h index aa04c77207..5fe7c33bc2 100644 --- a/src/Gui/DlgSettingsUnitsImp.h +++ b/src/Gui/DlgSettingsUnitsImp.h @@ -40,14 +40,14 @@ class DlgSettingsUnitsImp : public PreferencePage Q_OBJECT public: - DlgSettingsUnitsImp(QWidget* parent = nullptr); - ~DlgSettingsUnitsImp(); + explicit DlgSettingsUnitsImp(QWidget* parent = nullptr); + ~DlgSettingsUnitsImp() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; public Q_SLOTS: void on_comboBox_ViewSystem_currentIndexChanged(int index); diff --git a/src/Gui/DlgSettingsViewColor.h b/src/Gui/DlgSettingsViewColor.h index 9f0b8c12d0..394c13892e 100644 --- a/src/Gui/DlgSettingsViewColor.h +++ b/src/Gui/DlgSettingsViewColor.h @@ -41,14 +41,14 @@ class DlgSettingsViewColor : public PreferencePage Q_OBJECT public: - DlgSettingsViewColor(QWidget* parent = nullptr); - ~DlgSettingsViewColor(); + explicit DlgSettingsViewColor(QWidget* parent = nullptr); + ~DlgSettingsViewColor() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; protected Q_SLOTS: void onSwitchGradientColorsPressed(); diff --git a/src/Gui/DlgSettingsViewColor.ui b/src/Gui/DlgSettingsViewColor.ui index 75b851b83b..09f46a983b 100644 --- a/src/Gui/DlgSettingsViewColor.ui +++ b/src/Gui/DlgSettingsViewColor.ui @@ -290,9 +290,9 @@ - 51 - 51 - 101 + 150 + 150 + 170 @@ -336,9 +336,9 @@ - 151 - 151 - 170 + 212 + 212 + 200 diff --git a/src/Gui/DlgToolbarsImp.cpp b/src/Gui/DlgToolbarsImp.cpp index 3a9245a041..99e2642bcb 100644 --- a/src/Gui/DlgToolbarsImp.cpp +++ b/src/Gui/DlgToolbarsImp.cpp @@ -49,7 +49,7 @@ typedef std::vector< std::pair > GroupMap; struct GroupMap_find { const QLatin1String& item; - GroupMap_find(const QLatin1String& item) : item(item) {} + explicit GroupMap_find(const QLatin1String& item) : item(item) {} bool operator () (const std::pair& elem) const { return elem.first == item; @@ -831,7 +831,7 @@ void DlgCustomToolbarsImp::moveUpCustomCommand(const QString& name, const QByteA continue; } } - if (before != nullptr) { + if (before) { QList group = getActionGroup(*it); bars.front()->removeAction(*it); bars.front()->insertAction(before, *it); diff --git a/src/Gui/DlgToolbarsImp.h b/src/Gui/DlgToolbarsImp.h index 496c2e1e2d..55ffb692fc 100644 --- a/src/Gui/DlgToolbarsImp.h +++ b/src/Gui/DlgToolbarsImp.h @@ -46,8 +46,8 @@ class DlgCustomToolbars : public CustomizeActionPage protected: enum Type { Toolbar, Toolboxbar }; - DlgCustomToolbars(Type, QWidget* parent = nullptr); - virtual ~DlgCustomToolbars(); + explicit DlgCustomToolbars(Type, QWidget* parent = nullptr); + ~DlgCustomToolbars() override; protected Q_SLOTS: void on_categoryBox_activated(int index); @@ -59,13 +59,13 @@ protected Q_SLOTS: void on_newButton_clicked(); void on_renameButton_clicked(); void on_deleteButton_clicked(); - void onAddMacroAction(const QByteArray&); - void onRemoveMacroAction(const QByteArray&); - void onModifyMacroAction(const QByteArray&); + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; protected: - void changeEvent(QEvent *e); - void hideEvent(QHideEvent * event); + void changeEvent(QEvent *e) override; + void hideEvent(QHideEvent * event) override; virtual void addCustomToolbar(const QString&); virtual void removeCustomToolbar(const QString&); virtual void renameCustomToolbar(const QString&, const QString&); @@ -94,18 +94,18 @@ class DlgCustomToolbarsImp : public DlgCustomToolbars Q_OBJECT public: - DlgCustomToolbarsImp(QWidget* parent = nullptr); - ~DlgCustomToolbarsImp(); + explicit DlgCustomToolbarsImp(QWidget* parent = nullptr); + ~DlgCustomToolbarsImp() override; protected: - void changeEvent(QEvent *e); - virtual void addCustomToolbar(const QString&); - virtual void removeCustomToolbar(const QString&); - virtual void renameCustomToolbar(const QString&, const QString&); - virtual void addCustomCommand(const QString&, const QByteArray&); - virtual void removeCustomCommand(const QString&, const QByteArray&); - virtual void moveUpCustomCommand(const QString&, const QByteArray&); - virtual void moveDownCustomCommand(const QString&, const QByteArray&); + void changeEvent(QEvent *e) override; + void addCustomToolbar(const QString&) override; + void removeCustomToolbar(const QString&) override; + void renameCustomToolbar(const QString&, const QString&) override; + void addCustomCommand(const QString&, const QByteArray&) override; + void removeCustomCommand(const QString&, const QByteArray&) override; + void moveUpCustomCommand(const QString&, const QByteArray&) override; + void moveDownCustomCommand(const QString&, const QByteArray&) override; private: QList getActionGroup(QAction*); @@ -126,11 +126,11 @@ class DlgCustomToolBoxbarsImp : public DlgCustomToolbars Q_OBJECT public: - DlgCustomToolBoxbarsImp(QWidget* parent = nullptr); - ~DlgCustomToolBoxbarsImp(); + explicit DlgCustomToolBoxbarsImp(QWidget* parent = nullptr); + ~DlgCustomToolBoxbarsImp() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; }; } // namespace Dialog diff --git a/src/Gui/DlgUndoRedo.h b/src/Gui/DlgUndoRedo.h index cc615b1bab..e35714a2a9 100644 --- a/src/Gui/DlgUndoRedo.h +++ b/src/Gui/DlgUndoRedo.h @@ -37,8 +37,8 @@ class UndoDialog : public QMenu Q_OBJECT public: - UndoDialog( QWidget* parent = nullptr ); - virtual ~UndoDialog(); + explicit UndoDialog( QWidget* parent = nullptr ); + ~UndoDialog() override; protected Q_SLOTS: void onSelected(); @@ -53,8 +53,8 @@ class RedoDialog : public QMenu Q_OBJECT public: - RedoDialog( QWidget* parent = nullptr ); - virtual ~RedoDialog(); + explicit RedoDialog( QWidget* parent = nullptr ); + ~RedoDialog() override; protected Q_SLOTS: void onSelected(); diff --git a/src/Gui/DlgUnitsCalculatorImp.cpp b/src/Gui/DlgUnitsCalculatorImp.cpp index 10f03a2ca2..de783e19bc 100644 --- a/src/Gui/DlgUnitsCalculatorImp.cpp +++ b/src/Gui/DlgUnitsCalculatorImp.cpp @@ -180,13 +180,13 @@ void DlgUnitsCalculator::parseError(const QString& errorText) ui->ValueOutput->setText(errorText); } -void DlgUnitsCalculator::copy(void) +void DlgUnitsCalculator::copy() { QClipboard *cb = QApplication::clipboard(); cb->setText(ui->ValueOutput->text()); } -void DlgUnitsCalculator::returnPressed(void) +void DlgUnitsCalculator::returnPressed() { if (ui->pushButton_Copy->isEnabled()) { ui->textEdit->append(ui->ValueInput->text() + QString::fromLatin1(" = ") + ui->ValueOutput->text()); diff --git a/src/Gui/DlgUnitsCalculatorImp.h b/src/Gui/DlgUnitsCalculatorImp.h index a060010aa2..4f9f2da786 100644 --- a/src/Gui/DlgUnitsCalculatorImp.h +++ b/src/Gui/DlgUnitsCalculatorImp.h @@ -42,12 +42,12 @@ class DlgUnitsCalculator : public QDialog Q_OBJECT public: - DlgUnitsCalculator(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgUnitsCalculator(); + explicit DlgUnitsCalculator(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgUnitsCalculator() override; protected: - void accept(); - void reject(); + void accept() override; + void reject() override; protected Q_SLOTS: void textChanged(const QString); @@ -56,8 +56,8 @@ protected Q_SLOTS: void on_comboBoxScheme_activated(int); void on_spinBoxDecimals_valueChanged(int); - void copy(void); - void returnPressed(void); + void copy(); + void returnPressed(); void parseError(const QString& errorText); diff --git a/src/Gui/DlgWorkbenchesImp.h b/src/Gui/DlgWorkbenchesImp.h index b436d7c00a..dc3cf907e3 100644 --- a/src/Gui/DlgWorkbenchesImp.h +++ b/src/Gui/DlgWorkbenchesImp.h @@ -40,20 +40,20 @@ class DlgWorkbenchesImp : public CustomizeActionPage Q_OBJECT public: - DlgWorkbenchesImp(QWidget* parent = nullptr); - ~DlgWorkbenchesImp(); + explicit DlgWorkbenchesImp(QWidget* parent = nullptr); + ~DlgWorkbenchesImp() override; static QStringList load_enabled_workbenches(); static QStringList load_disabled_workbenches(); static const QString all_workbenches; protected: - void changeEvent(QEvent *e); - void hideEvent(QHideEvent * event); + void changeEvent(QEvent *e) override; + void hideEvent(QHideEvent * event) override; protected Q_SLOTS: - void onAddMacroAction(const QByteArray&); - void onRemoveMacroAction(const QByteArray&); - void onModifyMacroAction(const QByteArray&); + void onAddMacroAction(const QByteArray&) override; + void onRemoveMacroAction(const QByteArray&) override; + void onModifyMacroAction(const QByteArray&) override; void on_add_to_enabled_workbenches_btn_clicked(); void on_remove_from_enabled_workbenches_btn_clicked(); void on_shift_workbench_up_btn_clicked(); diff --git a/src/Gui/DockWindow.h b/src/Gui/DockWindow.h index 08da4c8dc7..68db73da26 100644 --- a/src/Gui/DockWindow.h +++ b/src/Gui/DockWindow.h @@ -53,30 +53,30 @@ public: * the view will attach to the active document. Be aware there isn't * always an active document available! */ - DockWindow ( Gui::Document* pcDocument=nullptr, QWidget *parent=nullptr ); + explicit DockWindow ( Gui::Document* pcDocument=nullptr, QWidget *parent=nullptr ); /** View destructor * Detach the view from the document, if attached. */ - virtual ~DockWindow(); + ~DockWindow() override; /** @name methods to override */ //@{ /// get called when the document is updated - virtual void onUpdate(void){} + void onUpdate() override{} /// returns the name of the view (important for messages) - virtual const char *getName(void) const { return "DockWindow"; } + const char *getName() const override { return "DockWindow"; } /// Message handler - virtual bool onMsg(const char* ,const char** ){ return false; } + bool onMsg(const char* ,const char** ) override{ return false; } /// Message handler test - virtual bool onHasMsg(const char*) const { return false; } + bool onHasMsg(const char*) const override { return false; } /// overwrite when checking on close state - virtual bool canClose(void){return true;} + bool canClose() override{return true;} //@} Q_SIGNALS: /// sends a message to the document - void sendCloseView(MDIView* theView); + void sendCloseView(Gui::MDIView* theView); }; } // namespace Gui diff --git a/src/Gui/DockWindowManager.cpp b/src/Gui/DockWindowManager.cpp index 0ca9b195cb..3a4bce1854 100644 --- a/src/Gui/DockWindowManager.cpp +++ b/src/Gui/DockWindowManager.cpp @@ -102,7 +102,7 @@ DockWindowManager* DockWindowManager::_instance = nullptr; DockWindowManager* DockWindowManager::instance() { - if ( _instance == nullptr ) + if (!_instance) _instance = new DockWindowManager; return _instance; } @@ -370,27 +370,6 @@ void DockWindowManager::setup(DockWindowItems* items) } } -#if 0 // FIXME: don't tabify always after switching the workbench - // tabify dock widgets for which "tabbed" is true and which have the same position - for (int i=0; i<4; i++) { - const QList& dws = areas[i]; - for (QList::ConstIterator it = dws.begin(); it != dws.end(); ++it) { - if (*it != dws.front()) { - getMainWindow()->tabifyDockWidget(dws.front(), *it); - } - } - } -#endif - -#if 0 - // hide all dock windows which we don't need for the moment - for (QList::Iterator it = docked.begin(); it != docked.end(); ++it) { - QByteArray dockName = (*it)->toggleViewAction()->data().toByteArray(); - hPref->SetBool(dockName.constData(), (*it)->isVisible()); - (*it)->hide(); - (*it)->toggleViewAction()->setVisible(false); - } -#endif } void DockWindowManager::saveState() diff --git a/src/Gui/DockWindowManager.h b/src/Gui/DockWindowManager.h index 571ebfde3f..de314b6af7 100644 --- a/src/Gui/DockWindowManager.h +++ b/src/Gui/DockWindowManager.h @@ -109,7 +109,7 @@ private: QDockWidget* findDockWidget(const QList&, const QString&) const; DockWindowManager(); - ~DockWindowManager(); + ~DockWindowManager() override; static DockWindowManager* _instance; struct DockWindowManagerP* d; }; diff --git a/src/Gui/Document.cpp b/src/Gui/Document.cpp index d28598bf11..e666e66fa6 100644 --- a/src/Gui/Document.cpp +++ b/src/Gui/Document.cpp @@ -457,11 +457,11 @@ void Document::setEditingTransform(const Base::Matrix4D &mat) { activeView->getViewer()->setEditingTransform(mat); } -void Document::resetEdit(void) { +void Document::resetEdit() { Application::Instance->setEditDocument(nullptr); } -void Document::_resetEdit(void) +void Document::_resetEdit() { std::list::iterator it; if (d->_editViewProvider) { @@ -487,17 +487,7 @@ void Document::_resetEdit(void) // changed into a private one, _resetEdit(). And the exposed // resetEdit() above calls into Application->setEditDocument(0) which // will prevent recursive calling. -#if 0 - // Nullify the member variable before calling finishEditing(). - // This is to avoid a possible stack overflow when a view provider wrongly - // invokes the document's resetEdit() method. - ViewProvider* editViewProvider = d->_editViewProvider; - d->_editViewProvider = nullptr; - editViewProvider->finishEditing(); - if (editViewProvider->isDerivedFrom(ViewProviderDocumentObject::getClassTypeId())) - signalResetEdit(*(static_cast(editViewProvider))); -#endif App::GetApplication().closeActiveTransaction(); } d->_editViewProviderParent = nullptr; @@ -759,9 +749,6 @@ void Document::slotDeletedObject(const App::DocumentObject& Obj) handleChildren3D(viewProvider,true); -#if 0 // With this we can show child objects again if this method was called by undo - viewProvider->onDelete(std::vector()); -#endif if (viewProvider && viewProvider->getTypeId().isDerivedFrom (ViewProviderDocumentObject::getClassTypeId())) { // go through the views @@ -796,7 +783,6 @@ void Document::beforeDelete() { void Document::slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) { - //Base::Console().Log("Document::slotChangedObject() called\n"); ViewProvider* viewProvider = getViewProvider(&Obj); if (viewProvider) { try { @@ -939,7 +925,7 @@ void Document::slotSkipRecompute(const App::Document& doc, const std::vectorgetNameInDocument() || (objs.size() && objs.front()!=obj)) + if(!obj || !obj->getNameInDocument() || (!objs.empty() && objs.front()!=obj)) return; obj->recomputeFeature(true); } @@ -1036,7 +1022,7 @@ std::vector > Document::getViewProvid return ret; } -App::Document* Document::getDocument(void) const +App::Document* Document::getDocument() const { return d->_pcDocument; } @@ -1130,7 +1116,7 @@ bool Document::askIfSavingFailed(const QString& error) } /// Save the document -bool Document::save(void) +bool Document::save() { if (d->_pcDocument->isSaved()) { try { @@ -1213,14 +1199,14 @@ bool Document::save(void) } /// Save the document under a new file name -bool Document::saveAs(void) +bool Document::saveAs() { getMainWindow()->showMessage(QObject::tr("Save document under new filename...")); QString exe = qApp->applicationName(); QString fn = FileDialog::getSaveFileName(getMainWindow(), QObject::tr("Save %1 Document").arg(exe), QString::fromUtf8(getDocument()->FileName.getValue()), - QString::fromLatin1("%1 %2 (*.FCStd)").arg(exe).arg(QObject::tr("Document"))); + QString::fromLatin1("%1 %2 (*.FCStd)").arg(exe, QObject::tr("Document"))); if (!fn.isEmpty()) { QFileInfo fi; @@ -1314,7 +1300,7 @@ void Document::saveAll() } /// Save a copy of the document under a new file name -bool Document::saveCopy(void) +bool Document::saveCopy() { getMainWindow()->showMessage(QObject::tr("Save a copy of the document under new filename...")); @@ -1339,7 +1325,7 @@ bool Document::saveCopy(void) } } -unsigned int Document::getMemSize (void) const +unsigned int Document::getMemSize () const { unsigned int size = 0; @@ -1900,7 +1886,7 @@ void Document::detachView(Gui::BaseView* pcView, bool bPassiv) d->baseViews.remove(pcView); // last view? - if (d->baseViews.size() == 0) { + if (d->baseViews.empty()) { // decouple a passive view std::list::iterator it = d->passiveViews.begin(); while (it != d->passiveViews.end()) { @@ -1918,7 +1904,7 @@ void Document::detachView(Gui::BaseView* pcView, bool bPassiv) } } -void Document::onUpdate(void) +void Document::onUpdate() { #ifdef FC_LOGUPDATECHAIN Base::Console().Log("Acti: Gui::Document::onUpdate()"); @@ -1935,7 +1921,7 @@ void Document::onUpdate(void) } } -void Document::onRelabel(void) +void Document::onRelabel() { #ifdef FC_LOGUPDATECHAIN Base::Console().Log("Acti: Gui::Document::onRelabel()"); @@ -1954,7 +1940,7 @@ void Document::onRelabel(void) d->connectChangeDocumentBlocker.unblock(); } -bool Document::isLastView(void) +bool Document::isLastView() { if (d->baseViews.size() <= 1) return true; @@ -1988,7 +1974,7 @@ bool Document::canClose (bool checkModify, bool checkLink) // } //} - if (checkLink && App::PropertyXLink::getDocumentInList(getDocument()).size()) + if (checkLink && !App::PropertyXLink::getDocumentInList(getDocument()).empty()) return true; if (getDocument()->testStatus(App::Document::TempDoc)) @@ -2113,7 +2099,7 @@ bool Document::sendMsgToFirstView(const Base::Type& typeId, const char* pMsg, co } /// Getter for the active view -MDIView* Document::getActiveView(void) const +MDIView* Document::getActiveView() const { // get the main window's active view MDIView* active = getMainWindow()->activeWindow(); @@ -2276,29 +2262,29 @@ void Document::openCommand(const char* sName) getDocument()->openTransaction(sName); } -void Document::commitCommand(void) +void Document::commitCommand() { getDocument()->commitTransaction(); } -void Document::abortCommand(void) +void Document::abortCommand() { getDocument()->abortTransaction(); } -bool Document::hasPendingCommand(void) const +bool Document::hasPendingCommand() const { return getDocument()->hasPendingTransaction(); } /// Get a string vector with the 'Undo' actions -std::vector Document::getUndoVector(void) const +std::vector Document::getUndoVector() const { return getDocument()->getAvailableUndoNames(); } /// Get a string vector with the 'Redo' actions -std::vector Document::getRedoVector(void) const +std::vector Document::getRedoVector() const { return getDocument()->getAvailableRedoNames(); } @@ -2328,7 +2314,7 @@ bool Document::checkTransactionID(bool undo, int iSteps) { currentSteps = steps; } } - if(prompts.size()) { + if(!prompts.empty()) { std::ostringstream str; int i=0; for(auto doc : prompts) { @@ -2338,20 +2324,18 @@ bool Document::checkTransactionID(bool undo, int iSteps) { } str << " " << doc->getName() << "\n"; } - int ret = QMessageBox::warning(getMainWindow(), - undo?QObject::tr("Undo"):QObject::tr("Redo"), - QString::fromLatin1("%1,\n%2%3") - .arg(QObject::tr( - "There are grouped transactions in the following documents with " - "other preceding transactions")) - .arg(QString::fromUtf8(str.str().c_str())) - .arg(QObject::tr("Choose 'Yes' to roll back all preceding transactions.\n" - "Choose 'No' to roll back in the active document only.\n" - "Choose 'Abort' to abort")), + int ret = QMessageBox::warning(getMainWindow(), undo ? QObject::tr("Undo") : QObject::tr("Redo"), + QString::fromLatin1("%1,\n%2%3").arg( + QObject::tr("There are grouped transactions in the following documents with " + "other preceding transactions"), + QString::fromStdString(str.str()), + QObject::tr("Choose 'Yes' to roll back all preceding transactions.\n" + "Choose 'No' to roll back in the active document only.\n" + "Choose 'Abort' to abort")), QMessageBox::Yes|QMessageBox::No|QMessageBox::Abort, QMessageBox::Yes); - if(ret == QMessageBox::Abort) + if (ret == QMessageBox::Abort) return false; - if(ret == QMessageBox::No) + if (ret == QMessageBox::No) return true; } for(auto &v : dmap) { @@ -2401,7 +2385,7 @@ void Document::redo(int iSteps) d->_redoViewProviders.clear(); } -PyObject* Document::getPyObject(void) +PyObject* Document::getPyObject() { _pcDocPy->IncRef(); return _pcDocPy; diff --git a/src/Gui/Document.h b/src/Gui/Document.h index cd6ad74a70..73df51510d 100644 --- a/src/Gui/Document.h +++ b/src/Gui/Document.h @@ -69,7 +69,7 @@ class GuiExport Document : public Base::Persistence { public: Document(App::Document* pcDocument, Application * app); - ~Document(); + ~Document() override; protected: /** @name I/O of the document */ @@ -141,23 +141,23 @@ public: /** @name I/O of the document */ //@{ - unsigned int getMemSize (void) const; + unsigned int getMemSize () const override; /// Save the document - bool save(void); + bool save(); /// Save the document under a new file name - bool saveAs(void); + bool saveAs(); /// Save a copy of the document under a new file name - bool saveCopy(void); + bool saveCopy(); /// Save all open document static void saveAll(); /// This method is used to save properties or very small amounts of data to an XML document. - virtual void Save (Base::Writer &writer) const; + void Save (Base::Writer &writer) const override; /// This method is used to restore properties from an XML document. - virtual void Restore(Base::XMLReader &reader); + void Restore(Base::XMLReader &reader) override; /// This method is used to save large amounts of data to a binary file. - virtual void SaveDocFile (Base::Writer &writer) const; + void SaveDocFile (Base::Writer &writer) const override; /// This method is used to restore large amounts of data from a binary file. - virtual void RestoreDocFile(Base::Reader &reader); + void RestoreDocFile(Base::Reader &reader) override; void exportObjects(const std::vector&, Base::Writer&); void importObjects(const std::vector&, Base::Reader&, const std::map& nameMapping); @@ -170,12 +170,12 @@ public: bool isModified() const; /// Getter for the App Document - App::Document* getDocument(void) const; + App::Document* getDocument() const; /** @name methods for View handling */ //@{ /// Getter for the active view - Gui::MDIView* getActiveView(void) const; + Gui::MDIView* getActiveView() const; void setActiveWindow(Gui::MDIView* view); Gui::MDIView* getEditingViewOfViewProvider(Gui::ViewProvider*) const; Gui::MDIView* getViewOfViewProvider(const Gui::ViewProvider*) const; @@ -207,9 +207,9 @@ public: /// Get all view providers along the path and the corresponding node index in the path std::vector > getViewProvidersByPath(SoPath * path) const; /// call update on all attached views - void onUpdate(void); + void onUpdate(); /// call relabel to all attached views - void onRelabel(void); + void onRelabel(); /// returns a list of all attached MDI views std::list getMDIViews() const; /// returns a list of all MDI views of a certain type @@ -244,9 +244,9 @@ public: const Base::Matrix4D &getEditingTransform() const; void setEditingTransform(const Base::Matrix4D &mat); /// reset from edit mode, this cause all document to reset edit - void resetEdit(void); + void resetEdit(); /// reset edit of this document - void _resetEdit(void); + void _resetEdit(); /// get the in edit ViewProvider or NULL ViewProvider *getInEdit(ViewProviderDocumentObject **parentVp=nullptr, std::string *subname=nullptr, int *mode=nullptr, std::string *subElement=nullptr) const; @@ -265,15 +265,15 @@ public: /// Open a new Undo transaction on the document void openCommand(const char* sName=nullptr); /// Commit the Undo transaction on the document - void commitCommand(void); + void commitCommand(); /// Abort the Undo transaction on the document - void abortCommand(void); + void abortCommand(); /// Check if an Undo transaction is open - bool hasPendingCommand(void) const; + bool hasPendingCommand() const; /// Get an Undo string vector with the Undo names - std::vector getUndoVector(void) const; + std::vector getUndoVector() const; /// Get an Redo string vector with the Redo names - std::vector getRedoVector(void) const; + std::vector getRedoVector() const; /// Will UNDO one or more steps void undo(int iSteps); /// Will REDO one or more steps @@ -288,12 +288,12 @@ public: /// handles the application close event bool canClose(bool checkModify=true, bool checkLink=false); - bool isLastView(void); + bool isLastView(); /// called by Application before being deleted void beforeDelete(); - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; const char *getCameraSettings() const; bool saveCameraSettings(const char *) const; diff --git a/src/Gui/DocumentModel.cpp b/src/Gui/DocumentModel.cpp index 054087914f..a528388a06 100644 --- a/src/Gui/DocumentModel.cpp +++ b/src/Gui/DocumentModel.cpp @@ -48,10 +48,10 @@ namespace Gui { // Base class class DocumentModelIndex : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~DocumentModelIndex() + ~DocumentModelIndex() override { qDeleteAll(childItems); } void setParent(DocumentModelIndex* parent) @@ -113,13 +113,13 @@ namespace Gui { // Root node class ApplicationIndex : public DocumentModelIndex { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: ApplicationIndex(){} int findChild(const Gui::Document& d) const; - Qt::ItemFlags flags() const; - QVariant data(int role) const; + Qt::ItemFlags flags() const override; + QVariant data(int role) const override; }; // ------------------------------------------------------------------------ @@ -128,7 +128,7 @@ namespace Gui { class DocumentIndex : public DocumentModelIndex { friend class ViewProviderIndex; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); static QIcon* documentIcon; typedef boost::unordered_set IndexSet; std::map vp_nodes; @@ -137,19 +137,19 @@ namespace Gui { public: const Gui::Document& d; - DocumentIndex(const Gui::Document& d) : d(d) + explicit DocumentIndex(const Gui::Document& d) : d(d) { if (!documentIcon) documentIcon = new QIcon(Gui::BitmapFactory().pixmap("Document")); } - ~DocumentIndex() + ~DocumentIndex() override { qDeleteAll(childItems); childItems.clear(); } ViewProviderIndex* cloneViewProvider(const ViewProviderDocumentObject&) const; int rowOfViewProvider(const ViewProviderDocumentObject&) const; void findViewProviders(const ViewProviderDocumentObject&, QList&) const; - QVariant data(int role) const; + QVariant data(int role) const override; }; // ------------------------------------------------------------------------ @@ -157,15 +157,15 @@ namespace Gui { // Object nodes class ViewProviderIndex : public DocumentModelIndex { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: const Gui::ViewProviderDocumentObject& v; ViewProviderIndex(const Gui::ViewProviderDocumentObject& v, DocumentIndex* d); - ~ViewProviderIndex(); + ~ViewProviderIndex() override; ViewProviderIndex* clone() const; void findViewProviders(const ViewProviderDocumentObject&, QList&) const; - QVariant data(int role) const; + QVariant data(int role) const override; private: DocumentIndex* d; diff --git a/src/Gui/DocumentModel.h b/src/Gui/DocumentModel.h index becb4dedf1..1de48eb7ff 100644 --- a/src/Gui/DocumentModel.h +++ b/src/Gui/DocumentModel.h @@ -38,18 +38,18 @@ class ViewProviderDocumentObject; class DocumentModel : public QAbstractItemModel { public: - DocumentModel(QObject* parent); - virtual ~DocumentModel(); + explicit DocumentModel(QObject* parent); + ~DocumentModel() override; - int columnCount (const QModelIndex & parent = QModelIndex()) const; - QVariant data (const QModelIndex & index, int role = Qt::DisplayRole) const; - bool setData (const QModelIndex & idx, const QVariant & value, int role); - Qt::ItemFlags flags(const QModelIndex &index) const; - QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex()) const; - QModelIndex parent (const QModelIndex & index) const; - int rowCount (const QModelIndex & parent = QModelIndex()) const; - QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole); + int columnCount (const QModelIndex & parent = QModelIndex()) const override; + QVariant data (const QModelIndex & index, int role = Qt::DisplayRole) const override; + bool setData (const QModelIndex & idx, const QVariant & value, int role) override; + Qt::ItemFlags flags(const QModelIndex &index) const override; + QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex()) const override; + QModelIndex parent (const QModelIndex & index) const override; + int rowCount (const QModelIndex & parent = QModelIndex()) const override; + QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole) override; private: void slotNewDocument(const Gui::Document&); diff --git a/src/Gui/DocumentObserver.cpp b/src/Gui/DocumentObserver.cpp index e0e7acc8aa..a5cb320fbb 100644 --- a/src/Gui/DocumentObserver.cpp +++ b/src/Gui/DocumentObserver.cpp @@ -422,7 +422,7 @@ void DocumentObserver::attachDocument(Document* doc) { detachDocument(); - if (doc == nullptr) + if (!doc) return; this->connectDocumentCreatedObject = doc->signalNewObject.connect(std::bind diff --git a/src/Gui/DocumentObserver.h b/src/Gui/DocumentObserver.h index eb405f9feb..ca9bf81f10 100644 --- a/src/Gui/DocumentObserver.h +++ b/src/Gui/DocumentObserver.h @@ -46,9 +46,9 @@ public: /*! Constructor */ DocumentT(); /*! Constructor */ - DocumentT(Document*); + explicit DocumentT(Document*); /*! Constructor */ - DocumentT(const std::string&); + explicit DocumentT(const std::string&); /*! Constructor */ DocumentT(const DocumentT&); /*! Destructor */ @@ -90,7 +90,7 @@ public: /*! Constructor */ ViewProviderT(ViewProviderT &&); /*! Constructor */ - ViewProviderT(const ViewProviderDocumentObject*); + explicit ViewProviderT(const ViewProviderDocumentObject*); /*! Destructor */ ~ViewProviderT(); /*! Assignment operator */ @@ -134,7 +134,7 @@ private: class GuiExport DocumentWeakPtrT { public: - DocumentWeakPtrT(Gui::Document*) noexcept; + explicit DocumentWeakPtrT(Gui::Document*) noexcept; ~DocumentWeakPtrT(); /*! @@ -173,7 +173,7 @@ private: class GuiExport ViewProviderWeakPtrT { public: - ViewProviderWeakPtrT(ViewProviderDocumentObject*); + explicit ViewProviderWeakPtrT(ViewProviderDocumentObject*); ~ViewProviderWeakPtrT(); /*! @@ -236,7 +236,7 @@ template class WeakPtrT { public: - WeakPtrT(T* t) : ptr(t) { + explicit WeakPtrT(T* t) : ptr(t) { } ~WeakPtrT() { } @@ -319,7 +319,7 @@ class GuiExport DocumentObserver public: /// Constructor DocumentObserver(); - DocumentObserver(Document*); + explicit DocumentObserver(Document*); virtual ~DocumentObserver(); /** Attaches to another document, the old document diff --git a/src/Gui/DocumentPyImp.cpp b/src/Gui/DocumentPyImp.cpp index 0f94e6fb32..7e520d4a09 100644 --- a/src/Gui/DocumentPyImp.cpp +++ b/src/Gui/DocumentPyImp.cpp @@ -50,7 +50,7 @@ using namespace Gui; // returns a string which represent the object e.g. when printed in python -std::string DocumentPy::representation(void) const +std::string DocumentPy::representation() const { std::stringstream str; str << ""; @@ -377,7 +377,7 @@ PyObject* DocumentPy::toggleInSceneGraph(PyObject *args) { Py_Return; } -Py::Object DocumentPy::getActiveObject(void) const +Py::Object DocumentPy::getActiveObject() const { App::DocumentObject *object = getDocumentPtr()->getDocument()->getActiveObject(); if (object) { @@ -394,7 +394,7 @@ void DocumentPy::setActiveObject(Py::Object /*arg*/) throw Py::AttributeError("'Document' object attribute 'ActiveObject' is read-only"); } -Py::Object DocumentPy::getActiveView(void) const +Py::Object DocumentPy::getActiveView() const { Gui::MDIView *view = getDocumentPtr()->getActiveView(); if (view) { @@ -411,7 +411,7 @@ void DocumentPy::setActiveView(Py::Object /*arg*/) throw Py::AttributeError("'Document' object attribute 'ActiveView' is read-only"); } -Py::Object DocumentPy::getDocument(void) const +Py::Object DocumentPy::getDocument() const { App::Document *doc = getDocumentPtr()->getDocument(); if (doc) { @@ -423,7 +423,7 @@ Py::Object DocumentPy::getDocument(void) const } } -Py::Object DocumentPy::getEditingTransform(void) const +Py::Object DocumentPy::getEditingTransform() const { return Py::asObject(new Base::MatrixPy(new Base::Matrix4D( getDocumentPtr()->getEditingTransform()))); @@ -438,7 +438,7 @@ void DocumentPy::setEditingTransform(Py::Object arg) *static_cast(arg.ptr())->getMatrixPtr()); } -Py::Object DocumentPy::getInEditInfo(void) const { +Py::Object DocumentPy::getInEditInfo() const { ViewProviderDocumentObject *vp = nullptr; std::string subname,subelement; int mode = 0; @@ -462,7 +462,7 @@ void DocumentPy::setInEditInfo(Py::Object arg) pyobj)->getViewProviderDocumentObjectPtr(),subname); } -Py::Int DocumentPy::getEditMode(void) const +Py::Int DocumentPy::getEditMode() const { int mode = -1; getDocumentPtr()->getInEdit(nullptr,nullptr,&mode); @@ -475,7 +475,7 @@ Py::Boolean DocumentPy::getTransacting() const return Py::Boolean(getDocumentPtr()->isPerformingTransaction()); } -Py::Boolean DocumentPy::getModified(void) const +Py::Boolean DocumentPy::getModified() const { return Py::Boolean(getDocumentPtr()->isModified()); } diff --git a/src/Gui/DocumentRecovery.cpp b/src/Gui/DocumentRecovery.cpp index 0305ddea48..978b62abdd 100644 --- a/src/Gui/DocumentRecovery.cpp +++ b/src/Gui/DocumentRecovery.cpp @@ -723,7 +723,7 @@ void DocumentRecoveryCleaner::subtractFiles(QStringList& files) void DocumentRecoveryCleaner::subtractDirs(QFileInfoList& dirs) { if (!ignoreDirs.isEmpty() && !dirs.isEmpty()) { - for (const auto& it : ignoreDirs) { + for (const auto& it : qAsConst(ignoreDirs)) { dirs.removeOne(it); } } diff --git a/src/Gui/DocumentRecovery.h b/src/Gui/DocumentRecovery.h index c8183beff6..46fb2696b5 100644 --- a/src/Gui/DocumentRecovery.h +++ b/src/Gui/DocumentRecovery.h @@ -43,15 +43,15 @@ class DocumentRecovery : public QDialog Q_OBJECT public: - DocumentRecovery(const QList&, QWidget* parent = nullptr); - virtual ~DocumentRecovery(); + explicit DocumentRecovery(const QList&, QWidget* parent = nullptr); + ~DocumentRecovery() override; - void accept(); + void accept() override; bool foundDocuments() const; protected: - void closeEvent(QCloseEvent*); - void contextMenuEvent(QContextMenuEvent*); + void closeEvent(QCloseEvent*) override; + void contextMenuEvent(QContextMenuEvent*) override; QString createProjectFile(const QString&); void cleanup(QDir&, const QList&, const QString&); diff --git a/src/Gui/DownloadItem.h b/src/Gui/DownloadItem.h index ff3df9d4bb..793b22f5a2 100644 --- a/src/Gui/DownloadItem.h +++ b/src/Gui/DownloadItem.h @@ -42,8 +42,8 @@ class EditTableView : public QTableView Q_OBJECT public: - EditTableView(QWidget *parent = nullptr); - void keyPressEvent(QKeyEvent *event); + explicit EditTableView(QWidget *parent = nullptr); + void keyPressEvent(QKeyEvent *event) override; public Q_SLOTS: void removeOne(); @@ -55,10 +55,10 @@ class SqueezeLabel : public QLabel Q_OBJECT public: - SqueezeLabel(QWidget *parent = nullptr); + explicit SqueezeLabel(QWidget *parent = nullptr); protected: - void paintEvent(QPaintEvent *event); + void paintEvent(QPaintEvent *event) override; }; @@ -72,15 +72,15 @@ class AutoSaver : public QObject { Q_OBJECT public: - AutoSaver(QObject *parent); - ~AutoSaver(); + explicit AutoSaver(QObject *parent); + ~AutoSaver() override; void saveIfNecessary(); public Q_SLOTS: void changeOccurred(); protected: - void timerEvent(QTimerEvent *event); + void timerEvent(QTimerEvent *event) override; private: QBasicTimer m_timer; @@ -93,7 +93,7 @@ class NetworkAccessManager : public QNetworkAccessManager Q_OBJECT public: - NetworkAccessManager(QObject *parent = nullptr); + explicit NetworkAccessManager(QObject *parent = nullptr); private Q_SLOTS: void authenticationRequired(QNetworkReply *reply, QAuthenticator *auth); // clazy:exclude=overridden-signal @@ -114,7 +114,7 @@ Q_SIGNALS: void statusChanged(); public: - DownloadItem(QNetworkReply *reply = nullptr, bool requestFileName = false, QWidget *parent = nullptr); + explicit DownloadItem(QNetworkReply *reply = nullptr, bool requestFileName = false, QWidget *parent = nullptr); bool downloading() const; bool downloadedSuccessfully() const; @@ -137,7 +137,7 @@ private Q_SLOTS: void finished(); private: - void contextMenuEvent(QContextMenuEvent *); + void contextMenuEvent(QContextMenuEvent *) override; void getFileName(); void init(); void updateInfoLabel(); diff --git a/src/Gui/DownloadManager.h b/src/Gui/DownloadManager.h index f306051d75..420cea2ab5 100644 --- a/src/Gui/DownloadManager.h +++ b/src/Gui/DownloadManager.h @@ -29,6 +29,7 @@ #include #include #include +#include class AutoSaver; @@ -43,8 +44,6 @@ class Ui_DownloadManager; class GuiExport DownloadManager : public QDialog { Q_OBJECT - Q_PROPERTY(RemovePolicy removePolicy READ removePolicy WRITE setRemovePolicy) - Q_ENUMS(RemovePolicy) public: enum RemovePolicy { @@ -53,11 +52,15 @@ public: SuccessFullDownload }; + Q_PROPERTY(RemovePolicy removePolicy READ removePolicy WRITE setRemovePolicy) // clazy:exclude=qproperty-without-notify + Q_ENUM(RemovePolicy) + +public: static DownloadManager* getInstance(); private: - DownloadManager(QWidget *parent = nullptr); - ~DownloadManager(); + explicit DownloadManager(QWidget *parent = nullptr); + ~DownloadManager() override; public: int activeDownloads() const; @@ -66,7 +69,7 @@ public: RemovePolicy removePolicy() const; void setRemovePolicy(RemovePolicy policy); - void closeEvent(QCloseEvent* e); + void closeEvent(QCloseEvent* e) override; QUrl redirectUrl(const QUrl&) const; public Q_SLOTS: @@ -104,10 +107,10 @@ class DownloadModel : public QAbstractListModel Q_OBJECT public: - DownloadModel(DownloadManager *downloadManager, QObject *parent = nullptr); - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - int rowCount(const QModelIndex &parent = QModelIndex()) const; - bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); + explicit DownloadModel(DownloadManager *downloadManager, QObject *parent = nullptr); + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; private: DownloadManager *m_downloadManager; diff --git a/src/Gui/EditorView.cpp b/src/Gui/EditorView.cpp index 34dfc6d692..f8449620ba 100644 --- a/src/Gui/EditorView.cpp +++ b/src/Gui/EditorView.cpp @@ -311,7 +311,7 @@ bool EditorView::onHasMsg(const char* pMsg) const } /** Checking on close state. */ -bool EditorView::canClose(void) +bool EditorView::canClose() { if ( !d->textEdit->document()->isModified() ) return true; @@ -341,7 +341,7 @@ void EditorView::setDisplayName(EditorView::DisplayName type) /** * Saves the content of the editor to a file specified by the appearing file dialog. */ -bool EditorView::saveAs(void) +bool EditorView::saveAs() { QString fn = FileDialog::getSaveFileName(this, QObject::tr("Save Macro"), QString(), QString::fromLatin1("%1 (*.FCMacro);;Python (*.py)").arg(tr("FreeCAD macro"))); @@ -382,7 +382,7 @@ bool EditorView::open(const QString& fileName) * Copies the selected text to the clipboard and deletes it from the text edit. * If there is no selected text nothing happens. */ -void EditorView::cut(void) +void EditorView::cut() { d->textEdit->cut(); } @@ -390,7 +390,7 @@ void EditorView::cut(void) /** * Copies any selected text to the clipboard. */ -void EditorView::copy(void) +void EditorView::copy() { d->textEdit->copy(); } @@ -399,7 +399,7 @@ void EditorView::copy(void) * Pastes the text from the clipboard into the text edit at the current cursor position. * If there is no text in the clipboard nothing happens. */ -void EditorView::paste(void) +void EditorView::paste() { d->textEdit->paste(); } @@ -408,7 +408,7 @@ void EditorView::paste(void) * Undoes the last operation. * If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing happens. */ -void EditorView::undo(void) +void EditorView::undo() { d->lock = true; if (!d->undos.isEmpty()) { @@ -423,7 +423,7 @@ void EditorView::undo(void) * Redoes the last operation. * If there is no operation to undo, i.e. there is no undo step in the undo/redo history, nothing happens. */ -void EditorView::redo(void) +void EditorView::redo() { d->lock = true; if (!d->redos.isEmpty()) { diff --git a/src/Gui/EditorView.h b/src/Gui/EditorView.h index 2ab987124d..19a700246b 100644 --- a/src/Gui/EditorView.h +++ b/src/Gui/EditorView.h @@ -50,7 +50,7 @@ class GuiExport EditorView : public MDIView, public WindowParameter { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: enum DisplayName { @@ -60,19 +60,19 @@ public: }; EditorView(QPlainTextEdit* editor, QWidget* parent); - ~EditorView(); + ~EditorView() override; QPlainTextEdit* getEditor() const; void setDisplayName(DisplayName); - void OnChange(Base::Subject &rCaller,const char* rcReason); + void OnChange(Base::Subject &rCaller,const char* rcReason) override; - const char *getName(void) const {return "EditorView";} - void onUpdate(void){} + const char *getName() const override {return "EditorView";} + void onUpdate() override{} - bool onMsg(const char* pMsg,const char** ppReturn); - bool onHasMsg(const char* pMsg) const; + bool onMsg(const char* pMsg,const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; - bool canClose(void); + bool canClose() override; /** @name Standard actions of the editor */ //@{ @@ -83,21 +83,21 @@ public: void paste (); void undo (); void redo (); - void print (); - void printPdf(); - void printPreview(); - void print(QPrinter*); + void print () override; + void printPdf() override; + void printPreview() override; + void print(QPrinter*) override; //@} - QStringList undoActions() const; - QStringList redoActions() const; + QStringList undoActions() const override; + QStringList redoActions() const override; QString fileName() const; protected: - void focusInEvent(QFocusEvent* e); - void showEvent(QShowEvent*); - void hideEvent(QHideEvent*); - void closeEvent(QCloseEvent*); + void focusInEvent(QFocusEvent* e) override; + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; + void closeEvent(QCloseEvent*) override; private Q_SLOTS: void checkTimestamp(); @@ -121,14 +121,14 @@ class GuiExport PythonEditorView : public EditorView { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PythonEditorView(PythonEditor* editor, QWidget* parent); - ~PythonEditorView(); + ~PythonEditorView() override; - bool onMsg(const char* pMsg,const char** ppReturn); - bool onHasMsg(const char* pMsg) const; + bool onMsg(const char* pMsg,const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; public Q_SLOTS: void executeScript(); @@ -146,13 +146,13 @@ class SearchBar : public QWidget Q_OBJECT public: - SearchBar(QWidget* parent = nullptr); + explicit SearchBar(QWidget* parent = nullptr); void setEditor(QPlainTextEdit *textEdit); protected: - void keyPressEvent(QKeyEvent*); - void changeEvent(QEvent*); + void keyPressEvent(QKeyEvent*) override; + void changeEvent(QEvent*) override; public Q_SLOTS: void activate(); diff --git a/src/Gui/ExpressionBinding.cpp b/src/Gui/ExpressionBinding.cpp index 4f4cbb3d74..f6ad623b4c 100644 --- a/src/Gui/ExpressionBinding.cpp +++ b/src/Gui/ExpressionBinding.cpp @@ -77,7 +77,7 @@ void Gui::ExpressionBinding::setExpression(std::shared_ptr expr) if (expr) { const std::string error = docObj->ExpressionEngine.validateExpression(path, expr); - if (error.size()) + if (!error.empty()) throw Base::RuntimeError(error.c_str()); } @@ -238,7 +238,7 @@ bool ExpressionBinding::apply() { Property * prop(path.getProperty()); - assert(prop != nullptr); + assert(prop); Q_UNUSED(prop); DocumentObject * docObj(path.getDocumentObject()); diff --git a/src/Gui/ExpressionBindingPy.cpp b/src/Gui/ExpressionBindingPy.cpp index d134347d0d..f8e7a5e5c4 100644 --- a/src/Gui/ExpressionBindingPy.cpp +++ b/src/Gui/ExpressionBindingPy.cpp @@ -43,37 +43,39 @@ void ExpressionBindingPy::init_type() behaviors().set_tp_new(PyMake); behaviors().readyType(); - add_varargs_method("bind",&ExpressionBindingPy::bind,"Bind with an expression"); - add_varargs_method("isBound",&ExpressionBindingPy::isBound,"Check if already bound with an expression"); - add_varargs_method("apply",&ExpressionBindingPy::apply,"apply"); - add_varargs_method("hasExpression",&ExpressionBindingPy::hasExpression,"hasExpression"); - add_varargs_method("autoApply",&ExpressionBindingPy::autoApply,"autoApply"); - add_varargs_method("setAutoApply",&ExpressionBindingPy::setAutoApply,"setAutoApply"); + add_varargs_method("bind", &ExpressionBindingPy::bind, "Bind with an expression"); + add_varargs_method("isBound", &ExpressionBindingPy::isBound, "Check if already bound with an expression"); + add_varargs_method("apply", &ExpressionBindingPy::apply, "apply"); + add_varargs_method("hasExpression", &ExpressionBindingPy::hasExpression, "hasExpression"); + add_varargs_method("autoApply", &ExpressionBindingPy::autoApply, "autoApply"); + add_varargs_method("setAutoApply", &ExpressionBindingPy::setAutoApply, "setAutoApply"); } PyObject *ExpressionBindingPy::PyMake(struct _typeobject *, PyObject * args, PyObject *) { - Py::Tuple tuple(args); + PyObject* pyObj; + if (!PyArg_ParseTuple(args, "O", &pyObj)) + return nullptr; ExpressionBinding* expr = nullptr; PythonWrapper wrap; wrap.loadWidgetsModule(); - QWidget* obj = dynamic_cast(wrap.toQObject(tuple.getItem(0))); + QWidget* obj = dynamic_cast(wrap.toQObject(Py::Object(pyObj))); if (obj) { do { - QuantitySpinBox* sb = qobject_cast(obj); - if (sb) { - expr = sb; + QuantitySpinBox* qsb = qobject_cast(obj); + if (qsb) { + expr = qsb; break; } - InputField* le = qobject_cast(obj); - if (le) { - expr = le; + InputField* inp = qobject_cast(obj); + if (inp) { + expr = inp; break; } } - while(false); + while (false); } if (!expr) { diff --git a/src/Gui/ExpressionBindingPy.h b/src/Gui/ExpressionBindingPy.h index b02f52a873..c68345a72b 100644 --- a/src/Gui/ExpressionBindingPy.h +++ b/src/Gui/ExpressionBindingPy.h @@ -31,12 +31,12 @@ class ExpressionBinding; class ExpressionBindingPy : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods - ExpressionBindingPy(ExpressionBinding*); - ~ExpressionBindingPy(); + explicit ExpressionBindingPy(ExpressionBinding*); + ~ExpressionBindingPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object bind(const Py::Tuple&); Py::Object isBound(const Py::Tuple&); diff --git a/src/Gui/ExpressionCompleter.cpp b/src/Gui/ExpressionCompleter.cpp index 392f6cf5f9..d6c6f3b45e 100644 --- a/src/Gui/ExpressionCompleter.cpp +++ b/src/Gui/ExpressionCompleter.cpp @@ -138,7 +138,7 @@ public: return res; } - QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const { + QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const override { if(role!=Qt::EditRole && role!=Qt::DisplayRole && role!=Qt::UserRole) return QVariant(); QVariant v; @@ -260,7 +260,7 @@ public: return; } - QModelIndex parent(const QModelIndex & index) const { + QModelIndex parent(const QModelIndex & index) const override { if(!index.isValid()) return QModelIndex(); Info info; @@ -277,7 +277,7 @@ public: return QModelIndex(); } - QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const { + QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const override { if(row<0) return QModelIndex(); Info info; @@ -296,7 +296,7 @@ public: return createIndex(row,column,infoId(info)); } - int rowCount(const QModelIndex & parent = QModelIndex()) const { + int rowCount(const QModelIndex & parent = QModelIndex()) const override { Info info; int row = 0; if(!parent.isValid()) { @@ -318,7 +318,7 @@ public: return count; } - int columnCount(const QModelIndex &) const { + int columnCount(const QModelIndex &) const override { return 1; } @@ -407,9 +407,9 @@ QStringList ExpressionCompleter::splitPath ( const QString & input ) const std::vector sl = p.getStringList(); std::vector::const_iterator sli = sl.begin(); - if(retry && sl.size()) + if(retry && !sl.empty()) sl.pop_back(); - if(trim.size() && boost::ends_with(sl.back(),trim)) + if(!trim.empty() && boost::ends_with(sl.back(),trim)) sl.back().resize(sl.back().size()-trim.size()); while (sli != sl.end()) { l << Base::Tools::fromStdString(*sli); @@ -588,7 +588,7 @@ void ExpressionLineEdit::setDocumentObject(const App::DocumentObject * currentDo completer->setDocumentObject(currentDocObj, checkInList); return; } - if (currentDocObj != nullptr) { + if (currentDocObj) { completer = new ExpressionCompleter(currentDocObj, this, noProperty, checkInList); completer->setWidget(this); completer->setCaseSensitivity(Qt::CaseInsensitive); @@ -701,7 +701,7 @@ void ExpressionTextEdit::setDocumentObject(const App::DocumentObject * currentDo return; } - if (currentDocObj != nullptr) { + if (currentDocObj) { completer = new ExpressionCompleter(currentDocObj, this); if (!exactMatch) completer->setFilterMode(Qt::MatchContains); diff --git a/src/Gui/ExpressionCompleter.h b/src/Gui/ExpressionCompleter.h index deae91f554..3cafbf9e92 100644 --- a/src/Gui/ExpressionCompleter.h +++ b/src/Gui/ExpressionCompleter.h @@ -69,8 +69,8 @@ public Q_SLOTS: private: void init(); - virtual QString pathFromIndex ( const QModelIndex & index ) const; - virtual QStringList splitPath ( const QString & path ) const; + QString pathFromIndex ( const QModelIndex & index ) const override; + QStringList splitPath ( const QString & path ) const override; int prefixStart = 0; int prefixEnd = 0; @@ -97,8 +97,8 @@ public Q_SLOTS: void slotTextChanged(const QString & text); void slotCompleteText(const QString & completionPrefix); protected: - void keyPressEvent(QKeyEvent * event); - void contextMenuEvent(QContextMenuEvent * event); + void keyPressEvent(QKeyEvent * event) override; + void contextMenuEvent(QContextMenuEvent * event) override; private: ExpressionCompleter * completer; bool block; @@ -117,8 +117,8 @@ public: void hideCompleter(); void setExactMatch(bool enabled=true); protected: - void keyPressEvent(QKeyEvent * event); - void contextMenuEvent(QContextMenuEvent * event); + void keyPressEvent(QKeyEvent * event) override; + void contextMenuEvent(QContextMenuEvent * event) override; Q_SIGNALS: void textChanged2(QString text, int pos); public Q_SLOTS: diff --git a/src/Gui/FileDialog.cpp b/src/Gui/FileDialog.cpp index fb284b956e..642414744e 100644 --- a/src/Gui/FileDialog.cpp +++ b/src/Gui/FileDialog.cpp @@ -93,6 +93,27 @@ void FileDialog::onSelectedFilter(const QString& /*filter*/) } } +QList FileDialog::fetchSidebarUrls() +{ + QStringList list; + list << QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); + list << QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); + list << QStandardPaths::writableLocation(QStandardPaths::HomeLocation); + list << QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); + list << getWorkingDirectory(); + list << restoreLocation(); + list << QDir::currentPath(); + + QList urls; + for (const auto& it : list) { + if (QFileInfo::exists(it)) { + urls << QUrl::fromLocalFile(it); + } + } + + return urls; +} + bool FileDialog::hasSuffix(const QString& ext) const { QRegExp rx(QString::fromLatin1("\\*.(%1)\\W").arg(ext)); @@ -156,7 +177,7 @@ QString FileDialog::getSaveFileName (QWidget * parent, const QString & caption, // get the suffix for the filter: use the selected filter if there is one, // otherwise find the first valid suffix in the complete list of filters const QString *filterToSearch; - if (selectedFilter != nullptr) { + if (selectedFilter) { filterToSearch = selectedFilter; } else { @@ -182,18 +203,9 @@ QString FileDialog::getSaveFileName (QWidget * parent, const QString & caption, // before showing the file dialog. QString file; if (DialogOptions::dontUseNativeFileDialog()) { - QList urls; + QList urls = fetchSidebarUrls(); options |= QFileDialog::DontUseNativeDialog; - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MusicLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MoviesLocation)); - urls << QUrl::fromLocalFile(getWorkingDirectory()); - urls << QUrl::fromLocalFile(restoreLocation()); - urls << QUrl::fromLocalFile(QDir::currentPath()); FileDialog dlg(parent); dlg.setOptions(options); @@ -264,18 +276,9 @@ QString FileDialog::getOpenFileName(QWidget * parent, const QString & caption, c QString file; if (DialogOptions::dontUseNativeFileDialog()) { - QList urls; + QList urls = fetchSidebarUrls(); options |= QFileDialog::DontUseNativeDialog; - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MusicLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MoviesLocation)); - urls << QUrl::fromLocalFile(getWorkingDirectory()); - urls << QUrl::fromLocalFile(restoreLocation()); - urls << QUrl::fromLocalFile(QDir::currentPath()); FileDialog dlg(parent); dlg.setOptions(options); @@ -326,18 +329,9 @@ QStringList FileDialog::getOpenFileNames (QWidget * parent, const QString & capt QStringList files; if (DialogOptions::dontUseNativeFileDialog()) { - QList urls; + QList urls = fetchSidebarUrls(); options |= QFileDialog::DontUseNativeDialog; - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::HomeLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MusicLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)); - urls << QUrl::fromLocalFile(QStandardPaths::writableLocation(QStandardPaths::MoviesLocation)); - urls << QUrl::fromLocalFile(getWorkingDirectory()); - urls << QUrl::fromLocalFile(restoreLocation()); - urls << QUrl::fromLocalFile(QDir::currentPath()); FileDialog dlg(parent); dlg.setOptions(options); @@ -766,6 +760,15 @@ void FileChooser::chooseFile() } } +/** + * Sets the accept mode. + */ +void FileChooser::setAcceptMode(FileChooser::AcceptMode mode) +{ + accMode = mode; + Q_EMIT acceptModeChanged(accMode); +} + /** * \property FileChooser::mode * @@ -786,6 +789,7 @@ FileChooser::Mode FileChooser::mode() const void FileChooser::setMode( FileChooser::Mode m ) { md = m; + Q_EMIT modeChanged(md); } /** @@ -807,6 +811,7 @@ QString FileChooser::filter() const void FileChooser::setFilter ( const QString& filter ) { _filter = filter; + Q_EMIT filterChanged(_filter); } /** @@ -818,6 +823,7 @@ void FileChooser::setButtonText( const QString& txt ) int w1 = 2 * QtTools::horizontalAdvance(button->fontMetrics(), txt); int w2 = 2 * QtTools::horizontalAdvance(button->fontMetrics(), QLatin1String(" ... ")); button->setFixedWidth( (w1 > w2 ? w1 : w2) ); + Q_EMIT buttonTextChanged(txt); } /** diff --git a/src/Gui/FileDialog.h b/src/Gui/FileDialog.h index 1a9e5c3bfb..871e3b8c68 100644 --- a/src/Gui/FileDialog.h +++ b/src/Gui/FileDialog.h @@ -76,16 +76,17 @@ public: static QString restoreLocation(); static void saveLocation(const QString&); - FileDialog(QWidget * parent = nullptr); - ~FileDialog(); + explicit FileDialog(QWidget * parent = nullptr); + ~FileDialog() override; - void accept(); + void accept() override; private Q_SLOTS: void onSelectedFilter(const QString&); private: bool hasSuffix(const QString&) const; + static QList fetchSidebarUrls(); static QString workingDirectory; }; @@ -107,9 +108,9 @@ public: }; FileOptionsDialog ( QWidget* parent, Qt::WindowFlags ); - virtual ~FileOptionsDialog(); + ~FileOptionsDialog() override; - void accept(); + void accept() override; void setOptionsWidget( ExtensionPosition pos , QWidget*, bool show = false ); QWidget* getOptionsWidget() const; @@ -134,11 +135,11 @@ class FileIconProvider : public QFileIconProvider { public: FileIconProvider(); - ~FileIconProvider(); + ~FileIconProvider() override; - QIcon icon(IconType type) const; - QIcon icon(const QFileInfo & info) const; - QString type(const QFileInfo & info) const; + QIcon icon(IconType type) const override; + QIcon icon(const QFileInfo & info) const override; + QString type(const QFileInfo & info) const override; }; // ---------------------------------------------------------------------- @@ -152,20 +153,21 @@ class GuiExport FileChooser : public QWidget { Q_OBJECT - Q_ENUMS( Mode ) - Q_PROPERTY( Mode mode READ mode WRITE setMode ) - Q_ENUMS( AcceptMode ) - Q_PROPERTY( AcceptMode acceptMode READ acceptMode WRITE setAcceptMode ) - Q_PROPERTY( QString fileName READ fileName WRITE setFileName ) - Q_PROPERTY( QString filter READ filter WRITE setFilter ) - Q_PROPERTY( QString buttonText READ buttonText WRITE setButtonText ) - public: enum Mode { File, Directory }; enum AcceptMode { AcceptOpen, AcceptSave }; - FileChooser ( QWidget * parent = nullptr ); - virtual ~FileChooser(); + Q_ENUM( Mode ) + Q_PROPERTY(Mode mode READ mode WRITE setMode NOTIFY modeChanged) + Q_ENUM( AcceptMode ) + Q_PROPERTY(AcceptMode acceptMode READ acceptMode WRITE setAcceptMode NOTIFY acceptModeChanged) + Q_PROPERTY(QString fileName READ fileName WRITE setFileName NOTIFY fileNameChanged) + Q_PROPERTY(QString filter READ filter WRITE setFilter NOTIFY filterChanged) + Q_PROPERTY(QString buttonText READ buttonText WRITE setButtonText NOTIFY buttonTextChanged) + +public: + explicit FileChooser ( QWidget * parent = nullptr ); + ~FileChooser() override; /** * Returns the set filter. @@ -191,9 +193,7 @@ public: /** * Sets the accept mode. */ - void setAcceptMode(AcceptMode mode) { - accMode = mode; - } + void setAcceptMode(AcceptMode mode); /** * Returns the accept mode. */ @@ -203,20 +203,24 @@ public: public Q_SLOTS: virtual void setFileName( const QString &fn ); - virtual void setMode( Mode m ); + virtual void setMode( Gui::FileChooser::Mode m ); virtual void setFilter ( const QString & ); virtual void setButtonText ( const QString & ); Q_SIGNALS: void fileNameChanged( const QString & ); void fileNameSelected( const QString & ); + void filterChanged(const QString&); + void buttonTextChanged(const QString&); + void modeChanged(Gui::FileChooser::Mode); + void acceptModeChanged(Gui::FileChooser::AcceptMode); private Q_SLOTS: void chooseFile(); void editingFinished(); protected: - void resizeEvent(QResizeEvent*); + void resizeEvent(QResizeEvent*) override; private: QLineEdit *lineEdit; @@ -243,7 +247,7 @@ public: typedef QMap Dict; SelectModule (const QString& type, const Dict&, QWidget* parent); - virtual ~SelectModule(); + ~SelectModule() override; QString getModule() const; /** @name Import/Export handler @@ -258,8 +262,8 @@ public: static Dict importHandler(const QStringList& fn, const QString& filter=QString()); //@} - void accept(); - void reject(); + void accept() override; + void reject() override; private Q_SLOTS: void onButtonClicked(); diff --git a/src/Gui/Flag.h b/src/Gui/Flag.h index 2767cf5781..240eaf2409 100644 --- a/src/Gui/Flag.h +++ b/src/Gui/Flag.h @@ -36,66 +36,37 @@ class View3DInventorViewer; /** * @author Werner Mayer */ -#if 1 class GuiExport Flag : public QtGLWidget { Q_OBJECT public: Flag(QWidget* parent=nullptr); - ~Flag(); + ~Flag() override; - QSize sizeHint() const; + QSize sizeHint() const override; void setOrigin(const SbVec3f&); const SbVec3f& getOrigin() const; void drawLine(Gui::View3DInventorViewer*, int tox, int toy); void setText(const QString&); protected: - void initializeGL(); - void resizeGL(int width, int height); - void paintGL(); + void initializeGL() override; + void resizeGL(int width, int height) override; + void paintGL() override; - void paintEvent(QPaintEvent *); - void mouseMoveEvent(QMouseEvent *); - void mousePressEvent(QMouseEvent *); - void resizeEvent(QResizeEvent *); - void contextMenuEvent(QContextMenuEvent *); + void paintEvent(QPaintEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void mousePressEvent(QMouseEvent *) override; + void resizeEvent(QResizeEvent *) override; + void contextMenuEvent(QContextMenuEvent *) override; private: QString text; SbVec3f coord; QPoint dragPosition; }; -#else -class GuiExport Flag : public QWidget -{ - Q_OBJECT -public: - Flag(QWidget* parent=0); - ~Flag(); - - QSize sizeHint() const; - void setOrigin(const SbVec3f&); - const SbVec3f& getOrigin() const; - void drawLine(int tox, int toy); - void setText(const QString&); - -protected: - void paintEvent(QPaintEvent *); - void mouseMoveEvent(QMouseEvent *); - void mousePressEvent(QMouseEvent *); - void resizeEvent(QResizeEvent *); - void contextMenuEvent(QContextMenuEvent *); - -private: - QString text; - SbVec3f coord; - QPoint dragPosition; - QImage image; -}; -#endif class FlagLayout : public QLayout { @@ -106,18 +77,18 @@ public: FlagLayout(QWidget *parent, int margin = 0, int spacing = -1); FlagLayout(int spacing = -1); - ~FlagLayout(); + ~FlagLayout() override; - void addItem(QLayoutItem *item); + void addItem(QLayoutItem *item) override; void addWidget(QWidget *widget, Position position); - Qt::Orientations expandingDirections() const; - bool hasHeightForWidth() const; - int count() const; - QLayoutItem *itemAt(int index) const; - QSize minimumSize() const; - void setGeometry(const QRect &rect); - QSize sizeHint() const; - QLayoutItem *takeAt(int index); + Qt::Orientations expandingDirections() const override; + bool hasHeightForWidth() const override; + int count() const override; + QLayoutItem *itemAt(int index) const override; + QSize minimumSize() const override; + void setGeometry(const QRect &rect) override; + QSize sizeHint() const override; + QLayoutItem *takeAt(int index) override; void add(QLayoutItem *item, Position position); @@ -141,18 +112,18 @@ private: class GuiExport GLFlagWindow : public Gui::GLGraphicsItem { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GLFlagWindow(View3DInventorViewer*); - virtual ~GLFlagWindow(); + ~GLFlagWindow() override; void addFlag(Flag* item, FlagLayout::Position pos); void removeFlag(Flag* item); void deleteFlags(); Flag* getFlag(int) const; int countFlags() const; - void paintGL(); + void paintGL() override; private: View3DInventorViewer* _viewer; diff --git a/src/Gui/GLPainter.h b/src/Gui/GLPainter.h index af69c24e31..f6b3307eed 100644 --- a/src/Gui/GLPainter.h +++ b/src/Gui/GLPainter.h @@ -37,6 +37,7 @@ #endif #include +#include #include #include @@ -84,13 +85,13 @@ private: class GuiExport GLGraphicsItem : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GLGraphicsItem() { } - virtual ~GLGraphicsItem() + ~GLGraphicsItem() override { } virtual void paintGL() = 0; @@ -104,16 +105,16 @@ class GuiExport Rubberband : public Gui::GLGraphicsItem bool working, stipple; public: - Rubberband(View3DInventorViewer* v); + explicit Rubberband(View3DInventorViewer* v); Rubberband(); - ~Rubberband(); + ~Rubberband() override; void setWorking(bool on); void setLineStipple(bool on); bool isWorking(); void setViewer(View3DInventorViewer* v); void setCoords(int x1, int y1, int x2, int y2); void setColor(float r, float g, float b, float a); - void paintGL(); + void paintGL() override; }; class GuiExport Polyline : public Gui::GLGraphicsItem @@ -126,9 +127,9 @@ class GuiExport Polyline : public Gui::GLGraphicsItem GLPainter p; public: - Polyline(View3DInventorViewer* v); + explicit Polyline(View3DInventorViewer* v); Polyline(); - ~Polyline(); + ~Polyline() override; void setWorking(bool on); bool isWorking() const; void setViewer(View3DInventorViewer* v); @@ -140,7 +141,7 @@ public: void addNode(const QPoint& p); void popNode(); void clear(); - void paintGL(); + void paintGL() override; }; } // namespace Gui diff --git a/src/Gui/GestureNavigationStyle.cpp b/src/Gui/GestureNavigationStyle.cpp index 251385beb5..7fa7c73675 100644 --- a/src/Gui/GestureNavigationStyle.cpp +++ b/src/Gui/GestureNavigationStyle.cpp @@ -222,7 +222,7 @@ class NS::NaviMachine : public sc::state_machine public: typedef sc::state_machine superclass; - NaviMachine(NS& ns) : ns(ns) {} + explicit NaviMachine(NS& ns) : ns(ns) {} NS& ns; public: @@ -238,7 +238,7 @@ class NS::IdleState : public sc::state public: typedef sc::custom_reaction reactions; - IdleState(my_context ctx):my_base(ctx) + explicit IdleState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::IDLE); @@ -347,7 +347,7 @@ private: int hold_timeout; //in milliseconds public: - AwaitingMoveState(my_context ctx):my_base(ctx) + explicit AwaitingMoveState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; if (ns.logging) @@ -486,7 +486,7 @@ private: SbVec2s base_pos; public: - RotateState(my_context ctx):my_base(ctx) + explicit RotateState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::DRAGGING); @@ -529,7 +529,7 @@ private: float ratio; public: - PanState(my_context ctx):my_base(ctx) + explicit PanState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::PANNING); @@ -576,7 +576,7 @@ private: float ratio; public: - StickyPanState(my_context ctx):my_base(ctx) + explicit StickyPanState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::PANNING); @@ -622,7 +622,7 @@ private: SbVec2s base_pos; public: - TiltState(my_context ctx):my_base(ctx) + explicit TiltState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::DRAGGING); @@ -672,7 +672,7 @@ private: bool enableTilt = false; public: - GestureState(my_context ctx):my_base(ctx) + explicit GestureState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::PANNING); @@ -753,7 +753,7 @@ public: typedef sc::custom_reaction reactions; public: - AwaitingReleaseState(my_context ctx):my_base(ctx) + explicit AwaitingReleaseState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; if (ns.logging) @@ -803,7 +803,7 @@ public: typedef sc::custom_reaction reactions; public: - InteractState(my_context ctx):my_base(ctx) + explicit InteractState(my_context ctx):my_base(ctx) { auto &ns = this->outermost_context().ns; ns.setViewingMode(NavigationStyle::INTERACT); @@ -994,7 +994,7 @@ void GestureNavigationStyle::onRollGesture(int direction) cmd = App::GetApplication().GetParameterGroupByPath ("User parameter:BaseApp/Preferences/View")->GetASCII("GestureRollBackCommand"); } - if (cmd.size() == 0) + if (cmd.empty()) return; std::stringstream code; code << "Gui.runCommand(\"" << cmd << "\")"; diff --git a/src/Gui/GestureNavigationStyle.h b/src/Gui/GestureNavigationStyle.h index cdf6aa0f04..c2ec99a10e 100644 --- a/src/Gui/GestureNavigationStyle.h +++ b/src/Gui/GestureNavigationStyle.h @@ -39,7 +39,7 @@ class GestureNavigationStyle: public UserNavigationStyle public: GestureNavigationStyle(); - virtual ~GestureNavigationStyle() override; + ~GestureNavigationStyle() override; const char* mouseButtons(ViewerMode) override; protected: diff --git a/src/Gui/GraphicsViewZoom.h b/src/Gui/GraphicsViewZoom.h index 1c6612ddfd..6fd5690147 100644 --- a/src/Gui/GraphicsViewZoom.h +++ b/src/Gui/GraphicsViewZoom.h @@ -87,7 +87,7 @@ private: double _zoom_factor_base; bool m_invert_zoom; QPointF target_scene_pos, target_viewport_pos; - bool eventFilter(QObject* object, QEvent* event); + bool eventFilter(QObject* object, QEvent* event) override; }; #endif // GRAPHICSVIEWZOOM_H diff --git a/src/Gui/GraphvizView.cpp b/src/Gui/GraphvizView.cpp index 8af0912aac..510f2cb65f 100644 --- a/src/Gui/GraphvizView.cpp +++ b/src/Gui/GraphvizView.cpp @@ -64,12 +64,12 @@ namespace Gui { class GraphvizWorker : public QThread { Q_OBJECT public: - GraphvizWorker(QObject * parent = nullptr) + explicit GraphvizWorker(QObject * parent = nullptr) : QThread(parent) { } - virtual ~GraphvizWorker() + ~GraphvizWorker() override { dotProc.moveToThread(this); unflattenProc.moveToThread(this); @@ -90,7 +90,7 @@ public: Q_EMIT emitFinished(); } - void run() { + void run() override { QByteArray preprocessed = str; ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/DependencyGraph"); @@ -140,7 +140,7 @@ class GraphvizGraphicsView final : public QGraphicsView { public: GraphvizGraphicsView(QGraphicsScene* scene, QWidget* parent); - ~GraphvizGraphicsView() = default; + ~GraphvizGraphicsView() override = default; GraphvizGraphicsView(const GraphvizGraphicsView&) = delete; GraphvizGraphicsView(GraphvizGraphicsView&&) = delete; @@ -164,8 +164,7 @@ GraphvizGraphicsView::GraphvizGraphicsView(QGraphicsScene* scene, QWidget* paren void GraphvizGraphicsView::mousePressEvent(QMouseEvent* e) { - if(e && e->button() == Qt::LeftButton) - { + if (e && e->button() == Qt::LeftButton) { isPanning = true; panStart = e->pos(); e->accept(); @@ -179,20 +178,14 @@ void GraphvizGraphicsView::mousePressEvent(QMouseEvent* e) void GraphvizGraphicsView::mouseMoveEvent(QMouseEvent *e) { - if(e == nullptr) - { + if (!e) return; - } - if(isPanning) - { - auto* horizontalScrollbar = horizontalScrollBar(); - auto* verticalScrollbar = verticalScrollBar(); - if(horizontalScrollbar == nullptr || - verticalScrollbar == nullptr) - { + if (isPanning) { + auto *horizontalScrollbar = horizontalScrollBar(); + auto *verticalScrollbar = verticalScrollBar(); + if (!horizontalScrollbar || !verticalScrollbar) return; - } auto direction = e->pos() - panStart; horizontalScrollbar->setValue(horizontalScrollbar->value() - direction.x()); diff --git a/src/Gui/GraphvizView.h b/src/Gui/GraphvizView.h index 1e3ea5dd35..cff5d9c171 100644 --- a/src/Gui/GraphvizView.h +++ b/src/Gui/GraphvizView.h @@ -42,24 +42,24 @@ class GuiExport GraphvizView : public MDIView Q_OBJECT public: - GraphvizView(App::Document &_doc, QWidget* parent=nullptr); - ~GraphvizView(); + explicit GraphvizView(App::Document &_doc, QWidget* parent=nullptr); + ~GraphvizView() override; QByteArray exportGraph(const QString& filter); /// Message handler - virtual bool onMsg(const char* pMsg,const char** ppReturn); + bool onMsg(const char* pMsg,const char** ppReturn) override; /// Message handler test - virtual bool onHasMsg(const char* pMsg) const; + bool onHasMsg(const char* pMsg) const override; /** @name Printing */ //@{ - virtual void print(QPrinter* printer); + void print(QPrinter* printer) override; /** Print content of view */ - virtual void print(); + void print() override; /** Print to PDF file */ - virtual void printPdf(); + void printPdf() override; /** Show a preview dialog */ - virtual void printPreview(); + void printPreview() override; //@} private Q_SLOTS: diff --git a/src/Gui/GuiApplication.cpp b/src/Gui/GuiApplication.cpp index a39f5d2ab3..6c607d5528 100644 --- a/src/Gui/GuiApplication.cpp +++ b/src/Gui/GuiApplication.cpp @@ -165,7 +165,7 @@ bool GUIApplication::event(QEvent * ev) class GUISingleApplication::Private { public: - Private(GUISingleApplication *q_ptr) + explicit Private(GUISingleApplication *q_ptr) : q_ptr(q_ptr) , timer(new QTimer(q_ptr)) , server(nullptr) diff --git a/src/Gui/GuiApplication.h b/src/Gui/GuiApplication.h index 85b7f2cf31..4dc32685e8 100644 --- a/src/Gui/GuiApplication.h +++ b/src/Gui/GuiApplication.h @@ -42,13 +42,13 @@ class GUIApplication : public GUIApplicationNativeEventAware public: explicit GUIApplication(int & argc, char ** argv); - virtual ~GUIApplication(); + ~GUIApplication() override; /** * Make forwarding events exception-safe and get more detailed information * where an unhandled exception comes from. */ - bool notify (QObject * receiver, QEvent * event); + bool notify (QObject * receiver, QEvent * event) override; /// Pointer to exceptions caught in Qt event handler std::shared_ptr caughtException; @@ -57,7 +57,7 @@ public Q_SLOTS: void commitData(QSessionManager &manager); protected: - bool event(QEvent * event); + bool event(QEvent * event) override; }; class GUISingleApplication : public GUIApplication @@ -66,7 +66,7 @@ class GUISingleApplication : public GUIApplication public: explicit GUISingleApplication(int & argc, char ** argv); - virtual ~GUISingleApplication(); + ~GUISingleApplication() override; bool isRunning() const; bool sendMessage(const QByteArray &message, int timeout = 5000); @@ -88,8 +88,8 @@ class WheelEventFilter : public QObject Q_OBJECT public: - WheelEventFilter(QObject* parent); - bool eventFilter(QObject* obj, QEvent* ev); + explicit WheelEventFilter(QObject* parent); + bool eventFilter(QObject* obj, QEvent* ev) override; }; class KeyboardFilter : public QObject @@ -97,8 +97,8 @@ class KeyboardFilter : public QObject Q_OBJECT public: - KeyboardFilter(QObject* parent); - bool eventFilter(QObject* obj, QEvent* ev); + explicit KeyboardFilter(QObject* parent); + bool eventFilter(QObject* obj, QEvent* ev) override; }; } diff --git a/src/Gui/GuiApplicationNativeEventAware.h b/src/Gui/GuiApplicationNativeEventAware.h index b1d18b14b0..8a0d2f7a1a 100644 --- a/src/Gui/GuiApplicationNativeEventAware.h +++ b/src/Gui/GuiApplicationNativeEventAware.h @@ -39,7 +39,7 @@ namespace Gui Q_OBJECT public: GUIApplicationNativeEventAware(int &argc, char *argv[]); - ~GUIApplicationNativeEventAware(); + ~GUIApplicationNativeEventAware() override; void initSpaceball(QMainWindow *window); bool isSpaceballPresent() const {return spaceballPresent;} void setSpaceballPresent(bool present) {spaceballPresent = present;} diff --git a/src/Gui/GuiConsole.cpp b/src/Gui/GuiConsole.cpp index 0e101873aa..89144e0d3f 100644 --- a/src/Gui/GuiConsole.cpp +++ b/src/Gui/GuiConsole.cpp @@ -107,8 +107,8 @@ void GUIConsole::SendLog(const std::string& msg, Base::LogStyle level) #else /* FC_OS_LINUX */ // safely ignore GUIConsole::s_nMaxLines and GUIConsole::s_nRefCount -GUIConsole::GUIConsole (void) {} -GUIConsole::~GUIConsole (void) {} +GUIConsole::GUIConsole () {} +GUIConsole::~GUIConsole () {} void GUIConsole::SendLog(const std::string& msg, Base::LogStyle level) { switch(level){ diff --git a/src/Gui/GuiConsole.h b/src/Gui/GuiConsole.h index bca7a14a22..6e55983529 100644 --- a/src/Gui/GuiConsole.h +++ b/src/Gui/GuiConsole.h @@ -44,11 +44,11 @@ class GuiExport GUIConsole :public Base::ILogger { public: /// Constructor - GUIConsole(void); + GUIConsole(); /// Destructor - virtual ~GUIConsole(void); + ~GUIConsole() override; void SendLog(const std::string& msg, Base::LogStyle level) override; - const char* Name(void) override {return "GUIConsole";} + const char* Name() override {return "GUIConsole";} protected: static const unsigned int s_nMaxLines; diff --git a/src/Gui/Icons/edit-cut.svg b/src/Gui/Icons/edit-cut.svg index fb051257b8..b9ac930c91 100644 --- a/src/Gui/Icons/edit-cut.svg +++ b/src/Gui/Icons/edit-cut.svg @@ -2,26 +2,34 @@ + inkscape:export-ydpi="90" + inkscape:output_extension="org.inkscape.output.svg.inkscape"> + @@ -362,14 +370,26 @@ showgrid="true" inkscape:document-units="px" inkscape:grid-bbox="true" - gridempspacing="4" gridtolerance="0.5px" inkscape:window-width="1011" - inkscape:window-height="1110" - inkscape:window-x="378" - inkscape:window-y="0" + inkscape:window-height="818" + inkscape:window-x="177" + inkscape:window-y="30" stroke="#a40000" - inkscape:showpageshadow="false" /> + inkscape:showpageshadow="false"> + + @@ -392,7 +412,7 @@ + rdf:resource="http://creativecommons.org/licenses/publicdomain/" /> Jakub Steiner @@ -400,21 +420,13 @@ + rdf:about="http://creativecommons.org/licenses/publicdomain/"> + rdf:resource="http://creativecommons.org/ns#Reproduction" /> - - - + rdf:resource="http://creativecommons.org/ns#Distribution" /> - + rdf:resource="http://creativecommons.org/ns#DerivativeWorks" /> diff --git a/src/Gui/InputField.cpp b/src/Gui/InputField.cpp index edc8698278..19fbba42e1 100644 --- a/src/Gui/InputField.cpp +++ b/src/Gui/InputField.cpp @@ -52,11 +52,11 @@ namespace Gui { class InputValidator : public QValidator { public: - InputValidator(InputField* parent); - ~InputValidator(); + explicit InputValidator(InputField* parent); + ~InputValidator() override; - void fixup(QString& input) const; - State validate(QString& input, int& pos) const; + void fixup(QString& input) const override; + State validate(QString& input, int& pos) const override; private: InputField* dptr; @@ -323,14 +323,14 @@ void InputField::pushToHistory(const QString &valueq) snprintf(hist1,20,"Hist%i",i+1); snprintf(hist0,20,"Hist%i",i); std::string tHist = _handle->GetASCII(hist0,""); - if(tHist != "") + if(!tHist.empty()) _handle->SetASCII(hist1,tHist.c_str()); } _handle->SetASCII("Hist0",value.c_str()); } } -std::vector InputField::getHistory(void) +std::vector InputField::getHistory() { std::vector res; @@ -340,7 +340,7 @@ std::vector InputField::getHistory(void) for(int i = 0 ; i< HistorySize ;i++){ snprintf(hist,20,"Hist%i",i); tmp = _handle->GetASCII(hist,""); - if( tmp != "") + if( !tmp.empty()) res.push_back(QString::fromUtf8(tmp.c_str())); else break; // end of history reached @@ -349,7 +349,7 @@ std::vector InputField::getHistory(void) return res; } -void InputField::setToLastUsedValue(void) +void InputField::setToLastUsedValue() { std::vector hist = getHistory(); if(!hist.empty()) @@ -371,14 +371,14 @@ void InputField::pushToSavedValues(const QString &valueq) snprintf(hist1,20,"Save%i",i+1); snprintf(hist0,20,"Save%i",i); std::string tHist = _handle->GetASCII(hist0,""); - if(tHist != "") + if(!tHist.empty()) _handle->SetASCII(hist1,tHist.c_str()); } _handle->SetASCII("Save0",value.c_str()); } } -std::vector InputField::getSavedValues(void) +std::vector InputField::getSavedValues() { std::vector res; @@ -388,7 +388,7 @@ std::vector InputField::getSavedValues(void) for(int i = 0 ; i< SaveSize ;i++){ snprintf(hist,20,"Save%i",i); tmp = _handle->GetASCII(hist,""); - if( tmp != "") + if( !tmp.empty()) res.push_back(QString::fromUtf8(tmp.c_str())); else break; // end of history reached @@ -451,7 +451,7 @@ const Base::Unit& InputField::getUnit() const } /// get stored, valid quantity as a string -QString InputField::getQuantityString(void) const +QString InputField::getQuantityString() const { return actQuantity.getUserString(); } @@ -465,7 +465,7 @@ void InputField::setQuantityString(const QString& text) } /// return the quantity in C locale, i.e. decimal separator is a dot. -QString InputField::rawText(void) const +QString InputField::rawText() const { double factor; QString unit; @@ -484,7 +484,7 @@ void InputField::setRawText(const QString& text) } /// get the value of the singleStep property -double InputField::singleStep(void)const +double InputField::singleStep()const { return StepSize; } @@ -496,7 +496,7 @@ void InputField::setSingleStep(double s) } /// get the value of the maximum property -double InputField::maximum(void)const +double InputField::maximum()const { return Maximum; } @@ -512,7 +512,7 @@ void InputField::setMaximum(double m) } /// get the value of the minimum property -double InputField::minimum(void)const +double InputField::minimum()const { return Minimum; } @@ -538,7 +538,7 @@ void InputField::setUnitText(const QString& str) } } -QString InputField::getUnitText(void) +QString InputField::getUnitText() { double dFactor; QString unitStr; @@ -576,7 +576,7 @@ void InputField::setFormat(const QString& format) } // get the value of the minimum property -int InputField::historySize(void)const +int InputField::historySize()const { return HistorySize; } @@ -590,7 +590,7 @@ void InputField::setHistorySize(int i) HistorySize = i; } -void InputField::selectNumber(void) +void InputField::selectNumber() { QString str = text(); unsigned int i = 0; @@ -642,6 +642,19 @@ void InputField::focusInEvent(QFocusEvent *event) void InputField::focusOutEvent(QFocusEvent *event) { + try { + if (Quantity::parse(this->text()).getUnit().isEmpty()) { + // if user didn't enter a unit, we virtually compensate + // the multiplication factor induced by user unit system + double factor; + QString unitStr; + actQuantity.getUserString(factor, unitStr); + actQuantity = actQuantity * factor; + } + } + catch (const Base::ParserError&) { + // do nothing, let apply the last known good value + } this->setText(actQuantity.getUserString()); QLineEdit::focusOutEvent(event); } diff --git a/src/Gui/InputField.h b/src/Gui/InputField.h index cacbbf41db..2a22dbe73e 100644 --- a/src/Gui/InputField.h +++ b/src/Gui/InputField.h @@ -59,23 +59,23 @@ class GuiExport InputField : public ExpressionLineEdit, public ExpressionBinding { Q_OBJECT - Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) - Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep ) - Q_PROPERTY(double maximum READ maximum WRITE setMaximum ) - Q_PROPERTY(double minimum READ minimum WRITE setMinimum ) + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double maximum READ maximum WRITE setMaximum ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double minimum READ minimum WRITE setMinimum ) // clazy:exclude=qproperty-without-notify Q_PROPERTY(double rawValue READ rawValue WRITE setValue NOTIFY valueChanged) - Q_PROPERTY(int historySize READ historySize WRITE setHistorySize ) - Q_PROPERTY(QString unit READ getUnitText WRITE setUnitText ) - Q_PROPERTY(int precision READ getPrecision WRITE setPrecision ) - Q_PROPERTY(QString format READ getFormat WRITE setFormat ) - Q_PROPERTY(Base::Quantity quantity READ getQuantity WRITE setValue ) - Q_PROPERTY(QString quantityString READ getQuantityString WRITE setQuantityString ) - Q_PROPERTY(QString rawText READ rawText WRITE setRawText ) + Q_PROPERTY(int historySize READ historySize WRITE setHistorySize ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QString unit READ getUnitText WRITE setUnitText ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(int precision READ getPrecision WRITE setPrecision ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QString format READ getFormat WRITE setFormat ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(Base::Quantity quantity READ getQuantity WRITE setValue NOTIFY valueChanged) + Q_PROPERTY(QString quantityString READ getQuantityString WRITE setQuantityString ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QString rawText READ rawText WRITE setRawText ) // clazy:exclude=qproperty-without-notify public: InputField (QWidget * parent = nullptr); - virtual ~InputField(); + ~InputField() override; /// set the field with a quantity void setValue(const Base::Quantity&); @@ -83,18 +83,18 @@ public: void setValue(const double&); /// get the current value - Base::Quantity getQuantity(void)const{return this->actQuantity;} + Base::Quantity getQuantity()const{return this->actQuantity;} /// Get the current quantity without unit double rawValue() const; /// get stored, valid quantity as a string (user string - avoid storing) - QString getQuantityString(void) const; + QString getQuantityString() const; /// set, validate and display quantity from a string. Must match existing units. void setQuantityString(const QString& text); /// return the quantity in C locale, i.e. decimal separator is a dot. - QString rawText(void) const; + QString rawText() const; /// expects the string in C locale and internally converts it into the OS-specific locale void setRawText(const QString& text); @@ -114,37 +114,37 @@ public: const Base::Unit& getUnit() const; /// set the input field to the last used value (works only if the setParamGrpPath() was called) - void setToLastUsedValue(void); + void setToLastUsedValue(); /// get the value of the singleStep property - double singleStep(void)const; + double singleStep()const; /// set the value of the singleStep property void setSingleStep(double); /// get the value of the maximum property - double maximum(void)const; + double maximum()const; /// set the value of the maximum property void setMaximum(double); /// get the value of the minimum property - double minimum(void)const; + double minimum()const; /// set the value of the minimum property void setMinimum(double); /// get the value of the minimum property - int historySize(void)const; + int historySize()const; /// set the value of the minimum property void setHistorySize(int); /// set the unit by a string (can be used in the *.ui file) void setUnitText(const QString&); /// get the unit as a string (can be used in the *.ui file) - QString getUnitText(void); + QString getUnitText(); /// get the value of the precision property - int getPrecision(void) const; + int getPrecision() const; /// set the value of the precision property (can be used in the *.ui file) void setPrecision(const int); /// get the value of the format property: "f" (fixed), "e" (scientific), "g" (general) - QString getFormat(void) const; + QString getFormat() const; /// set the value of the format property (can be used in the *.ui file) void setFormat(const QString&); /// set the number portion selected (use after setValue()) - void selectNumber(void); + void selectNumber(); /// input validation void fixup(QString& input) const; /// input validation @@ -159,16 +159,16 @@ public: /// push a new value to the history, if no string given the actual text of the input field is used. void pushToHistory(const QString &valueq = QString()); /// get the history of the field, newest first - std::vector getHistory(void); + std::vector getHistory(); /// push a new value to the history, if no string given the actual text of the input field is used. void pushToSavedValues(const QString &valueq = QString()); /// get the history of the field, newest first - std::vector getSavedValues(void); + std::vector getSavedValues(); //@} - void bind(const App::ObjectIdentifier &_path); - bool apply(const std::string &propName); - bool apply(); + void bind(const App::ObjectIdentifier &_path) override; + bool apply(const std::string &propName) override; + bool apply() override; Q_SIGNALS: /** gets emitted if the user has entered a VALID input @@ -194,13 +194,13 @@ protected Q_SLOTS: void updateIconLabel(const QString& text); protected: - virtual void showEvent(QShowEvent * event); - virtual void focusInEvent(QFocusEvent * event); - virtual void focusOutEvent(QFocusEvent * event); - virtual void keyPressEvent(QKeyEvent * event); - virtual void wheelEvent(QWheelEvent * event); - virtual void contextMenuEvent(QContextMenuEvent * event); - virtual void resizeEvent(QResizeEvent*); + void showEvent(QShowEvent * event) override; + void focusInEvent(QFocusEvent * event) override; + void focusOutEvent(QFocusEvent * event) override; + void keyPressEvent(QKeyEvent * event) override; + void wheelEvent(QWheelEvent * event) override; + void contextMenuEvent(QContextMenuEvent * event) override; + void resizeEvent(QResizeEvent*) override; private: QPixmap getValidationIcon(const char* name, const QSize& size) const; diff --git a/src/Gui/InputVector.h b/src/Gui/InputVector.h index ddef82a6ab..0ef3f512e0 100644 --- a/src/Gui/InputVector.h +++ b/src/Gui/InputVector.h @@ -43,8 +43,8 @@ class GuiExport LocationWidget : public QWidget public: LocationWidget (QWidget * parent = nullptr); - virtual ~LocationWidget(); - QSize sizeHint() const; + ~LocationWidget() override; + QSize sizeHint() const override; Base::Vector3d getPosition() const; void setPosition(const Base::Vector3d&); @@ -56,7 +56,7 @@ private Q_SLOTS: void on_direction_activated(int); private: - void changeEvent(QEvent*); + void changeEvent(QEvent*) override; void retranslateUi(); private: @@ -81,10 +81,10 @@ class GuiExport LocationDialog : public QDialog protected: LocationDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - virtual ~LocationDialog(); + ~LocationDialog() override; protected: - virtual void changeEvent(QEvent *e) = 0; + void changeEvent(QEvent *e) override = 0; private Q_SLOTS: void on_direction_activated(int); @@ -118,7 +118,7 @@ public: this->setupUi(this); this->retranslate(); } - virtual ~LocationDialogUi(){} + ~LocationDialogUi() override{} void retranslate() { @@ -162,7 +162,7 @@ public: this->zPos->value().getValue()); } - Base::Vector3d getDirection() const + Base::Vector3d getDirection() const override { QVariant data = this->direction->itemData (this->direction->currentIndex()); if (data.canConvert()) { @@ -174,7 +174,7 @@ public: } protected: - void changeEvent(QEvent *e) + void changeEvent(QEvent *e) override { if (e->type() == QEvent::LanguageChange) { this->retranslate(); @@ -212,7 +212,7 @@ private: QVariant::fromValue(dir)); this->direction->setCurrentIndex(this->direction->count()-2); } - void directionActivated(int index) + void directionActivated(int index) override { // last item is selected to define direction by user if (index+1 == this->direction->count()) { @@ -367,18 +367,18 @@ public: : LocationDialog(parent, fl), ui(this) { } - virtual ~LocationDialogImp() + ~LocationDialogImp() override { // no need to delete child widgets, Qt does it all for us } - Base::Vector3d getDirection() const + Base::Vector3d getDirection() const override { return ui.getDirection(); } protected: - void changeEvent(QEvent *e) + void changeEvent(QEvent *e) override { if (e->type() == QEvent::LanguageChange) { ui.retranslate(this); @@ -389,7 +389,7 @@ protected: } private: - void directionActivated(int index) + void directionActivated(int index) override { ui.directionActivated(this,index); } @@ -428,16 +428,16 @@ public: LocationImpUi(Ui* ui) : ui(ui) { } - ~LocationImpUi() + ~LocationImpUi() override { } - boost::any get() + boost::any get() override { return ui; } - void retranslate(QDialog *dlg) + void retranslate(QDialog *dlg) override { ui->retranslateUi(dlg); @@ -465,21 +465,21 @@ public: } } - void setPosition(const Base::Vector3d& v) + void setPosition(const Base::Vector3d& v) override { ui->xPos->setValue(v.x); ui->yPos->setValue(v.y); ui->zPos->setValue(v.z); } - Base::Vector3d getPosition() const + Base::Vector3d getPosition() const override { return Base::Vector3d(ui->xPos->value().getValue(), ui->yPos->value().getValue(), ui->zPos->value().getValue()); } - Base::Vector3d getDirection() const + Base::Vector3d getDirection() const override { QVariant data = ui->direction->itemData (ui->direction->currentIndex()); if (data.canConvert()) { @@ -491,7 +491,7 @@ public: } public: - void setDirection(const Base::Vector3d& dir) + void setDirection(const Base::Vector3d& dir) override { if (dir.Length() < Base::Vector3d::epsilon()) { return; @@ -518,7 +518,7 @@ public: QVariant::fromValue(dir)); ui->direction->setCurrentIndex(ui->direction->count()-2); } - bool directionActivated(LocationDialog* dlg, int index) + bool directionActivated(LocationDialog* dlg, int index) override { // last item is selected to define direction by user if (index+1 == ui->direction->count()) { @@ -560,17 +560,17 @@ public: uit->setupUi(this); ui->retranslate(this); } - virtual ~LocationDialogUiImp(); + ~LocationDialogUiImp() override; - Base::Vector3d getDirection() const; + Base::Vector3d getDirection() const override; Base::Vector3d getPosition() const; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: - void directionActivated(int index); + void directionActivated(int index) override; protected: std::unique_ptr ui; diff --git a/src/Gui/Inventor/SoAutoZoomTranslation.cpp b/src/Gui/Inventor/SoAutoZoomTranslation.cpp index fb76513b18..f708597243 100644 --- a/src/Gui/Inventor/SoAutoZoomTranslation.cpp +++ b/src/Gui/Inventor/SoAutoZoomTranslation.cpp @@ -94,7 +94,7 @@ void SoAutoZoomTranslation::doAction(SoAction * action) auto state = action->getState(); SbRotation r,so; SbVec3f s,t; - SbMatrix matrix = SoModelMatrixElement::get(action->getState()); + SbMatrix matrix = SoModelMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft matrix.getTransform(t,r,s,so); matrix.multVecMatrix(SbVec3f(0,0,0),t); // reset current model scale factor diff --git a/src/Gui/Inventor/SoDrawingGrid.h b/src/Gui/Inventor/SoDrawingGrid.h index 1637faf002..70fde0203f 100644 --- a/src/Gui/Inventor/SoDrawingGrid.h +++ b/src/Gui/Inventor/SoDrawingGrid.h @@ -23,10 +23,8 @@ #ifndef GUI_INVENTOR_SODRAWINGGRID_H #define GUI_INVENTOR_SODRAWINGGRID_H -//#include #include - namespace Gui { namespace Inventor { class GuiExport SoDrawingGrid : public SoShape { diff --git a/src/Gui/Language/Translator.cpp b/src/Gui/Language/Translator.cpp index 935532511f..3ce5221163 100644 --- a/src/Gui/Language/Translator.cpp +++ b/src/Gui/Language/Translator.cpp @@ -113,14 +113,14 @@ public: }; } -Translator* Translator::instance(void) +Translator* Translator::instance() { if (!_pcSingleton) _pcSingleton = new Translator; return _pcSingleton; } -void Translator::destruct (void) +void Translator::destruct () { if (_pcSingleton) delete _pcSingleton; @@ -213,7 +213,7 @@ TStringMap Translator::supportedLocales() const // List all .qm files for (const auto& domainMap : d->mapLanguageTopLevelDomain) { - for (const auto& directoryName : d->paths) { + for (const auto& directoryName : qAsConst(d->paths)) { QDir dir(directoryName); QString filter = QString::fromLatin1("*_%1.qm").arg(QString::fromStdString(domainMap.second)); QStringList fileNames = dir.entryList(QStringList(filter), QDir::Files, QDir::Name); diff --git a/src/Gui/LinkViewPyImp.cpp b/src/Gui/LinkViewPyImp.cpp index 13fb912348..1fa83985f5 100644 --- a/src/Gui/LinkViewPyImp.cpp +++ b/src/Gui/LinkViewPyImp.cpp @@ -46,7 +46,7 @@ int LinkViewPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) // returns a string which represent the object e.g. when printed in python -std::string LinkViewPy::representation(void) const +std::string LinkViewPy::representation() const { return ""; } @@ -337,7 +337,7 @@ int LinkViewPy::setCustomAttributes(const char*, PyObject*) return 0; } -Py::Object LinkViewPy::getRootNode(void) const +Py::Object LinkViewPy::getRootNode() const { try { SoNode* node = getLinkViewPtr()->getLinkRoot(); diff --git a/src/Gui/MDIView.cpp b/src/Gui/MDIView.cpp index f4be44e31e..7e09c817ae 100644 --- a/src/Gui/MDIView.cpp +++ b/src/Gui/MDIView.cpp @@ -182,7 +182,7 @@ bool MDIView::onHasMsg(const char* pMsg) const return false; } -bool MDIView::canClose(void) +bool MDIView::canClose() { if (getAppDocument() && getAppDocument()->testStatus(App::Document::TempDoc)) return true; diff --git a/src/Gui/MDIView.h b/src/Gui/MDIView.h index f6a1e4d672..a37c93642d 100644 --- a/src/Gui/MDIView.h +++ b/src/Gui/MDIView.h @@ -36,6 +36,7 @@ QT_END_NAMESPACE namespace Gui { class Document; +class MainWindow; class ViewProvider; class ViewProviderDocumentObject; @@ -55,7 +56,7 @@ class GuiExport MDIView : public QMainWindow, public BaseView { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** View constructor @@ -67,21 +68,21 @@ public: /** View destructor * Detach the view from the document, if attached. */ - ~MDIView(); + ~MDIView() override; /// get called when the document is updated - virtual void onRelabel(Gui::Document *pDoc); + void onRelabel(Gui::Document *pDoc) override; virtual void viewAll(); /// Message handler - virtual bool onMsg(const char* pMsg,const char** ppReturn); + bool onMsg(const char* pMsg,const char** ppReturn) override; /// Message handler test - virtual bool onHasMsg(const char* pMsg) const; + bool onHasMsg(const char* pMsg) const override; /// overwrite when checking on close state - virtual bool canClose(void); + bool canClose() override; /// delete itself - virtual void deleteSelf(); - virtual PyObject *getPyObject(); + void deleteSelf() override; + PyObject *getPyObject() override; /** @name Printing */ //@{ public Q_SLOTS: @@ -106,7 +107,7 @@ public: virtual QStringList redoActions() const; //@} - QSize minimumSizeHint () const; + QSize minimumSizeHint () const override; /// MDI view mode enum enum ViewMode { @@ -165,12 +166,12 @@ protected Q_SLOTS: * whenever the window state of the active view changes. * The default implementation does nothing. */ - virtual void windowStateChanged(MDIView*); + virtual void windowStateChanged(Gui::MDIView*); protected: - void closeEvent(QCloseEvent *e); + void closeEvent(QCloseEvent *e) override; /** \internal */ - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; protected: PyObject* pythonObject; @@ -182,6 +183,8 @@ private: ActiveObjectList ActiveObjects; typedef boost::signals2::connection Connection; Connection connectDelObject; //remove active object upon delete. + + friend class MainWindow; }; } // namespace Gui diff --git a/src/Gui/MDIViewPy.h b/src/Gui/MDIViewPy.h index 86ced43a8b..824423f199 100644 --- a/src/Gui/MDIViewPy.h +++ b/src/Gui/MDIViewPy.h @@ -41,10 +41,10 @@ public: static Py::Object type(); static Py::ExtensionObject create(MDIView *mdi); - MDIViewPy(MDIView *mdi); - ~MDIViewPy(); + explicit MDIViewPy(MDIView *mdi); + ~MDIViewPy() override; - Py::Object repr(); + Py::Object repr() override; /** @name Printing */ //@{ diff --git a/src/Gui/Macro.cpp b/src/Gui/Macro.cpp index 35a415701e..4babc16b5e 100644 --- a/src/Gui/Macro.cpp +++ b/src/Gui/Macro.cpp @@ -97,7 +97,7 @@ void MacroManager::open(MacroType eType, const char *sName) Base::Console().Log("CmdM: Open macro: %s\n", sName); } -void MacroManager::commit(void) +void MacroManager::commit() { QFile file(this->macroName); if (file.open(QFile::WriteOnly)) @@ -155,7 +155,7 @@ void MacroManager::commit(void) } } -void MacroManager::cancel(void) +void MacroManager::cancel() { Base::Console().Log("Cancel macro: %s\n",(const char*)this->macroName.toUtf8()); @@ -176,7 +176,7 @@ void MacroManager::addLine(LineType Type, const char* sLine, bool pending) if(!sLine) return; - if(pendingLine.size()) { + if(!pendingLine.empty()) { if(Type == Cmt) { pendingLine.emplace_back(Type,sLine); return; diff --git a/src/Gui/Macro.h b/src/Gui/Macro.h index c38a6cfd84..7d6b5bde13 100644 --- a/src/Gui/Macro.h +++ b/src/Gui/Macro.h @@ -44,7 +44,7 @@ class GuiExport MacroManager : public Base::Observer { protected: MacroManager(); - ~MacroManager(); + ~MacroManager() override; public: @@ -73,11 +73,11 @@ public: */ void open(MacroType eType,const char *sName); /// close (and save) the recording session - void commit(void); + void commit(); /// cancels the recording session - void cancel(void); + void cancel(); /// indicates if a macro recording is in progress - bool isOpen(void) const {return openMacro;} + bool isOpen() const {return openMacro;} /// insert a new line in the macro void addLine(LineType Type,const char* sLine,bool pending=false); /** Set the active module @@ -90,7 +90,7 @@ public: /// Get the Python debugger PythonDebugger* debugger() const; /** Observes its parameter group. */ - void OnChange(Base::Subject &rCaller, const char * sReason); + void OnChange(Base::Subject &rCaller, const char * sReason) override; /// Return the added lines regardless of recording or not long getLines() const {return totalLines;} diff --git a/src/Gui/MainWindow.cpp b/src/Gui/MainWindow.cpp index 9e94227395..a309cfe883 100644 --- a/src/Gui/MainWindow.cpp +++ b/src/Gui/MainWindow.cpp @@ -101,8 +101,6 @@ FC_LOG_LEVEL_INIT("MainWindow",false,true,true) #if defined(Q_OS_WIN32) #define slots -//#include -//#include #endif using namespace Gui; @@ -128,7 +126,7 @@ public: CustomMessageEvent(int t, const QString& s, int timeout=0) : QEvent(QEvent::User), _type(t), msg(s), _timeout(timeout) { } - ~CustomMessageEvent() + ~CustomMessageEvent() override { } int type() const { return _type; } @@ -167,20 +165,20 @@ struct MainWindowP class MDITabbar : public QTabBar { public: - MDITabbar( QWidget * parent = nullptr ) : QTabBar(parent) + explicit MDITabbar( QWidget * parent = nullptr ) : QTabBar(parent) { menu = new QMenu(this); setDrawBase(false); setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); } - ~MDITabbar() + ~MDITabbar() override { delete menu; } protected: - void contextMenuEvent ( QContextMenuEvent * e ) + void contextMenuEvent ( QContextMenuEvent * e ) override { menu->clear(); CommandManager& cMgr = Application::Instance->commandManager(); @@ -336,18 +334,6 @@ MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags f) if (ht != config.end()) hiddenDockWindows = ht->second; - // Show all dockable windows over the workbench facility - // -#if 0 - // Toolbox - if (hiddenDockWindows.find("Std_ToolBox") == std::string::npos) { - ToolBox* toolBox = new ToolBox(this); - toolBox->setObjectName(QT_TRANSLATE_NOOP("QDockWidget","Toolbox")); - pDockMgr->registerDockWindow("Std_ToolBox", toolBox); - ToolBoxManager::getInstance()->setToolBox( toolBox ); - } -#endif - bool treeView = false, propertyView = false; if (hiddenDockWindows.find("Std_TreeView") == std::string::npos) { //work through parameter. @@ -435,7 +421,7 @@ MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags f) } //TODO: Add external object support for DAGView -#if 1 + //Dag View. if (hiddenDockWindows.find("Std_DAGView") == std::string::npos) { //work through parameter. @@ -459,25 +445,6 @@ MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags f) pDockMgr->registerDockWindow("Std_DAGView", dagDockWindow); } } -#endif - -#if 0 //defined(Q_OS_WIN32) this portion of code is not able to run with a vanilla Qtlib build on Windows. - // The MainWindowTabBar is used to show tabbed dock windows with icons - // - // add our own QTabBar-derived class to the main window layout - // NOTE: This uses some private stuff from QMainWindow which doesn't - // seem to be accessible on all platforms. - QMainWindowLayout* l = static_cast(this->layout()); - for (int i=0; i<5; i++) { - MainWindowTabBar* result = new MainWindowTabBar(this); - result->setDrawBase(true); - result->setElideMode(Qt::ElideRight); - result->hide(); // avoid to show horizontal bar in top left area - //result->setDocumentMode(_documentMode); - connect(result, SIGNAL(currentChanged(int)), l, SLOT(tabChanged())); - l->unusedTabBars << result; - } -#endif // accept drops on the window, get handled in dropEvent, dragEnterEvent setAcceptDrops(true); @@ -676,7 +643,7 @@ void MainWindow::activateWorkbench(const QString& name) ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); bool saveWB = hGrp->GetBool("SaveWBbyTab", false); QMdiSubWindow* subWin = d->mdiArea->activeSubWindow(); - if (subWin /*!= nullptr*/ && saveWB) { + if (subWin && saveWB) { QString currWb = subWin->property("ownWB").toString(); if (currWb.isEmpty() || currWb != name) { subWin->setProperty("ownWB", name); @@ -909,10 +876,8 @@ void MainWindow::addWindow(MDIView* view) d->mdiArea->addSubWindow(child); } - connect(view, SIGNAL(message(const QString&, int)), - this, SLOT(showMessage(const QString&, int))); - connect(this, SIGNAL(windowStateChanged(MDIView*)), - view, SLOT(windowStateChanged(MDIView*))); + connect(view, &MDIView::message, this, &MainWindow::showMessage); + connect(this, &MainWindow::windowStateChanged, view, &MDIView::windowStateChanged); // listen to the incoming events of the view view->installEventFilter(this); @@ -933,10 +898,9 @@ void MainWindow::addWindow(MDIView* view) void MainWindow::removeWindow(Gui::MDIView* view, bool close) { // free all connections - disconnect(view, SIGNAL(message(const QString&, int)), - this, SLOT(showMessage(const QString&, int ))); - disconnect(this, SIGNAL(windowStateChanged(MDIView*)), - view, SLOT(windowStateChanged(MDIView*))); + disconnect(view, &MDIView::message, this, &MainWindow::showMessage); + disconnect(this, &MainWindow::windowStateChanged, view, &MDIView::windowStateChanged); + view->removeEventFilter(this); // check if the focus widget is a child of the view @@ -1143,7 +1107,7 @@ QList MainWindow::windows(QMdiArea::WindowOrder order) const return mdis; } -MDIView* MainWindow::activeWindow(void) const +MDIView* MainWindow::activeWindow() const { // each activated window notifies this main window when it is activated return d->activeView; @@ -1224,7 +1188,7 @@ void MainWindow::processMessages(const QList & msg) QByteArray action("OpenFile:"); for (QList::const_iterator it = msg.begin(); it != msg.end(); ++it) { if (it->startsWith(action)) - files.push_back(std::string(it->mid(action.size()).constData())); + files.emplace_back(it->mid(action.size()).constData()); } files = App::Application::processFiles(files); for (std::list::iterator it = files.begin(); it != files.end(); ++it) { @@ -1275,7 +1239,7 @@ void MainWindow::delayedStartup() // Create new document? ParameterGrp::handle hGrp = WindowParameter::getDefaultParameter()->GetGroup("Document"); if (hGrp->GetBool("CreateNewDoc", false)) { - if (App::GetApplication().getDocuments().size()==0){ + if (App::GetApplication().getDocuments().empty()){ App::GetApplication().newDocument(); Gui::Command::doCommand(Gui::Command::Gui, "Gui.activeDocument().activeView().viewDefaultOrientation()"); @@ -1450,7 +1414,7 @@ void MainWindow::saveWindowSettings() ToolBarManager::getInstance()->saveState(); } -void MainWindow::startSplasher(void) +void MainWindow::startSplasher() { // startup splasher // when running in verbose mode no splasher @@ -1468,7 +1432,7 @@ void MainWindow::startSplasher(void) } } -void MainWindow::stopSplasher(void) +void MainWindow::stopSplasher() { if (d->splashscreen) { d->splashscreen->finish(this); @@ -1624,17 +1588,6 @@ void MainWindow::dragEnterEvent (QDragEnterEvent * e) // Here we must allow uri drafs and check them in dropEvent const QMimeData* data = e->mimeData(); if (data->hasUrls()) { -#if 0 -#ifdef QT_NO_OPENSSL - QList urls = data->urls(); - for (QList::ConstIterator it = urls.begin(); it != urls.end(); ++it) { - if (it->scheme().toLower() == QLatin1String("https")) { - e->ignore(); - return; - } - } -#endif -#endif e->accept(); } else { @@ -1670,7 +1623,7 @@ QMimeData * MainWindow::createMimeDataFromSelection () const std::vector unsaved; bool hasXLink = App::PropertyXLink::hasXLink(sel,&unsaved); - if(unsaved.size()) { + if(!unsaved.empty()) { QMessageBox::critical(getMainWindow(), tr("Unsaved document"), tr("The exported object contains external link. Please save the document" "at least once before exporting.")); @@ -1850,7 +1803,7 @@ void MainWindow::loadUrls(App::Document* doc, const QList& urls) Gui::Dialog::DownloadManager* dm = Gui::Dialog::DownloadManager::getInstance(); dm->download(dm->redirectUrl(*it)); } -//#ifndef QT_NO_OPENSSL + else if (it->scheme().toLower() == QLatin1String("https")) { QUrl url = *it; QUrlQuery urlq(url); @@ -1862,7 +1815,7 @@ void MainWindow::loadUrls(App::Document* doc, const QList& urls) Gui::Dialog::DownloadManager* dm = Gui::Dialog::DownloadManager::getInstance(); dm->download(dm->redirectUrl(url)); } -//#endif + else if (it->scheme().toLower() == QLatin1String("ftp")) { Gui::Dialog::DownloadManager::getInstance()->download(*it); } diff --git a/src/Gui/MainWindow.h b/src/Gui/MainWindow.h index 871adf6b93..d0a9f7e5f5 100644 --- a/src/Gui/MainWindow.h +++ b/src/Gui/MainWindow.h @@ -55,10 +55,10 @@ class GuiExport UrlHandler : public QObject Q_OBJECT public: - UrlHandler(QObject* parent = nullptr) + explicit UrlHandler(QObject* parent = nullptr) : QObject(parent){ } - virtual ~UrlHandler() { + ~UrlHandler() override { } virtual void openUrl(App::Document*, const QUrl&) { } @@ -85,13 +85,13 @@ public: * Constructs an empty main window. For default \a parent is 0, as there usually is * no toplevel window there. */ - MainWindow(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Window); + explicit MainWindow(QWidget * parent = nullptr, Qt::WindowFlags f = Qt::Window); /** Destroys the object and frees any allocated resources. */ - ~MainWindow(); + ~MainWindow() override; /** * Filters events if this object has been installed as an event filter for the watched object. */ - bool eventFilter(QObject* o, QEvent* e); + bool eventFilter(QObject* o, QEvent* e) override; /** * Adds an MDI window \a view to the main window's workspace and adds a new tab * to the tab bar. @@ -129,16 +129,16 @@ public: /** * Returns true that the context menu contains the 'Customize...' menu item. */ - QMenu * createPopupMenu(); + QMenu * createPopupMenu() override; /** @name Splasher and access methods */ //@{ /** Gets the one and only instance. */ static MainWindow* getInstance(); /** Starts the splasher at startup. */ - void startSplasher(void); + void startSplasher(); /** Stops the splasher after startup. */ - void stopSplasher(void); + void stopSplasher(); /* The image of the About dialog, it might be empty. */ QPixmap aboutImage() const; /* The image of the splash screen of the application. */ @@ -253,28 +253,28 @@ protected: /** * This method checks if the main window can be closed by checking all open documents and views. */ - void closeEvent (QCloseEvent * e); - void showEvent (QShowEvent * e); - void hideEvent (QHideEvent * e); - void timerEvent (QTimerEvent * ) { + void closeEvent (QCloseEvent * e) override; + void showEvent (QShowEvent * e) override; + void hideEvent (QHideEvent * e) override; + void timerEvent (QTimerEvent * ) override { Q_EMIT timeEvent(); } - void customEvent(QEvent * e); - bool event (QEvent * e); + void customEvent(QEvent * e) override; + bool event (QEvent * e) override; /** * Try to interpret dropped elements. */ - void dropEvent (QDropEvent * e); + void dropEvent (QDropEvent * e) override; /** * Checks if a mime source object can be interpreted. */ - void dragEnterEvent(QDragEnterEvent * e); + void dragEnterEvent(QDragEnterEvent * e) override; /** * This method is called from the Qt framework automatically whenever a * QTranslator object has been installed. This allows to translate all * relevant user visible text. */ - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private Q_SLOTS: /** @@ -320,7 +320,7 @@ private Q_SLOTS: Q_SIGNALS: void timeEvent(); - void windowStateChanged(MDIView*); + void windowStateChanged(Gui::MDIView*); void workbenchActivated(const QString&); void mainWindowClosed(); @@ -349,7 +349,7 @@ class StatusBarObserver: public WindowParameter, public Base::ILogger { public: StatusBarObserver(); - virtual ~StatusBarObserver(); + ~StatusBarObserver() override; /** Observes its parameter group. */ void OnChange(Base::Subject &rCaller, const char * sReason) override; @@ -357,7 +357,7 @@ public: void SendLog(const std::string& msg, Base::LogStyle level) override; /// name of the observer - const char *Name(void) override {return "StatusBar";} + const char *Name() override {return "StatusBar";} friend class MainWindow; private: @@ -375,7 +375,7 @@ public: static int EventType; enum Style {Restore, Clear}; - ActionStyleEvent(Style type); + explicit ActionStyleEvent(Style type); Style getType() const; private: diff --git a/src/Gui/MainWindowPy.h b/src/Gui/MainWindowPy.h index abc03bb013..36eded65ee 100644 --- a/src/Gui/MainWindowPy.h +++ b/src/Gui/MainWindowPy.h @@ -42,10 +42,10 @@ public: static Py::Object type(); static Py::ExtensionObject create(MainWindow *mw); - MainWindowPy(MainWindow *mw); - ~MainWindowPy(); + explicit MainWindowPy(MainWindow *mw); + ~MainWindowPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object getWindows(const Py::Tuple&); Py::Object getWindowsOfType(const Py::Tuple&); diff --git a/src/Gui/ManualAlignment.cpp b/src/Gui/ManualAlignment.cpp index e7bae457e2..7e0b8e7fad 100644 --- a/src/Gui/ManualAlignment.cpp +++ b/src/Gui/ManualAlignment.cpp @@ -429,14 +429,14 @@ public: static_cast(getViewer(1)->getSoRenderManager()->getSceneGraph())-> addChild(setupHeadUpDisplay(tr("Fixed object"))); } - ~AlignmentView() + ~AlignmentView() override { } - PyObject* getPyObject() + PyObject* getPyObject() override { Py_Return; } - bool canClose() + bool canClose() override { return false; } @@ -518,7 +518,7 @@ public: static void reorientCamera(SoCamera * cam, const SbRotation & rot) { - if (cam == nullptr) + if (!cam) return; // Find global coordinates of focal point. diff --git a/src/Gui/ManualAlignment.h b/src/Gui/ManualAlignment.h index 69e9a46050..4631c0e743 100644 --- a/src/Gui/ManualAlignment.h +++ b/src/Gui/ManualAlignment.h @@ -191,7 +191,7 @@ class GuiExport ManualAlignment : public QObject protected: ManualAlignment(); - ~ManualAlignment(); + ~ManualAlignment() override; public: static ManualAlignment* instance(); diff --git a/src/Gui/MenuManager.h b/src/Gui/MenuManager.h index dfdcbd3740..416838a497 100644 --- a/src/Gui/MenuManager.h +++ b/src/Gui/MenuManager.h @@ -38,7 +38,7 @@ class GuiExport MenuItem { public: MenuItem(); - MenuItem(MenuItem*); + explicit MenuItem(MenuItem*); ~MenuItem(); void setCommand(const std::string&); diff --git a/src/Gui/MergeDocuments.cpp b/src/Gui/MergeDocuments.cpp index 8b7dcfd3e6..8af6c864d4 100644 --- a/src/Gui/MergeDocuments.cpp +++ b/src/Gui/MergeDocuments.cpp @@ -48,11 +48,11 @@ public: : Base::XMLReader(FileName, str), nameMap(name) {} - void addName(const char* s1, const char* s2) + void addName(const char* s1, const char* s2) override { nameMap[s1] = s2; } - const char* getName(const char* name) const + const char* getName(const char* name) const override { std::map::const_iterator it = nameMap.find(name); if (it != nameMap.end()) @@ -60,59 +60,12 @@ public: else return name; } - bool doNameMapping() const + bool doNameMapping() const override { return true; } protected: - // See App::MergeDocument::XMLMergeReader for comments, with one additional - // benefits, we can save repetitive coding here. -#if 0 - void startElement(const XMLCh* const uri, const XMLCh* const localname, - const XMLCh* const qname, - const XERCES_CPP_NAMESPACE_QUALIFIER Attributes& attrs) - { - Base::XMLReader::startElement(uri, localname, qname, attrs); - if (LocalName == "Property") - propertyStack.push(std::make_pair(AttrMap["name"],AttrMap["type"])); - if (!propertyStack.empty()) { - // replace the stored object name with the real one - if (LocalName == "Link" || LocalName == "LinkSub" || (LocalName == "String" && propertyStack.top().first == "Label")) { - for (std::map::iterator it = AttrMap.begin(); it != AttrMap.end(); ++it) { - std::map::const_iterator jt = nameMap.find(it->second); - if (jt != nameMap.end()) - it->second = jt->second; - } - } - // update the expression if name of the object is used - else if (LocalName == "Expression") { - std::map::iterator it = AttrMap.find("expression"); - if (it != AttrMap.end()) { - // search for the part before the first dot that should be the object name. - std::string expression = it->second; - std::string::size_type dotpos = expression.find_first_of("."); - if (dotpos != std::string::npos) { - std::string name = expression.substr(0, dotpos); - std::map::const_iterator jt = nameMap.find(name); - if (jt != nameMap.end()) { - std::string newexpression = jt->second; - newexpression += expression.substr(dotpos); - it->second = newexpression; - } - } - } - } - } - } - - void endElement(const XMLCh* const uri, const XMLCh *const localname, const XMLCh *const qname) - { - Base::XMLReader::endElement(uri, localname, qname); - if (LocalName == "Property") - propertyStack.pop(); - } -#endif private: std::map& nameMap; @@ -136,7 +89,7 @@ MergeDocuments::~MergeDocuments() connectImport.disconnect(); } -unsigned int MergeDocuments::getMemSize (void) const +unsigned int MergeDocuments::getMemSize () const { return 0; } diff --git a/src/Gui/MergeDocuments.h b/src/Gui/MergeDocuments.h index a3129abc1d..92612e7532 100644 --- a/src/Gui/MergeDocuments.h +++ b/src/Gui/MergeDocuments.h @@ -39,16 +39,16 @@ class Document; class GuiExport MergeDocuments : public Base::Persistence { public: - MergeDocuments(App::Document* doc); - ~MergeDocuments(); - unsigned int getMemSize (void) const; + explicit MergeDocuments(App::Document* doc); + ~MergeDocuments() override; + unsigned int getMemSize () const override; std::vector importObjects(std::istream&); void importObject(const std::vector& o, Base::XMLReader & r); void exportObject(const std::vector& o, Base::Writer & w); - void Save (Base::Writer & w) const; - void Restore(Base::XMLReader &r); - void SaveDocFile (Base::Writer & w) const; - void RestoreDocFile(Base::Reader & r); + void Save (Base::Writer & w) const override; + void Restore(Base::XMLReader &r) override; + void SaveDocFile (Base::Writer & w) const override; + void RestoreDocFile(Base::Reader & r) override; private: zipios::ZipInputStream* stream; diff --git a/src/Gui/MouseSelection.cpp b/src/Gui/MouseSelection.cpp index ecfea6f386..ee4c5c5f07 100644 --- a/src/Gui/MouseSelection.cpp +++ b/src/Gui/MouseSelection.cpp @@ -117,87 +117,6 @@ BaseMouseSelection::BaseMouseSelection() { } -// ----------------------------------------------------------------------------------- -#if 0 -/* XPM */ -static const char* cursor_polypick[]= { - "32 32 2 1", - "# c #646464", - ". c None", - "................................", - "................................", - ".......#........................", - ".......#........................", - ".......#........................", - "................................", - ".......#........................", - "..###.###.###...................", - ".......#...............#........", - "......................##........", - ".......#..............#.#.......", - ".......#.............#..#.......", - ".......#............#...#.......", - "....................#....#......", - "...................#.....#......", - "..................#......#......", - "............#.....#.......#.....", - "...........#.##..#........#.....", - "..........#....##.........#.....", - ".........#...............#......", - "........#................#......", - ".......#................#.......", - "......#.................#.......", - ".....#.................#........", - "....#####..............#........", - ".........#########....#.........", - "..................#####.........", - "................................", - "................................", - "................................", - "................................", - "................................" -}; - -/* XPM */ -static const char* cursor_scissors[]= { - "32 32 3 1", - "# c #000000", - "+ c #ffffff", - ". c None", - "....+...........................", - "....+...........................", - "....+...........................", - "................................", - "+++.+.+++.......................", - "................................", - "....+...........................", - "....+...................#####...", - "....+.................########..", - ".....................#########..", - ".....###............##########..", - "....##++##.........#####...###..", - "...#++++++##.......####...####..", - "...##+++++++#......####.######..", - ".....#+++++++##....##########...", - "......##+++++++##.##########....", - "........##+++++++#########......", - "..........#+++++++#####.........", - "...........##+++++####..........", - "...........##+++++###...........", - ".........##+++++++########......", - "........##+++++++###########....", - "......##+++++++##.###########...", - "....##+++++++##....##########...", - "...#+++++++##......####..#####..", - "...#++++++#........#####..####..", - "....##++##..........#####..###..", - "......#.............##########..", - ".....................#########..", - ".......................######...", - "................................", - "................................" -}; -#endif static const char* cursor_cut_scissors[]= { "32 32 6 1", "a c #800000", diff --git a/src/Gui/MouseSelection.h b/src/Gui/MouseSelection.h index 0909ba7176..8b227bf2a4 100644 --- a/src/Gui/MouseSelection.h +++ b/src/Gui/MouseSelection.h @@ -58,7 +58,7 @@ public: enum { Continue=0, Restart=1, Finish=2, Cancel=3, Ignore=4 }; AbstractMouseSelection(); - virtual ~AbstractMouseSelection(void) {} + virtual ~AbstractMouseSelection() {} /// implement this in derived classes virtual void initialize() = 0; /// implement this in derived classes @@ -112,7 +112,7 @@ class GuiExport BaseMouseSelection : public AbstractMouseSelection { public: BaseMouseSelection(); - virtual ~BaseMouseSelection(){} + ~BaseMouseSelection() override{} }; // ----------------------------------------------------------------------------------- @@ -126,21 +126,21 @@ class GuiExport PolyPickerSelection : public BaseMouseSelection { public: PolyPickerSelection(); - virtual ~PolyPickerSelection(); + ~PolyPickerSelection() override; void setLineWidth(float l); void setColor(float r, float g, float b, float a = 1.0); - virtual void initialize(); - virtual void terminate(bool abort = false); + void initialize() override; + void terminate(bool abort = false) override; protected: - virtual int mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos); - virtual int locationEvent(const SoLocation2Event* const e, const QPoint& pos); - virtual int keyboardEvent(const SoKeyboardEvent* const e); + int mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos) override; + int locationEvent(const SoLocation2Event* const e, const QPoint& pos) override; + int keyboardEvent(const SoKeyboardEvent* const e) override; /// draw the polygon - virtual void draw(); + void draw() override; virtual int popupMenu(); protected: @@ -159,7 +159,7 @@ class GuiExport PolyClipSelection : public PolyPickerSelection { public: PolyClipSelection(); - virtual ~PolyClipSelection(); + ~PolyClipSelection() override; inline void setRole(SelectionRole pos, bool on) { selectionBits.set(static_cast(pos), on); @@ -169,7 +169,7 @@ public: } protected: - virtual int popupMenu(); + int popupMenu() override; private: std::bitset<8> selectionBits; @@ -185,14 +185,14 @@ class GuiExport FreehandSelection : public PolyPickerSelection { public: FreehandSelection(); - virtual ~FreehandSelection(); + ~FreehandSelection() override; void setClosed(bool c); protected: - virtual int popupMenu(); - virtual int mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos); - virtual int locationEvent(const SoLocation2Event* const e, const QPoint& pos); + int popupMenu() override; + int mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos) override; + int locationEvent(const SoLocation2Event* const e, const QPoint& pos) override; }; // ----------------------------------------------------------------------------------- @@ -206,20 +206,20 @@ class GuiExport RubberbandSelection : public BaseMouseSelection { public: RubberbandSelection(); - virtual ~RubberbandSelection(); + ~RubberbandSelection() override; void setColor(float r, float g, float b, float a = 1.0); - virtual void initialize(); - virtual void terminate(bool abort = false); + void initialize() override; + void terminate(bool abort = false) override; protected: - virtual int mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos); - virtual int locationEvent(const SoLocation2Event* const e, const QPoint& pos); - virtual int keyboardEvent(const SoKeyboardEvent* const e); + int mouseButtonEvent(const SoMouseButtonEvent* const e, const QPoint& pos) override; + int locationEvent(const SoLocation2Event* const e, const QPoint& pos) override; + int keyboardEvent(const SoKeyboardEvent* const e) override; /// draw the rectangle - virtual void draw(); + void draw() override; protected: Gui::Rubberband rubberband; @@ -236,7 +236,7 @@ class GuiExport RectangleSelection : public RubberbandSelection { public: RectangleSelection(); - virtual ~RectangleSelection(); + ~RectangleSelection() override; }; // ----------------------------------------------------------------------------------- @@ -250,8 +250,8 @@ class GuiExport BoxZoomSelection : public RubberbandSelection { public: BoxZoomSelection(); - ~BoxZoomSelection(); - void terminate(bool abort = false); + ~BoxZoomSelection() override; + void terminate(bool abort = false) override; }; } // namespace Gui diff --git a/src/Gui/NaviCube.cpp b/src/Gui/NaviCube.cpp index fe72a8f9bc..0362baee15 100644 --- a/src/Gui/NaviCube.cpp +++ b/src/Gui/NaviCube.cpp @@ -112,13 +112,13 @@ public: class NaviCubeImplementation : public ParameterGrp::ObserverType { public: - NaviCubeImplementation(Gui::View3DInventorViewer*); - virtual ~NaviCubeImplementation(); + explicit NaviCubeImplementation(Gui::View3DInventorViewer*); + ~NaviCubeImplementation() override; void drawNaviCube(); void createContextMenu(const std::vector& cmd); /// Observer message from the ParameterGrp - virtual void OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp::MessageType Reason); + void OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp::MessageType Reason) override; bool processSoEvent(const SoEvent* ev); private: @@ -617,17 +617,17 @@ void NaviCubeImplementation::addFace(float gap, const Vector3f& x, const Vector3 int t = m_VertexArray.size(); - m_VertexArray.push_back(z - x - y); - m_VertexArray2.push_back(z - x2 - y2); + m_VertexArray.emplace_back(z - x - y); + m_VertexArray2.emplace_back(z - x2 - y2); m_TextureCoordArray.emplace_back(0, 0); - m_VertexArray.push_back(z + x - y); - m_VertexArray2.push_back(z + x2 - y2); + m_VertexArray.emplace_back(z + x - y); + m_VertexArray2.emplace_back(z + x2 - y2); m_TextureCoordArray.emplace_back(1, 0); - m_VertexArray.push_back(z + x + y); - m_VertexArray2.push_back(z + x2 + y2); + m_VertexArray.emplace_back(z + x + y); + m_VertexArray2.emplace_back(z + x2 + y2); m_TextureCoordArray.emplace_back(1, 1); - m_VertexArray.push_back(z - x + y); - m_VertexArray2.push_back(z - x2 + y2); + m_VertexArray.emplace_back(z - x + y); + m_VertexArray2.emplace_back(z - x2 + y2); m_TextureCoordArray.emplace_back(0, 1); // TEX_TOP, TEX_FRONT_FACE, TEX_TOP @@ -903,7 +903,7 @@ void NaviCubeImplementation::drawNaviCube(bool pickMode) { // FIXME actually now that we have Qt5, we could probably do this earlier (as we do not need the opengl context) if (!m_NaviCubeInitialised) { QtGLWidget* gl = static_cast(m_View3DInventorViewer->viewport()); - if (gl == nullptr) + if (!gl) return; initNaviCube(gl); m_NaviCubeInitialised = true; @@ -1267,10 +1267,9 @@ bool NaviCubeImplementation::mouseReleased(short x, short y) { float tilt = 90 - Base::toDegrees(atan(sqrt(2.0))); int pick = pickFace(x, y); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); - long step = Base::clamp(hGrp->GetInt("NaviStepByTurn", 8), 4L, 36L); - float rotStepAngle = 360.0f / step; ParameterGrp::handle hGrpNavi = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/NaviCube"); + long step = Base::clamp(hGrpNavi->GetInt("NaviStepByTurn", 8), 4L, 36L); + float rotStepAngle = 360.0f / step; bool toNearest = hGrpNavi->GetBool("NaviRotateToNearest", true); bool applyRotation = true; @@ -1790,11 +1789,11 @@ QMenu* NaviCubeImplementation::createNaviCubeMenu() { vector commands = NaviCubeImplementation::m_commands; if (commands.empty()) { - commands.push_back("ViewOrthographicCmd"); - commands.push_back("ViewPerspectiveCmd"); - commands.push_back("ViewIsometricCmd"); - commands.push_back("Separator"); - commands.push_back("ViewZoomToFit"); + commands.emplace_back("ViewOrthographicCmd"); + commands.emplace_back("ViewPerspectiveCmd"); + commands.emplace_back("ViewIsometricCmd"); + commands.emplace_back("Separator"); + commands.emplace_back("ViewZoomToFit"); } for (vector::iterator i = commands.begin(); i != commands.end(); ++i) { diff --git a/src/Gui/NavigationStyle.cpp b/src/Gui/NavigationStyle.cpp index fe616a4d30..d80bf0d2db 100644 --- a/src/Gui/NavigationStyle.cpp +++ b/src/Gui/NavigationStyle.cpp @@ -93,23 +93,23 @@ public: { } - void setViewVolume (const SbViewVolume &vol) + void setViewVolume (const SbViewVolume &vol) override { inherited::setViewVolume(vol); } - void setWorkingSpace (const SbMatrix &space) + void setWorkingSpace (const SbMatrix &space) override { //inherited::setWorkingSpace(space); this->worldToScreen = space.inverse(); } - SbVec3f project(const SbVec2f &point) + SbVec3f project(const SbVec2f &point) override { return inherited::project(point); } - SbRotation getRotation(const SbVec3f &point1, const SbVec3f &point2) + SbRotation getRotation(const SbVec3f &point1, const SbVec3f &point2) override { SbRotation rot = inherited::getRotation(point1, point2); if (orbit == Trackball) @@ -325,7 +325,7 @@ void NavigationStyle::seekToPoint(const SbVec3f& scenepos) SbBool NavigationStyle::lookAtPoint(const SbVec2s screenpos) { SoCamera* cam = viewer->getSoRenderManager()->getCamera(); - if (cam == nullptr) + if (!cam) return false; SoRayPickAction rpaction(viewer->getSoRenderManager()->getViewportRegion()); @@ -348,7 +348,7 @@ SbBool NavigationStyle::lookAtPoint(const SbVec2s screenpos) void NavigationStyle::lookAtPoint(const SbVec3f& pos) { SoCamera* cam = viewer->getSoRenderManager()->getCamera(); - if (cam == nullptr) + if (!cam) return; PRIVATE(this)->rotationCenterFound = false; @@ -407,7 +407,7 @@ void NavigationStyle::lookAtPoint(const SbVec3f& pos) void NavigationStyle::setCameraOrientation(const SbRotation& rot, SbBool moveToCenter) { SoCamera* cam = viewer->getSoRenderManager()->getCamera(); - if (cam == nullptr) + if (!cam) return; // Find global coordinates of focal point. @@ -559,15 +559,6 @@ void NavigationStyle::viewAll() if (box.isEmpty()) return; -#if 0 - // check whether the box is very wide or tall, if not do nothing - float box_width, box_height, box_depth; - box.getSize( box_width, box_height, box_depth ); - if (box_width < 5.0f*box_height && box_width < 5.0f*box_depth && - box_height < 5.0f*box_width && box_height < 5.0f*box_depth && - box_depth < 5.0f*box_width && box_depth < 5.0f*box_height ) - return; -#endif SoCamera* cam = viewer->getSoRenderManager()->getCamera(); if (!cam) @@ -592,23 +583,7 @@ void NavigationStyle::viewAll() float aspect = cam->aspectRatio.getValue(); - if (cam->getTypeId() == SoPerspectiveCamera::getClassTypeId()) { - // set the new camera position dependent on the occupied space of projected bounding box - //SbVec3f direction = cam->position.getValue() - box.getCenter(); - //float movelength = direction.length(); - //direction.normalize(); - //float fRatio = getViewportRegion().getViewportAspectRatio(); - //if ( fRatio > 1.0f ) { - // float factor = std::max(s[0]/fRatio,s[1]); - // movelength = factor * movelength; - //} - //else { - // float factor = std::max(s[0],s[1]/fRatio); - // movelength = factor * movelength; - //} - //cam->position.setValue(box.getCenter() + direction * movelength); - } - else if (cam->getTypeId() == SoOrthographicCamera::getClassTypeId()) { + if (cam->getTypeId() == SoOrthographicCamera::getClassTypeId()) { SoOrthographicCamera* ocam = (SoOrthographicCamera *)cam; // safe downward cast, knows the type if (aspect < 1.0f) ocam->height = cam_height / aspect; @@ -622,7 +597,7 @@ void NavigationStyle::viewAll() */ void NavigationStyle::reorientCamera(SoCamera * cam, const SbRotation & rot) { - if (cam == nullptr) + if (!cam) return; // Find global coordinates of focal point. @@ -642,7 +617,7 @@ void NavigationStyle::reorientCamera(SoCamera * cam, const SbRotation & rot) void NavigationStyle::panCamera(SoCamera * cam, float aspectratio, const SbPlane & panplane, const SbVec2f & currpos, const SbVec2f & prevpos) { - if (cam == nullptr) // can happen for empty scenegraph + if (!cam) // can happen for empty scenegraph return; if (currpos == prevpos) // useless invocation return; @@ -673,7 +648,7 @@ void NavigationStyle::pan(SoCamera* camera) // The plane we're projecting the mouse coordinates to get 3D // coordinates should stay the same during the whole pan // operation, so we should calculate this value here. - if (camera == nullptr) { // can happen for empty scenegraph + if (!camera) { // can happen for empty scenegraph this->panningplane = SbPlane(SbVec3f(0, 0, 1), 0); } else { @@ -703,7 +678,7 @@ void NavigationStyle::panToCenter(const SbPlane & pplane, const SbVec2f & currpo */ void NavigationStyle::zoom(SoCamera * cam, float diffvalue) { - if (cam == nullptr) // can happen for empty scenegraph + if (!cam) // can happen for empty scenegraph return; SoType t = cam->getTypeId(); SbName tname = t.getName(); @@ -885,7 +860,7 @@ void NavigationStyle::setRotationCenter(const SbVec3f& cnt) SbVec3f NavigationStyle::getFocalPoint() const { SoCamera* cam = viewer->getSoRenderManager()->getCamera(); - if (cam == nullptr) + if (!cam) return SbVec3f(0,0,0); // Find global coordinates of focal point. @@ -903,7 +878,7 @@ void NavigationStyle::spin(const SbVec2f & pointerpos) { if (this->log.historysize < 2) return; - assert(this->spinprojector != nullptr); + assert(this->spinprojector); const SbViewportRegion & vp = viewer->getSoRenderManager()->getViewportRegion(); SbVec2s glsize(vp.getViewportSizePixels()); @@ -981,7 +956,7 @@ void NavigationStyle::spin(const SbVec2f & pointerpos) * \param prevpos previous normalized position of mouse pointer */ void NavigationStyle::spin_simplified(SoCamera* cam, SbVec2f curpos, SbVec2f prevpos){ - assert(this->spinprojector != nullptr); + assert(this->spinprojector); // 0000333: Turntable camera rotation SbMatrix mat; diff --git a/src/Gui/NavigationStyle.h b/src/Gui/NavigationStyle.h index 2d8dbe3c61..a621cc1466 100644 --- a/src/Gui/NavigationStyle.h +++ b/src/Gui/NavigationStyle.h @@ -60,8 +60,8 @@ class AbstractMouseSelection; class GuiExport NavigationStyleEvent : public QEvent { public: - NavigationStyleEvent(const Base::Type& s); - ~NavigationStyleEvent(); + explicit NavigationStyleEvent(const Base::Type& s); + ~NavigationStyleEvent() override; const Base::Type& style() const; private: Base::Type t; @@ -73,7 +73,7 @@ private: */ class GuiExport NavigationStyle : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: enum ViewerMode { @@ -112,7 +112,7 @@ public: public: NavigationStyle(); - virtual ~NavigationStyle(); + ~NavigationStyle() override; NavigationStyle& operator = (const NavigationStyle& ns); void setViewer(View3DInventorViewer*); @@ -278,11 +278,11 @@ private: * @author Werner Mayer */ class GuiExport UserNavigationStyle : public NavigationStyle { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: UserNavigationStyle(){} - ~UserNavigationStyle(){} + ~UserNavigationStyle() override{} virtual const char* mouseButtons(ViewerMode) = 0; virtual std::string userFriendlyName() const; static std::map getUserFriendlyNames(); @@ -291,30 +291,30 @@ public: class GuiExport InventorNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: InventorNavigationStyle(); - ~InventorNavigationStyle(); - const char* mouseButtons(ViewerMode); - virtual std::string userFriendlyName() const; + ~InventorNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; + std::string userFriendlyName() const override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; }; class GuiExport CADNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: CADNavigationStyle(); - ~CADNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~CADNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; private: SbBool lockButton1; @@ -323,15 +323,15 @@ private: class GuiExport RevitNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: RevitNavigationStyle(); - ~RevitNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~RevitNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; private: SbBool lockButton1; @@ -340,15 +340,15 @@ private: class GuiExport BlenderNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: BlenderNavigationStyle(); - ~BlenderNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~BlenderNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; private: SbBool lockButton1; @@ -357,15 +357,15 @@ private: class GuiExport MayaGestureNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: MayaGestureNavigationStyle(); - ~MayaGestureNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~MayaGestureNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; SbVec2s mousedownPos;//the position where some mouse button was pressed (local pixel coordinates). short mouseMoveThreshold;//setting. Minimum move required to consider it a move (in pixels). @@ -381,57 +381,57 @@ protected: class GuiExport TouchpadNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: TouchpadNavigationStyle(); - ~TouchpadNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~TouchpadNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; }; class GuiExport OpenCascadeNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: OpenCascadeNavigationStyle(); - ~OpenCascadeNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~OpenCascadeNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; }; class GuiExport OpenSCADNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: OpenSCADNavigationStyle(); - ~OpenSCADNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~OpenSCADNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; }; class GuiExport TinkerCADNavigationStyle : public UserNavigationStyle { typedef UserNavigationStyle inherited; - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: TinkerCADNavigationStyle(); - ~TinkerCADNavigationStyle(); - const char* mouseButtons(ViewerMode); + ~TinkerCADNavigationStyle() override; + const char* mouseButtons(ViewerMode) override; protected: - SbBool processSoEvent(const SoEvent * const ev); + SbBool processSoEvent(const SoEvent * const ev) override; }; } // namespace Gui diff --git a/src/Gui/NetworkRetriever.cpp b/src/Gui/NetworkRetriever.cpp index 1cf3c895c8..9c4d9d5f15 100644 --- a/src/Gui/NetworkRetriever.cpp +++ b/src/Gui/NetworkRetriever.cpp @@ -414,7 +414,7 @@ StdCmdDownloadOnlineHelp::~StdCmdDownloadOnlineHelp() delete wget; } -Action * StdCmdDownloadOnlineHelp::createAction(void) +Action * StdCmdDownloadOnlineHelp::createAction() { Action *pcAction; diff --git a/src/Gui/NetworkRetriever.h b/src/Gui/NetworkRetriever.h index 51110c387f..271bfdc826 100644 --- a/src/Gui/NetworkRetriever.h +++ b/src/Gui/NetworkRetriever.h @@ -43,7 +43,7 @@ class NetworkRetriever : public QObject public: NetworkRetriever( QObject * parent = nullptr ); - virtual ~NetworkRetriever(); + ~NetworkRetriever() override; void setNumberOfTries( int ); void setOutputFile( const QString& ); @@ -83,15 +83,15 @@ class StdCmdDownloadOnlineHelp : public QObject, public Command public: StdCmdDownloadOnlineHelp(QObject * parent = nullptr); - virtual ~StdCmdDownloadOnlineHelp(); + ~StdCmdDownloadOnlineHelp() override; /** i18n stuff of the command. */ - virtual void languageChange(); + void languageChange() override; protected: - virtual void activated(int iMsg); + void activated(int iMsg) override; /** Creates the action object. */ - virtual Action* createAction(); + Action* createAction() override; private Q_SLOTS: void wgetFinished(); diff --git a/src/Gui/OnlineDocumentation.h b/src/Gui/OnlineDocumentation.h index ea38b59c93..d55b386494 100644 --- a/src/Gui/OnlineDocumentation.h +++ b/src/Gui/OnlineDocumentation.h @@ -45,7 +45,7 @@ class PythonOnlineHelp : public QObject public: PythonOnlineHelp(); - ~PythonOnlineHelp(); + ~PythonOnlineHelp() override; QByteArray loadResource(const QString& filename) const; QByteArray fileNotFound() const; @@ -60,9 +60,9 @@ class HttpServer : public QTcpServer Q_OBJECT public: - HttpServer(QObject* parent = nullptr); + explicit HttpServer(QObject* parent = nullptr); - void incomingConnection(qintptr socket); + void incomingConnection(qintptr socket) override; void pause(); void resume(); @@ -81,12 +81,12 @@ class StdCmdPythonHelp : public Command { public: StdCmdPythonHelp(); - ~StdCmdPythonHelp(); - const char* className() const + ~StdCmdPythonHelp() override; + const char* className() const override { return "Gui::StdCmdPythonHelp"; } protected: - void activated(int iMsg); + void activated(int iMsg) override; private: HttpServer* server; diff --git a/src/Gui/Placement.cpp b/src/Gui/Placement.cpp index 8b352ced14..0e3fb59865 100644 --- a/src/Gui/Placement.cpp +++ b/src/Gui/Placement.cpp @@ -53,7 +53,7 @@ namespace Gui { namespace Dialog { class find_placement { public: - find_placement(const std::string& name) : propertyname(name) + explicit find_placement(const std::string& name) : propertyname(name) { } bool operator () (const std::pair& elem) const @@ -371,7 +371,7 @@ void Placement::on_selectedVertex_clicked() Base::Vector3d firstSelected; //first selected will be central point when 3 points picked for (std::vector::iterator it=selection.begin(); it!=selection.end(); ++it){ std::vector points = it->getPickedPoints(); - if (it==selection.begin() && points.size()>0){ + if (it==selection.begin() && !points.empty()){ firstSelected=points[0]; } picked.insert(picked.begin(),points.begin(),points.end()); diff --git a/src/Gui/Placement.h b/src/Gui/Placement.h index fd70e9631d..50ffabf595 100644 --- a/src/Gui/Placement.h +++ b/src/Gui/Placement.h @@ -43,21 +43,21 @@ class GuiExport Placement : public Gui::LocationDialog Q_OBJECT public: - Placement(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~Placement(); - void accept(); - void reject(); + explicit Placement(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~Placement() override; + void accept() override; + void reject() override; void bindObject(); - Base::Vector3d getDirection() const; + Base::Vector3d getDirection() const override; void setPlacement(const Base::Placement&); Base::Placement getPlacement() const; void showDefaultButtons(bool); protected: - void open(); - void changeEvent(QEvent *e); - void keyPressEvent(QKeyEvent*); + void open() override; + void changeEvent(QEvent *e) override; + void keyPressEvent(QKeyEvent*) override; private Q_SLOTS: void openTransaction(); @@ -75,7 +75,7 @@ private: Base::Placement getPlacementData() const; Base::Vector3d getCenterData() const; QString getPlacementString() const; - void directionActivated(int); + void directionActivated(int) override; void applyPlacement(const Base::Placement& p, bool incremental); void applyPlacement(const QString& p, bool incremental); void revertTransformation(); @@ -114,11 +114,11 @@ class GuiExport DockablePlacement : public Placement Q_OBJECT public: - DockablePlacement(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DockablePlacement(); + explicit DockablePlacement(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DockablePlacement() override; - void accept(); - void reject(); + void accept() override; + void reject() override; }; class TaskPlacement : public Gui::TaskView::TaskDialog @@ -127,24 +127,24 @@ class TaskPlacement : public Gui::TaskView::TaskDialog public: TaskPlacement(); - ~TaskPlacement(); + ~TaskPlacement() override; public: void setPropertyName(const QString&); void setPlacement(const Base::Placement&); void bindObject(); - bool accept(); - bool reject(); - void clicked(int id); + bool accept() override; + bool reject() override; + void clicked(int id) override; - void open(); - bool isAllowedAlterDocument(void) const + void open() override; + bool isAllowedAlterDocument() const override { return true; } - bool isAllowedAlterView(void) const + bool isAllowedAlterView() const override { return true; } - bool isAllowedAlterSelection(void) const + bool isAllowedAlterSelection() const override { return true; } - QDialogButtonBox::StandardButtons getStandardButtons() const; + QDialogButtonBox::StandardButtons getStandardButtons() const override; public Q_SLOTS: void slotPlacementChanged(const QVariant &, bool, bool); diff --git a/src/Gui/PrefWidgets.cpp b/src/Gui/PrefWidgets.cpp index 07f41daaf3..0765983b2c 100644 --- a/src/Gui/PrefWidgets.cpp +++ b/src/Gui/PrefWidgets.cpp @@ -641,7 +641,7 @@ void PrefQuantitySpinBox::contextMenuEvent(QContextMenuEvent *event) // data structure to remember actions for values QStringList history = d->history.asStringList(); - for (QStringList::const_iterator it = history.begin();it != history.end(); ++it) { + for (QStringList::const_iterator it = history.cbegin();it != history.cend(); ++it) { QAction* action = menu->addAction(*it); action->setProperty("history_value", *it); } diff --git a/src/Gui/PrefWidgets.h b/src/Gui/PrefWidgets.h index ae17fc6071..35c473f5bc 100644 --- a/src/Gui/PrefWidgets.h +++ b/src/Gui/PrefWidgets.h @@ -75,7 +75,7 @@ public: */ void setPrefPath(const QByteArray& name); - virtual void OnChange(Base::Subject &rCaller, const char * sReason); + void OnChange(Base::Subject &rCaller, const char * sReason) override; void onSave(); void onRestore(); @@ -96,7 +96,7 @@ protected: void failedToRestore(const QString&) const; PrefWidget(); - virtual ~PrefWidget(); + ~PrefWidget() override; private: QByteArray m_sPrefName; @@ -113,17 +113,17 @@ class GuiExport PrefSpinBox : public QSpinBox, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefSpinBox ( QWidget * parent = nullptr ); - virtual ~PrefSpinBox(); + explicit PrefSpinBox ( QWidget * parent = nullptr ); + ~PrefSpinBox() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** The PrefDoubleSpinBox class. @@ -133,17 +133,17 @@ class GuiExport PrefDoubleSpinBox : public QDoubleSpinBox, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefDoubleSpinBox ( QWidget * parent = nullptr ); - virtual ~PrefDoubleSpinBox(); + explicit PrefDoubleSpinBox ( QWidget * parent = nullptr ); + ~PrefDoubleSpinBox() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -154,17 +154,17 @@ class GuiExport PrefLineEdit : public QLineEdit, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefLineEdit ( QWidget * parent = nullptr ); - virtual ~PrefLineEdit(); + explicit PrefLineEdit ( QWidget * parent = nullptr ); + ~PrefLineEdit() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -175,17 +175,17 @@ class GuiExport PrefTextEdit : public QTextEdit, public PrefWidget { Q_OBJECT - Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) - Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) // clazy:exclude=qproperty-without-notify public: - PrefTextEdit(QWidget* parent = nullptr); - virtual ~PrefTextEdit(); + explicit PrefTextEdit(QWidget* parent = nullptr); + ~PrefTextEdit() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -196,17 +196,17 @@ class GuiExport PrefFileChooser : public FileChooser, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefFileChooser ( QWidget * parent = nullptr ); - virtual ~PrefFileChooser(); + explicit PrefFileChooser ( QWidget * parent = nullptr ); + ~PrefFileChooser() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -217,17 +217,17 @@ class GuiExport PrefComboBox : public QComboBox, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefComboBox ( QWidget * parent = nullptr ); - virtual ~PrefComboBox(); + explicit PrefComboBox ( QWidget * parent = nullptr ); + ~PrefComboBox() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -238,17 +238,17 @@ class GuiExport PrefCheckBox : public QCheckBox, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefCheckBox ( QWidget * parent = nullptr ); - virtual ~PrefCheckBox(); + explicit PrefCheckBox ( QWidget * parent = nullptr ); + ~PrefCheckBox() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -259,17 +259,17 @@ class GuiExport PrefRadioButton : public QRadioButton, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefRadioButton ( QWidget * parent = nullptr ); - virtual ~PrefRadioButton(); + explicit PrefRadioButton ( QWidget * parent = nullptr ); + ~PrefRadioButton() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -280,17 +280,17 @@ class GuiExport PrefSlider : public QSlider, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefSlider ( QWidget * parent = nullptr ); - virtual ~PrefSlider(); + explicit PrefSlider ( QWidget * parent = nullptr ); + ~PrefSlider() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** @@ -301,17 +301,17 @@ class GuiExport PrefColorButton : public ColorButton, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefColorButton ( QWidget * parent = nullptr ); - virtual ~PrefColorButton(); + explicit PrefColorButton ( QWidget * parent = nullptr ); + ~PrefColorButton() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; /** The PrefUnitSpinBox class. @@ -323,17 +323,17 @@ class GuiExport PrefUnitSpinBox : public QuantitySpinBox, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefUnitSpinBox ( QWidget * parent = nullptr ); - virtual ~PrefUnitSpinBox(); + explicit PrefUnitSpinBox ( QWidget * parent = nullptr ); + ~PrefUnitSpinBox() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; class PrefQuantitySpinBoxPrivate; @@ -346,13 +346,13 @@ class GuiExport PrefQuantitySpinBox : public QuantitySpinBox, public PrefWidget { Q_OBJECT - Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) - Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) - Q_PROPERTY(int historySize READ historySize WRITE setHistorySize) + Q_PROPERTY(QByteArray prefEntry READ entryName WRITE setEntryName) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(int historySize READ historySize WRITE setHistorySize) // clazy:exclude=qproperty-without-notify public: - PrefQuantitySpinBox (QWidget * parent = nullptr); - virtual ~PrefQuantitySpinBox(); + explicit PrefQuantitySpinBox (QWidget * parent = nullptr); + ~PrefQuantitySpinBox() override; /// set the input field to the last used value (works only if the setParamGrpPath() was called) void setToLastUsedValue(); @@ -370,10 +370,10 @@ public: //@} protected: - virtual void contextMenuEvent(QContextMenuEvent * event); + void contextMenuEvent(QContextMenuEvent * event) override; // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; private: QScopedPointer d_ptr; @@ -388,17 +388,17 @@ class GuiExport PrefFontBox : public QFontComboBox, public PrefWidget { Q_OBJECT - Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) - Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) + Q_PROPERTY( QByteArray prefEntry READ entryName WRITE setEntryName ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( QByteArray prefPath READ paramGrpPath WRITE setParamGrpPath ) // clazy:exclude=qproperty-without-notify public: - PrefFontBox ( QWidget * parent = nullptr ); - virtual ~PrefFontBox(); + explicit PrefFontBox ( QWidget * parent = nullptr ); + ~PrefFontBox() override; protected: // restore from/save to parameters - void restorePreferences(); - void savePreferences(); + void restorePreferences() override; + void savePreferences() override; }; } // namespace Gui diff --git a/src/Gui/PreferencePackManager.cpp b/src/Gui/PreferencePackManager.cpp index 6931d89e49..7bc3d7a084 100644 --- a/src/Gui/PreferencePackManager.cpp +++ b/src/Gui/PreferencePackManager.cpp @@ -243,7 +243,7 @@ std::string findUnusedName(const std::string &basename, ParameterGrp::handle par bool PreferencePackManager::isVisible(const std::string& addonName, const std::string& preferencePackName) const { - if (addonName == "" || preferencePackName == "") + if (addonName.empty() || preferencePackName.empty()) return true; auto pref = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General/HiddenPreferencePacks"); @@ -259,7 +259,7 @@ bool PreferencePackManager::isVisible(const std::string& addonName, const std::s void PreferencePackManager::toggleVisibility(const std::string& addonName, const std::string& preferencePackName) { - if (preferencePackName == "") + if (preferencePackName.empty()) return; auto pref = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General/HiddenPreferencePacks"); auto hiddenPacks = pref->GetGroups(); @@ -282,7 +282,7 @@ void PreferencePackManager::toggleVisibility(const std::string& addonName, const void Gui::PreferencePackManager::deleteUserPack(const std::string& name) { - if (name == "") + if (name.empty()) return; auto savedPreferencePacksDirectory = fs::path(App::Application::getUserAppDataDir()) / "SavedPreferencePacks"; auto savedPath = savedPreferencePacksDirectory / name; @@ -386,14 +386,14 @@ void PreferencePackManager::save(const std::string& name, const std::vector(); metadata->setName("User-Saved PreferencePacks"); metadata->setDescription("Generated automatically -- edits may be lost when saving new preferencePacks"); - metadata->setVersion(1); + metadata->setVersion(static_cast(1)); metadata->addMaintainer(App::Meta::Contact("No Maintainer", "email@freecadweb.org")); metadata->addLicense(App::Meta::License("(Unspecified)", "(Unspecified)")); metadata->addUrl(App::Meta::Url("https://github.com/FreeCAD/FreeCAD", App::Meta::UrlType::repository)); } App::Metadata newPreferencePackMetadata; newPreferencePackMetadata.setName(name); - newPreferencePackMetadata.setVersion(1); + newPreferencePackMetadata.setVersion(static_cast(1)); metadata->addContentItem("preferencepack", newPreferencePackMetadata); metadata->write(savedPreferencePacksDirectory / "package.xml"); diff --git a/src/Gui/PreferencePackTemplates/CMakeLists.txt b/src/Gui/PreferencePackTemplates/CMakeLists.txt index 52e1c41faf..b915b05b1f 100644 --- a/src/Gui/PreferencePackTemplates/CMakeLists.txt +++ b/src/Gui/PreferencePackTemplates/CMakeLists.txt @@ -6,6 +6,7 @@ SET(PreferencePackTemplates_Files Editor_Colors.cfg Editor_Font.cfg Main_window_layout.cfg + Part_Colors.cfg Path_Colors.cfg Sketcher_Colors.cfg Start_Colors.cfg diff --git a/src/Gui/PreferencePackTemplates/Part_Colors.cfg b/src/Gui/PreferencePackTemplates/Part_Colors.cfg new file mode 100644 index 0000000000..eb4c32a70e --- /dev/null +++ b/src/Gui/PreferencePackTemplates/Part_Colors.cfg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/Gui/PreferencePackTemplates/View.cfg b/src/Gui/PreferencePackTemplates/View.cfg index f2805c10b3..a0ef5b960d 100644 --- a/src/Gui/PreferencePackTemplates/View.cfg +++ b/src/Gui/PreferencePackTemplates/View.cfg @@ -7,6 +7,7 @@ + @@ -15,7 +16,6 @@ - diff --git a/src/Gui/PreferencePacks/FreeCAD Classic Colors/FreeCAD Classic Colors.cfg b/src/Gui/PreferencePacks/FreeCAD Classic Colors/FreeCAD Classic Colors.cfg index c18797a155..13b2a13da2 100644 --- a/src/Gui/PreferencePacks/FreeCAD Classic Colors/FreeCAD Classic Colors.cfg +++ b/src/Gui/PreferencePacks/FreeCAD Classic Colors/FreeCAD Classic Colors.cfg @@ -21,6 +21,11 @@ + + + + + @@ -111,9 +116,9 @@ - - - + + + diff --git a/src/Gui/ProgressBar.cpp b/src/Gui/ProgressBar.cpp index fa696abb34..685d9cebc9 100644 --- a/src/Gui/ProgressBar.cpp +++ b/src/Gui/ProgressBar.cpp @@ -553,7 +553,7 @@ void ProgressBar::setupTaskBarProgress() bool ProgressBar::eventFilter(QObject* o, QEvent* e) { - if (sequencer->isRunning() && e != nullptr) { + if (sequencer->isRunning() && e) { QThread* currentThread = QThread::currentThread(); QThread* thr = this->thread(); // this is the main thread if (thr != currentThread) { diff --git a/src/Gui/ProgressBar.h b/src/Gui/ProgressBar.h index f27d09233e..265de9c51b 100644 --- a/src/Gui/ProgressBar.h +++ b/src/Gui/ProgressBar.h @@ -106,13 +106,13 @@ public: /** Returns an instance of the progress bar. It creates one if needed. */ QProgressBar* getProgressBar(QWidget* parent=nullptr); - virtual void checkAbort() override; + void checkAbort() override; protected: /** Construction */ SequencerBar(); /** Destruction */ - ~SequencerBar(); + ~SequencerBar() override; /** Puts text to the status bar */ void setText (const char* pszTxt) override; @@ -147,12 +147,12 @@ public: /** Construction */ ProgressBar (SequencerBar* s, QWidget * parent=nullptr); /** Destruction */ - ~ProgressBar (); + ~ProgressBar () override; /** Handles all incoming events while the progress bar is running. All key and mouse * events are ignored to block user input. */ - bool eventFilter(QObject* o, QEvent* e); + bool eventFilter(QObject* o, QEvent* e) override; /** Returns the time in milliseconds that must pass before the progress bar appears. */ int minimumDuration() const; @@ -168,11 +168,12 @@ public Q_SLOTS: */ void setMinimumDuration (int ms); +public: bool canAbort() const; protected: - void showEvent(QShowEvent*); - void hideEvent(QHideEvent*); + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; protected Q_SLOTS: /* Shows the progress bar if it is still hidden after the operation has been started diff --git a/src/Gui/ProgressDialog.h b/src/Gui/ProgressDialog.h index 0297563f90..f86376fd1f 100644 --- a/src/Gui/ProgressDialog.h +++ b/src/Gui/ProgressDialog.h @@ -40,27 +40,27 @@ class GuiExport SequencerDialog : public Base::SequencerBase { public: static SequencerDialog* instance(); - void pause(); - void resume(); - bool isBlocking() const; + void pause() override; + void resume() override; + bool isBlocking() const override; bool canAbort() const; protected: /** Construction */ SequencerDialog (); /** Destruction */ - ~SequencerDialog (); + ~SequencerDialog () override; /** Puts text to the progress dialog */ - void setText (const char* pszTxt); + void setText (const char* pszTxt) override; /** Starts the progress dialog */ - void startStep(); + void startStep() override; /** Increase the step indicator of the progress dialog. */ - void nextStep(bool canAbort); + void nextStep(bool canAbort) override; /** Sets the progress indicator to a certain position. */ - void setProgress(size_t); + void setProgress(size_t) override; /** Resets the sequencer */ - void resetData(); + void resetData() override; void showRemainingTime(); private: @@ -83,9 +83,9 @@ class ProgressDialog : public QProgressDialog public: /** Construction */ - ProgressDialog (SequencerDialog* s, QWidget * parent=nullptr); + explicit ProgressDialog (SequencerDialog* s, QWidget * parent=nullptr); /** Destruction */ - ~ProgressDialog (); + ~ProgressDialog () override; protected Q_SLOTS: void onCancel(); @@ -96,8 +96,8 @@ private Q_SLOTS: void setValueEx(int value); void aboutToShow(); void aboutToHide(); - void showEvent(QShowEvent*); - void hideEvent(QHideEvent*); + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; protected: bool canAbort() const; diff --git a/src/Gui/ProjectView.h b/src/Gui/ProjectView.h index 7718d7ca8f..f41a5f1dca 100644 --- a/src/Gui/ProjectView.h +++ b/src/Gui/ProjectView.h @@ -39,8 +39,8 @@ class ProjectWidget : public QTreeView Q_OBJECT public: - ProjectWidget(QWidget* parent=nullptr); - ~ProjectWidget(); + explicit ProjectWidget(QWidget* parent=nullptr); + ~ProjectWidget() override; private: QFileSystemModel *fileModel; diff --git a/src/Gui/PropertyPage.cpp b/src/Gui/PropertyPage.cpp index 22e2616364..388bd8e12c 100644 --- a/src/Gui/PropertyPage.cpp +++ b/src/Gui/PropertyPage.cpp @@ -148,7 +148,7 @@ void PreferenceUiForm::changeEvent(QEvent *e) } template -void PreferenceUiForm::loadPrefWidgets(void) +void PreferenceUiForm::loadPrefWidgets() { QList pw = form->findChildren(); for (typename QList::iterator it = pw.begin(); it != pw.end(); ++it) @@ -156,7 +156,7 @@ void PreferenceUiForm::loadPrefWidgets(void) } template -void PreferenceUiForm::savePrefWidgets(void) +void PreferenceUiForm::savePrefWidgets() { QList pw = form->findChildren(); for (typename QList::iterator it = pw.begin(); it != pw.end(); ++it) diff --git a/src/Gui/PropertyPage.h b/src/Gui/PropertyPage.h index 024686b906..4a67b21e36 100644 --- a/src/Gui/PropertyPage.h +++ b/src/Gui/PropertyPage.h @@ -38,8 +38,8 @@ class GuiExport PropertyPage : public QWidget Q_OBJECT public: - PropertyPage(QWidget* parent = nullptr); - virtual ~PropertyPage(); + explicit PropertyPage(QWidget* parent = nullptr); + ~PropertyPage() override; bool isModified(); void setModified(bool b); @@ -68,15 +68,15 @@ class GuiExport PreferencePage : public QWidget Q_OBJECT public: - PreferencePage(QWidget* parent = nullptr); - virtual ~PreferencePage(); + explicit PreferencePage(QWidget* parent = nullptr); + ~PreferencePage() override; public Q_SLOTS: virtual void loadSettings()=0; virtual void saveSettings()=0; protected: - virtual void changeEvent(QEvent *e) = 0; + void changeEvent(QEvent *e) override = 0; }; /** Subclass that embeds a form from a UI file. @@ -87,14 +87,14 @@ class GuiExport PreferenceUiForm : public PreferencePage Q_OBJECT public: - PreferenceUiForm(const QString& fn, QWidget* parent = nullptr); - virtual ~PreferenceUiForm(); + explicit PreferenceUiForm(const QString& fn, QWidget* parent = nullptr); + ~PreferenceUiForm() override; - void loadSettings(); - void saveSettings(); + void loadSettings() override; + void saveSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: template @@ -114,12 +114,12 @@ class GuiExport CustomizeActionPage : public QWidget Q_OBJECT public: - CustomizeActionPage(QWidget* parent = nullptr); - virtual ~CustomizeActionPage(); + explicit CustomizeActionPage(QWidget* parent = nullptr); + ~CustomizeActionPage() override; protected: - bool event(QEvent* e); - virtual void changeEvent(QEvent *e) = 0; + bool event(QEvent* e) override; + void changeEvent(QEvent *e) override = 0; protected Q_SLOTS: virtual void onAddMacroAction(const QByteArray&)=0; diff --git a/src/Gui/PropertyView.cpp b/src/Gui/PropertyView.cpp index 5426716f58..196a58ff13 100644 --- a/src/Gui/PropertyView.cpp +++ b/src/Gui/PropertyView.cpp @@ -161,7 +161,8 @@ bool PropertyView::showAll() { void PropertyView::setShowAll(bool enable) { if(_ShowAll != enable) { _ShowAll = enable; - for(auto view : getMainWindow()->findChildren()) { + const auto views = getMainWindow()->findChildren(); + for(auto view : views) { if(view->isVisible()) { view->propertyEditorData->buildUp(); view->propertyEditorView->buildUp(); @@ -310,7 +311,7 @@ struct PropertyView::PropInfo struct PropertyView::PropFind { const PropInfo& item; - PropFind(const PropInfo& item) : item(item) {} + explicit PropFind(const PropInfo& item) : item(item) {} bool operator () (const PropInfo& elem) const { return (elem.propId == item.propId) && diff --git a/src/Gui/PropertyView.h b/src/Gui/PropertyView.h index ff6a5e8aee..9e400fba0e 100644 --- a/src/Gui/PropertyView.h +++ b/src/Gui/PropertyView.h @@ -56,8 +56,8 @@ class PropertyView : public QWidget, public Gui::SelectionObserver Q_OBJECT public: - PropertyView(QWidget *parent=nullptr); - virtual ~PropertyView(); + explicit PropertyView(QWidget *parent=nullptr); + ~PropertyView() override; Gui::PropertyEditor::PropertyEditor* propertyEditorView; Gui::PropertyEditor::PropertyEditor* propertyEditorData; @@ -120,8 +120,8 @@ class PropertyDockView : public Gui::DockWindow Q_OBJECT public: - PropertyDockView(Gui::Document* pcDocument, QWidget *parent=nullptr); - virtual ~PropertyDockView(); + explicit PropertyDockView(Gui::Document* pcDocument, QWidget *parent=nullptr); + ~PropertyDockView() override; }; } // namespace DockWnd diff --git a/src/Gui/PythonConsole.cpp b/src/Gui/PythonConsole.cpp index 8317833eb4..95653adf6c 100644 --- a/src/Gui/PythonConsole.cpp +++ b/src/Gui/PythonConsole.cpp @@ -190,8 +190,8 @@ PyObject* InteractiveInterpreter::compile(const char* source) const PyObject* eval = PyObject_CallObject(func,args); // must decref later #endif - Py_DECREF(args); - Py_DECREF(func); + Py_XDECREF(args); + Py_XDECREF(func); if (eval){ return eval; @@ -300,10 +300,10 @@ void InteractiveInterpreter::runCode(PyCodeObject* code) const Base::PyGILStateLocker lock; PyObject *module, *dict, *presult; /* "exec code in d, d" */ module = PyImport_AddModule("__main__"); /* get module, init python */ - if (module == nullptr) + if (!module) throw Base::PyException(); /* not incref'd */ dict = PyModule_GetDict(module); /* get dict namespace */ - if (dict == nullptr) + if (!dict) throw Base::PyException(); /* not incref'd */ // It seems that the return value is always 'None' or Null @@ -356,11 +356,10 @@ void InteractiveInterpreter::runCode(PyCodeObject* code) const */ bool InteractiveInterpreter::push(const char* line) { - d->buffer.append(QString::fromLatin1(line)); + d->buffer.append(QString::fromUtf8(line)); QString source = d->buffer.join(QLatin1String("\n")); try { - // Source is already UTF-8, so we can use toLatin1() - bool more = runSource(source.toLatin1()); + bool more = runSource(source.toUtf8()); if (!more) d->buffer.clear(); return more; @@ -378,7 +377,7 @@ bool InteractiveInterpreter::push(const char* line) return false; } -bool InteractiveInterpreter::hasPendingInput( void ) const +bool InteractiveInterpreter::hasPendingInput( ) const { return (!d->buffer.isEmpty()); } @@ -1083,7 +1082,7 @@ void PythonConsole::insertFromMimeData (const QMimeData * source) } } -QTextCursor PythonConsole::inputBegin(void) const +QTextCursor PythonConsole::inputBegin() const { // construct cursor at begin of input line ... QTextCursor inputLineBegin(this->textCursor()); @@ -1362,7 +1361,7 @@ void PythonConsole::onCopyCommand() d->type = PythonConsoleP::Normal; } -QString PythonConsole::readline( void ) +QString PythonConsole::readline( ) { QEventLoop loop; // output is set to the current prompt which we need to extract @@ -1421,7 +1420,7 @@ void PythonConsole::saveHistory() const // only save last 100 entries so we don't inflate forever... if (hist.length() > 100) hist = hist.mid(hist.length()-100); - for (QStringList::ConstIterator it = hist.begin(); it != hist.end(); ++it) + for (QStringList::ConstIterator it = hist.cbegin(); it != hist.cend(); ++it) t << *it << "\n"; f.close(); } @@ -1575,7 +1574,7 @@ const QStringList& ConsoleHistory::values() const /** * restart resets the history access to the latest item. */ -void ConsoleHistory::restart( void ) +void ConsoleHistory::restart( ) { _it = _history.cend(); } @@ -1585,7 +1584,7 @@ void ConsoleHistory::restart( void ) * Note: with simply remembering a start index, it does not work to nest scratch regions. * However, just replace the index keeping by a stack - in case this is be a concern. */ -void ConsoleHistory::markScratch( void ) +void ConsoleHistory::markScratch( ) { _scratchBegin = _history.length(); } @@ -1593,7 +1592,7 @@ void ConsoleHistory::markScratch( void ) /** * doScratch removes the tail of the history list, starting from the index marked lately. */ -void ConsoleHistory::doScratch( void ) +void ConsoleHistory::doScratch( ) { if (_scratchBegin < _history.length()) { diff --git a/src/Gui/PythonConsole.h b/src/Gui/PythonConsole.h index f0ac8e0c43..1db269840e 100644 --- a/src/Gui/PythonConsole.h +++ b/src/Gui/PythonConsole.h @@ -44,7 +44,7 @@ public: bool push(const char*); int compileCommand(const char*) const; - bool hasPendingInput( void ) const; + bool hasPendingInput( ) const; void setBuffer(const QStringList&); QStringList getBuffer() const; void clearBuffer(); @@ -78,8 +78,8 @@ public: void append(const QString &inputLine); const QStringList& values() const; void restart(); - void markScratch( void ); - void doScratch( void ); + void markScratch( ); + void doScratch( ); private: QStringList _history; @@ -105,12 +105,12 @@ public: Special = 3 }; - PythonConsole(QWidget *parent = nullptr); - ~PythonConsole(); + explicit PythonConsole(QWidget *parent = nullptr); + ~PythonConsole() override; - void OnChange( Base::Subject &rCaller,const char* rcReason ); + void OnChange( Base::Subject &rCaller,const char* rcReason ) override; void printStatement( const QString& cmd ); - QString readline( void ); + QString readline( ); public Q_SLOTS: void onSaveHistoryAs(); @@ -124,22 +124,22 @@ private Q_SLOTS: void visibilityChanged (bool visible); protected: - void keyPressEvent ( QKeyEvent * e ); - void showEvent ( QShowEvent * e ); - void dropEvent ( QDropEvent * e ); - void dragEnterEvent ( QDragEnterEvent * e ); - void dragMoveEvent ( QDragMoveEvent * e ); - void changeEvent ( QEvent * e ); - void mouseReleaseEvent( QMouseEvent * e ); + void keyPressEvent ( QKeyEvent * e ) override; + void showEvent ( QShowEvent * e ) override; + void dropEvent ( QDropEvent * e ) override; + void dragEnterEvent ( QDragEnterEvent * e ) override; + void dragMoveEvent ( QDragMoveEvent * e ) override; + void changeEvent ( QEvent * e ) override; + void mouseReleaseEvent( QMouseEvent * e ) override; void overrideCursor(const QString& txt); /** Pops up the context menu with some extensions */ - void contextMenuEvent ( QContextMenuEvent* e ); - bool canInsertFromMimeData ( const QMimeData * source ) const; - QMimeData * createMimeDataFromSelection () const; - void insertFromMimeData ( const QMimeData * source ); - QTextCursor inputBegin( void ) const; + void contextMenuEvent ( QContextMenuEvent* e ) override; + bool canInsertFromMimeData ( const QMimeData * source ) const override; + QMimeData * createMimeDataFromSelection () const override; + void insertFromMimeData ( const QMimeData * source ) override; + QTextCursor inputBegin( ) const; private: void runSource(const QString&); @@ -153,7 +153,7 @@ private: void saveHistory() const; Q_SIGNALS: - void pendingSource( void ); + void pendingSource( ); private: struct PythonConsoleP* d; @@ -174,13 +174,13 @@ private: class GuiExport PythonConsoleHighlighter : public PythonSyntaxHighlighter { public: - PythonConsoleHighlighter(QObject* parent); - ~PythonConsoleHighlighter(); + explicit PythonConsoleHighlighter(QObject* parent); + ~PythonConsoleHighlighter() override; - void highlightBlock (const QString & text); + void highlightBlock (const QString & text) override; protected: - void colorChanged(const QString& type, const QColor& col); + void colorChanged(const QString& type, const QColor& col) override; }; } // namespace Gui diff --git a/src/Gui/PythonConsolePy.h b/src/Gui/PythonConsolePy.h index 052e6b8f2b..1b1c290b02 100644 --- a/src/Gui/PythonConsolePy.h +++ b/src/Gui/PythonConsolePy.h @@ -45,13 +45,13 @@ private: PythonConsole* pyConsole; public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods - PythonStdout(PythonConsole *pc); - ~PythonStdout(); + explicit PythonStdout(PythonConsole *pc); + ~PythonStdout() override; - Py::Object getattr(const char *name); - Py::Object repr(); + Py::Object getattr(const char *name) override; + Py::Object repr() override; Py::Object write(const Py::Tuple&); Py::Object flush(const Py::Tuple&); Py::Object isatty(); @@ -71,13 +71,13 @@ private: PythonConsole* pyConsole; public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods - PythonStderr(PythonConsole *pc); - ~PythonStderr(); + explicit PythonStderr(PythonConsole *pc); + ~PythonStderr() override; - Py::Object getattr(const char *name); - Py::Object repr(); + Py::Object getattr(const char *name) override; + Py::Object repr() override; Py::Object write(const Py::Tuple&); Py::Object flush(const Py::Tuple&); Py::Object isatty(); @@ -94,13 +94,13 @@ public: class OutputStdout : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods OutputStdout(); - ~OutputStdout(); + ~OutputStdout() override; - Py::Object getattr(const char *name); - Py::Object repr(); + Py::Object getattr(const char *name) override; + Py::Object repr() override; Py::Object write(const Py::Tuple&); Py::Object flush(const Py::Tuple&); Py::Object isatty(); @@ -117,13 +117,13 @@ public: class OutputStderr : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods OutputStderr(); - ~OutputStderr(); + ~OutputStderr() override; - Py::Object getattr(const char *name); - Py::Object repr(); + Py::Object getattr(const char *name) override; + Py::Object repr() override; Py::Object write(const Py::Tuple&); Py::Object flush(const Py::Tuple&); Py::Object isatty(); @@ -139,12 +139,12 @@ private: PythonConsole* pyConsole; public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods - PythonStdin(PythonConsole *pc); - ~PythonStdin(); + explicit PythonStdin(PythonConsole *pc); + ~PythonStdin() override; - Py::Object repr(); + Py::Object repr() override; Py::Object readline(const Py::Tuple&); }; diff --git a/src/Gui/PythonDebugger.cpp b/src/Gui/PythonDebugger.cpp index cd44e9b1c2..8a50016fe8 100644 --- a/src/Gui/PythonDebugger.cpp +++ b/src/Gui/PythonDebugger.cpp @@ -98,7 +98,7 @@ int Breakpoint::lineIndex(int ind)const // ----------------------------------------------------- -void PythonDebugModule::init_module(void) +void PythonDebugModule::init_module() { PythonDebugStdout::init_type(); PythonDebugStderr::init_type(); @@ -321,7 +321,7 @@ class PythonDebuggerPy : public Py::PythonExtension { public: PythonDebuggerPy(PythonDebugger* d) : dbg(d), depth(0) { } - ~PythonDebuggerPy() {} + ~PythonDebuggerPy() override {} PythonDebugger* dbg; int depth; }; @@ -438,18 +438,18 @@ void PythonDebugger::runFile(const QString& fn) module = PyImport_AddModule("__main__"); dict = PyModule_GetDict(module); dict = PyDict_Copy(dict); - if (PyDict_GetItemString(dict, "__file__") == nullptr) { - PyObject *f = PyUnicode_FromString((const char*)pxFileName); - if (f == nullptr) { + if (!PyDict_GetItemString(dict, "__file__")) { + PyObject *pyObj = PyUnicode_FromString((const char*)pxFileName); + if (!pyObj) { fclose(fp); return; } - if (PyDict_SetItemString(dict, "__file__", f) < 0) { - Py_DECREF(f); + if (PyDict_SetItemString(dict, "__file__", pyObj) < 0) { + Py_DECREF(pyObj); fclose(fp); return; } - Py_DECREF(f); + Py_DECREF(pyObj); } PyObject *result = PyRun_File(fp, (const char*)pxFileName, Py_file_input, dict, dict); diff --git a/src/Gui/PythonDebugger.h b/src/Gui/PythonDebugger.h index 042c47bc05..489c992b15 100644 --- a/src/Gui/PythonDebugger.h +++ b/src/Gui/PythonDebugger.h @@ -95,7 +95,7 @@ inline bool Breakpoint::operator ==(const QString& fn) class GuiExport PythonDebugModule : public Py::ExtensionModule { public: - static void init_module(void); + static void init_module(); PythonDebugModule(); virtual ~PythonDebugModule(); @@ -113,7 +113,7 @@ private: class GuiExport PythonDebugStdout : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods PythonDebugStdout(); ~PythonDebugStdout(); @@ -129,7 +129,7 @@ public: class GuiExport PythonDebugStderr : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods PythonDebugStderr(); ~PythonDebugStderr(); @@ -144,7 +144,7 @@ public: class GuiExport PythonDebugExcept : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods PythonDebugExcept(); ~PythonDebugExcept(); diff --git a/src/Gui/PythonEditor.h b/src/Gui/PythonEditor.h index d2851e6670..7ddc5aa628 100644 --- a/src/Gui/PythonEditor.h +++ b/src/Gui/PythonEditor.h @@ -41,8 +41,8 @@ class GuiExport PythonEditor : public TextEditor Q_OBJECT public: - PythonEditor(QWidget *parent = nullptr); - ~PythonEditor(); + explicit PythonEditor(QWidget *parent = nullptr); + ~PythonEditor() override; void toggleBreakpoint(); void showDebugMarker(int line); @@ -64,8 +64,8 @@ public Q_SLOTS: protected: /** Pops up the context menu with some extensions */ - void contextMenuEvent ( QContextMenuEvent* e ); - void drawMarker(int line, int x, int y, QPainter*); + void contextMenuEvent ( QContextMenuEvent* e ) override; + void drawMarker(int line, int x, int y, QPainter*) override; private: //PythonSyntaxHighlighter* pythonSyntax; @@ -79,7 +79,7 @@ private: class GuiExport PythonSyntaxHighlighter : public SyntaxHighlighter { public: - PythonSyntaxHighlighter(QObject* parent); + explicit PythonSyntaxHighlighter(QObject* parent); virtual ~PythonSyntaxHighlighter(); void highlightBlock (const QString & text); diff --git a/src/Gui/PythonWorkbenchPyImp.cpp b/src/Gui/PythonWorkbenchPyImp.cpp index 5c8d93dca3..6ba70d6027 100644 --- a/src/Gui/PythonWorkbenchPyImp.cpp +++ b/src/Gui/PythonWorkbenchPyImp.cpp @@ -40,7 +40,7 @@ using namespace Gui; */ // returns a string which represent the object e.g. when printed in python -std::string PythonWorkbenchPy::representation(void) const +std::string PythonWorkbenchPy::representation() const { return std::string(""); } @@ -62,14 +62,14 @@ PyObject* PythonWorkbenchPy::appendMenu(PyObject *args) PyObject* item = PyList_GetItem(pPath, j); if (PyUnicode_Check(item)) { const char* pItem = PyUnicode_AsUTF8(item); - path.push_back(pItem); + path.emplace_back(pItem); } else { continue; } } } else if (PyUnicode_Check(pPath)) { const char* pItem = PyUnicode_AsUTF8(pPath); - path.push_back(pItem); + path.emplace_back(pItem); } else { PyErr_SetString(PyExc_AssertionError, "Expected either a string or a stringlist as first argument"); return nullptr; @@ -83,14 +83,14 @@ PyObject* PythonWorkbenchPy::appendMenu(PyObject *args) PyObject* item = PyList_GetItem(pItems, i); if (PyUnicode_Check(item)) { const char* pItem = PyUnicode_AsUTF8(item); - items.push_back(pItem); + items.emplace_back(pItem); } else { continue; } } } else if (PyUnicode_Check(pItems)) { const char* pItem = PyUnicode_AsUTF8(pItems); - items.push_back(pItem); + items.emplace_back(pItem); } else { PyErr_SetString(PyExc_AssertionError, "Expected either a string or a stringlist as first argument"); return nullptr; @@ -132,14 +132,14 @@ PyObject* PythonWorkbenchPy::appendContextMenu(PyObject *args) PyObject* item = PyList_GetItem(pPath, j); if (PyUnicode_Check(item)) { const char* pItem = PyUnicode_AsUTF8(item); - path.push_back(pItem); + path.emplace_back(pItem); } else { continue; } } } else if (PyUnicode_Check(pPath)) { const char* pItem = PyUnicode_AsUTF8(pPath); - path.push_back(pItem); + path.emplace_back(pItem); } else { PyErr_SetString(PyExc_AssertionError, "Expected either a string or a stringlist as first argument"); return nullptr; @@ -153,14 +153,14 @@ PyObject* PythonWorkbenchPy::appendContextMenu(PyObject *args) PyObject* item = PyList_GetItem(pItems, i); if (PyUnicode_Check(item)) { const char* pItem = PyUnicode_AsUTF8(item); - items.push_back(pItem); + items.emplace_back(pItem); } else { continue; } } } else if (PyUnicode_Check(pItems)) { const char* pItem = PyUnicode_AsUTF8(pItems); - items.push_back(pItem); + items.emplace_back(pItem); } else { PyErr_SetString(PyExc_AssertionError, "Expected either a string or a stringlist as first argument"); return nullptr; @@ -204,7 +204,7 @@ PyObject* PythonWorkbenchPy::appendToolbar(PyObject *args) PyObject* item = PyList_GetItem(pObject, i); if (PyUnicode_Check(item)) { const char* pItem = PyUnicode_AsUTF8(item); - items.push_back(pItem); + items.emplace_back(pItem); } else { continue; } @@ -247,7 +247,7 @@ PyObject* PythonWorkbenchPy::appendCommandbar(PyObject *args) PyObject* item = PyList_GetItem(pObject, i); if (PyUnicode_Check(item)) { const char* pItem = PyUnicode_AsUTF8(item); - items.push_back(pItem); + items.emplace_back(pItem); } else { continue; } diff --git a/src/Gui/PythonWrapper.cpp b/src/Gui/PythonWrapper.cpp index d520760b25..ced8eb0295 100644 --- a/src/Gui/PythonWrapper.cpp +++ b/src/Gui/PythonWrapper.cpp @@ -363,7 +363,7 @@ QObject* PythonWrapper::toQObject(const Py::Object& pyobject) return reinterpret_cast(ptr); #endif -#if 0 // Unwrapping using sip/PyQt +#ifdef HAVE_PYQT // Unwrapping using sip/PyQt void* ptr = qt_getCppPointer(pyobject, "sip", "unwrapinstance"); return reinterpret_cast(ptr); #endif @@ -499,7 +499,7 @@ Py::Object PythonWrapper::fromQObject(QObject* object, const char* className) // return qt_wrapInstance(object, className, "shiboken2", "PySide2.QtCore", "wrapInstance"); #endif -#if 0 // Unwrapping using sip/PyQt +#ifdef HAVE_PYQT // Unwrapping using sip/PyQt Q_UNUSED(className); return qt_wrapInstance(object, "QObject", "sip", "PyQt5.QtCore", "wrapinstance"); #endif @@ -529,7 +529,7 @@ Py::Object PythonWrapper::fromQWidget(QWidget* widget, const char* className) return qt_wrapInstance(widget, className, "shiboken2", "PySide2.QtWidgets", "wrapInstance"); #endif -#if 0 // Unwrapping using sip/PyQt +#ifdef HAVE_PYQT // Unwrapping using sip/PyQt Q_UNUSED(className); return qt_wrapInstance(widget, "QWidget", "sip", "PyQt5.QtWidgets", "wrapinstance"); #endif diff --git a/src/Gui/QListWidgetCustom.cpp b/src/Gui/QListWidgetCustom.cpp index 9c221387f1..ced5555e1c 100644 --- a/src/Gui/QListWidgetCustom.cpp +++ b/src/Gui/QListWidgetCustom.cpp @@ -24,7 +24,6 @@ #include "PreCompiled.h" #ifndef _PreComp_ # include -# include # include #endif @@ -46,7 +45,7 @@ QListWidgetCustom::~QListWidgetCustom() */ void QListWidgetCustom::dragMoveEvent(QDragMoveEvent *e) { - if (e->source() != nullptr) { + if (e->source()) { QVariant prop = this->property("OnlyAcceptFrom"); if (prop.isValid()) { QStringList filter = prop.toStringList(); diff --git a/src/Gui/QListWidgetCustom.h b/src/Gui/QListWidgetCustom.h index ab97ac3d85..89f255cec9 100644 --- a/src/Gui/QListWidgetCustom.h +++ b/src/Gui/QListWidgetCustom.h @@ -34,10 +34,10 @@ class QListWidgetCustom : public QListWidget public: QListWidgetCustom (QWidget *parent); - virtual ~QListWidgetCustom (); + ~QListWidgetCustom () override; protected: - void dragMoveEvent(QDragMoveEvent *e); + void dragMoveEvent(QDragMoveEvent *e) override; }; #endif diff --git a/src/Gui/QSint/actionpanel/actionbox.h b/src/Gui/QSint/actionpanel/actionbox.h index 1327d5b0f7..3692d9938a 100644 --- a/src/Gui/QSint/actionpanel/actionbox.h +++ b/src/Gui/QSint/actionpanel/actionbox.h @@ -163,8 +163,8 @@ class QSINT_EXPORT ActionBox : public QFrame { Q_OBJECT - Q_PROPERTY(QPixmap icon READ icon WRITE setIcon) - Q_PROPERTY(ActionLabel header READ header) + Q_PROPERTY(QPixmap icon READ icon WRITE setIcon) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(ActionLabel header READ header) // clazy:exclude=qproperty-without-notify public: /** Constructor. diff --git a/src/Gui/QSint/actionpanel/actiongroup.h b/src/Gui/QSint/actionpanel/actiongroup.h index 315b421183..b8a87dc8d6 100644 --- a/src/Gui/QSint/actionpanel/actiongroup.h +++ b/src/Gui/QSint/actionpanel/actiongroup.h @@ -36,9 +36,9 @@ class QSINT_EXPORT ActionGroup : public QWidget { Q_OBJECT - Q_PROPERTY(bool expandable READ isExpandable WRITE setExpandable) - Q_PROPERTY(bool header READ hasHeader WRITE setHeader) - Q_PROPERTY(QString headerText READ headerText WRITE setHeaderText) + Q_PROPERTY(bool expandable READ isExpandable WRITE setExpandable) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool header READ hasHeader WRITE setHeader) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QString headerText READ headerText WRITE setHeaderText) // clazy:exclude=qproperty-without-notify public: /** Constructor. Creates ActionGroup without header. diff --git a/src/Gui/QSint/actionpanel/actionpanelscheme.cpp b/src/Gui/QSint/actionpanel/actionpanelscheme.cpp index cd84243c99..ca75b260cc 100644 --- a/src/Gui/QSint/actionpanel/actionpanelscheme.cpp +++ b/src/Gui/QSint/actionpanel/actionpanelscheme.cpp @@ -89,6 +89,22 @@ const char* ActionPanelDefaultStyle = "background-color: #ddeeff;" "color: #006600;" "}" + + // set a QGroupBox to avoid that the OS style is used, see + // https://github.com/FreeCAD/FreeCAD/issues/6102 + // the px values are taken from Behave-dark.qss, except the padding + "QSint--ActionGroup QFrame[class='content'] QGroupBox {" + "border: 1px solid #bbbbbb;" + "border-radius: 3px;" + "margin-top: 10px;" + "padding: 2px;" + "}" + // since we set a custom frame we also need to set the title + "QSint--ActionGroup QFrame[class='content'] QGroupBox::title {" + "padding-left: 3px;" + "top: -6px;" + "left: 12px;" + "}" ; diff --git a/src/Gui/QSint/actionpanel/freecadscheme.cpp b/src/Gui/QSint/actionpanel/freecadscheme.cpp index 09e756a060..e9da9e5917 100644 --- a/src/Gui/QSint/actionpanel/freecadscheme.cpp +++ b/src/Gui/QSint/actionpanel/freecadscheme.cpp @@ -93,6 +93,22 @@ const char* ActionPanelFreeCAD = "background-color: #ddeeff;" "color: #006600;" "}" + + // set a QGroupBox to avoid that the OS style is used, see + // https://github.com/FreeCAD/FreeCAD/issues/6102 + // the px values are taken from Behave-dark.qss, except the padding + "QSint--ActionGroup QFrame[class='content'] QGroupBox {" + "border: 1px solid #bbbbbb;" + "border-radius: 3px;" + "margin-top: 10px;" + "padding: 2px;" + "}" + // since we set a custom frame we also need to set the title + "QSint--ActionGroup QFrame[class='content'] QGroupBox::title {" + "padding-left: 3px;" + "top: -6px;" + "left: 12px;" + "}" ; const char* MinimumActionPanelFreeCAD = diff --git a/src/Gui/QSint/actionpanel/taskheader_p.cpp b/src/Gui/QSint/actionpanel/taskheader_p.cpp index 6fa3d58d30..627d5c3f34 100644 --- a/src/Gui/QSint/actionpanel/taskheader_p.cpp +++ b/src/Gui/QSint/actionpanel/taskheader_p.cpp @@ -192,20 +192,6 @@ void TaskHeader::fold() { if (myExpandable) { Q_EMIT activated(); - // Toggling the 'm_fold' member here may lead to inconsistencies with its ActionGroup. - // Thus, the method setFold() was added and called from ActionGroup when required. -#if 0 - m_fold = !m_fold; - changeIcons(); - if (myButton) { - myButton->setProperty("fold", m_fold); - if (myButton->style()) { - myButton->style()->unpolish(myButton); - myButton->style()->polish(myButton); - myButton->update(); - } - } -#endif } } diff --git a/src/Gui/QuantitySpinBox.cpp b/src/Gui/QuantitySpinBox.cpp index e54c236743..82d11bd677 100644 --- a/src/Gui/QuantitySpinBox.cpp +++ b/src/Gui/QuantitySpinBox.cpp @@ -315,10 +315,12 @@ QuantitySpinBox::QuantitySpinBox(QWidget *parent) { d_ptr->locale = locale(); this->setContextMenuPolicy(Qt::DefaultContextMenu); - QObject::connect(lineEdit(), SIGNAL(textChanged(QString)), - this, SLOT(userInput(QString))); - QObject::connect(this, SIGNAL(editingFinished()), - this, SLOT(handlePendingEmit())); + connect(lineEdit(), &QLineEdit::textChanged, + this, &QuantitySpinBox::userInput); + connect(this, &QuantitySpinBox::editingFinished, + this, [&]{ + this->handlePendingEmit(true); + }); // When a style sheet is set the text margins for top/bottom must be set to avoid to squash the widget #ifndef Q_OS_MAC @@ -441,8 +443,8 @@ bool QuantitySpinBox::apply(const std::string & propName) Gui::Command::doCommand(Gui::Command::Doc, "%s = %f", propName.c_str(), dValue); return true; } - else - return false; + + return false; } void QuantitySpinBox::resizeEvent(QResizeEvent * event) @@ -601,7 +603,7 @@ void QuantitySpinBox::updateFromCache(bool notify, bool updateUnit /* = true */) d->pendingEmit = false; Q_EMIT valueChanged(res); Q_EMIT valueChanged(res.getValue()); - textChanged(text); + Q_EMIT textChanged(text); } } } @@ -631,7 +633,7 @@ void QuantitySpinBox::setUnitText(const QString& str) } } -QString QuantitySpinBox::unitText(void) +QString QuantitySpinBox::unitText() { Q_D(QuantitySpinBox); return d->unitStr; @@ -889,27 +891,6 @@ void QuantitySpinBox::closeEvent(QCloseEvent * event) bool QuantitySpinBox::event(QEvent * event) { - // issue #0004059: Tooltips for Gui::QuantitySpinBox not showing - // Here we must not try to show the tooltip of the icon label - // because it would override a custom tooltip set to this widget. - // - // We could also check if the text of this tooltip is empty but - // it will fail in cases where the widget is embedded into the - // property editor and the corresponding item has set a tooltip. - // Instead of showing the item's tooltip it will again show the - // tooltip of the icon label. -#if 0 - if (event->type() == QEvent::ToolTip) { - if (isBound() && getExpression() && lineEdit()->isReadOnly()) { - QHelpEvent * helpEvent = static_cast(event); - - QToolTip::showText( helpEvent->globalPos(), Base::Tools::fromStdString(getExpression()->toString()), this); - event->accept(); - return true; - } - } -#endif - return QAbstractSpinBox::event(event); } @@ -1002,7 +983,6 @@ Base::Quantity QuantitySpinBox::valueFromText(const QString &text) const QValidator::State QuantitySpinBox::validate(QString &text, int &pos) const { Q_D(const QuantitySpinBox); - QValidator::State state; d->validateAndInterpret(text, pos, state); return state; diff --git a/src/Gui/QuantitySpinBox.h b/src/Gui/QuantitySpinBox.h index 2ea41dc361..f2db970f2b 100644 --- a/src/Gui/QuantitySpinBox.h +++ b/src/Gui/QuantitySpinBox.h @@ -39,18 +39,18 @@ class GuiExport QuantitySpinBox : public QAbstractSpinBox, public ExpressionSpin { Q_OBJECT - Q_PROPERTY(QString unit READ unitText WRITE setUnitText) - Q_PROPERTY(double minimum READ minimum WRITE setMinimum) - Q_PROPERTY(double maximum READ maximum WRITE setMaximum) - Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep) + Q_PROPERTY(QString unit READ unitText WRITE setUnitText) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double minimum READ minimum WRITE setMinimum) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double maximum READ maximum WRITE setMaximum) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double singleStep READ singleStep WRITE setSingleStep) // clazy:exclude=qproperty-without-notify Q_PROPERTY(double rawValue READ rawValue WRITE setValue NOTIFY valueChanged) Q_PROPERTY(Base::Quantity value READ value WRITE setValue NOTIFY valueChanged USER true) - Q_PROPERTY(QString binding READ boundToName WRITE setBoundToByName) - Q_PROPERTY(QString expression READ expressionText) + Q_PROPERTY(QString binding READ boundToName WRITE setBoundToByName) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QString expression READ expressionText) // clazy:exclude=qproperty-without-notify public: explicit QuantitySpinBox(QWidget *parent = nullptr); - virtual ~QuantitySpinBox(); + ~QuantitySpinBox() override; /// Get the current quantity Base::Quantity value() const; @@ -72,7 +72,7 @@ public: /// Set the unit property void setUnitText(const QString&); /// Get the unit property - QString unitText(void); + QString unitText(); /// Get the value of the singleStep property double singleStep() const; @@ -116,20 +116,20 @@ public: Base::Quantity valueFromText(const QString &text) const; QString textFromValue(const Base::Quantity& val) const; - virtual void stepBy(int steps); - virtual void clear(); - virtual QValidator::State validate(QString &input, int &pos) const; - virtual void fixup(QString &str) const; + void stepBy(int steps) override; + void clear() override; + QValidator::State validate(QString &input, int &pos) const override; + void fixup(QString &str) const override; /// This is a helper function to determine the size this widget requires to fully display the text QSize sizeForText(const QString&) const; - QSize sizeHint() const; - QSize minimumSizeHint() const; - bool event(QEvent *event); + QSize sizeHint() const override; + QSize minimumSizeHint() const override; + bool event(QEvent *event) override; - void setNumberExpression(App::NumberExpression*); - void bind(const App::ObjectIdentifier &_path); - bool apply(const std::string &propName); + void setNumberExpression(App::NumberExpression*) override; + void bind(const App::ObjectIdentifier &_path) override; + bool apply(const std::string &propName) override; using ExpressionSpinBox::apply; public Q_SLOTS: @@ -143,17 +143,17 @@ protected Q_SLOTS: void handlePendingEmit(bool updateUnit = true); protected: - virtual void setExpression(std::shared_ptr expr); - virtual void openFormulaDialog(); - virtual StepEnabled stepEnabled() const; - virtual void showEvent(QShowEvent * event); - virtual void hideEvent(QHideEvent * event); - virtual void closeEvent(QCloseEvent * event); - virtual void focusInEvent(QFocusEvent * event); - virtual void focusOutEvent(QFocusEvent * event); - virtual void keyPressEvent(QKeyEvent *event); - virtual void resizeEvent(QResizeEvent *event); - virtual void paintEvent(QPaintEvent *event); + void setExpression(std::shared_ptr expr) override; + void openFormulaDialog() override; + StepEnabled stepEnabled() const override; + void showEvent(QShowEvent * event) override; + void hideEvent(QHideEvent * event) override; + void closeEvent(QCloseEvent * event) override; + void focusInEvent(QFocusEvent * event) override; + void focusOutEvent(QFocusEvent * event) override; + void keyPressEvent(QKeyEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void paintEvent(QPaintEvent *event) override; private: void validateInput(); diff --git a/src/Gui/QuantitySpinBox_p.h b/src/Gui/QuantitySpinBox_p.h index 3b1c7aa5e8..ec475a30e4 100644 --- a/src/Gui/QuantitySpinBox_p.h +++ b/src/Gui/QuantitySpinBox_p.h @@ -40,7 +40,7 @@ public: } protected: - void mouseReleaseEvent(QMouseEvent * event) { + void mouseReleaseEvent(QMouseEvent * event) override { if (rect().contains(event->pos())) Q_EMIT clicked(); } diff --git a/src/Gui/Quarter/DragDropHandler.cpp b/src/Gui/Quarter/DragDropHandler.cpp index f8b957c42b..b75c57f2b0 100644 --- a/src/Gui/Quarter/DragDropHandler.cpp +++ b/src/Gui/Quarter/DragDropHandler.cpp @@ -119,7 +119,7 @@ DragDropHandlerP::dragEnterEvent(QDragEnterEvent * event) return; if (mimedata->hasUrls()) { - QFileInfo fileinfo(mimedata->urls().takeFirst().path()); + QFileInfo fileinfo(mimedata->urls().constFirst().path()); QString suffix = fileinfo.suffix().toLower(); if (!this->suffixes.contains(suffix)) { return; @@ -139,7 +139,7 @@ DragDropHandlerP::dropEvent(QDropEvent * event) QByteArray bytes; if (mimedata->hasUrls()) { - QUrl url = mimedata->urls().takeFirst(); + QUrl url = mimedata->urls().constFirst(); if (url.scheme().isEmpty() || url.scheme().toLower() == QString("file") ) { // attempt to open file if (!in.openFile(url.toLocalFile().toLatin1().constData())) @@ -155,7 +155,7 @@ DragDropHandlerP::dropEvent(QDropEvent * event) // attempt to import it root = SoDB::readAll(&in); - if (root == nullptr) + if (!root) return; // set new scenegraph diff --git a/src/Gui/Quarter/KeyboardP.cpp b/src/Gui/Quarter/KeyboardP.cpp index 4a8c028c8c..b73e81c414 100644 --- a/src/Gui/Quarter/KeyboardP.cpp +++ b/src/Gui/Quarter/KeyboardP.cpp @@ -45,7 +45,7 @@ KeyboardP::KeyboardP(Keyboard * publ) PUBLIC(this) = publ; this->keyboard = new SoKeyboardEvent; - if (keyboardmap == nullptr) { + if (!keyboardmap) { keyboardmap = new KeyMap; keypadmap = new KeyMap; this->initKeyMap(); @@ -235,15 +235,6 @@ KeyboardP::initKeyMap() keypadmap->insert(Qt::Key_Delete, SoKeyboardEvent::PAD_DELETE); keypadmap->insert(Qt::Key_Period, SoKeyboardEvent::PAD_PERIOD); - -#if 0 // FIXME: don't know what to do with these (20070306 frodo) - keyboardmap->insert(Qt::, SoKeyboardEvent::RIGHT_SHIFT); - keyboardmap->insert(Qt::, SoKeyboardEvent::RIGHT_CONTROL); - keyboardmap->insert(Qt::, SoKeyboardEvent::RIGHT_ALT); - keyboardmap->insert(Qt::, SoKeyboardEvent::PRIOR); - keyboardmap->insert(Qt::, SoKeyboardEvent::NEXT); - keyboardmap->insert(Qt::, SoKeyboardEvent::SHIFT_LOCK); -#endif } #undef PUBLIC diff --git a/src/Gui/Quarter/QuarterP.cpp b/src/Gui/Quarter/QuarterP.cpp index 2cd533006b..98a99b751a 100644 --- a/src/Gui/Quarter/QuarterP.cpp +++ b/src/Gui/Quarter/QuarterP.cpp @@ -43,7 +43,7 @@ QuarterP::QuarterP() { this->sensormanager = new SensorManager; this->imagereader = new ImageReader; - assert(QuarterP::statecursormap == nullptr); + assert(!QuarterP::statecursormap); QuarterP::statecursormap = new StateCursorMap; } @@ -53,11 +53,11 @@ QuarterP::~QuarterP() delete this->imagereader; delete this->sensormanager; - assert(QuarterP::statecursormap != nullptr); + assert(QuarterP::statecursormap); delete QuarterP::statecursormap; // FIXME: Why not use an atexit mechanism for this? - if (KeyboardP::keyboardmap != nullptr) { + if (KeyboardP::keyboardmap) { KeyboardP::keyboardmap->clear(); KeyboardP::keypadmap->clear(); delete KeyboardP::keyboardmap; diff --git a/src/Gui/Quarter/QuarterWidget.cpp b/src/Gui/Quarter/QuarterWidget.cpp index 5e1f89e04d..fb00de28c5 100644 --- a/src/Gui/Quarter/QuarterWidget.cpp +++ b/src/Gui/Quarter/QuarterWidget.cpp @@ -681,10 +681,10 @@ QuarterWidget::setSoRenderManager(SoRenderManager * manager) SoNode * scene = nullptr; SoCamera * camera = nullptr; SbViewportRegion vp; - if (PRIVATE(this)->sorendermanager && (manager != nullptr)) { + if (PRIVATE(this)->sorendermanager && manager) { scene = PRIVATE(this)->sorendermanager->getSceneGraph(); camera = PRIVATE(this)->sorendermanager->getCamera(); - vp = PRIVATE(this)->sorendermanager->getViewportRegion(); + vp = PRIVATE(this)->sorendermanager->getViewportRegion(); // clazy:exclude=rule-of-two-soft carrydata = true; } @@ -726,10 +726,10 @@ QuarterWidget::setSoEventManager(SoEventManager * manager) SoNode * scene = nullptr; SoCamera * camera = nullptr; SbViewportRegion vp; - if (PRIVATE(this)->soeventmanager && (manager != nullptr)) { + if (PRIVATE(this)->soeventmanager && manager) { scene = PRIVATE(this)->soeventmanager->getSceneGraph(); camera = PRIVATE(this)->soeventmanager->getCamera(); - vp = PRIVATE(this)->soeventmanager->getViewportRegion(); + vp = PRIVATE(this)->soeventmanager->getViewportRegion(); // clazy:exclude=rule-of-two-soft carrydata = true; } @@ -924,31 +924,7 @@ void QuarterWidget::paintEvent(QPaintEvent* event) bool QuarterWidget::viewportEvent(QEvent* event) { - // Disable the old implementation of this method as it show - // problems with panning and rotations when a widget item is - // added to the scene. -#if 0 - if (event->type() == QEvent::Paint || event->type() == QEvent::Resize) { - return QGraphicsView::viewportEvent(event); - } - else if (event->type() == QEvent::MouseMove || - event->type() == QEvent::Wheel || - event->type() == QEvent::MouseButtonDblClick || - event->type() == QEvent::MouseButtonRelease || - event->type() == QEvent::MouseButtonPress) { - QMouseEvent* mouse = static_cast(event); - QGraphicsItem *item = itemAt(mouse->pos()); - if (!item) { - return false; - } - return QGraphicsView::viewportEvent(event); - } - - //if we return false the events get processed normally, this means they get passed to the quarter - //event filters for processing in the scene graph. If we return true event processing stops here. - return false; -#else // If no item is selected still let the graphics scene handle it but // additionally handle it by this viewer. This is e.g. needed when // resizing a widget item because the cursor may already be outside @@ -973,7 +949,6 @@ bool QuarterWidget::viewportEvent(QEvent* event) } return QGraphicsView::viewportEvent(event); -#endif } /*! @@ -1217,19 +1192,13 @@ QuarterWidget::setNavigationModeFile(const QUrl & url) if (url.scheme()=="coin") { filename = url.path(); - //FIXME: This conditional needs to be implemented when the - //CoinResources systems if working -#if 0 - //#if (COIN_MAJOR_VERSION==3) && (COIN_MINOR_VERSION==0) -#endif + //Workaround for differences between url scheme, and Coin internal //scheme in Coin 3.0. if (filename[0]=='/') { filename.remove(0,1); } -#if 0 - //#endif -#endif + filename = url.scheme()+':'+filename; } else if (url.scheme()=="file") diff --git a/src/Gui/Quarter/QuarterWidget.h b/src/Gui/Quarter/QuarterWidget.h index 2d777ae4e0..f1d7f586cc 100644 --- a/src/Gui/Quarter/QuarterWidget.h +++ b/src/Gui/Quarter/QuarterWidget.h @@ -4,22 +4,22 @@ /**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: - * + * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -62,31 +62,7 @@ class QUARTER_DLL_API QuarterWidget : public QGraphicsView { typedef QGraphicsView inherited; Q_OBJECT - Q_PROPERTY(QUrl navigationModeFile READ navigationModeFile WRITE setNavigationModeFile RESET resetNavigationModeFile) - Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) - Q_PROPERTY(bool contextMenuEnabled READ contextMenuEnabled WRITE setContextMenuEnabled) - Q_PROPERTY(bool headlightEnabled READ headlightEnabled WRITE setHeadlightEnabled) - Q_PROPERTY(bool clearZBuffer READ clearZBuffer WRITE setClearZBuffer) - Q_PROPERTY(bool clearWindow READ clearWindow WRITE setClearWindow) - Q_PROPERTY(bool interactionModeEnabled READ interactionModeEnabled WRITE setInteractionModeEnabled) - Q_PROPERTY(bool interactionModeOn READ interactionModeOn WRITE setInteractionModeOn) - - Q_PROPERTY(TransparencyType transparencyType READ transparencyType WRITE setTransparencyType) - Q_PROPERTY(RenderMode renderMode READ renderMode WRITE setRenderMode) - Q_PROPERTY(StereoMode stereoMode READ stereoMode WRITE setStereoMode) - Q_PROPERTY(qreal devicePixelRatio READ devicePixelRatio NOTIFY devicePixelRatioChanged) - - Q_ENUMS(TransparencyType) - Q_ENUMS(RenderMode) - Q_ENUMS(StereoMode) - - public: - explicit QuarterWidget(QWidget * parent = nullptr, const QtGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - explicit QuarterWidget(QtGLContext * context, QWidget * parent = nullptr, const QtGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - explicit QuarterWidget(const QtGLFormat & format, QWidget * parent = nullptr, const QtGLWidget * shareWidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - virtual ~QuarterWidget(); - enum TransparencyType { SCREEN_DOOR = SoGLRenderAction::SCREEN_DOOR, ADD = SoGLRenderAction::ADD, @@ -118,6 +94,31 @@ public: INTERLEAVED_COLUMNS = SoRenderManager::INTERLEAVED_COLUMNS }; + Q_PROPERTY(QUrl navigationModeFile READ navigationModeFile WRITE setNavigationModeFile RESET resetNavigationModeFile) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool contextMenuEnabled READ contextMenuEnabled WRITE setContextMenuEnabled) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool headlightEnabled READ headlightEnabled WRITE setHeadlightEnabled) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool clearZBuffer READ clearZBuffer WRITE setClearZBuffer) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool clearWindow READ clearWindow WRITE setClearWindow) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool interactionModeEnabled READ interactionModeEnabled WRITE setInteractionModeEnabled) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(bool interactionModeOn READ interactionModeOn WRITE setInteractionModeOn) // clazy:exclude=qproperty-without-notify + + Q_PROPERTY(TransparencyType transparencyType READ transparencyType WRITE setTransparencyType) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(RenderMode renderMode READ renderMode WRITE setRenderMode) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(StereoMode stereoMode READ stereoMode WRITE setStereoMode) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(qreal devicePixelRatio READ devicePixelRatio NOTIFY devicePixelRatioChanged) + + Q_ENUM(TransparencyType) + Q_ENUM(RenderMode) + Q_ENUM(StereoMode) + + +public: + explicit QuarterWidget(QWidget * parent = nullptr, const QtGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + explicit QuarterWidget(QtGLContext * context, QWidget * parent = nullptr, const QtGLWidget * sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + explicit QuarterWidget(const QtGLFormat & format, QWidget * parent = nullptr, const QtGLWidget * shareWidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + virtual ~QuarterWidget(); + TransparencyType transparencyType() const; RenderMode renderMode() const; StereoMode stereoMode() const; @@ -183,9 +184,9 @@ public Q_SLOTS: void redraw(); - void setRenderMode(RenderMode mode); - void setStereoMode(StereoMode mode); - void setTransparencyType(TransparencyType type); + void setRenderMode(SIM::Coin3D::Quarter::QuarterWidget::RenderMode mode); + void setStereoMode(SIM::Coin3D::Quarter::QuarterWidget::StereoMode mode); + void setTransparencyType(SIM::Coin3D::Quarter::QuarterWidget::TransparencyType type); Q_SIGNALS: void devicePixelRatioChanged(qreal dev_pixel_ratio); diff --git a/src/Gui/Quarter/QuarterWidgetP.cpp b/src/Gui/Quarter/QuarterWidgetP.cpp index ea59fc0fb2..c7031c4452 100644 --- a/src/Gui/Quarter/QuarterWidgetP.cpp +++ b/src/Gui/Quarter/QuarterWidgetP.cpp @@ -136,7 +136,7 @@ QuarterWidgetP::getCacheContextId() const QuarterWidgetP_cachecontext * QuarterWidgetP::findCacheContext(QuarterWidget * widget, const QtGLWidget * sharewidget) { - if (cachecontext_list == nullptr) { + if (!cachecontext_list) { // FIXME: static memory leak cachecontext_list = new SbList ; } diff --git a/src/Gui/Quarter/SoQTQuarterAdaptor.cpp b/src/Gui/Quarter/SoQTQuarterAdaptor.cpp index c86ae53314..c016a6aa88 100644 --- a/src/Gui/Quarter/SoQTQuarterAdaptor.cpp +++ b/src/Gui/Quarter/SoQTQuarterAdaptor.cpp @@ -318,10 +318,10 @@ void SIM::Coin3D::Quarter::SoQTQuarterAdaptor::setViewing(SbBool enable) // Turn off the selection indicators when we go back from picking // mode into viewing mode. - if(m_viewingflag) { + if (m_viewingflag) { SoGLRenderAction* action = getSoRenderManager()->getGLRenderAction(); - if(action != nullptr) + if (action) SoLocateHighlight::turnOffCurrentHighlight(action); } } @@ -756,3 +756,5 @@ SbVec2f SIM::Coin3D::Quarter::SoQTQuarterAdaptor::addFrametime(double starttime) this->starttime = timeofday; return SbVec2f(1000 * this->drawtime, 1.0f / this->frametime); } + +#include "moc_SoQTQuarterAdaptor.cpp" diff --git a/src/Gui/Quarter/SoQTQuarterAdaptor.h b/src/Gui/Quarter/SoQTQuarterAdaptor.h index 4536430de4..1b5021ba8d 100644 --- a/src/Gui/Quarter/SoQTQuarterAdaptor.h +++ b/src/Gui/Quarter/SoQTQuarterAdaptor.h @@ -44,6 +44,8 @@ typedef void SoQTQuarterAdaptorCB(void* data, SoQTQuarterAdaptor* viewer); class QUARTER_DLL_API SoQTQuarterAdaptor : public QuarterWidget { + Q_OBJECT + public: explicit SoQTQuarterAdaptor(QWidget* parent = nullptr, const QtGLWidget* sharewidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); explicit SoQTQuarterAdaptor(const QtGLFormat& format, QWidget* parent = nullptr, const QtGLWidget* shareWidget = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); diff --git a/src/Gui/ReportView.cpp b/src/Gui/ReportView.cpp index 0c56c300e9..82a8dfc1b5 100644 --- a/src/Gui/ReportView.cpp +++ b/src/Gui/ReportView.cpp @@ -270,7 +270,7 @@ public: CustomReportEvent(ReportHighlighter::Paragraph p, const QString& s) : QEvent(QEvent::Type(QEvent::User)) { par = p; msg = s;} - ~CustomReportEvent() + ~CustomReportEvent() override { } const QString& message() const { return msg; } diff --git a/src/Gui/ReportView.h b/src/Gui/ReportView.h index 54187b253c..ff6989fe3c 100644 --- a/src/Gui/ReportView.h +++ b/src/Gui/ReportView.h @@ -51,11 +51,11 @@ class ReportView : public QWidget Q_OBJECT public: - ReportView( QWidget* parent = nullptr); - ~ReportView(); + explicit ReportView( QWidget* parent = nullptr); + ~ReportView() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: QTabWidget* tabWidget; @@ -77,11 +77,11 @@ public: }; public: - ReportHighlighter(QTextEdit* ); - ~ReportHighlighter(); + explicit ReportHighlighter(QTextEdit* ); + ~ReportHighlighter() override; /** Parses the given text and highlight it in the right colors. */ - void highlightBlock ( const QString & text ); + void highlightBlock ( const QString & text ) override; /** * Sets the current paragraph type used in ReportOutput * @see ReportOutput::Message @@ -128,8 +128,8 @@ class GuiExport ReportOutput : public QTextEdit, public WindowParameter, public Q_OBJECT public: - ReportOutput(QWidget* parent=nullptr); - virtual ~ReportOutput(); + explicit ReportOutput(QWidget* parent=nullptr); + ~ReportOutput() override; /** Observes its parameter group. */ void OnChange(Base::Subject &rCaller, const char * sReason) override; @@ -137,7 +137,7 @@ public: void SendLog(const std::string& msg, Base::LogStyle level) override; /// returns the name for observer handling - const char* Name(void) override {return "ReportOutput";} + const char* Name() override {return "ReportOutput";} /** Restore the default font settings. */ void restoreFont (); @@ -207,12 +207,12 @@ class ReportOutputObserver : public QObject Q_OBJECT public: - ReportOutputObserver (ReportOutput* view); - bool eventFilter(QObject *obj, QEvent *event); + explicit ReportOutputObserver (ReportOutput* view); + bool eventFilter(QObject *obj, QEvent *event) override; protected: QPointer reportView; - void showReportView(void); + void showReportView(); }; } // namespace DockWnd diff --git a/src/Gui/SceneInspector.h b/src/Gui/SceneInspector.h index 2fb933b4c3..8857cc3b16 100644 --- a/src/Gui/SceneInspector.h +++ b/src/Gui/SceneInspector.h @@ -42,23 +42,23 @@ class SceneModel : public QStandardItemModel public: SceneModel(QObject* parent); - virtual ~SceneModel(); + ~SceneModel() override; /// Tree structure: column count is 1. - int columnCount (const QModelIndex & parent = QModelIndex()) const; + int columnCount (const QModelIndex & parent = QModelIndex()) const override; /** returns empty QVariant, unless orientation == Qt::Horizontal, * role == Qt::DisplayRole and section == 0 where it returns * "Inventor Tree" */ - QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; /// header data not used: returns false - bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole); + bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole) override; /// insert the first node in tree void setNode(SoNode* node); /// set names per node void setNodeNames(const QHash& names); /// returns standard parent's flags - Qt::ItemFlags flags (const QModelIndex & index) const; + Qt::ItemFlags flags (const QModelIndex & index) const override; private: void setNode(QModelIndex, SoNode*); @@ -72,7 +72,7 @@ class DlgInspector : public QDialog public: DlgInspector(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgInspector(); + ~DlgInspector() override; void setDocument(Gui::Document* doc); @@ -80,7 +80,7 @@ private Q_SLOTS: void on_refreshButton_clicked(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void setNode(SoNode* node); void setNodeNames(Gui::Document*); diff --git a/src/Gui/Selection.cpp b/src/Gui/Selection.cpp index 5c35241465..ec45a76e80 100644 --- a/src/Gui/Selection.cpp +++ b/src/Gui/Selection.cpp @@ -68,9 +68,9 @@ SelectionGateFilterExternal::SelectionGateFilterExternal(const char *docName, co bool SelectionGateFilterExternal::allow(App::Document *doc ,App::DocumentObject *obj, const char*) { if(!doc || !obj) return true; - if(DocName.size() && doc->getName()!=DocName) + if(!DocName.empty() && doc->getName()!=DocName) notAllowedReason = "Cannot select external object"; - else if(ObjName.size() && ObjName==obj->getNameInDocument()) + else if(!ObjName.empty() && ObjName==obj->getNameInDocument()) notAllowedReason = "Cannot select self"; else return true; @@ -133,7 +133,7 @@ void SelectionObserver::attachSelection() connectSelection = signal.connect(boost::bind (&SelectionObserver::_onSelectionChanged, this, bp::_1)); - if (filterDocName.size()) { + if (!filterDocName.empty()) { Selection().addSelectionGate( new SelectionGateFilterExternal(filterDocName.c_str(),filterObjName.c_str())); } @@ -159,7 +159,7 @@ void SelectionObserver::detachSelection() { if (connectSelection.connected()) { connectSelection.disconnect(); - if (filterDocName.size()) + if (!filterDocName.empty()) Selection().rmvSelectionGate(); } } @@ -397,7 +397,7 @@ std::vector SelectionSingleton::getSelection(const c if (resolve != ResolveMode::NoResolve && !objMap[obj].insert(std::string(subelement ? subelement : "")).second) continue; - if (single && temp.size()) { + if (single && !temp.empty()) { temp.clear(); break; } @@ -536,19 +536,19 @@ std::vector SelectionSingleton::getObjectList(const char* pDocN if (subelement && *subelement) { if (resolve != ResolveMode::NoResolve && !temp[it->second]._SubNameSet.insert(subelement).second) continue; - temp[it->second].SubNames.push_back(subelement); + temp[it->second].SubNames.emplace_back(subelement); temp[it->second].SelPoses.emplace_back(sel.x,sel.y,sel.z); } } else { - if (single && temp.size()) { + if (single && !temp.empty()) { temp.clear(); break; } // create a new entry temp.emplace_back(obj); if (subelement && *subelement) { - temp.back().SubNames.push_back(subelement); + temp.back().SubNames.emplace_back(subelement); temp.back().SelPoses.emplace_back(sel.x,sel.y,sel.z); if (resolve != ResolveMode::NoResolve) temp.back()._SubNameSet.insert(subelement); @@ -582,7 +582,7 @@ void SelectionSingleton::notify(SelectionChanges &&Chng) } Base::FlagToggler flag(Notifying); NotificationQueue.push_back(std::move(Chng)); - while(NotificationQueue.size()) { + while(!NotificationQueue.empty()) { const auto &msg = NotificationQueue.front(); bool notify; switch(msg.Type) { @@ -618,7 +618,7 @@ void SelectionSingleton::notify(SelectionChanges &&Chng) bool SelectionSingleton::hasPickedList() const { - return _PickedList.size(); + return !_PickedList.empty(); } int SelectionSingleton::getAsPropertyLinkSubList(App::PropertyLinkSubList &prop) const @@ -632,7 +632,7 @@ int SelectionSingleton::getAsPropertyLinkSubList(App::PropertyLinkSubList &prop) const std::vector &subnames = selitem.getSubNames(); //whole object is selected - if (subnames.size() == 0){ + if (subnames.empty()){ objs.push_back(obj); subs.emplace_back(); } @@ -657,7 +657,7 @@ App::DocumentObject *SelectionSingleton::getObjectOfType(_SelObj &sel, Base::Typ const char *subname = sel.SubName.c_str(); if (resolve != ResolveMode::NoResolve) { obj = sel.pResolvedObject; - if (resolve == ResolveMode::NewStyleElement && sel.elementName.first.size()) + if (resolve == ResolveMode::NewStyleElement && !sel.elementName.first.empty()) subname = sel.elementName.first.c_str(); else subname = sel.elementName.second.c_str(); @@ -742,7 +742,7 @@ void SelectionSingleton::slotSelectionChanged(const SelectionChanges& msg) msg.Type == SelectionChanges::HideSelection) return; - if(msg.Object.getSubName().size()) { + if(!msg.Object.getSubName().empty()) { auto pParent = msg.Object.getObject(); if(!pParent) return; @@ -754,7 +754,7 @@ void SelectionSingleton::slotSelectionChanged(const SelectionChanges& msg) return; SelectionChanges msg2(msg.Type,pObject->getDocument()->getName(), pObject->getNameInDocument(), - newElementName.size()?newElementName.c_str():oldElementName.c_str(), + !newElementName.empty()?newElementName.c_str():oldElementName.c_str(), pObject->getTypeId().getName(), msg.x,msg.y,msg.z); try { @@ -792,18 +792,6 @@ int SelectionSingleton::setPreselect(const char* pDocName, const char* pObjectNa if (!pSubName) pSubName = ""; if (DocName==pDocName && FeatName==pObjectName && SubName==pSubName) { - // MovePreselect is likely going to slow down large scene rendering. - // Disable it for now. -#if 0 - if(hx!=x || hy!=y || hz!=z) { - hx = x; - hy = y; - hz = z; - SelectionChanges Chng(SelectionChanges::MovePreselect, - DocName,FeatName,SubName,std::string(),x,y,z); - notify(Chng); - } -#endif return -1; } @@ -826,7 +814,7 @@ int SelectionSingleton::setPreselect(const char* pDocName, const char* pObjectNa if (!pObject) return 0; if (gateResolve > ResolveMode::OldStyleElement) - subelement = newElementName.size() ? newElementName.c_str() : oldElementName.c_str(); + subelement = !newElementName.empty() ? newElementName.c_str() : oldElementName.c_str(); else subelement = oldElementName.c_str(); } @@ -876,7 +864,7 @@ int SelectionSingleton::setPreselect(const char* pDocName, const char* pObjectNa notify(Chng); - if (signal == SelectionChanges::MsgSource::Internal && DocName.size()) { + if (signal == SelectionChanges::MsgSource::Internal && !DocName.empty()) { FC_TRACE("preselect "< tmpStack; _SelStackForward.swap(tmpStack); - while(_SelStackBack.size()) { + while(!_SelStackBack.empty()) { bool found = false; for(auto &sobjT : _SelStackBack.back()) { if(sobjT.getSubObject()) { @@ -1203,7 +1190,7 @@ void SelectionSingleton::selStackGoForward(int count) { count = _SelStackForward.size(); if(count<=0) return; - if(_SelList.size()) { + if(!_SelList.empty()) { selStackPush(false,true); clearCompleteSelection(); } @@ -1266,7 +1253,7 @@ std::vector SelectionSingleton::selStackGet(const char* pDocNam bool SelectionSingleton::addSelections(const char* pDocName, const char* pObjectName, const std::vector& pSubNames) { - if(_PickedList.size()) { + if(!_PickedList.empty()) { _PickedList.clear(); notify(SelectionChanges(SelectionChanges::PickedListChanged)); } @@ -1397,7 +1384,7 @@ void SelectionSingleton::rmvSelection(const char* pDocName, const char* pObjectN if(It->DocName!=temp.DocName || It->FeatName!=temp.FeatName) continue; // if no subname is specified, remove all subobjects of the matching object - if(temp.SubName.size()) { + if(!temp.SubName.empty()) { // otherwise, match subojects with common prefix, separated by '.' if(!boost::starts_with(It->SubName,temp.SubName) || (It->SubName.length()!=temp.SubName.length() && It->SubName[temp.SubName.length()-1]!='.')) @@ -1418,7 +1405,7 @@ void SelectionSingleton::rmvSelection(const char* pDocName, const char* pObjectN // as this can invalidate the iterators and thus leads to undefined // behaviour. // So, the notification is done after the loop, see also #0003469 - if(changes.size()) { + if(!changes.empty()) { for(auto &Chng : changes) { FC_LOG("Rmv Selection "<getNameInDocument(); sel.TypeName = sel.pObject->getTypeId().getName(); const char *element = nullptr; @@ -1697,7 +1684,7 @@ int SelectionSingleton::checkSelection(const char *pDocName, const char *pObject std::string prefix; if(pSubName && element) { prefix = std::string(pSubName, element-pSubName); - if(sel.elementName.first.size()) { + if(!sel.elementName.first.empty()) { // make sure the selected sub name is a new style if available subname = prefix + sel.elementName.first; pSubName = subname.c_str(); @@ -1724,7 +1711,7 @@ int SelectionSingleton::checkSelection(const char *pDocName, const char *pObject continue; if(!pSubName[0]) return 1; - if (s.elementName.first.size()) { + if (!s.elementName.first.empty()) { if (s.elementName.first == sel.elementName.first) return 1; } @@ -1773,7 +1760,7 @@ void SelectionSingleton::slotDeletedObject(const App::DocumentObject& Obj) _SelList.erase(it); } } - if(changes.size()) { + if(!changes.empty()) { for(auto &Chng : changes) { FC_LOG("Rmv Selection "<updateActions(); } - if(_PickedList.size()) { + if(!_PickedList.empty()) { bool changed = false; for(auto it=_PickedList.begin(),itNext=it;it!=_PickedList.end();it=itNext) { ++itNext; @@ -1829,16 +1816,16 @@ SelectionSingleton::~SelectionSingleton() SelectionSingleton* SelectionSingleton::_pcSingleton = nullptr; -SelectionSingleton& SelectionSingleton::instance(void) +SelectionSingleton& SelectionSingleton::instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) _pcSingleton = new SelectionSingleton; return *_pcSingleton; } -void SelectionSingleton::destruct (void) +void SelectionSingleton::destruct () { - if (_pcSingleton != nullptr) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } @@ -1899,7 +1886,7 @@ PyMethodDef SelectionSingleton::Methods[] = { "obj : App.DocumentObject\n Object to check.\n" "subName : str\n Name of the subelement.\n" "resolve : int\n Resolve subelement reference."}, - {"setPreselection", reinterpret_cast(reinterpret_cast( SelectionSingleton::sSetPreselection )), METH_VARARGS|METH_KEYWORDS, + {"setPreselection", reinterpret_cast(reinterpret_cast( SelectionSingleton::sSetPreselection )), METH_VARARGS|METH_KEYWORDS, "setPreselection(obj, subName, x=0, y=0, z=0, type=1) -> None\n" "\n" "Set preselected object.\n" @@ -2116,7 +2103,6 @@ PyObject *SelectionSingleton::sAddSelection(PyObject * /*self*/, PyObject *args) docObj->getNameInDocument(), subname.c_str(), 0, 0, 0, nullptr, Base::asBoolean(clearPreselect)); } - Py_Return; } } diff --git a/src/Gui/Selection.h b/src/Gui/Selection.h index 4400d16de4..0c2abdef16 100644 --- a/src/Gui/Selection.h +++ b/src/Gui/Selection.h @@ -102,9 +102,10 @@ public: pDocName = Object.getDocumentName().c_str(); pObjectName = Object.getObjectName().c_str(); pSubName = Object.getSubName().c_str(); - if(typeName) TypeName = typeName; + if (typeName) + TypeName = typeName; pTypeName = TypeName.c_str(); - } + }//explicit bombs SelectionChanges(MsgType type, const std::string &docName, @@ -229,7 +230,7 @@ public: * 1 resolve sub-object with old style element name * 2 resolve sub-object with new style element name */ - SelectionObserver(bool attach = true, ResolveMode resolve = ResolveMode::OldStyleElement); + explicit SelectionObserver(bool attach = true, ResolveMode resolve = ResolveMode::OldStyleElement); /** Constructor * * @param vp: filtering view object. @@ -242,7 +243,7 @@ public: * Constructs an selection observer that receives only selection event of * objects within the same document as the input view object. */ - SelectionObserver(const Gui::ViewProviderDocumentObject *vp, bool attach=true, ResolveMode resolve = ResolveMode::OldStyleElement); + explicit SelectionObserver(const Gui::ViewProviderDocumentObject *vp, bool attach=true, ResolveMode resolve = ResolveMode::OldStyleElement); virtual ~SelectionObserver(); bool blockSelection(bool block); @@ -279,14 +280,14 @@ class GuiExport SelectionObserverPython : public SelectionObserver public: /// Constructor - SelectionObserverPython(const Py::Object& obj, ResolveMode resolve = ResolveMode::OldStyleElement); - virtual ~SelectionObserverPython(); + explicit SelectionObserverPython(const Py::Object& obj, ResolveMode resolve = ResolveMode::OldStyleElement); + ~SelectionObserverPython() override; static void addObserver(const Py::Object& obj, ResolveMode resolve = ResolveMode::OldStyleElement); static void removeObserver(const Py::Object& obj); private: - void onSelectionChanged(const SelectionChanges& msg); + void onSelectionChanged(const SelectionChanges& msg) override; void addSelection(const SelectionChanges&); void removeSelection(const SelectionChanges&); void setSelection(const SelectionChanges&); @@ -341,8 +342,8 @@ public: class GuiExport SelectionGateFilterExternal: public SelectionGate { public: - SelectionGateFilterExternal(const char *docName, const char *objName=nullptr); - virtual bool allow(App::Document*,App::DocumentObject*, const char*) override; + explicit SelectionGateFilterExternal(const char *docName, const char *objName=nullptr); + bool allow(App::Document*,App::DocumentObject*, const char*) override; private: std::string DocName; std::string ObjName; @@ -418,11 +419,11 @@ public: /// sets different coords for the preselection void setPreselectCoord(float x, float y, float z); /// returns the present preselection - const SelectionChanges& getPreselection(void) const; + const SelectionChanges& getPreselection() const; /// add a SelectionGate to control what is selectable void addSelectionGate(Gui::SelectionGate *gate, ResolveMode resolve = ResolveMode::OldStyleElement); /// remove the active SelectionGate - void rmvSelectionGate(void); + void rmvSelectionGate(); int disableCommandLog(); int enableCommandLog(bool silent=false); @@ -567,7 +568,7 @@ public: bool hasPreselection() const; /// Size of selected entities for all documents - unsigned int size(void) const { + unsigned int size() const { return static_cast(_SelList.size()); } @@ -642,8 +643,8 @@ public: const char* pDocName=nullptr, Base::Type typeId=App::DocumentObject::getClassTypeId()) const; //@} - static SelectionSingleton& instance(void); - static void destruct (void); + static SelectionSingleton& instance(); + static void destruct (); friend class SelectionFilter; // Python interface @@ -680,7 +681,7 @@ protected: /// Construction SelectionSingleton(); /// Destruction - virtual ~SelectionSingleton(); + ~SelectionSingleton() override; /// Observer message from the App doc void slotDeletedObject(const App::DocumentObject&); @@ -761,7 +762,7 @@ inline std::vector SelectionSingleton::getObjectsOfType(const char* pDocName } /// Get the global instance -inline SelectionSingleton& Selection(void) +inline SelectionSingleton& Selection() { return SelectionSingleton::instance(); } @@ -770,7 +771,7 @@ inline SelectionSingleton& Selection(void) */ class GuiExport SelectionLogDisabler { public: - SelectionLogDisabler(bool silent=false) :silent(silent) { + explicit SelectionLogDisabler(bool silent=false) :silent(silent) { Selection().disableCommandLog(); } ~SelectionLogDisabler() { diff --git a/src/Gui/SelectionFilter.cpp b/src/Gui/SelectionFilter.cpp index 5a43c0b1d0..fc4e3b4bdc 100644 --- a/src/Gui/SelectionFilter.cpp +++ b/src/Gui/SelectionFilter.cpp @@ -161,7 +161,7 @@ SelectionFilter::~SelectionFilter() { } -bool SelectionFilter::match(void) +bool SelectionFilter::match() { if (!Ast) return false; @@ -386,7 +386,7 @@ public: // show the parser the lexer method #define yylex SelectionFilterlex -int SelectionFilterlex(void); +int SelectionFilterlex(); // Parser, defined in SelectionFilter.y #include "SelectionFilter.tab.c" @@ -410,7 +410,7 @@ int SelectionFilterlex(void); #endif // DOXYGEN_SHOULD_SKIP_THIS } -bool SelectionFilter::parse(void) +bool SelectionFilter::parse() { Errors = ""; SelectionParser::YY_BUFFER_STATE my_string_buffer = SelectionParser::SelectionFilter_scan_string (Filter.c_str()); diff --git a/src/Gui/SelectionFilter.h b/src/Gui/SelectionFilter.h index aff05b6715..69b5208f27 100644 --- a/src/Gui/SelectionFilter.h +++ b/src/Gui/SelectionFilter.h @@ -52,8 +52,8 @@ class GuiExport SelectionFilter public: /** Constructs a SelectionFilter object. */ - SelectionFilter(const char* filter); - SelectionFilter(const std::string& filter); + explicit SelectionFilter(const char* filter); + explicit SelectionFilter(const std::string& filter); virtual ~SelectionFilter(); /// Set a new filter string @@ -66,7 +66,7 @@ public: * against the filter and returns true if the * described object(s) are selected. */ - bool match(void); + bool match(); /** Test objects * This method tests if a given object is described in the * filter. If SubName is not NULL the Subelement gets also @@ -81,12 +81,12 @@ public: std::vector > Result; /// true if a valid filter is set - bool isValid(void) const {return Ast ? true : false;} + bool isValid() const {return Ast ? true : false;} protected: std::string Filter; std::string Errors; - bool parse(void); + bool parse(); std::shared_ptr Ast; }; @@ -103,10 +103,10 @@ class GuiExport SelectionFilterGate: public SelectionGate { public: /// construct with the filter string - SelectionFilterGate(const char* filter); - SelectionFilterGate(SelectionFilter* filter); - ~SelectionFilterGate(); - virtual bool allow(App::Document*,App::DocumentObject*, const char*); + explicit SelectionFilterGate(const char* filter); + explicit SelectionFilterGate(SelectionFilter* filter); + ~SelectionFilterGate() override; + bool allow(App::Document*,App::DocumentObject*, const char*) override; protected: static SelectionFilter* nullPointer() { @@ -130,10 +130,10 @@ class SelectionGatePython : public SelectionGate { public: /// Constructor - SelectionGatePython(const Py::Object& obj); - virtual ~SelectionGatePython(); + explicit SelectionGatePython(const Py::Object& obj); + ~SelectionGatePython() override; - bool allow(App::Document*, App::DocumentObject*, const char*); + bool allow(App::Document*, App::DocumentObject*, const char*) override; private: Py::Object gate; @@ -154,12 +154,12 @@ public: SelectionFilter filter; public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods - SelectionFilterPy(const std::string&); - ~SelectionFilterPy(); + explicit SelectionFilterPy(const std::string&); + ~SelectionFilterPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object match(const Py::Tuple&); Py::Object result(const Py::Tuple&); Py::Object test(const Py::Tuple&); @@ -189,10 +189,10 @@ class SelectionFilterGatePython : public SelectionGate { public: /// Constructor - SelectionFilterGatePython(SelectionFilterPy* obj); - virtual ~SelectionFilterGatePython(); + explicit SelectionFilterGatePython(SelectionFilterPy* obj); + ~SelectionFilterGatePython() override; - bool allow(App::Document*, App::DocumentObject*, const char*); + bool allow(App::Document*, App::DocumentObject*, const char*) override; private: SelectionFilterPy* filter; @@ -202,7 +202,7 @@ private: struct Node_Slice { - Node_Slice(int min=1,int max=INT_MAX):Min(min),Max(max){} + explicit Node_Slice(int min=1,int max=INT_MAX):Min(min),Max(max){} int Min,Max; }; @@ -229,7 +229,7 @@ typedef std::shared_ptr Node_ObjectPtr; struct Node_Block { - Node_Block(Node_Object* obj){ + explicit Node_Block(Node_Object* obj){ Objects.emplace_back(obj); } std::vector Objects; diff --git a/src/Gui/SelectionObject.cpp b/src/Gui/SelectionObject.cpp index df1287f272..2707dac1a1 100644 --- a/src/Gui/SelectionObject.cpp +++ b/src/Gui/SelectionObject.cpp @@ -50,7 +50,7 @@ SelectionObject::SelectionObject(const Gui::SelectionChanges& msg) DocName = msg.pDocName ? msg.pDocName : ""; TypeName = msg.pTypeName ? msg.pTypeName : ""; if (msg.pSubName) { - SubNames.push_back(msg.pSubName); + SubNames.emplace_back(msg.pSubName); SelPoses.emplace_back(msg.x, msg.y, msg.z); } } @@ -66,7 +66,7 @@ SelectionObject::~SelectionObject() { } -const App::DocumentObject * SelectionObject::getObject(void) const +const App::DocumentObject * SelectionObject::getObject() const { if (!DocName.empty()) { App::Document *doc = App::GetApplication().getDocument(DocName.c_str()); @@ -76,7 +76,7 @@ const App::DocumentObject * SelectionObject::getObject(void) const return nullptr; } -App::DocumentObject * SelectionObject::getObject(void) +App::DocumentObject * SelectionObject::getObject() { if (!DocName.empty()) { App::Document *doc = App::GetApplication().getDocument(DocName.c_str()); @@ -92,7 +92,7 @@ bool SelectionObject::isObjectTypeOf(const Base::Type& typeId) const return (obj && obj->getTypeId().isDerivedFrom(typeId)); } -std::string SelectionObject::getAsPropertyLinkSubString(void)const +std::string SelectionObject::getAsPropertyLinkSubString()const { std::ostringstream str; str << "(" << Gui::Command::getObjectCmd(getObject()) << ",["; diff --git a/src/Gui/SelectionObject.h b/src/Gui/SelectionObject.h index bf5701886d..44e8e3b6bb 100644 --- a/src/Gui/SelectionObject.h +++ b/src/Gui/SelectionObject.h @@ -26,6 +26,7 @@ #include #include +#include #include namespace App { @@ -41,44 +42,44 @@ class SelectionChanges; */ class GuiExport SelectionObject : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** Constructs a SelectionObject object. */ SelectionObject(); /*! Constructs a SelectionObject from the SelectionChanges structure. */ - SelectionObject(const SelectionChanges& msg); + explicit SelectionObject(const SelectionChanges& msg); explicit SelectionObject(App::DocumentObject*); - virtual ~SelectionObject(); + ~SelectionObject() override; /** * The default implementation returns an instance of @ref SelectionObjectPy. */ - PyObject* getPyObject(); + PyObject* getPyObject() override; /// get the SubElement name of this SelectionObject - inline const std::vector &getSubNames(void) const { return SubNames; } + inline const std::vector &getSubNames() const { return SubNames; } /// are there any SubNames selected - bool hasSubNames(void)const { return SubNames.size() != 0; } + bool hasSubNames()const { return !SubNames.empty(); } /// get the name of the Document of this SelctionObject - inline const char* getDocName(void) const { return DocName.c_str(); } + inline const char* getDocName() const { return DocName.c_str(); } /// get the name of the Document Object of this SelectionObject - inline const char* getFeatName(void) const { return FeatName.c_str(); } + inline const char* getFeatName() const { return FeatName.c_str(); } /// get the Type of the selected Object - inline const char* getTypeName(void) const { return TypeName.c_str(); } + inline const char* getTypeName() const { return TypeName.c_str(); } /// get the selection points - inline const std::vector getPickedPoints(void) const { return SelPoses; } + inline const std::vector getPickedPoints() const { return SelPoses; } /// returns the selected DocumentObject or NULL if the object is already deleted - const App::DocumentObject *getObject(void) const; + const App::DocumentObject *getObject() const; /// returns the selected DocumentObject or NULL if the object is already deleted - App::DocumentObject *getObject(void); + App::DocumentObject *getObject(); /// check the selected object is a special type or derived of bool isObjectTypeOf(const Base::Type& typeId) const; /// returns python expreasion sutably for assigning to a LinkSub property - std::string getAsPropertyLinkSubString(void) const; + std::string getAsPropertyLinkSubString() const; friend class SelectionSingleton; diff --git a/src/Gui/SelectionObjectPyImp.cpp b/src/Gui/SelectionObjectPyImp.cpp index cc6343da1a..d7efc14e92 100644 --- a/src/Gui/SelectionObjectPyImp.cpp +++ b/src/Gui/SelectionObjectPyImp.cpp @@ -38,7 +38,7 @@ using namespace Gui; // returns a string which represents the object e.g. when printed in python -std::string SelectionObjectPy::representation(void) const +std::string SelectionObjectPy::representation() const { return ""; } @@ -68,12 +68,12 @@ PyObject* SelectionObjectPy::isObjectTypeOf(PyObject * args) return Py_BuildValue("O", (ok ? Py_True : Py_False)); } -Py::String SelectionObjectPy::getObjectName(void) const +Py::String SelectionObjectPy::getObjectName() const { return Py::String(getSelectionObjectPtr()->getFeatName()); } -Py::Tuple SelectionObjectPy::getSubElementNames(void) const +Py::Tuple SelectionObjectPy::getSubElementNames() const { std::vector objs = getSelectionObjectPtr()->getSubNames(); @@ -85,22 +85,22 @@ Py::Tuple SelectionObjectPy::getSubElementNames(void) const return temp; } -Py::String SelectionObjectPy::getFullName(void) const +Py::String SelectionObjectPy::getFullName() const { return Py::String(getSelectionObjectPtr()->getAsPropertyLinkSubString()); } -Py::String SelectionObjectPy::getTypeName(void) const +Py::String SelectionObjectPy::getTypeName() const { return Py::String(getSelectionObjectPtr()->getTypeName()); } -Py::String SelectionObjectPy::getDocumentName(void) const +Py::String SelectionObjectPy::getDocumentName() const { return Py::String(getSelectionObjectPtr()->getDocName()); } -Py::Object SelectionObjectPy::getDocument(void) const +Py::Object SelectionObjectPy::getDocument() const { App::DocumentObject *obj = getSelectionObjectPtr()->getObject(); if (!obj) @@ -108,7 +108,7 @@ Py::Object SelectionObjectPy::getDocument(void) const return Py::Object(obj->getDocument()->getPyObject(), true); } -Py::Object SelectionObjectPy::getObject(void) const +Py::Object SelectionObjectPy::getObject() const { App::DocumentObject *obj = getSelectionObjectPtr()->getObject(); if (!obj) @@ -116,7 +116,7 @@ Py::Object SelectionObjectPy::getObject(void) const return Py::Object(obj->getPyObject(), true); } -Py::Tuple SelectionObjectPy::getSubObjects(void) const +Py::Tuple SelectionObjectPy::getSubObjects() const { App::DocumentObject *obj = getSelectionObjectPtr()->getObject(); if (!obj) @@ -140,12 +140,12 @@ Py::Tuple SelectionObjectPy::getSubObjects(void) const return temp; } -Py::Boolean SelectionObjectPy::getHasSubObjects(void) const +Py::Boolean SelectionObjectPy::getHasSubObjects() const { return Py::Boolean(getSelectionObjectPtr()->hasSubNames()); } -Py::Tuple SelectionObjectPy::getPickedPoints(void) const +Py::Tuple SelectionObjectPy::getPickedPoints() const { const std::vector& points = getSelectionObjectPtr()->getPickedPoints(); diff --git a/src/Gui/SelectionView.cpp b/src/Gui/SelectionView.cpp index 9b62ff34a5..b190fb7d87 100644 --- a/src/Gui/SelectionView.cpp +++ b/src/Gui/SelectionView.cpp @@ -177,7 +177,8 @@ void SelectionView::onSelectionChanged(const SelectionChanges &Reason) str << Reason.pDocName; str << "#"; // remove all items - for(auto item : selectionView->findItems(selObject,Qt::MatchStartsWith)) + const auto items = selectionView->findItems(selObject,Qt::MatchStartsWith); + for(auto item : items) delete item; } } @@ -306,7 +307,7 @@ void SelectionView::search(const QString& text) } } -void SelectionView::validateSearch(void) +void SelectionView::validateSearch() { if (!searchList.empty()) { App::Document* doc = App::GetApplication().getActiveDocument(); @@ -340,7 +341,7 @@ void SelectionView::select(QListWidgetItem* item) } } -void SelectionView::deselect(void) +void SelectionView::deselect() { QListWidgetItem *item = selectionView->currentItem(); if (!item) @@ -381,15 +382,15 @@ void SelectionView::toggleSelect(QListWidgetItem* item) if(Gui::Selection().isSelected(docname,objname,subname)) cmd = QString::fromLatin1("Gui.Selection.removeSelection(" "App.getDocument('%1').getObject('%2'),'%3')") - .arg(QString::fromLatin1(docname)) - .arg(QString::fromLatin1(objname)) - .arg(QString::fromLatin1(subname)); + .arg(QString::fromLatin1(docname), + QString::fromLatin1(objname), + QString::fromLatin1(subname)); else cmd = QString::fromLatin1("Gui.Selection.addSelection(" "App.getDocument('%1').getObject('%2'),'%3',%4,%5,%6)") - .arg(QString::fromLatin1(docname)) - .arg(QString::fromLatin1(objname)) - .arg(QString::fromLatin1(subname)) + .arg(QString::fromLatin1(docname), + QString::fromLatin1(objname), + QString::fromLatin1(subname)) .arg(x).arg(y).arg(z); try { Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); @@ -419,9 +420,9 @@ void SelectionView::preselect(QListWidgetItem* item) } QString cmd = QString::fromLatin1("Gui.Selection.setPreselection(" "App.getDocument('%1').getObject('%2'),'%3',tp=2)") - .arg(QString::fromLatin1(docname)) - .arg(QString::fromLatin1(objname)) - .arg(QString::fromLatin1(subname)); + .arg(QString::fromLatin1(docname), + QString::fromLatin1(objname), + QString::fromLatin1(subname)); try { Gui::Command::runCommand(Gui::Command::Gui,cmd.toLatin1()); }catch(Base::Exception &e) { @@ -429,7 +430,7 @@ void SelectionView::preselect(QListWidgetItem* item) } } -void SelectionView::zoom(void) +void SelectionView::zoom() { select(); try { @@ -439,7 +440,7 @@ void SelectionView::zoom(void) } } -void SelectionView::treeSelect(void) +void SelectionView::treeSelect() { select(); try { @@ -449,7 +450,7 @@ void SelectionView::treeSelect(void) } } -void SelectionView::touch(void) +void SelectionView::touch() { QListWidgetItem *item = selectionView->currentItem(); if (!item) @@ -465,7 +466,7 @@ void SelectionView::touch(void) } } -void SelectionView::toPython(void) +void SelectionView::toPython() { QListWidgetItem *item = selectionView->currentItem(); if (!item) @@ -498,7 +499,7 @@ void SelectionView::toPython(void) } } -void SelectionView::showPart(void) +void SelectionView::showPart() { QListWidgetItem *item = selectionView->currentItem(); if (!item) @@ -614,7 +615,7 @@ void SelectionView::onItemContextMenu(const QPoint& point) menu.exec(selectionView->mapToGlobal(point)); } -void SelectionView::onUpdate(void) +void SelectionView::onUpdate() { } diff --git a/src/Gui/SelectionView.h b/src/Gui/SelectionView.h index d73ba2cd8c..318d67d6bc 100644 --- a/src/Gui/SelectionView.h +++ b/src/Gui/SelectionView.h @@ -51,25 +51,25 @@ public: * A constructor. * A more elaborate description of the constructor. */ - SelectionView(Gui::Document* pcDocument, QWidget *parent=nullptr); + explicit SelectionView(Gui::Document* pcDocument, QWidget *parent=nullptr); /** * A destructor. * A more elaborate description of the destructor. */ - virtual ~SelectionView(); + ~SelectionView() override; /// Observer message from the Selection - virtual void onSelectionChanged(const SelectionChanges& msg) override; + void onSelectionChanged(const SelectionChanges& msg) override; - virtual void leaveEvent(QEvent*) override; + void leaveEvent(QEvent*) override; bool onMsg(const char* pMsg,const char** ppReturn) override; - virtual const char *getName(void) const override {return "SelectionView";} + const char *getName() const override {return "SelectionView";} /// get called when the document is changed or updated - virtual void onUpdate(void) override; + void onUpdate() override; QListWidget* selectionView; QLabel* countLabel; @@ -81,17 +81,17 @@ public Q_SLOTS: /// get called when text is entered in the search box void search(const QString& text); /// get called when enter is pressed in the search box - void validateSearch(void); + void validateSearch(); /// get called when the list is right-clicked void onItemContextMenu(const QPoint& point); /// different actions void select(QListWidgetItem* item=nullptr); - void deselect(void); - void zoom(void); - void treeSelect(void); - void toPython(void); - void touch(void); - void showPart(void); + void deselect(); + void zoom(); + void treeSelect(); + void toPython(); + void touch(); + void showPart(); void onEnablePickList(); void toggleSelect(QListWidgetItem* item=nullptr); void preselect(QListWidgetItem* item=nullptr); diff --git a/src/Gui/SoAxisCrossKit.cpp b/src/Gui/SoAxisCrossKit.cpp index 17adf476e9..6daac87e49 100644 --- a/src/Gui/SoAxisCrossKit.cpp +++ b/src/Gui/SoAxisCrossKit.cpp @@ -62,7 +62,7 @@ using namespace Gui; SO_KIT_SOURCE(SoShapeScale) // Constructor. -SoShapeScale::SoShapeScale(void) +SoShapeScale::SoShapeScale() { SO_KIT_CONSTRUCTOR(SoShapeScale); @@ -82,7 +82,7 @@ SoShapeScale::~SoShapeScale() } void -SoShapeScale::initClass(void) +SoShapeScale::initClass() { SO_KIT_INIT_CLASS(SoShapeScale, SoBaseKit, "BaseKit"); } diff --git a/src/Gui/SoAxisCrossKit.h b/src/Gui/SoAxisCrossKit.h index 4d9c8dd362..80631e00ce 100644 --- a/src/Gui/SoAxisCrossKit.h +++ b/src/Gui/SoAxisCrossKit.h @@ -47,8 +47,8 @@ class GuiExport SoShapeScale : public SoBaseKit { SO_KIT_CATALOG_ENTRY_HEADER(shape); public: - SoShapeScale(void); - static void initClass(void); + SoShapeScale(); + static void initClass(); SoSFFloat active; SoSFFloat scaleFactor; diff --git a/src/Gui/SoFCBackgroundGradient.cpp b/src/Gui/SoFCBackgroundGradient.cpp index 025e8832cf..4f40eb7140 100644 --- a/src/Gui/SoFCBackgroundGradient.cpp +++ b/src/Gui/SoFCBackgroundGradient.cpp @@ -61,7 +61,7 @@ SoFCBackgroundGradient::~SoFCBackgroundGradient() } // doc from parent -void SoFCBackgroundGradient::initClass(void) +void SoFCBackgroundGradient::initClass() { SO_NODE_INIT_CLASS(SoFCBackgroundGradient,SoNode,"Node"); } diff --git a/src/Gui/SoFCBackgroundGradient.h b/src/Gui/SoFCBackgroundGradient.h index ad1a7028ed..1a07c8bc7b 100644 --- a/src/Gui/SoFCBackgroundGradient.h +++ b/src/Gui/SoFCBackgroundGradient.h @@ -39,9 +39,9 @@ class GuiExport SoFCBackgroundGradient : public SoNode { SO_NODE_HEADER(Gui::SoFCBackgroundGradient); public: - static void initClass(void); - static void finish(void); - SoFCBackgroundGradient(void); + static void initClass(); + static void finish(); + SoFCBackgroundGradient(); void GLRender (SoGLRenderAction *action); void setColorGradient(const SbColor& fromColor, const SbColor& toColor); diff --git a/src/Gui/SoFCBoundingBox.cpp b/src/Gui/SoFCBoundingBox.cpp index 685958c218..07bfa024a9 100644 --- a/src/Gui/SoFCBoundingBox.cpp +++ b/src/Gui/SoFCBoundingBox.cpp @@ -256,7 +256,7 @@ SoSkipBoundingGroup::~SoSkipBoundingGroup() } void -SoSkipBoundingGroup::initClass(void) +SoSkipBoundingGroup::initClass() { SO_NODE_INIT_CLASS(SoSkipBoundingGroup,SoGroup,"Group"); } diff --git a/src/Gui/SoFCBoundingBox.h b/src/Gui/SoFCBoundingBox.h index 9431694d45..bdfcfeb96f 100644 --- a/src/Gui/SoFCBoundingBox.h +++ b/src/Gui/SoFCBoundingBox.h @@ -83,9 +83,9 @@ class GuiExport SoSkipBoundingGroup : public SoGroup { SO_NODE_HEADER(Gui::SoSkipBoundingGroup); public: - static void initClass(void); - static void finish(void); - SoSkipBoundingGroup(void); + static void initClass(); + static void finish(); + SoSkipBoundingGroup(); enum Modes { INCLUDE_BBOX, EXCLUDE_BBOX diff --git a/src/Gui/SoFCCSysDragger.cpp b/src/Gui/SoFCCSysDragger.cpp index 1e89a52a5f..27a3a1c8ca 100644 --- a/src/Gui/SoFCCSysDragger.cpp +++ b/src/Gui/SoFCCSysDragger.cpp @@ -216,7 +216,7 @@ void TDragger::fieldSensorCB(void *f, SoSensor *) { TDragger *sudoThis = static_cast(f); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft sudoThis->workFieldsIntoTransform(matrix); sudoThis->setMotionMatrix(matrix); } @@ -225,7 +225,7 @@ void TDragger::valueChangedCB(void *, SoDragger *d) { TDragger *sudoThis = dynamic_cast(d); assert(sudoThis); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft //all this just to get the translation? SbVec3f trans, scaleDummy; @@ -318,7 +318,7 @@ SbBool TDragger::setUpConnections(SbBool onoff, SbBool doitalways) } else { - if (this->fieldSensor.getAttachedField() != nullptr) + if (this->fieldSensor.getAttachedField()) this->fieldSensor.detach(); inherited::setUpConnections(onoff, doitalways); } @@ -488,7 +488,7 @@ void RDragger::fieldSensorCB(void *f, SoSensor *) { RDragger *sudoThis = static_cast(f); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft sudoThis->workFieldsIntoTransform(matrix); sudoThis->setMotionMatrix(matrix); } @@ -497,7 +497,7 @@ void RDragger::valueChangedCB(void *, SoDragger *d) { RDragger *sudoThis = dynamic_cast(d); assert(sudoThis); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft //all this just to get the translation? SbVec3f translationDummy, scaleDummy; @@ -603,7 +603,7 @@ SbBool RDragger::setUpConnections(SbBool onoff, SbBool doitalways) } else { - if (this->fieldSensor.getAttachedField() != nullptr) + if (this->fieldSensor.getAttachedField()) this->fieldSensor.detach(); inherited::setUpConnections(onoff, doitalways); } @@ -857,10 +857,10 @@ SbBool SoFCCSysDragger::setUpConnections(SbBool onoff, SbBool doitalways) inherited::setUpConnections(onoff, doitalways); - if (this->translationSensor.getAttachedField() != nullptr) + if (this->translationSensor.getAttachedField()) this->translationSensor.detach(); - if (this->rotationSensor.getAttachedField() != nullptr) + if (this->rotationSensor.getAttachedField()) this->rotationSensor.detach(); } return !(this->connectionsSetUp = onoff); @@ -870,7 +870,7 @@ void SoFCCSysDragger::translationSensorCB(void *f, SoSensor *) { SoFCCSysDragger *sudoThis = static_cast(f); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft sudoThis->workFieldsIntoTransform(matrix); sudoThis->setMotionMatrix(matrix); } @@ -879,7 +879,7 @@ void SoFCCSysDragger::rotationSensorCB(void *f, SoSensor *) { SoFCCSysDragger *sudoThis = static_cast(f); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft sudoThis->workFieldsIntoTransform(matrix); sudoThis->setMotionMatrix(matrix); } @@ -888,7 +888,7 @@ void SoFCCSysDragger::valueChangedCB(void *, SoDragger *d) { SoFCCSysDragger *sudoThis = dynamic_cast(d); assert(sudoThis); - SbMatrix matrix = sudoThis->getMotionMatrix(); + SbMatrix matrix = sudoThis->getMotionMatrix(); // clazy:exclude=rule-of-two-soft //all this just to get the translation? SbVec3f localTranslation, scaleDummy; diff --git a/src/Gui/SoFCCSysDragger.h b/src/Gui/SoFCCSysDragger.h index fb2ecf085d..acdca57807 100644 --- a/src/Gui/SoFCCSysDragger.h +++ b/src/Gui/SoFCCSysDragger.h @@ -62,8 +62,8 @@ public: SoSFFloat autoScaleResult; //!< set from parent dragger. protected: - virtual ~TDragger() override; - virtual SbBool setUpConnections(SbBool onoff, SbBool doitalways = FALSE) override; + ~TDragger() override; + SbBool setUpConnections(SbBool onoff, SbBool doitalways = FALSE) override; static void startCB(void *, SoDragger * d); static void motionCB(void *, SoDragger * d); @@ -107,8 +107,8 @@ public: SoSFColor color; //!< set from outside. non-active color. protected: - virtual ~RDragger() override; - virtual SbBool setUpConnections(SbBool onoff, SbBool doitalways = FALSE) override; + ~RDragger() override; + SbBool setUpConnections(SbBool onoff, SbBool doitalways = FALSE) override; static void startCB(void *, SoDragger * d); static void motionCB(void *, SoDragger * d); diff --git a/src/Gui/SoFCColorBar.cpp b/src/Gui/SoFCColorBar.cpp index 604d5f5735..ed021c8d4d 100644 --- a/src/Gui/SoFCColorBar.cpp +++ b/src/Gui/SoFCColorBar.cpp @@ -159,8 +159,8 @@ class SoFCColorBarProxyObject : public QObject public: SoFCColorBarProxyObject(SoFCColorBar* b) : QObject(nullptr), bar(b) {} - ~SoFCColorBarProxyObject() {} - void customEvent(QEvent *) + ~SoFCColorBarProxyObject() override {} + void customEvent(QEvent *) override { bar->customize(bar->getActiveBar()); this->deleteLater(); diff --git a/src/Gui/SoFCColorBar.h b/src/Gui/SoFCColorBar.h index c6515aa779..afde2c6a90 100644 --- a/src/Gui/SoFCColorBar.h +++ b/src/Gui/SoFCColorBar.h @@ -54,7 +54,7 @@ public: static void initClass(); static void finish(); - virtual void GLRenderBelowPath ( SoGLRenderAction *action ); + void GLRenderBelowPath ( SoGLRenderAction *action ) override; /** * Sets the range of the colorbar from the maximum \a fMax to the minimum \a fMin. @@ -68,7 +68,7 @@ public: * * This method must be implemented in subclasses. */ - virtual App::Color getColor(float fVal) const = 0; + App::Color getColor(float fVal) const override = 0; /** * Returns always true if the color bar is in mode to show colors to arbitrary values of \a fVal, * otherwise true is returned if \a fVal is within the specified parameter range, if not false is @@ -135,7 +135,7 @@ protected: void setModified(); SoFCColorBarBase (); - virtual ~SoFCColorBarBase (); + ~SoFCColorBarBase () override; private: float _boxWidth; @@ -165,51 +165,51 @@ public: /** * Handles the mouse button events and checks if the user has clicked on the area of the currently active color bar. */ - void handleEvent (SoHandleEventAction *action); + void handleEvent (SoHandleEventAction *action) override; /** * Sets the range of all color bars from the maximum \a fMax to the minimum \a fMin. * \a prec indicates the post decimal positions, \a prec should be in between 0 and 6. */ - void setRange( float fMin, float fMax, int prec=3 ); + void setRange( float fMin, float fMax, int prec=3 ) override; /** * Returns the associated color to the value \a fVal of the currently active color bar. */ - App::Color getColor(float fVal) const; + App::Color getColor(float fVal) const override; /** * Sets whether values outside the range should be in gray, */ - void setOutsideGrayed (bool bVal); + void setOutsideGrayed (bool bVal) override; /** * Returns the return value of the currently active color bar. */ - bool isVisible (float fVal) const; + bool isVisible (float fVal) const override; /** * Returns the current minimum of the parameter range of the currently active color bar. */ - float getMinValue () const; + float getMinValue () const override; /** * Returns the current maximum of the parameter range of the currently active color bar. */ - float getMaxValue () const; + float getMaxValue () const override; /** * Customizes the currently active color bar. */ - void customize(SoFCColorBarBase*); + void customize(SoFCColorBarBase*) override; /** * Notify observers */ - void triggerChange(SoFCColorBarBase*); + void triggerChange(SoFCColorBarBase*) override; /** Returns the name of the color bar. */ - const char* getColorBarName() const { return "Color Bar"; } + const char* getColorBarName() const override { return "Color Bar"; } protected: /** * Sets the current viewer size to all color bars to recalculate their new position. */ - void setViewportSize( const SbVec2s& size ); + void setViewportSize( const SbVec2s& size ) override; - virtual ~SoFCColorBar(); + ~SoFCColorBar() override; private: static void eventCallback(void * userdata, SoEventCallback * node); diff --git a/src/Gui/SoFCColorGradient.h b/src/Gui/SoFCColorGradient.h index d7994b9220..f45fddbea2 100644 --- a/src/Gui/SoFCColorGradient.h +++ b/src/Gui/SoFCColorGradient.h @@ -50,36 +50,36 @@ public: * Sets the range of the colorbar from the maximum \a fMax to the minimum \a fMin. * \a prec indicates the post decimal positions, \a prec should be in between 0 and 6. */ - void setRange( float fMin, float fMax, int prec=3 ); + void setRange( float fMin, float fMax, int prec=3 ) override; /** * Returns the associated color to the value \a fVal. */ - App::Color getColor (float fVal) const { return _cColGrad.getColor(fVal); } - void setOutsideGrayed (bool bVal) { _cColGrad.setOutsideGrayed(bVal); } + App::Color getColor (float fVal) const override { return _cColGrad.getColor(fVal); } + void setOutsideGrayed (bool bVal) override { _cColGrad.setOutsideGrayed(bVal); } /** * Returns always true if the gradient is in mode to show colors to arbitrary values of \a fVal, * otherwise true is returned if \a fVal is within the specified parameter range, if not false is * returned. */ - bool isVisible (float fVal) const; + bool isVisible (float fVal) const override; /** Returns the current minimum of the parameter range. */ - float getMinValue () const { return _cColGrad.getMinValue(); } + float getMinValue () const override { return _cColGrad.getMinValue(); } /** Returns the current maximum of the parameter range. */ - float getMaxValue () const { return _cColGrad.getMaxValue(); } + float getMaxValue () const override { return _cColGrad.getMaxValue(); } /** * Opens a dialog to customize the current settings of the color gradient bar. */ - void customize(SoFCColorBarBase*); + void customize(SoFCColorBarBase*) override; /** Returns the name of the color bar. */ - const char* getColorBarName() const { return "Color Gradient"; } + const char* getColorBarName() const override { return "Color Gradient"; } protected: /** * Sets the current viewer size this color gradient is embedded into, to recalculate its new position. */ - void setViewportSize( const SbVec2s& size ); + void setViewportSize( const SbVec2s& size ) override; - virtual ~SoFCColorGradient(); + ~SoFCColorGradient() override; /** * Sets the color model of the underlying color gradient to \a index. */ diff --git a/src/Gui/SoFCColorLegend.h b/src/Gui/SoFCColorLegend.h index 17d1142330..49ebeee116 100644 --- a/src/Gui/SoFCColorLegend.h +++ b/src/Gui/SoFCColorLegend.h @@ -51,30 +51,30 @@ public: * Sets the range of the colorbar from the maximum \a fMax to the minimum \a fMin. * \a prec indicates the post decimal positions, \a prec should be in between 0 and 6. */ - void setRange( float fMin, float fMax, int prec=3 ); + void setRange( float fMin, float fMax, int prec=3 ) override; /** * Updates the node with the given color legend. */ void setColorLegend (const App::ColorLegend& legend); unsigned short getColorIndex (float fVal) const { return _currentLegend.getColorIndex(fVal); } - App::Color getColor (float fVal) const { return _currentLegend.getColor(fVal); } - void setOutsideGrayed (bool bVal) { _currentLegend.setOutsideGrayed(bVal); } - bool isVisible (float) const { return false; } - float getMinValue () const { return _currentLegend.getMinValue(); } - float getMaxValue () const { return _currentLegend.getMaxValue(); } + App::Color getColor (float fVal) const override { return _currentLegend.getColor(fVal); } + void setOutsideGrayed (bool bVal) override { _currentLegend.setOutsideGrayed(bVal); } + bool isVisible (float) const override { return false; } + float getMinValue () const override { return _currentLegend.getMinValue(); } + float getMaxValue () const override { return _currentLegend.getMaxValue(); } std::size_t countColors () const { return _currentLegend.hasNumberOfFields(); } - void customize(SoFCColorBarBase*) { } - const char* getColorBarName() const { return "Color Legend"; } + void customize(SoFCColorBarBase*) override { } + const char* getColorBarName() const override { return "Color Legend"; } // virtual void handleEvent(SoHandleEventAction * action); // virtual void GLRenderBelowPath(SoGLRenderAction * action); // virtual void GLRenderInPath(SoGLRenderAction * action); protected: - void setViewportSize( const SbVec2s& size ); - virtual ~SoFCColorLegend(); + void setViewportSize( const SbVec2s& size ) override; + ~SoFCColorLegend() override; // virtual void redrawHighlighted(SoAction * act, SbBool flag); private: void setMarkerLabel(const SoMFString& label); diff --git a/src/Gui/SoFCDB.cpp b/src/Gui/SoFCDB.cpp index 95b758ab0f..36e4f0657c 100644 --- a/src/Gui/SoFCDB.cpp +++ b/src/Gui/SoFCDB.cpp @@ -83,7 +83,7 @@ using namespace Gui::PropertyEditor; static SbBool init_done = false; static SoGroup *storage = nullptr; -SbBool Gui::SoFCDB::isInitialized(void) +SbBool Gui::SoFCDB::isInitialized() { return init_done; } @@ -406,59 +406,6 @@ bool Gui::SoFCDB::writeToX3D(SoNode* node, const char* filename, bool binary) bool Gui::SoFCDB::writeToX3D(SoNode* node, bool exportViewpoints, std::string& buffer) { -#if 0 - writeToVRML(node, buffer); - if (buffer.empty()) - return false; - - QString filename = QDir::tempPath(); - filename += QLatin1String("/sceneXXXXXX.wrl"); - QTemporaryFile wrlFile(filename); - if (wrlFile.open()) { - filename = wrlFile.fileName(); - wrlFile.write(buffer.c_str(), buffer.size()); - wrlFile.close(); - - QString exe(QLatin1String("tovrmlx3d")); - QStringList args; - args << filename << QLatin1String("--encoding") << QLatin1String("xml"); - QProcess proc; - proc.setEnvironment(QProcess::systemEnvironment()); - proc.start(exe, args); - if (proc.waitForStarted() && proc.waitForFinished()) { - QByteArray x3d = proc.readAll(); - if (x3d.isEmpty()) - return false; - - x3d.replace('\t', " "); - - if (exportViewpoints) { - // compute a sensible view point - SoGetBoundingBoxAction bboxAction(SbViewportRegion(1280, 1024)); - bboxAction.apply(node); - SbBox3f bbox = bboxAction.getBoundingBox(); - SbSphere bs; - bs.circumscribe(bbox); - const SbVec3f& cnt = bs.getCenter(); - float dist = bs.getRadius(); - - QString vp = QString::fromLatin1(" \n") - .arg(cnt[0]).arg(cnt[1]).arg(cnt[2]).arg(cnt[2] + 2.0f * dist); - int index = x3d.indexOf("\n"); - if (index >= 0) { - x3d.insert(index + 8, vp); - } - } - - buffer = x3d.data(); - return true; - } - } - - return false; -#else SoNode* noSwitches = replaceSwitchesInSceneGraph(node); noSwitches->ref(); SoVRMLAction vrml2; @@ -510,7 +457,6 @@ bool Gui::SoFCDB::writeToX3D(SoNode* node, bool exportViewpoints, std::string& b noSwitches->unref(); return true; -#endif } void Gui::SoFCDB::writeX3DFields(SoNode* node, std::map& nodeMap, diff --git a/src/Gui/SoFCDB.h b/src/Gui/SoFCDB.h index aca7014756..d9ecb349eb 100644 --- a/src/Gui/SoFCDB.h +++ b/src/Gui/SoFCDB.h @@ -41,7 +41,7 @@ namespace Gui { class GuiExport SoFCDB { public: - static SbBool isInitialized(void); + static SbBool isInitialized(); static void init(); static void finish(); static SoNode* replaceSwitches(SoNode* node); diff --git a/src/Gui/SoFCInteractiveElement.cpp b/src/Gui/SoFCInteractiveElement.cpp index dda3b49e45..0c0ca65e08 100644 --- a/src/Gui/SoFCInteractiveElement.cpp +++ b/src/Gui/SoFCInteractiveElement.cpp @@ -28,12 +28,11 @@ #include "SoFCInteractiveElement.h" - using namespace Gui; SO_ELEMENT_SOURCE(SoFCInteractiveElement) -void SoFCInteractiveElement::initClass(void) +void SoFCInteractiveElement::initClass() { SO_ELEMENT_INIT_CLASS(SoFCInteractiveElement, inherited); SO_ENABLE(SoGLRenderAction, SoFCInteractiveElement); @@ -74,7 +73,7 @@ const SoFCInteractiveElement * SoFCInteractiveElement::getInstance(SoState * sta SO_ELEMENT_SOURCE(SoGLWidgetElement) -void SoGLWidgetElement::initClass(void) +void SoGLWidgetElement::initClass() { SO_ELEMENT_INIT_CLASS(SoGLWidgetElement, inherited); SO_ENABLE(SoGLRenderAction, SoGLWidgetElement); @@ -120,7 +119,7 @@ SbBool SoGLWidgetElement::matches(const SoElement * /*element*/) const return true; } -SoElement * SoGLWidgetElement::copyMatchInfo(void) const +SoElement * SoGLWidgetElement::copyMatchInfo() const { return nullptr; } @@ -129,7 +128,7 @@ SoElement * SoGLWidgetElement::copyMatchInfo(void) const SO_ELEMENT_SOURCE(SoGLRenderActionElement) -void SoGLRenderActionElement::initClass(void) +void SoGLRenderActionElement::initClass() { SO_ELEMENT_INIT_CLASS(SoGLRenderActionElement, inherited); SO_ENABLE(SoGLRenderAction, SoGLRenderActionElement); @@ -175,7 +174,7 @@ SbBool SoGLRenderActionElement::matches(const SoElement * /*element*/) const return true; } -SoElement * SoGLRenderActionElement::copyMatchInfo(void) const +SoElement * SoGLRenderActionElement::copyMatchInfo() const { return nullptr; } @@ -187,7 +186,7 @@ SO_NODE_SOURCE(SoGLWidgetNode) /*! Constructor. */ -SoGLWidgetNode::SoGLWidgetNode(void) : window(nullptr) +SoGLWidgetNode::SoGLWidgetNode() : window(nullptr) { SO_NODE_CONSTRUCTOR(SoGLWidgetNode); } @@ -200,7 +199,7 @@ SoGLWidgetNode::~SoGLWidgetNode() } // Doc from superclass. -void SoGLWidgetNode::initClass(void) +void SoGLWidgetNode::initClass() { SO_NODE_INIT_CLASS(SoGLWidgetNode, SoNode, "Node"); @@ -223,7 +222,7 @@ void SoGLWidgetNode::GLRender(SoGLRenderAction * action) SO_ELEMENT_SOURCE(SoGLVBOActivatedElement) -void SoGLVBOActivatedElement::initClass(void) +void SoGLVBOActivatedElement::initClass() { SO_ELEMENT_INIT_CLASS(SoGLVBOActivatedElement, inherited); SO_ENABLE(SoGLRenderAction, SoGLVBOActivatedElement); @@ -279,7 +278,7 @@ SbBool SoGLVBOActivatedElement::matches(const SoElement * /*element*/) const return true; } -SoElement * SoGLVBOActivatedElement::copyMatchInfo(void) const +SoElement * SoGLVBOActivatedElement::copyMatchInfo() const { return nullptr; } diff --git a/src/Gui/SoFCInteractiveElement.h b/src/Gui/SoFCInteractiveElement.h index e849886179..d28f7e688d 100644 --- a/src/Gui/SoFCInteractiveElement.h +++ b/src/Gui/SoFCInteractiveElement.h @@ -42,7 +42,7 @@ class GuiExport SoFCInteractiveElement : public SoReplacedElement { SO_ELEMENT_HEADER(SoFCInteractiveElement); public: - static void initClass(void); + static void initClass(); virtual void init(SoState * state); static void set(SoState * const state, SoNode * const node, SbBool mode); @@ -63,14 +63,14 @@ class GuiExport SoGLWidgetElement : public SoElement { SO_ELEMENT_HEADER(SoGLWidgetElement); public: - static void initClass(void); + static void initClass(); virtual void init(SoState * state); virtual void push(SoState * state); virtual void pop(SoState * state, const SoElement * prevTopElement); virtual SbBool matches(const SoElement * element) const; - virtual SoElement * copyMatchInfo(void) const; + virtual SoElement * copyMatchInfo() const; static void set(SoState * state, QtGLWidget * window); static void get(SoState * state, QtGLWidget *& window); @@ -88,14 +88,14 @@ class GuiExport SoGLRenderActionElement : public SoElement { SO_ELEMENT_HEADER(SoGLRenderActionElement); public: - static void initClass(void); + static void initClass(); virtual void init(SoState * state); virtual void push(SoState * state); virtual void pop(SoState * state, const SoElement * prevTopElement); virtual SbBool matches(const SoElement * element) const; - virtual SoElement * copyMatchInfo(void) const; + virtual SoElement * copyMatchInfo() const; static void set(SoState * state, SoGLRenderAction * action); static void get(SoState * state, SoGLRenderAction * & action); @@ -113,8 +113,8 @@ class GuiExport SoGLWidgetNode : public SoNode { SO_NODE_HEADER(SoGLWidgetNode); public: - static void initClass(void); - SoGLWidgetNode(void); + static void initClass(); + SoGLWidgetNode(); QtGLWidget * window; @@ -131,14 +131,14 @@ class GuiExport SoGLVBOActivatedElement : public SoElement { SO_ELEMENT_HEADER(SoGLVBOActivatedElement); public: - static void initClass(void); + static void initClass(); virtual void init(SoState * state); virtual void push(SoState * state); virtual void pop(SoState * state, const SoElement * prevTopElement); virtual SbBool matches(const SoElement * element) const; - virtual SoElement * copyMatchInfo(void) const; + virtual SoElement * copyMatchInfo() const; static void set(SoState * state, SbBool); static void get(SoState * state, SbBool& active); diff --git a/src/Gui/SoFCOffscreenRenderer.cpp b/src/Gui/SoFCOffscreenRenderer.cpp index 567000c970..dde06d2211 100644 --- a/src/Gui/SoFCOffscreenRenderer.cpp +++ b/src/Gui/SoFCOffscreenRenderer.cpp @@ -68,7 +68,7 @@ SoFCOffscreenRenderer* SoFCOffscreenRenderer::inst = nullptr; SoFCOffscreenRenderer& SoFCOffscreenRenderer::instance() { - if (inst==nullptr) + if (!inst) inst = new SoFCOffscreenRenderer(SbViewportRegion()); return *inst; } @@ -423,7 +423,7 @@ void SoQtOffscreenRenderer::init(const SbViewportRegion & vpr, } this->didallocation = glrenderaction ? false : true; - this->viewport = vpr; + this->viewport = vpr; // clazy:exclude=rule-of-two-soft this->framebuffer = nullptr; this->numSamples = -1; @@ -473,7 +473,7 @@ SoQtOffscreenRenderer::~SoQtOffscreenRenderer() void SoQtOffscreenRenderer::setViewportRegion(const SbViewportRegion & region) { - PRIVATE(this)->viewport = region; + PRIVATE(this)->viewport = region; // clazy:exclude=rule-of-two-soft } /*! diff --git a/src/Gui/SoFCOffscreenRenderer.h b/src/Gui/SoFCOffscreenRenderer.h index 501b281f6e..f8c0ff99f1 100644 --- a/src/Gui/SoFCOffscreenRenderer.h +++ b/src/Gui/SoFCOffscreenRenderer.h @@ -109,16 +109,16 @@ public: ~SoQtOffscreenRenderer(); void setViewportRegion(const SbViewportRegion & region); - const SbViewportRegion & getViewportRegion(void) const; + const SbViewportRegion & getViewportRegion() const; void setBackgroundColor(const SbColor4f & color); - const SbColor4f & getBackgroundColor(void) const; + const SbColor4f & getBackgroundColor() const; void setGLRenderAction(SoGLRenderAction * action); - SoGLRenderAction * getGLRenderAction(void) const; + SoGLRenderAction * getGLRenderAction() const; void setNumPasses(const int num); - int getNumPasses(void) const; + int getNumPasses() const; void setInternalTextureFormat(GLenum internalTextureFormat); GLenum internalTextureFormat() const; @@ -153,10 +153,10 @@ class SoQtOffscreenRendererPy : public Py::PythonExtensiongetTail()->isOfType(SoFCSelection::getClassTypeId()))) { currenthighlight->unref(); currenthighlight = nullptr; @@ -136,7 +127,7 @@ SoFCSelection::~SoFCSelection() // doc from parent void -SoFCSelection::initClass(void) +SoFCSelection::initClass() { SO_NODE_INIT_CLASS(SoFCSelection,SoGroup,"Group"); } @@ -331,19 +322,6 @@ SoFCSelection::getPickedPoint(SoHandleEventAction* action) const return nullptr; else if (points.getLength() == 1) return points[0]; - //const SoPickedPoint* pp0 = points[0]; - //const SoPickedPoint* pp1 = points[1]; - //const SoDetail* det0 = pp0->getDetail(); - //const SoDetail* det1 = pp1->getDetail(); - //if (det0 && det0->isOfType(SoFaceDetail::getClassTypeId()) && - // det1 && det1->isOfType(SoLineDetail::getClassTypeId())) { - // const SbVec3f& pt0 = pp0->getPoint(); - // const SbVec3f& pt1 = pp1->getPoint(); - // if (pt0.equals(pt1, 0.01f)) - // return pp1; - //} - - //return pp0; const SoPickedPoint* picked = points[0]; @@ -574,13 +552,6 @@ SoFCSelection::handleEvent(SoHandleEventAction * action) ,pp->getPoint()[2]); } } - //if(selected == SELECTED){ - // redrawHighlighted(action, true); - //} - //if(selectionCleared ){ - // redrawHighlighted(action, false); - // selectionCleared = false; - //} } // key press events else if (event->isOfType(SoKeyboardEvent ::getClassTypeId())) { @@ -861,7 +832,6 @@ SoFCSelection::redrawHighlighted(SoAction * action , SbBool doHighlight ) { Q_UNUSED(action); Q_UNUSED(doHighlight); - //Base::Console().Log("SoFCSelection::redrawHighlighted() (%p) doHigh=%d \n",this,doHighlight?1:0); #ifdef NO_FRONTBUFFER #else @@ -912,12 +882,8 @@ SoFCSelection::redrawHighlighted(SoAction * action , SbBool doHighlight ) SoState *state = action->getState(); - //void* window; - //void* context; - //void *display; QtGLWidget* window; SoGLRenderAction *glAction; - //SoWindowElement::get(state, window, context, display, glAction); SoGLWidgetElement::get(state, window); SoGLRenderActionElement::get(state, glAction); @@ -1094,4 +1060,3 @@ void SoFCSelection::applySettings () } } -//#undef THIS diff --git a/src/Gui/SoFCSelection.h b/src/Gui/SoFCSelection.h index 448d8c4285..d694bc1ebe 100644 --- a/src/Gui/SoFCSelection.h +++ b/src/Gui/SoFCSelection.h @@ -62,9 +62,9 @@ class GuiExport SoFCSelection : public SoGroup { SO_NODE_HEADER(Gui::SoFCSelection); public: - static void initClass(void); - static void finish(void); - SoFCSelection(void); + static void initClass(); + static void finish(); + SoFCSelection(); /// Load highlight settings from the configuration void applySettings (); @@ -85,7 +85,7 @@ public: EMISSIVE, EMISSIVE_DIFFUSE, BOX }; - SbBool isHighlighted(void) const {return highlighted;} + SbBool isHighlighted() const {return highlighted;} SoSFColor colorHighlight; SoSFColor colorSelection; @@ -99,16 +99,16 @@ public: SoSFString subElementName; SoSFBool useNewSelection; - virtual void doAction(SoAction *action); - virtual void GLRender(SoGLRenderAction * action); + void doAction(SoAction *action) override; + void GLRender(SoGLRenderAction * action) override; - virtual void handleEvent(SoHandleEventAction * action); - virtual void GLRenderBelowPath(SoGLRenderAction * action); - virtual void GLRenderInPath(SoGLRenderAction * action); + void handleEvent(SoHandleEventAction * action) override; + void GLRenderBelowPath(SoGLRenderAction * action) override; + void GLRenderInPath(SoGLRenderAction * action) override; static void turnOffCurrentHighlight(SoGLRenderAction * action); protected: - virtual ~SoFCSelection(); + ~SoFCSelection() override; typedef SoFCSelectionContext SelContext; typedef std::shared_ptr SelContextPtr; @@ -117,7 +117,7 @@ protected: virtual void redrawHighlighted(SoAction * act, SbBool flag); - virtual SbBool readInstance(SoInput * in, unsigned short flags); + SbBool readInstance(SoInput * in, unsigned short flags) override; private: static int getPriority(const SoPickedPoint*); diff --git a/src/Gui/SoFCSelectionAction.cpp b/src/Gui/SoFCSelectionAction.cpp index 98a24c8b8e..1fef87e8be 100644 --- a/src/Gui/SoFCSelectionAction.cpp +++ b/src/Gui/SoFCSelectionAction.cpp @@ -1030,7 +1030,7 @@ SoBoxSelectionRenderActionP::initBoxGraph() void SoBoxSelectionRenderActionP::updateBbox(const SoPath * path) { - if (this->camerasearch == nullptr) { + if (!this->camerasearch) { this->camerasearch = new SoSearchAction; } @@ -1047,7 +1047,7 @@ SoBoxSelectionRenderActionP::updateBbox(const SoPath * path) this->localRoot->insertChild(this->camerasearch->getPath()->getTail(), 0); this->camerasearch->reset(); - if (this->bboxaction == nullptr) { + if (!this->bboxaction) { this->bboxaction = new SoGetBoundingBoxAction(SbViewportRegion(100, 100)); } this->bboxaction->setViewportRegion(PUBLIC(this)->getViewportRegion()); @@ -1063,7 +1063,7 @@ SoBoxSelectionRenderActionP::updateBbox(const SoPath * path) this->cube->height = y; this->cube->depth = z; - SbMatrix transform = box.getTransform(); + SbMatrix transform = box.getTransform(); // clazy:exclude=rule-of-two-soft // get center (in the local bbox coordinate system) SbVec3f center = box.SbBox3f::getCenter(); @@ -1086,12 +1086,12 @@ SO_ACTION_SOURCE(SoBoxSelectionRenderAction) // Overridden from parent class. void -SoBoxSelectionRenderAction::initClass(void) +SoBoxSelectionRenderAction::initClass() { SO_ACTION_INIT_CLASS(SoBoxSelectionRenderAction, SoGLRenderAction); } -SoBoxSelectionRenderAction::SoBoxSelectionRenderAction(void) +SoBoxSelectionRenderAction::SoBoxSelectionRenderAction() : inherited(SbViewportRegion()) { this->constructorCommon(); @@ -1107,7 +1107,7 @@ SoBoxSelectionRenderAction::SoBoxSelectionRenderAction(const SbViewportRegion & // private. called by both constructors // void -SoBoxSelectionRenderAction::constructorCommon(void) +SoBoxSelectionRenderAction::constructorCommon() { SO_ACTION_CONSTRUCTOR(SoBoxSelectionRenderAction); @@ -1116,7 +1116,6 @@ SoBoxSelectionRenderAction::constructorCommon(void) // Initialize local variables PRIVATE(this)->initBoxGraph(); - // this->hlVisible = true; this->hlVisible = false; PRIVATE(this)->basecolor->rgb.setValue(1.0f, 0.0f, 0.0f); @@ -1133,7 +1132,7 @@ SoBoxSelectionRenderAction::constructorCommon(void) PRIVATE(this)->highlightPath = nullptr; } -SoBoxSelectionRenderAction::~SoBoxSelectionRenderAction(void) +SoBoxSelectionRenderAction::~SoBoxSelectionRenderAction() { // clear highlighting node if (PRIVATE(this)->highlightPath) { @@ -1154,7 +1153,7 @@ SoBoxSelectionRenderAction::apply(SoNode * node) { SoGLRenderAction::apply(node); if (this->hlVisible) { - if (PRIVATE(this)->searchaction == nullptr) { + if (!PRIVATE(this)->searchaction) { PRIVATE(this)->searchaction = new SoSearchAction; } PRIVATE(this)->searchaction->setType(SoFCSelection::getClassTypeId()); @@ -1169,7 +1168,7 @@ SoBoxSelectionRenderAction::apply(SoNode * node) assert(selection->getTypeId().isDerivedFrom(SoFCSelection::getClassTypeId())); if (selection->selected.getValue() && selection->style.getValue() == SoFCSelection::BOX) { PRIVATE(this)->basecolor->rgb.setValue(selection->colorSelection.getValue()); - if (PRIVATE(this)->selectsearch == nullptr) { + if (!PRIVATE(this)->selectsearch) { PRIVATE(this)->selectsearch = new SoSearchAction; } PRIVATE(this)->selectsearch->setType(SoShape::getClassTypeId()); @@ -1188,8 +1187,8 @@ SoBoxSelectionRenderAction::apply(SoNode * node) selection->style.getValue() == SoFCSelection::BOX) { PRIVATE(this)->basecolor->rgb.setValue(selection->colorHighlight.getValue()); - if (PRIVATE(this)->selectsearch == nullptr) { - PRIVATE(this)->selectsearch = new SoSearchAction; + if (!PRIVATE(this)->selectsearch) { + PRIVATE(this)->selectsearch = new SoSearchAction; } PRIVATE(this)->selectsearch->setType(SoShape::getClassTypeId()); PRIVATE(this)->selectsearch->setInterest(SoSearchAction::FIRST); @@ -1236,8 +1235,8 @@ SoBoxSelectionRenderAction::apply(SoPath * path) selection->style.getValue() == SoFCSelection::BOX) { PRIVATE(this)->basecolor->rgb.setValue(selection->colorHighlight.getValue()); - if (PRIVATE(this)->selectsearch == nullptr) { - PRIVATE(this)->selectsearch = new SoSearchAction; + if (!PRIVATE(this)->selectsearch) { + PRIVATE(this)->selectsearch = new SoSearchAction; } PRIVATE(this)->selectsearch->setType(SoShape::getClassTypeId()); PRIVATE(this)->selectsearch->setInterest(SoSearchAction::FIRST); @@ -1273,7 +1272,7 @@ SoBoxSelectionRenderAction::setColor(const SbColor & color) } const SbColor & -SoBoxSelectionRenderAction::getColor(void) +SoBoxSelectionRenderAction::getColor() { return PRIVATE(this)->basecolor->rgb[0]; } @@ -1285,7 +1284,7 @@ SoBoxSelectionRenderAction::setLinePattern(unsigned short pattern) } unsigned short -SoBoxSelectionRenderAction::getLinePattern(void) const +SoBoxSelectionRenderAction::getLinePattern() const { return PRIVATE(this)->drawstyle->linePattern.getValue(); } @@ -1297,7 +1296,7 @@ SoBoxSelectionRenderAction::setLineWidth(const float width) } float -SoBoxSelectionRenderAction::getLineWidth(void) const +SoBoxSelectionRenderAction::getLineWidth() const { return PRIVATE(this)->drawstyle->lineWidth.getValue(); } diff --git a/src/Gui/SoFCSelectionAction.h b/src/Gui/SoFCSelectionAction.h index 545b3d4640..d818b7f9a4 100644 --- a/src/Gui/SoFCSelectionAction.h +++ b/src/Gui/SoFCSelectionAction.h @@ -29,7 +29,6 @@ #include #include - class SoSFString; class SoSFColor; @@ -51,7 +50,7 @@ public: ~SoFCHighlightAction(); static void initClass(); - static void finish(void); + static void finish(); const SelectionChanges &SelChange; @@ -76,7 +75,7 @@ public: ~SoFCSelectionAction(); static void initClass(); - static void finish(void); + static void finish(); const SelectionChanges &SelChange; @@ -103,7 +102,7 @@ public: SbBool selection; static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); @@ -128,7 +127,7 @@ public: SbBool highlight; static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); @@ -153,7 +152,7 @@ public: SoSFColor selectionColor; static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); @@ -178,7 +177,7 @@ public: SoSFColor highlightColor; static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); @@ -203,7 +202,7 @@ public: SoSFString documentName; static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); @@ -229,7 +228,7 @@ public: SbBool isHandled() const; static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); @@ -316,11 +315,11 @@ class GuiExport SoBoxSelectionRenderAction : public SoGLRenderAction { SO_ACTION_HEADER(SoBoxSelectionRenderAction); public: - SoBoxSelectionRenderAction(void); + SoBoxSelectionRenderAction(); SoBoxSelectionRenderAction(const SbViewportRegion & viewportregion); virtual ~SoBoxSelectionRenderAction(); - static void initClass(void); + static void initClass(); virtual void apply(SoNode * node); virtual void apply(SoPath * path); @@ -328,17 +327,17 @@ public: void setVisible(SbBool b) { hlVisible = b; } SbBool isVisible() const { return hlVisible; } void setColor(const SbColor & color); - const SbColor & getColor(void); + const SbColor & getColor(); void setLinePattern(unsigned short pattern); - unsigned short getLinePattern(void) const; + unsigned short getLinePattern() const; void setLineWidth(const float width); - float getLineWidth(void) const; + float getLineWidth() const; protected: SbBool hlVisible; private: - void constructorCommon(void); + void constructorCommon(); void drawBoxes(SoPath * pathtothis, const SoPathList * pathlist); SoBoxSelectionRenderActionP * pimpl; @@ -357,7 +356,7 @@ public: ~SoUpdateVBOAction(); static void initClass(); - static void finish(void); + static void finish(); protected: virtual void beginTraversal(SoNode *node); diff --git a/src/Gui/SoFCSelectionContext.cpp b/src/Gui/SoFCSelectionContext.cpp index 84b2253872..bc474d7df8 100644 --- a/src/Gui/SoFCSelectionContext.cpp +++ b/src/Gui/SoFCSelectionContext.cpp @@ -170,7 +170,7 @@ bool SoFCSelectionContextEx::applyColor(int idx, std::vector &packedCo } bool SoFCSelectionContextEx::isSingleColor(uint32_t &color, bool &hasTransparency) { - if(colors.size() && colors.begin()->first<0) { + if(!colors.empty() && colors.begin()->first<0) { color = packColor(colors.begin()->second,hasTransparency); return colors.size()==1; } diff --git a/src/Gui/SoFCSelectionContext.h b/src/Gui/SoFCSelectionContext.h index bc7c4d9bb0..82e78bce33 100644 --- a/src/Gui/SoFCSelectionContext.h +++ b/src/Gui/SoFCSelectionContext.h @@ -56,7 +56,7 @@ struct GuiExport SoFCSelectionContext : SoFCSelectionContextBase SbColor highlightColor; std::shared_ptr counter; - virtual ~SoFCSelectionContext(); + ~SoFCSelectionContext() override; bool isSelected() const { return !selectionIndex.empty(); @@ -68,7 +68,7 @@ struct GuiExport SoFCSelectionContext : SoFCSelectionContextBase } bool isSelectAll() const{ - return selectionIndex.size() && *selectionIndex.begin()<0; + return !selectionIndex.empty() && *selectionIndex.begin()<0; } bool isHighlighted() const { @@ -110,7 +110,7 @@ struct GuiExport SoFCSelectionContextEx : SoFCSelectionContext bool applyColor(int idx, std::vector &packedColors, bool &hasTransparency); bool isSingleColor(uint32_t &color, bool &hasTransparency); - virtual SoFCSelectionContextBasePtr copy() { + SoFCSelectionContextBasePtr copy() override { return std::make_shared(*this); } diff --git a/src/Gui/SoFCUnifiedSelection.cpp b/src/Gui/SoFCUnifiedSelection.cpp index 0de6df63a1..0b2bbad987 100644 --- a/src/Gui/SoFCUnifiedSelection.cpp +++ b/src/Gui/SoFCUnifiedSelection.cpp @@ -137,7 +137,7 @@ SoFCUnifiedSelection::~SoFCUnifiedSelection() { // If we're being deleted and we're the current highlight, // NULL out that variable - if (currenthighlight != nullptr) { + if (currenthighlight) { currenthighlight->unref(); currenthighlight = nullptr; } @@ -149,7 +149,7 @@ SoFCUnifiedSelection::~SoFCUnifiedSelection() // doc from parent void -SoFCUnifiedSelection::initClass(void) +SoFCUnifiedSelection::initClass() { SO_NODE_INIT_CLASS(SoFCUnifiedSelection,SoSeparator,"Separator"); } @@ -194,7 +194,7 @@ void SoFCUnifiedSelection::applySettings() } } -const char* SoFCUnifiedSelection::getFileFormatName(void) const +const char* SoFCUnifiedSelection::getFileFormatName() const { return "Separator"; } @@ -658,32 +658,6 @@ bool SoFCUnifiedSelection::setSelection(const std::vector &infos, bo } } -#if 0 // ViewProviderDocumentObject now has default implementation of getElementPicked - - // If no next hierarchy is found, do another try on view provider hierarchies, - // which is used by geo feature group. - if(!hasNext) { - bool found = false; - auto vps = this->pcDocument->getViewProvidersByPath(pPath); - for(auto it=vps.begin();it!=vps.end();++it) { - auto vpdNext = it->first; - if(Gui::Selection().isSelected(vpdNext->getObject(),"")) { - found = true; - continue; - } - if(!found || !vpdNext->useNewSelectionModel() || !vpdNext->isSelectable()) - continue; - hasNext = true; - vpd = vpdNext; - det = 0; - pPath->truncate(it->second+1); - objectName = vpd->getObject()->getNameInDocument(); - subName = ""; - break; - } - } -#endif - FC_TRACE("clearing selection"); Gui::Selection().clearSelection(); FC_TRACE("add selection"); @@ -749,7 +723,7 @@ SoFCUnifiedSelection::handleEvent(SoHandleEventAction * action) if (mymode == AUTO || mymode == ON) { // check to see if the mouse is over our geometry... auto infos = this->getPickedList(action,true); - if(infos.size()) + if(!infos.empty()) setHighlight(infos[0]); else { setHighlight(PickedInfo()); @@ -1042,7 +1016,7 @@ void SoFCSeparator::GLRenderBelowPath(SoGLRenderAction * action) { inherited::GLRenderBelowPath(action); } -void SoFCSeparator::initClass(void) +void SoFCSeparator::initClass() { SO_NODE_INIT_CLASS(SoFCSeparator,SoSeparator,"FCSeparator"); } @@ -1082,7 +1056,7 @@ static void so_bbox_destruct_data(void * closure) static SbStorage * so_bbox_storage = nullptr; // called from atexit -static void so_bbox_cleanup(void) +static void so_bbox_cleanup() { delete so_bbox_storage; } @@ -1112,7 +1086,7 @@ SoFCSelectionRoot::~SoFCSelectionRoot() { } -void SoFCSelectionRoot::initClass(void) +void SoFCSelectionRoot::initClass() { SO_NODE_INIT_CLASS(SoFCSelectionRoot,SoFCSeparator,"FCSelectionRoot"); @@ -1129,7 +1103,7 @@ void SoFCSelectionRoot::finish() } SoNode *SoFCSelectionRoot::getCurrentRoot(bool front, SoNode *def) { - if(SelStack.size()) + if(!SelStack.empty()) return front?SelStack.front():SelStack.back(); return def; } @@ -1229,7 +1203,7 @@ std::pair SoFCSelectionRoot::findActionContex bool SoFCSelectionRoot::renderBBox(SoGLRenderAction *action, SoNode *node, SbColor color) { auto data = (SoFCBBoxRenderInfo*) so_bbox_storage->get(); - if (data->bboxaction == nullptr) { + if (!data->bboxaction) { // The viewport region will be replaced every time the action is // used, so we can just feed it a dummy here. data->bboxaction = new SoGetBoundingBoxAction(SbViewportRegion()); @@ -1710,7 +1684,7 @@ void SoFCPathAnnotation::finish() atexit_cleanup(); } -void SoFCPathAnnotation::initClass(void) +void SoFCPathAnnotation::initClass() { SO_NODE_INIT_CLASS(SoFCPathAnnotation,SoSeparator,"Separator"); } diff --git a/src/Gui/SoFCUnifiedSelection.h b/src/Gui/SoFCUnifiedSelection.h index 38b33974d8..0383665eb6 100644 --- a/src/Gui/SoFCUnifiedSelection.h +++ b/src/Gui/SoFCUnifiedSelection.h @@ -60,17 +60,17 @@ class GuiExport SoFCUnifiedSelection : public SoSeparator { SO_NODE_HEADER(Gui::SoFCUnifiedSelection); public: - static void initClass(void); - static void finish(void); - SoFCUnifiedSelection(void); + static void initClass(); + static void finish(); + SoFCUnifiedSelection(); void applySettings(); enum HighlightModes { AUTO, ON, OFF }; - const char* getFileFormatName(void) const; - void write(SoWriteAction * action); + const char* getFileFormatName() const override; + void write(SoWriteAction * action) override; SoSFColor colorHighlight; SoSFColor colorSelection; @@ -79,11 +79,11 @@ public: SoSFBool selectionRole; SoSFBool useNewSelection; - virtual void doAction(SoAction *action); + void doAction(SoAction *action) override; //virtual void GLRender(SoGLRenderAction * action); - virtual void handleEvent(SoHandleEventAction * action); - virtual void GLRenderBelowPath(SoGLRenderAction * action); + void handleEvent(SoHandleEventAction * action) override; + void GLRenderBelowPath(SoGLRenderAction * action) override; //virtual void GLRenderInPath(SoGLRenderAction * action); //static void turnOffCurrentHighlight(SoGLRenderAction * action); @@ -92,7 +92,7 @@ public: friend class View3DInventorViewer; protected: - virtual ~SoFCUnifiedSelection(); + ~SoFCUnifiedSelection() override; //virtual void redrawHighlighted(SoAction * act, SbBool flag); //virtual SbBool readInstance(SoInput * in, unsigned short flags); @@ -135,8 +135,8 @@ class GuiExport SoFCPathAnnotation : public SoSeparator { SO_NODE_HEADER(Gui::SoFCPathAnnotation); public: - static void initClass(void); - static void finish(void); + static void initClass(); + static void finish(); SoFCPathAnnotation(); void setPath(SoPath *); @@ -144,14 +144,14 @@ public: void setDetail(SoDetail *d); SoDetail *getDetail() {return det;} - virtual void GLRenderBelowPath(SoGLRenderAction * action); - virtual void GLRender(SoGLRenderAction * action); - virtual void GLRenderInPath(SoGLRenderAction * action); + void GLRenderBelowPath(SoGLRenderAction * action) override; + void GLRender(SoGLRenderAction * action) override; + void GLRenderInPath(SoGLRenderAction * action) override; - virtual void getBoundingBox(SoGetBoundingBoxAction * action); + void getBoundingBox(SoGetBoundingBoxAction * action) override; protected: - virtual ~SoFCPathAnnotation(); + ~SoFCPathAnnotation() override; protected: SoPath *path; @@ -165,11 +165,11 @@ class GuiExport SoFCSeparator : public SoSeparator { SO_NODE_HEADER(Gui::SoFCSeparator); public: - static void initClass(void); - static void finish(void); - SoFCSeparator(bool trackCacheMode=true); + static void initClass(); + static void finish(); + explicit SoFCSeparator(bool trackCacheMode=true); - virtual void GLRenderBelowPath(SoGLRenderAction * action); + void GLRenderBelowPath(SoGLRenderAction * action) override; static void setCacheMode(CacheEnabled mode) { CacheMode = mode; @@ -189,22 +189,22 @@ class GuiExport SoFCSelectionRoot : public SoFCSeparator { SO_NODE_HEADER(Gui::SoFCSelectionRoot); public: - static void initClass(void); - static void finish(void); - SoFCSelectionRoot(bool trackCacheMode=false); + static void initClass(); + static void finish(); + explicit SoFCSelectionRoot(bool trackCacheMode=false); - virtual void GLRenderBelowPath(SoGLRenderAction * action); - virtual void GLRenderInPath(SoGLRenderAction * action); + void GLRenderBelowPath(SoGLRenderAction * action) override; + void GLRenderInPath(SoGLRenderAction * action) override; - virtual void doAction(SoAction *action); - virtual void pick(SoPickAction * action); - virtual void rayPick(SoRayPickAction * action); - virtual void handleEvent(SoHandleEventAction * action); - virtual void search(SoSearchAction * action); - virtual void getPrimitiveCount(SoGetPrimitiveCountAction * action); - virtual void getBoundingBox(SoGetBoundingBoxAction * action); - virtual void getMatrix(SoGetMatrixAction * action); - virtual void callback(SoCallbackAction *action); + void doAction(SoAction *action) override; + void pick(SoPickAction * action) override; + void rayPick(SoRayPickAction * action) override; + void handleEvent(SoHandleEventAction * action) override; + void search(SoSearchAction * action) override; + void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; + void getBoundingBox(SoGetBoundingBoxAction * action) override; + void getMatrix(SoGetMatrixAction * action) override; + void callback(SoCallbackAction *action) override; template static std::shared_ptr getRenderContext(SoNode *node, std::shared_ptr def = std::shared_ptr()) { @@ -326,7 +326,7 @@ public: static bool renderBBox(SoGLRenderAction *action, SoNode *node, SbColor color); protected: - virtual ~SoFCSelectionRoot(); + ~SoFCSelectionRoot() override; void renderPrivate(SoGLRenderAction *, bool inPath); bool _renderPrivate(SoGLRenderAction *, bool inPath); @@ -385,7 +385,7 @@ class GuiExport SoHighlightElementAction : public SoAction public: SoHighlightElementAction (); - ~SoHighlightElementAction(); + ~SoHighlightElementAction() override; void setHighlighted(SbBool); SbBool isHighlighted() const; @@ -397,7 +397,7 @@ public: static void initClass(); protected: - virtual void beginTraversal(SoNode *node); + void beginTraversal(SoNode *node) override; private: static void callDoAction(SoAction *action,SoNode *node); @@ -418,8 +418,8 @@ class GuiExport SoSelectionElementAction : public SoAction public: enum Type {None, Append, Remove, All, Color, Hide, Show}; - SoSelectionElementAction (Type=None, bool secondary = false); - ~SoSelectionElementAction(); + explicit SoSelectionElementAction (Type=None, bool secondary = false); + ~SoSelectionElementAction() override; Type getType() const; void setType(Type type) { @@ -449,7 +449,7 @@ public: static void initClass(); protected: - virtual void beginTraversal(SoNode *node); + void beginTraversal(SoNode *node) override; private: static void callDoAction(SoAction *action,SoNode *node); @@ -471,7 +471,7 @@ class GuiExport SoVRMLAction : public SoAction public: SoVRMLAction(); - ~SoVRMLAction(); + ~SoVRMLAction() override; void setOverrideMode(SbBool); SbBool isOverrideMode() const; diff --git a/src/Gui/SoFCVectorizeSVGAction.cpp b/src/Gui/SoFCVectorizeSVGAction.cpp index b37bcad4fd..efaa84d23c 100644 --- a/src/Gui/SoFCVectorizeSVGAction.cpp +++ b/src/Gui/SoFCVectorizeSVGAction.cpp @@ -57,7 +57,7 @@ public: class SoVectorizePoint : public SoVectorizeItem { public: - SoVectorizePoint(void) { + SoVectorizePoint() { this->type = POINT; this->vidx = 0; this->size = 1.0f; @@ -70,7 +70,7 @@ public: class SoVectorizeTriangle : public SoVectorizeItem { public: - SoVectorizeTriangle(void) { + SoVectorizeTriangle() { this->type = TRIANGLE; } int vidx[3]; // indices to BSPtree coordinates @@ -79,7 +79,7 @@ public: class SoVectorizeLine : public SoVectorizeItem { public: - SoVectorizeLine(void) { + SoVectorizeLine() { this->type = LINE; vidx[0] = 0; vidx[1] = 0; @@ -96,7 +96,7 @@ public: class SoVectorizeText : public SoVectorizeItem { public: - SoVectorizeText(void) { + SoVectorizeText() { this->type = TEXT; this->fontsize = 10; this->col = 0; @@ -119,7 +119,7 @@ public: class SoVectorizeImage : public SoVectorizeItem { public: - SoVectorizeImage(void) { + SoVectorizeImage() { this->type = IMAGE; this->image.data = nullptr; this->image.nc = 0; @@ -158,7 +158,7 @@ SbBool SoSVGVectorOutput::openFile (const char *filename) return this->file.is_open(); } -void SoSVGVectorOutput::closeFile (void) +void SoSVGVectorOutput::closeFile () { if (this->file.is_open()) this->file.close(); @@ -373,7 +373,7 @@ void SoFCVectorizeSVGActionP::printImage(const SoVectorizeImage * item) const SO_ACTION_SOURCE(SoFCVectorizeSVGAction) -void SoFCVectorizeSVGAction::initClass(void) +void SoFCVectorizeSVGAction::initClass() { SO_ACTION_INIT_CLASS(SoFCVectorizeSVGAction, SoVectorizeAction); } @@ -394,12 +394,12 @@ SoFCVectorizeSVGAction::~SoFCVectorizeSVGAction() } SoSVGVectorOutput * -SoFCVectorizeSVGAction::getSVGOutput(void) const +SoFCVectorizeSVGAction::getSVGOutput() const { return static_cast(SoVectorizeAction::getOutput()); } -void SoFCVectorizeSVGAction::printHeader(void) const +void SoFCVectorizeSVGAction::printHeader() const { std::ostream& str = this->getSVGOutput()->getFileStream(); str << "" << std::endl; @@ -421,18 +421,18 @@ void SoFCVectorizeSVGAction::printHeader(void) const str << "" << std::endl; } -void SoFCVectorizeSVGAction::printFooter(void) const +void SoFCVectorizeSVGAction::printFooter() const { std::ostream& str = this->getSVGOutput()->getFileStream(); str << "" << std::endl; str << ""; } -void SoFCVectorizeSVGAction::printViewport(void) const +void SoFCVectorizeSVGAction::printViewport() const { } -void SoFCVectorizeSVGAction::printBackground(void) const +void SoFCVectorizeSVGAction::printBackground() const { if (!getBackgroundState()) { return; diff --git a/src/Gui/SoFCVectorizeSVGAction.h b/src/Gui/SoFCVectorizeSVGAction.h index 2924418bd2..ed12f0dd88 100644 --- a/src/Gui/SoFCVectorizeSVGAction.h +++ b/src/Gui/SoFCVectorizeSVGAction.h @@ -37,7 +37,7 @@ public: virtual ~SoSVGVectorOutput(); virtual SbBool openFile (const char *filename); - virtual void closeFile (void); + virtual void closeFile (); std::fstream& getFileStream(); private: @@ -54,11 +54,11 @@ class GuiExport SoFCVectorizeSVGAction : public SoVectorizeAction { SO_ACTION_HEADER(SoFCVectorizeSVGAction); public: - SoFCVectorizeSVGAction(void); + SoFCVectorizeSVGAction(); virtual ~SoFCVectorizeSVGAction(); - static void initClass(void); - SoSVGVectorOutput * getSVGOutput(void) const; + static void initClass(); + SoSVGVectorOutput * getSVGOutput() const; virtual void setBackgroundState(bool b) { m_backgroundState = b; } virtual bool getBackgroundState(void) const { return m_backgroundState; } @@ -68,11 +68,11 @@ public: virtual bool getUseMM(void) const { return m_usemm; } protected: - virtual void printHeader(void) const; - virtual void printFooter(void) const; - virtual void printBackground(void) const; + virtual void printHeader() const; + virtual void printFooter() const; + virtual void printBackground() const; virtual void printItem(const SoVectorizeItem * item) const; - virtual void printViewport(void) const; + virtual void printViewport() const; private: SoFCVectorizeSVGActionP* p; diff --git a/src/Gui/SoFCVectorizeU3DAction.cpp b/src/Gui/SoFCVectorizeU3DAction.cpp index de876ad066..0e9f59afc0 100644 --- a/src/Gui/SoFCVectorizeU3DAction.cpp +++ b/src/Gui/SoFCVectorizeU3DAction.cpp @@ -58,7 +58,7 @@ public: class SoVectorizePoint : public SoVectorizeItem { public: - SoVectorizePoint(void) { + SoVectorizePoint() { this->type = POINT; this->vidx = 0; this->size = 1.0f; @@ -71,7 +71,7 @@ public: class SoVectorizeTriangle : public SoVectorizeItem { public: - SoVectorizeTriangle(void) { + SoVectorizeTriangle() { this->type = TRIANGLE; } int vidx[3]; // indices to BSPtree coordinates @@ -80,7 +80,7 @@ public: class SoVectorizeLine : public SoVectorizeItem { public: - SoVectorizeLine(void) { + SoVectorizeLine() { this->type = LINE; vidx[0] = 0; vidx[1] = 0; @@ -97,7 +97,7 @@ public: class SoVectorizeText : public SoVectorizeItem { public: - SoVectorizeText(void) { + SoVectorizeText() { this->type = TEXT; this->fontsize = 10; this->col = 0; @@ -120,7 +120,7 @@ public: class SoVectorizeImage : public SoVectorizeItem { public: - SoVectorizeImage(void) { + SoVectorizeImage() { this->type = IMAGE; this->image.data = nullptr; this->image.nc = 0; @@ -159,7 +159,7 @@ SbBool SoU3DVectorOutput::openFile (const char *filename) return this->file.is_open(); } -void SoU3DVectorOutput::closeFile (void) +void SoU3DVectorOutput::closeFile () { if (this->file.is_open()) this->file.close(); @@ -176,7 +176,7 @@ namespace Gui { class SoFCVectorizeU3DActionP { public: - SoFCVectorizeU3DActionP(SoFCVectorizeU3DAction * p) { + explicit SoFCVectorizeU3DActionP(SoFCVectorizeU3DAction * p) { this->publ = p; } @@ -293,7 +293,7 @@ void SoFCVectorizeU3DActionP::printImage(const SoVectorizeImage * item) const SO_ACTION_SOURCE(SoFCVectorizeU3DAction) -void SoFCVectorizeU3DAction::initClass(void) +void SoFCVectorizeU3DAction::initClass() { SO_ACTION_INIT_CLASS(SoFCVectorizeU3DAction, SoVectorizeAction); //SO_ACTION_ADD_METHOD(SoNode, SoFCVectorizeU3DAction::actionMethod); @@ -312,7 +312,7 @@ SoFCVectorizeU3DAction::~SoFCVectorizeU3DAction() } SoU3DVectorOutput * -SoFCVectorizeU3DAction::getU3DOutput(void) const +SoFCVectorizeU3DAction::getU3DOutput() const { return static_cast(SoVectorizeAction::getOutput()); } @@ -334,7 +334,7 @@ void SoFCVectorizeU3DAction::endTraversal(SoNode * node) inherited::endTraversal(node); } -void SoFCVectorizeU3DAction::printHeader(void) const +void SoFCVectorizeU3DAction::printHeader() const { std::ostream& str = this->getU3DOutput()->getFileStream(); str << "FILE_FORMAT \"IDTF\"" << std::endl @@ -358,15 +358,15 @@ void SoFCVectorizeU3DAction::printHeader(void) const str << Base::tabs(0) << "}" << std::endl; } -void SoFCVectorizeU3DAction::printFooter(void) const +void SoFCVectorizeU3DAction::printFooter() const { } -void SoFCVectorizeU3DAction::printViewport(void) const +void SoFCVectorizeU3DAction::printViewport() const { } -void SoFCVectorizeU3DAction::printBackground(void) const +void SoFCVectorizeU3DAction::printBackground() const { //SbVec2f mul = getRotatedViewportSize(); //SbVec2f add = getRotatedViewportStartpos(); diff --git a/src/Gui/SoFCVectorizeU3DAction.h b/src/Gui/SoFCVectorizeU3DAction.h index de5c01bdac..3142347726 100644 --- a/src/Gui/SoFCVectorizeU3DAction.h +++ b/src/Gui/SoFCVectorizeU3DAction.h @@ -36,7 +36,7 @@ public: virtual ~SoU3DVectorOutput(); virtual SbBool openFile (const char *filename); - virtual void closeFile (void); + virtual void closeFile (); std::fstream& getFileStream(); private: @@ -53,20 +53,20 @@ class GuiExport SoFCVectorizeU3DAction : public SoVectorizeAction { SO_ACTION_HEADER(SoFCVectorizeU3DAction); public: - SoFCVectorizeU3DAction(void); + SoFCVectorizeU3DAction(); virtual ~SoFCVectorizeU3DAction(); - static void initClass(void); - SoU3DVectorOutput * getU3DOutput(void) const; + static void initClass(); + SoU3DVectorOutput * getU3DOutput() const; protected: virtual void beginTraversal(SoNode * node); virtual void endTraversal(SoNode *node); - virtual void printHeader(void) const; - virtual void printFooter(void) const; - virtual void printBackground(void) const; + virtual void printHeader() const; + virtual void printFooter() const; + virtual void printBackground() const; virtual void printItem(const SoVectorizeItem * item) const; - virtual void printViewport(void) const; + virtual void printViewport() const; private: static void actionMethod(SoAction *, SoNode *); diff --git a/src/Gui/SoMouseWheelEvent.h b/src/Gui/SoMouseWheelEvent.h index a08b49a7b8..de630bbbb5 100644 --- a/src/Gui/SoMouseWheelEvent.h +++ b/src/Gui/SoMouseWheelEvent.h @@ -23,9 +23,6 @@ #ifndef SOMOUSEWHEELEVENT_H_FC #define SOMOUSEWHEELEVENT_H_FC -//#ifndef GuiExport -//#define GuiExport -//#endif #include #include diff --git a/src/Gui/SoNavigationDragger.cpp b/src/Gui/SoNavigationDragger.cpp index 75ac8715cc..f2556dbeb9 100644 --- a/src/Gui/SoNavigationDragger.cpp +++ b/src/Gui/SoNavigationDragger.cpp @@ -165,9 +165,9 @@ RotTransDragger::RotTransDragger() RotTransDragger::~RotTransDragger() { - if (rotFieldSensor!=nullptr) + if (rotFieldSensor) delete rotFieldSensor; - if (translFieldSensor!=nullptr) + if (translFieldSensor) delete translFieldSensor; } @@ -315,9 +315,9 @@ RotTransDragger::setUpConnections(SbBool onOff, SbBool doItAlways) unregisterChildDragger(ZD); // Disconnect the field sensors. - if (translFieldSensor->getAttachedField()!=nullptr) + if (translFieldSensor->getAttachedField()) translFieldSensor->detach(); - if (rotFieldSensor->getAttachedField()!=nullptr) + if (rotFieldSensor->getAttachedField()) rotFieldSensor->detach(); SoDragger::setUpConnections(onOff, doItAlways); @@ -334,7 +334,7 @@ RotTransDragger::valueChangedCB(void *, SoDragger *inDragger) RotTransDragger *myself = (RotTransDragger *) inDragger; // Factor the motionMatrix into its parts - SbMatrix motMat = myself->getMotionMatrix(); + SbMatrix motMat = myself->getMotionMatrix(); // clazy:exclude=rule-of-two-soft SbVec3f trans, scale; SbRotation rot, scaleOrient; motMat.getTransform(trans, rot, scale, scaleOrient); @@ -357,7 +357,7 @@ RotTransDragger::fieldSensorCB(void *inDragger, SoSensor *) { RotTransDragger *myself = (RotTransDragger *) inDragger; - SbMatrix motMat = myself->getMotionMatrix(); + SbMatrix motMat = myself->getMotionMatrix(); // clazy:exclude=rule-of-two-soft myself->workFieldsIntoTransform(motMat); myself->setMotionMatrix(motMat); @@ -374,7 +374,7 @@ RotTransDragger::invalidateSurroundScaleCB(void *parent, SoDragger *) // Invalidate the surroundScale, if it exists. SoSurroundScale *mySS = SO_CHECK_PART( myParentDragger, "surroundScale", SoSurroundScale); - if (mySS != nullptr) + if (mySS) mySS->invalidate(); } diff --git a/src/Gui/SoNavigationDragger.h b/src/Gui/SoNavigationDragger.h index 00c1091bae..a39fc8bcaa 100644 --- a/src/Gui/SoNavigationDragger.h +++ b/src/Gui/SoNavigationDragger.h @@ -105,20 +105,20 @@ class RotTransDragger : public SoDragger // and at the start/end of SoBaseKit::readInstance() // and on the new copy at the start/end of SoBaseKit::copy() // Returns the state of the node when this was called. - virtual SbBool setUpConnections( SbBool onOff, - SbBool doItAlways = false); + SbBool setUpConnections( SbBool onOff, + SbBool doItAlways = false) override; // This allows us to specify that certain parts do not // write out. We'll use this on the antiSquish and // surroundScale parts. - virtual void setDefaultOnNonWritingFields(); + void setDefaultOnNonWritingFields() override; private: static const char NavigationDraggerLayout[]; // Destructor. - ~RotTransDragger(); + ~RotTransDragger() override; }; #endif //SONAVIGATIONDRAGGER_H diff --git a/src/Gui/SoTextLabel.cpp b/src/Gui/SoTextLabel.cpp index 4fe5a78463..528b565c59 100644 --- a/src/Gui/SoTextLabel.cpp +++ b/src/Gui/SoTextLabel.cpp @@ -136,15 +136,12 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) SoMaterialBundle mb(action); mb.sendFirst(); const SbMatrix & mat = SoModelMatrixElement::get(state); - //const SbViewVolume & vv = SoViewVolumeElement::get(state); const SbMatrix & projmatrix = (mat * SoViewingMatrixElement::get(state) * SoProjectionMatrixElement::get(state)); const SbViewportRegion & vp = SoViewportRegionElement::get(state); SbVec2s vpsize = vp.getViewportSizePixels(); // font stuff - //float space = this->spacing.getValue(); - //float fontsize = SoFontSizeElement::get(state); SbName fontname = SoFontNameElement::get(state); int lines = this->string.getNum(); @@ -154,7 +151,6 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) nilpoint[0] = (nilpoint[0] + 1.0f) * 0.5f * vpsize[0]; nilpoint[1] = (nilpoint[1] + 1.0f) * 0.5f * vpsize[1]; -#if 1 // Unfortunately, the size of the label is stored in the pimpl class of // SoText2 which cannot be accessed directly. However, there is a trick // to get the required information: set model, viewing and projection @@ -203,40 +199,6 @@ void SoTextLabel::GLRender(SoGLRenderAction *action) if (lines > 1) { nilpoint[1] -= (float(lines-1)/(float)lines*height); } -#else - // Unfortunately, the required size (in pixels) is stored in a non-accessible way - // in the subclass SoText2. Thus, we try to get a satisfactory solution with Qt - // methods. - // The font name is of the form "family:style". If 'style' is given it can be - // 'Bold', 'Italic' or 'Bold Italic'. - QFont font; - QString fn = QString::fromLatin1(fontname.getString()); - int pos = fn.indexOf(QLatin1Char(':')); - if (pos > -1) { - if (fn.indexOf(QLatin1String("Bold"),pos,Qt::CaseInsensitive) > pos) - font.setBold(true); - if (fn.indexOf(QLatin1String("Italic"),pos,Qt::CaseInsensitive) > pos) - font.setItalic(true); - fn = fn.left(pos); - } - font.setFamily(fn); - font.setPixelSize((int)fontsize); - QFontMetrics fm(font); - - float width = 0.0f; - float height = 0.75f*fontsize*lines + (lines-1)*space;//fm.height(); - float hh=0; - for (int i = 0; i < lines; i++) { - SbString str = this->string[i]; - float w = fm.width(QLatin1String(this->string[i].getString())); - width = std::max(width, w); - hh = fm.height(); - } - - if (lines > 1) { - nilpoint[1] -= ((lines-1)*fontsize*0.75f+space); - } -#endif SbVec3f toppoint = nilpoint; toppoint[0] += width; @@ -377,25 +339,9 @@ void SoStringLabel::GLRender(SoGLRenderAction *action) glBlendFunc(GL_ONE,GL_SRC_ALPHA); - /* Background Box */ - //glColor4f(1,0.1f,0.1f,1); - //int ln =4; - //float ls = font.pixelSize()*1.5f; - //float bh = -1 + 2.0*(ls*(ln+.25))/float(window->height()); - - //glBegin(GL_QUADS); - //glVertex2f(-1.f,bh); glVertex2f(-1.f,-1.f); - //glVertex2f( 1.f,-1.f); glVertex2f( 1.f,bh); - //glEnd(); - - //float middleCol=window->width()*0.40; - //float rightCol=window->width()*0.85; - //float startPos = window->height()-(5+ls*(ln)); - // text color SbColor color = this->textColor.getValue(); glColor4f(color[0], color[1], color[2],1); - //window->renderText(20,20/*startPos+ 1*ls*/,QLatin1String(this->string[0].getString()),font); const SbMatrix & mat = SoModelMatrixElement::get(state); const SbMatrix & projmatrix = (mat * SoViewingMatrixElement::get(state) * SoProjectionMatrixElement::get(state)); @@ -404,11 +350,6 @@ void SoStringLabel::GLRender(SoGLRenderAction *action) QStringList list; for (int i=0; istring.getNum(); i++) list << QLatin1String(this->string[i].getString()); -#if 0 // Old OpenGL API - window->renderText(nil[0],nil[1],nil[2],list.join(QLatin1String("\n")),font); -#else - //FIXME: renderText -#endif // Leave 2D screen mode glPopAttrib(); @@ -523,76 +464,6 @@ void SoFrameLabel::drawImage() void SoFrameLabel::GLRender(SoGLRenderAction *action) { inherited::GLRender(action); -#if 0 - QtGLWidget* window; - SoState * state = action->getState(); - state->push(); - SoLazyElement::setLightModel(state, SoLazyElement::BASE_COLOR); - SoGLWidgetElement::get(state, window); - if (!window) { - state->pop(); - return; - } - - // Enter in 2D screen mode - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadIdentity(); - glOrtho(-1,1,-1,1,-1,1); - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadIdentity(); - glPushAttrib(GL_ENABLE_BIT); - glDisable(GL_DEPTH_TEST); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - - QFont font; - font.setStyleStrategy(QFont::NoAntialias); - font.setFamily(QLatin1String(this->name.getValue())); - font.setPixelSize(this->size.getValue()); - - glBlendFunc(GL_ONE,GL_SRC_ALPHA); - - /* Background Box */ - //glColor4f(1,0.1f,0.1f,1); - //int ln =4; - //float ls = font.pixelSize()*1.5f; - //float bh = -1 + 2.0*(ls*(ln+.25))/float(window->height()); - - //glBegin(GL_QUADS); - //glVertex2f(-1.f,bh); glVertex2f(-1.f,-1.f); - //glVertex2f( 1.f,-1.f); glVertex2f( 1.f,bh); - //glEnd(); - - //float middleCol=window->width()*0.40; - //float rightCol=window->width()*0.85; - //float startPos = window->height()-(5+ls*(ln)); - - // text color - SbColor color = this->textColor.getValue(); - glColor4f(color[0], color[1], color[2],1); - //window->renderText(20,20/*startPos+ 1*ls*/,QLatin1String(this->string[0].getString()),font); - const SbMatrix & mat = SoModelMatrixElement::get(state); - const SbMatrix & projmatrix = (mat * SoViewingMatrixElement::get(state) * - SoProjectionMatrixElement::get(state)); - SbVec3f nil(0.0f, 0.0f, 0.0f); - projmatrix.multVecMatrix(nil, nil); - QStringList list; - for (int i=0; istring.getNum(); i++) - list << QLatin1String(this->string[i].getString()); - window->renderText(nil[0],nil[1],nil[2],list.join(QLatin1String("\n")),font); - - // Leave 2D screen mode - glPopAttrib(); - glPopMatrix(); - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - glMatrixMode(GL_MODELVIEW); - - state->pop(); -#endif } // ------------------------------------------------------ diff --git a/src/Gui/SoTextLabel.h b/src/Gui/SoTextLabel.h index 882527523e..afcfc6ad15 100644 --- a/src/Gui/SoTextLabel.h +++ b/src/Gui/SoTextLabel.h @@ -55,8 +55,8 @@ public: SoSFFloat frameSize; protected: - virtual ~SoTextLabel() {} - virtual void GLRender(SoGLRenderAction *action); + ~SoTextLabel() override {} + void GLRender(SoGLRenderAction *action) override; }; /** @@ -91,8 +91,8 @@ public: SoSFInt32 size; protected: - virtual ~SoStringLabel() {}; - virtual void GLRender(SoGLRenderAction *action); + ~SoStringLabel() override {}; + void GLRender(SoGLRenderAction *action) override; }; class GuiExport SoFrameLabel : public SoImage { @@ -118,9 +118,9 @@ public: //SoSFImage image; protected: - virtual ~SoFrameLabel() {}; - virtual void notify(SoNotList * list); - virtual void GLRender(SoGLRenderAction *action); + ~SoFrameLabel() override {}; + void notify(SoNotList * list) override; + void GLRender(SoGLRenderAction *action) override; private: void drawImage(); @@ -137,7 +137,7 @@ public: private: // Destructor - ~TranslateManip(); + ~TranslateManip() override; }; } // namespace Gui diff --git a/src/Gui/SoTouchEvents.h b/src/Gui/SoTouchEvents.h index ccba4add80..809e167628 100644 --- a/src/Gui/SoTouchEvents.h +++ b/src/Gui/SoTouchEvents.h @@ -40,7 +40,7 @@ public: SO_EVENT_INIT_CLASS(SoGestureEvent, SoEvent); } SoGestureEvent() : state(SbGSNoGesture) {} - ~SoGestureEvent(){} + ~SoGestureEvent() override{} SbBool isSoGestureEvent(const SoEvent* ev) const; enum SbGestureState { @@ -61,7 +61,7 @@ public: } SoGesturePanEvent() {} SoGesturePanEvent(QPanGesture *qpan, QWidget *widget); - ~SoGesturePanEvent(){} + ~SoGesturePanEvent() override{} SbBool isSoGesturePanEvent(const SoEvent* ev) const; SbVec2f deltaOffset; @@ -79,7 +79,7 @@ public: { } SoGesturePinchEvent(QPinchGesture* qpinch, QWidget* widget); - ~SoGesturePinchEvent(){} + ~SoGesturePinchEvent() override{} SbBool isSoGesturePinchEvent(const SoEvent* ev) const; SbVec2f startCenter;//in GL pixel coordinates (from bottom left corner of view area) @@ -104,7 +104,7 @@ public: { } SoGestureSwipeEvent(QSwipeGesture* qwsipe, QWidget *widget); - ~SoGestureSwipeEvent(){} + ~SoGestureSwipeEvent() override{} SbBool isSoGestureSwipeEvent(const SoEvent* ev) const; double angle; @@ -115,10 +115,10 @@ public: class GesturesDevice : public Quarter::InputDevice { public: - GesturesDevice(QWidget* widget);//it needs to know the widget to do coordinate translation + explicit GesturesDevice(QWidget* widget);//it needs to know the widget to do coordinate translation - virtual ~GesturesDevice() {} - virtual const SoEvent* translateEvent(QEvent* event); + ~GesturesDevice() override {} + const SoEvent* translateEvent(QEvent* event) override; protected: QWidget* widget; }; diff --git a/src/Gui/SpaceballEvent.h b/src/Gui/SpaceballEvent.h index 8c10ebf681..ea56fc6d23 100644 --- a/src/Gui/SpaceballEvent.h +++ b/src/Gui/SpaceballEvent.h @@ -36,7 +36,7 @@ namespace Spaceball void setHandled(bool sig){handled = sig;} protected: - EventBase(QEvent::Type event); + explicit EventBase(QEvent::Type event); bool handled; }; diff --git a/src/Gui/SpinBox.cpp b/src/Gui/SpinBox.cpp index 39fdf910b2..b958e0fb07 100644 --- a/src/Gui/SpinBox.cpp +++ b/src/Gui/SpinBox.cpp @@ -171,7 +171,7 @@ void ExpressionSpinBox::openFormulaDialog() PropertyQuantity * qprop = freecad_dynamic_cast(getPath().getProperty()); Unit unit; - if (qprop != nullptr) + if (qprop) unit = qprop->getUnit(); Gui::Dialog::DlgExpressionInput* box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), unit, spinbox); diff --git a/src/Gui/SpinBox.h b/src/Gui/SpinBox.h index 144d505030..a81d0a454c 100644 --- a/src/Gui/SpinBox.h +++ b/src/Gui/SpinBox.h @@ -39,11 +39,11 @@ namespace Gui { class GuiExport ExpressionSpinBox : public ExpressionBinding { public: - ExpressionSpinBox(QAbstractSpinBox*); - virtual ~ExpressionSpinBox(); + explicit ExpressionSpinBox(QAbstractSpinBox*); + ~ExpressionSpinBox() override; - void bind(const App::ObjectIdentifier &_path); - void setExpression(std::shared_ptr expr); + void bind(const App::ObjectIdentifier &_path) override; + void setExpression(std::shared_ptr expr) override; protected: /*! Expression handling */ @@ -58,7 +58,7 @@ protected: void updateExpression(); //@} - void onChange(); + void onChange() override; virtual void setNumberExpression(App::NumberExpression*) = 0; void resizeWidget(); @@ -79,15 +79,15 @@ protected: class GuiExport UnsignedValidator : public QValidator { Q_OBJECT - Q_PROPERTY( uint bottom READ bottom WRITE setBottom ) - Q_PROPERTY( uint top READ top WRITE setTop ) + Q_PROPERTY( uint bottom READ bottom WRITE setBottom ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( uint top READ top WRITE setTop ) // clazy:exclude=qproperty-without-notify public: - UnsignedValidator( QObject * parent ); + explicit UnsignedValidator( QObject * parent ); UnsignedValidator( uint bottom, uint top, QObject * parent ); - ~UnsignedValidator(); + ~UnsignedValidator() override; - QValidator::State validate( QString &, int & ) const; + QValidator::State validate( QString &, int & ) const override; void setBottom( uint ); void setTop( uint ); @@ -115,23 +115,23 @@ class GuiExport UIntSpinBox : public QSpinBox, public ExpressionSpinBox Q_OVERRIDE( uint value READ value WRITE setValue ) public: - UIntSpinBox ( QWidget* parent=nullptr ); - virtual ~UIntSpinBox(); + explicit UIntSpinBox ( QWidget* parent=nullptr ); + ~UIntSpinBox() override; void setRange( uint minVal, uint maxVal ); uint value() const; - virtual QValidator::State validate ( QString & input, int & pos ) const; + QValidator::State validate ( QString & input, int & pos ) const override; uint minimum() const; void setMinimum( uint value ); uint maximum() const; void setMaximum( uint value ); - bool apply(const std::string &propName); + bool apply(const std::string &propName) override; using ExpressionSpinBox::apply; - void keyPressEvent(QKeyEvent *event); - void resizeEvent(QResizeEvent *event); - void paintEvent(QPaintEvent *event); + void keyPressEvent(QKeyEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void paintEvent(QPaintEvent *event) override; Q_SIGNALS: void valueChanged( uint value ); // clazy:exclude=overloaded-signal @@ -143,9 +143,9 @@ private Q_SLOTS: void valueChange( int value ); protected: - virtual QString textFromValue ( int v ) const; - virtual int valueFromText ( const QString & text ) const; - virtual void setNumberExpression(App::NumberExpression*); + QString textFromValue ( int v ) const override; + int valueFromText ( const QString & text ) const override; + void setNumberExpression(App::NumberExpression*) override; private: void updateValidator(); @@ -162,16 +162,16 @@ class GuiExport IntSpinBox : public QSpinBox, public ExpressionSpinBox Q_OBJECT public: - IntSpinBox ( QWidget* parent=nullptr ); - virtual ~IntSpinBox(); + explicit IntSpinBox ( QWidget* parent=nullptr ); + ~IntSpinBox() override; - bool apply(const std::string &propName); + bool apply(const std::string &propName) override; using ExpressionSpinBox::apply; - void setNumberExpression(App::NumberExpression*); + void setNumberExpression(App::NumberExpression*) override; - void keyPressEvent(QKeyEvent *event); - void resizeEvent(QResizeEvent *event); - void paintEvent(QPaintEvent *event); + void keyPressEvent(QKeyEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void paintEvent(QPaintEvent *event) override; }; /** @@ -184,16 +184,16 @@ class GuiExport DoubleSpinBox : public QDoubleSpinBox, public ExpressionSpinBox Q_OBJECT public: - DoubleSpinBox ( QWidget* parent=nullptr ); - virtual ~DoubleSpinBox(); + explicit DoubleSpinBox ( QWidget* parent=nullptr ); + ~DoubleSpinBox() override; - bool apply(const std::string &propName); + bool apply(const std::string &propName) override; using ExpressionSpinBox::apply; - void setNumberExpression(App::NumberExpression*); + void setNumberExpression(App::NumberExpression*) override; - void keyPressEvent(QKeyEvent *event); - void resizeEvent(QResizeEvent *event); - void paintEvent(QPaintEvent *event); + void keyPressEvent(QKeyEvent *event) override; + void resizeEvent(QResizeEvent *event) override; + void paintEvent(QPaintEvent *event) override; }; } // namespace Gui diff --git a/src/Gui/Splashscreen.cpp b/src/Gui/Splashscreen.cpp index 3965665159..70a0992f23 100644 --- a/src/Gui/Splashscreen.cpp +++ b/src/Gui/Splashscreen.cpp @@ -97,7 +97,7 @@ public: textColor = col; } } - virtual ~SplashObserver() + ~SplashObserver() override { Base::Console().DetachObserver(this); } @@ -686,9 +686,9 @@ void AboutDialog::on_copyButton_clicked() QString minor = QString::fromLatin1(config["BuildVersionMinor"].c_str()); QString build = QString::fromLatin1(config["BuildRevision"].c_str()); - QString deskEnv = QProcessEnvironment::systemEnvironment().value(QStringLiteral("XDG_CURRENT_DESKTOP"),QStringLiteral("")); - QString deskSess = QProcessEnvironment::systemEnvironment().value(QStringLiteral("DESKTOP_SESSION"),QStringLiteral("")); - QString deskInfo = QStringLiteral(""); + QString deskEnv = QProcessEnvironment::systemEnvironment().value(QStringLiteral("XDG_CURRENT_DESKTOP"), QString()); + QString deskSess = QProcessEnvironment::systemEnvironment().value(QStringLiteral("DESKTOP_SESSION"), QString()); + QString deskInfo; if ( !(deskEnv.isEmpty() && deskSess.isEmpty()) ) { if ( deskEnv.isEmpty() || deskSess.isEmpty() ) diff --git a/src/Gui/Splashscreen.h b/src/Gui/Splashscreen.h index 076242d793..a0368184f5 100644 --- a/src/Gui/Splashscreen.h +++ b/src/Gui/Splashscreen.h @@ -26,7 +26,7 @@ #include #include #include -#include "MDIView.h" +#include namespace Gui { @@ -41,11 +41,11 @@ class SplashScreen : public QSplashScreen Q_OBJECT public: - SplashScreen( const QPixmap & pixmap = QPixmap ( ), Qt::WindowFlags f = Qt::WindowFlags() ); - ~SplashScreen(); + explicit SplashScreen( const QPixmap & pixmap = QPixmap ( ), Qt::WindowFlags f = Qt::WindowFlags() ); + ~SplashScreen() override; protected: - void drawContents ( QPainter * painter ); + void drawContents ( QPainter * painter ) override; private: SplashObserver* messages; @@ -74,11 +74,11 @@ class GuiExport LicenseView : public Gui::MDIView Q_OBJECT public: - LicenseView(QWidget* parent=nullptr); - virtual ~LicenseView(); + explicit LicenseView(QWidget* parent=nullptr); + ~LicenseView() override; void setSource(const QUrl & url); - const char *getName(void) const { + const char *getName() const override { return "LicenseView"; } @@ -95,8 +95,8 @@ class GuiExport AboutDialog : public QDialog Q_OBJECT public: - AboutDialog(bool showLic, QWidget* parent = nullptr); - ~AboutDialog(); + explicit AboutDialog(bool showLic, QWidget* parent = nullptr); + ~AboutDialog() override; protected: void setupLabels(); diff --git a/src/Gui/SplitView3DInventor.cpp b/src/Gui/SplitView3DInventor.cpp index 125e2bc5e2..9945cbe0d6 100644 --- a/src/Gui/SplitView3DInventor.cpp +++ b/src/Gui/SplitView3DInventor.cpp @@ -286,10 +286,10 @@ void AbstractSplitView::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp (*it)->setPickRadius(rGrp.GetFloat("PickRadius", 5.0f)); } else { - unsigned long col1 = rGrp.GetUnsigned("BackgroundColor",3940932863UL); - unsigned long col2 = rGrp.GetUnsigned("BackgroundColor2",859006463UL); // default color (dark blue) - unsigned long col3 = rGrp.GetUnsigned("BackgroundColor3",2880160255UL); // default color (blue/grey) - unsigned long col4 = rGrp.GetUnsigned("BackgroundColor4",1869583359UL); // default color (blue/grey) + unsigned long col1 = rGrp.GetUnsigned("BackgroundColor", 3940932863UL); + unsigned long col2 = rGrp.GetUnsigned("BackgroundColor2", 2526456575UL); // default color (blue/grey) + unsigned long col3 = rGrp.GetUnsigned("BackgroundColor3", 3570714879UL); // default color (light yellow/blue) + unsigned long col4 = rGrp.GetUnsigned("BackgroundColor4", 1869583359UL); // default color (blue/grey) float r1,g1,b1,r2,g2,b2,r3,g3,b3,r4,g4,b4; r1 = ((col1 >> 24) & 0xff) / 255.0; g1 = ((col1 >> 16) & 0xff) / 255.0; b1 = ((col1 >> 8) & 0xff) / 255.0; r2 = ((col2 >> 24) & 0xff) / 255.0; g2 = ((col2 >> 16) & 0xff) / 255.0; b2 = ((col2 >> 8) & 0xff) / 255.0; @@ -305,12 +305,12 @@ void AbstractSplitView::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp } } -void AbstractSplitView::onUpdate(void) +void AbstractSplitView::onUpdate() { update(); } -const char *AbstractSplitView::getName(void) const +const char *AbstractSplitView::getName() const { return "SplitView3DInventor"; } @@ -423,7 +423,7 @@ void AbstractSplitView::setOverrideCursor(const QCursor& aCursor) //_viewer->getWidget()->setCursor(aCursor); } -PyObject *AbstractSplitView::getPyObject(void) +PyObject *AbstractSplitView::getPyObject() { if (!_viewerPy) _viewerPy = new AbstractSplitViewPy(this); @@ -502,7 +502,7 @@ Py::Object AbstractSplitViewPy::getattr(const char * attr) if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); - for (auto it : dict_base) { + for (const auto& it : dict_base) { dict_self.setItem(it.first, it.second); } return dict_self; @@ -728,7 +728,7 @@ Py::Object AbstractSplitViewPy::sequence_item(Py_ssize_t viewIndex) return Py::asObject(viewer); } -int AbstractSplitViewPy::sequence_length() +PyCxx_ssize_t AbstractSplitViewPy::sequence_length() { AbstractSplitView* view = getSplitViewPtr(); return view->getSize(); diff --git a/src/Gui/SplitView3DInventor.h b/src/Gui/SplitView3DInventor.h index 7cac36de13..f0c4e7d0e5 100644 --- a/src/Gui/SplitView3DInventor.h +++ b/src/Gui/SplitView3DInventor.h @@ -41,28 +41,28 @@ class GuiExport AbstractSplitView : public MDIView, public ParameterGrp::Observe { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: AbstractSplitView(Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags=Qt::WindowFlags()); - ~AbstractSplitView(); + ~AbstractSplitView() override; - virtual const char *getName(void) const; + const char *getName() const override; /// Message handler - virtual bool onMsg(const char* pMsg, const char** ppReturn); - virtual bool onHasMsg(const char* pMsg) const; - virtual void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason); - virtual void onUpdate(void); - virtual void deleteSelf(); - virtual void viewAll(); + bool onMsg(const char* pMsg, const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; + void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason) override; + void onUpdate() override; + void deleteSelf() override; + void viewAll() override; View3DInventorViewer *getViewer(unsigned int) const; - void setOverrideCursor(const QCursor&); - virtual bool containsViewProvider(const ViewProvider*) const; + void setOverrideCursor(const QCursor&) override; + bool containsViewProvider(const ViewProvider*) const override; - PyObject *getPyObject(void); - void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; int getSize(); protected: @@ -82,11 +82,11 @@ public: static void init_type(); // announce properties and methods AbstractSplitViewPy(AbstractSplitView *vi); - ~AbstractSplitViewPy(); + ~AbstractSplitViewPy() override; AbstractSplitView* getSplitViewPtr(); - Py::Object repr(); - Py::Object getattr(const char *); + Py::Object repr() override; + Py::Object getattr(const char *) override; Py::Object cast_to_base(const Py::Tuple&); Py::Object fitAll(const Py::Tuple&); @@ -98,9 +98,9 @@ public: Py::Object viewTop(const Py::Tuple&); Py::Object viewIsometric(const Py::Tuple&); Py::Object getViewer(const Py::Tuple&); - Py::Object sequence_item(Py_ssize_t); + Py::Object sequence_item(Py_ssize_t) override; Py::Object close(const Py::Tuple&); - int sequence_length(); + PyCxx_ssize_t sequence_length() override; private: Gui::MDIViewPy base; @@ -111,11 +111,11 @@ private: */ class GuiExport SplitView3DInventor : public AbstractSplitView { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: SplitView3DInventor(int views, Gui::Document* pcDocument, QWidget* parent, Qt::WindowFlags wflags=Qt::WindowFlags()); - ~SplitView3DInventor(); + ~SplitView3DInventor() override; }; } // namespace Gui diff --git a/src/Gui/Stylesheets/Behave-dark.qss b/src/Gui/Stylesheets/Behave-dark.qss index 03f2c1194c..76ecd5ee8c 100644 --- a/src/Gui/Stylesheets/Behave-dark.qss +++ b/src/Gui/Stylesheets/Behave-dark.qss @@ -181,12 +181,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #61D29D; + border: 2px #61D29D; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Dark-blue.qss b/src/Gui/Stylesheets/Dark-blue.qss index 6045930a2c..15e0e0c273 100644 --- a/src/Gui/Stylesheets/Dark-blue.qss +++ b/src/Gui/Stylesheets/Dark-blue.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #5e90fa; + border: 2px #5e90fa; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Dark-contrast.qss b/src/Gui/Stylesheets/Dark-contrast.qss index 95b97cf89b..2d0d6dd3f5 100644 --- a/src/Gui/Stylesheets/Dark-contrast.qss +++ b/src/Gui/Stylesheets/Dark-contrast.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #2053c0; + border: 2px #2053c0; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Dark-green.qss b/src/Gui/Stylesheets/Dark-green.qss index b0d489435e..bab84e98eb 100644 --- a/src/Gui/Stylesheets/Dark-green.qss +++ b/src/Gui/Stylesheets/Dark-green.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #94b30f; + border: 2px #94b30f; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Dark-orange.qss b/src/Gui/Stylesheets/Dark-orange.qss index ddecfea830..21529d214a 100644 --- a/src/Gui/Stylesheets/Dark-orange.qss +++ b/src/Gui/Stylesheets/Dark-orange.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #daa116; + border: 2px #daa116; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Darker-blue.qss b/src/Gui/Stylesheets/Darker-blue.qss index 407d781e62..97ee04decb 100644 --- a/src/Gui/Stylesheets/Darker-blue.qss +++ b/src/Gui/Stylesheets/Darker-blue.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #2053c0; + border: 2px #2053c0; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Darker-green.qss b/src/Gui/Stylesheets/Darker-green.qss index 0bb6608bbb..02f9df0be5 100644 --- a/src/Gui/Stylesheets/Darker-green.qss +++ b/src/Gui/Stylesheets/Darker-green.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #74831d; + border: 2px #74831d; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Darker-orange.qss b/src/Gui/Stylesheets/Darker-orange.qss index 1134deb704..6cca0e7e7f 100644 --- a/src/Gui/Stylesheets/Darker-orange.qss +++ b/src/Gui/Stylesheets/Darker-orange.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #b28416; + border: 2px #b28416; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Light-blue.qss b/src/Gui/Stylesheets/Light-blue.qss index be7a592570..2136fdcee3 100644 --- a/src/Gui/Stylesheets/Light-blue.qss +++ b/src/Gui/Stylesheets/Light-blue.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #5e90fa; + border: 2px #5e90fa; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Light-green.qss b/src/Gui/Stylesheets/Light-green.qss index aa97052ed2..a384a48428 100644 --- a/src/Gui/Stylesheets/Light-green.qss +++ b/src/Gui/Stylesheets/Light-green.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #94b30f; + border: 2px #94b30f; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/Light-orange.qss b/src/Gui/Stylesheets/Light-orange.qss index adbc6f7ee9..65b02d63dd 100644 --- a/src/Gui/Stylesheets/Light-orange.qss +++ b/src/Gui/Stylesheets/Light-orange.qss @@ -148,12 +148,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #daa116; + border: 2px #daa116; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/Stylesheets/ProDark.qss b/src/Gui/Stylesheets/ProDark.qss index 9fb73fb202..fe1cd94406 100644 --- a/src/Gui/Stylesheets/ProDark.qss +++ b/src/Gui/Stylesheets/ProDark.qss @@ -191,12 +191,20 @@ QMenu::right-arrow:selected { } QMenu::item { - padding: 2px 16px 2px 26px; /* make room for icon at left */ + padding: 2px 4px; /* make room for icon at left */ border: 1px solid transparent; /* reserve space for selection border */ } QMenu::icon { - margin-left: 2px; + margin-left: 1px; + margin-right: 1px; +} + +QMenu::icon:checked { /* appearance of a 'checked' icon */ + background: #557BB6; + border: 2px #557BB6; + position: absolute; + border-radius: 2px; } QMenu::separator { diff --git a/src/Gui/SyntaxHighlighter.h b/src/Gui/SyntaxHighlighter.h index a617cda0c4..b510bfcc5d 100644 --- a/src/Gui/SyntaxHighlighter.h +++ b/src/Gui/SyntaxHighlighter.h @@ -25,6 +25,7 @@ #define GUI_SYNTAXHIGHLIGHTER_H #include +#include namespace Gui { class SyntaxHighlighterP; diff --git a/src/Gui/TaskCSysDragger.h b/src/Gui/TaskCSysDragger.h index 0055fce7f6..b9d13b5901 100644 --- a/src/Gui/TaskCSysDragger.h +++ b/src/Gui/TaskCSysDragger.h @@ -38,11 +38,11 @@ namespace Gui Q_OBJECT public: TaskCSysDragger(ViewProviderDocumentObject *vpObjectIn, SoFCCSysDragger *draggerIn); - virtual ~TaskCSysDragger() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const override + ~TaskCSysDragger() override; + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok;} - virtual void open() override; - virtual bool accept() override; + void open() override; + bool accept() override; private Q_SLOTS: void onTIncrementSlot(double freshValue); void onRIncrementSlot(double freshValue); diff --git a/src/Gui/TaskDlgRelocation.h b/src/Gui/TaskDlgRelocation.h index 7b871b6002..d26d043b8f 100644 --- a/src/Gui/TaskDlgRelocation.h +++ b/src/Gui/TaskDlgRelocation.h @@ -38,8 +38,8 @@ class TaskBoxPosition : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskBoxPosition(QWidget *parent = nullptr); - ~TaskBoxPosition(); + explicit TaskBoxPosition(QWidget *parent = nullptr); + ~TaskBoxPosition() override; private Q_SLOTS: @@ -56,8 +56,8 @@ class TaskBoxAngle : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskBoxAngle(QWidget *parent = nullptr); - ~TaskBoxAngle(); + explicit TaskBoxAngle(QWidget *parent = nullptr); + ~TaskBoxAngle() override; private Q_SLOTS: @@ -77,22 +77,22 @@ class GuiExport TaskDlgRelocation : public Gui::TaskView::TaskDialog public: TaskDlgRelocation(); - ~TaskDlgRelocation(); + ~TaskDlgRelocation() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or rject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } protected: diff --git a/src/Gui/TaskElementColors.cpp b/src/Gui/TaskElementColors.cpp index 40a9007556..1bdfea3a36 100644 --- a/src/Gui/TaskElementColors.cpp +++ b/src/Gui/TaskElementColors.cpp @@ -72,7 +72,7 @@ public: std::string editSub; std::string editElement; - Private(ViewProviderDocumentObject* vp, const char *element="") + explicit Private(ViewProviderDocumentObject* vp, const char *element="") : ui(new Ui_TaskElementColors()), vp(vp),editElement(element) { vpDoc = vp->getDocument(); @@ -100,7 +100,7 @@ public: px = QPixmap(w,w); } - ~Private() { + ~Private() override { try { vpParent->OnTopWhenSelected.setValue(onTopMode); } @@ -109,7 +109,7 @@ public: } } - bool allow(App::Document *doc, App::DocumentObject *obj, const char *subname) { + bool allow(App::Document *doc, App::DocumentObject *obj, const char *subname) override { if(editDoc!=doc->getName() || editObj!=obj->getNameInDocument() || !boost::starts_with(subname,editSub)) @@ -206,7 +206,7 @@ public: } void removeAll() { - if(elements.size()) { + if(!elements.empty()) { hiddenSub.clear(); ui->elementList->clear(); elements.clear(); @@ -215,7 +215,8 @@ public: } void removeItems() { - for(auto item : ui->elementList->selectedItems()) { + const auto items = ui->elementList->selectedItems(); + for(auto item : items) { std::string sub = qPrintable(item->data(Qt::UserRole+1).value()); if(sub == hiddenSub) hiddenSub.clear(); @@ -259,8 +260,8 @@ public: editObj == msg.pObjectName && boost::starts_with(msg.pSubName,editSub)) { - for(auto item : ui->elementList->findItems( - QString::fromLatin1(msg.pSubName-editSub.size()), Qt::MatchExactly)) + const auto items = ui->elementList->findItems(QString::fromLatin1(msg.pSubName-editSub.size()), Qt::MatchExactly); + for(auto item : items) item->setSelected(msg.Type==SelectionChanges::AddSelection); } } @@ -285,7 +286,8 @@ public: } break; } - for(auto item : ui->elementList->selectedItems()) { + const auto items = ui->elementList->selectedItems(); + for(auto item : items) { std::string name(qPrintable(item->data(Qt::UserRole+1).value())); if(ViewProvider::hasHiddenMarker(name.c_str())) continue; @@ -384,7 +386,7 @@ void ElementColors::on_hideSelection_clicked() { if(d->editObj!=sel.getFeatName()) continue; const auto &subs = sel.getSubNames(); - if(subs.size()) { + if(!subs.empty()) { for(auto &sub : subs) { if(boost::starts_with(sub,d->editSub)) { auto name = Data::ComplexGeoData::noElementName(sub.c_str()+d->editSub.size()); @@ -420,7 +422,7 @@ void ElementColors::on_addSelection_clicked() break; } } - if(d->items.size()) { + if(!d->items.empty()) { auto color = d->items.front()->data(Qt::UserRole).value(); QColorDialog cd(color, this); cd.setOption(QColorDialog::ShowAlphaChannel); @@ -468,7 +470,7 @@ void ElementColors::changeEvent(QEvent *e) void ElementColors::leaveEvent(QEvent *e) { QWidget::leaveEvent(e); Selection().rmvPreselect(); - if(d->hiddenSub.size()) { + if(!d->hiddenSub.empty()) { d->vp->partialRender({d->hiddenSub},false); d->hiddenSub.clear(); } @@ -476,7 +478,7 @@ void ElementColors::leaveEvent(QEvent *e) { void ElementColors::on_elementList_itemEntered(QListWidgetItem *item) { std::string name(qPrintable(item->data(Qt::UserRole+1).value())); - if(d->hiddenSub.size()) { + if(!d->hiddenSub.empty()) { d->vp->partialRender({d->hiddenSub},false); d->hiddenSub.clear(); } diff --git a/src/Gui/TaskElementColors.h b/src/Gui/TaskElementColors.h index 34bb5b122b..75cefc93ff 100644 --- a/src/Gui/TaskElementColors.h +++ b/src/Gui/TaskElementColors.h @@ -38,8 +38,8 @@ class GuiExport ElementColors : public QWidget, public SelectionObserver Q_OBJECT public: - ElementColors(ViewProviderDocumentObject* vp, bool noHide=false); - ~ElementColors(); + explicit ElementColors(ViewProviderDocumentObject* vp, bool noHide=false); + ~ElementColors() override; bool accept(); bool reject(); @@ -57,9 +57,9 @@ private Q_SLOTS: void on_boxSelect_clicked(); protected: - void onSelectionChanged(const SelectionChanges& msg); - void changeEvent(QEvent *e); - void leaveEvent(QEvent *); + void onSelectionChanged(const SelectionChanges& msg) override; + void changeEvent(QEvent *e) override; + void leaveEvent(QEvent *) override; void slotDeleteDocument(const Document&); void slotDeleteObject(const ViewProvider&); private: @@ -72,16 +72,16 @@ class GuiExport TaskElementColors : public TaskView::TaskDialog Q_OBJECT public: - TaskElementColors(ViewProviderDocumentObject* vp, bool noHide=false); - ~TaskElementColors(); + explicit TaskElementColors(ViewProviderDocumentObject* vp, bool noHide=false); + ~TaskElementColors() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Gui/TaskView/TaskAppearance.h b/src/Gui/TaskView/TaskAppearance.h index f67e8b7441..81e6fdd634 100644 --- a/src/Gui/TaskView/TaskAppearance.h +++ b/src/Gui/TaskView/TaskAppearance.h @@ -45,11 +45,11 @@ class TaskAppearance : public TaskBox, public Gui::SelectionSingleton::ObserverT Q_OBJECT public: - TaskAppearance(QWidget *parent = nullptr); - ~TaskAppearance(); + explicit TaskAppearance(QWidget *parent = nullptr); + ~TaskAppearance() override; /// Observer message from the Selection void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason); + Gui::SelectionSingleton::MessageType Reason) override; private Q_SLOTS: void on_changeMode_activated(const QString&); @@ -59,7 +59,7 @@ private Q_SLOTS: void on_spinLineWidth_valueChanged(int); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: void slotChangedObject(const Gui::ViewProvider&, const App::Property& Prop); diff --git a/src/Gui/TaskView/TaskDialog.cpp b/src/Gui/TaskView/TaskDialog.cpp index a2358c161a..9e8a30abd5 100644 --- a/src/Gui/TaskView/TaskDialog.cpp +++ b/src/Gui/TaskView/TaskDialog.cpp @@ -55,7 +55,7 @@ TaskDialog::~TaskDialog() //==== Slots =============================================================== -const std::vector &TaskDialog::getDialogContent(void) const +const std::vector &TaskDialog::getDialogContent() const { return Content; } diff --git a/src/Gui/TaskView/TaskDialog.h b/src/Gui/TaskView/TaskDialog.h index 6494023ff0..b399793330 100644 --- a/src/Gui/TaskView/TaskDialog.h +++ b/src/Gui/TaskView/TaskDialog.h @@ -28,6 +28,7 @@ #include #include +#include namespace App { @@ -50,17 +51,17 @@ public: }; TaskDialog(); - ~TaskDialog(); + ~TaskDialog() override; void setButtonPosition(ButtonPosition p) { pos = p; } ButtonPosition buttonPosition() const { return pos; } - const std::vector &getDialogContent(void) const; + const std::vector &getDialogContent() const; bool canClose() const; /// tells the framework which buttons are wished for the dialog - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + virtual QDialogButtonBox::StandardButtons getStandardButtons() const { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } virtual void modifyStandardButtons(QDialogButtonBox*) {} @@ -90,19 +91,19 @@ public: Indicates whether this task dialog allows other commands to modify the document while it is open. */ - virtual bool isAllowedAlterDocument(void) const + virtual bool isAllowedAlterDocument() const { return false; } /*! Indicates whether this task dialog allows other commands to modify the 3d view while it is open. */ - virtual bool isAllowedAlterView(void) const + virtual bool isAllowedAlterView() const { return true; } /*! Indicates whether this task dialog allows other commands to modify the selection while it is open. */ - virtual bool isAllowedAlterSelection(void) const + virtual bool isAllowedAlterSelection() const { return true; } virtual bool needsFullSpace() const { return false; } diff --git a/src/Gui/TaskView/TaskDialogPython.cpp b/src/Gui/TaskView/TaskDialogPython.cpp index dd4643f3cf..e1588b3b61 100644 --- a/src/Gui/TaskView/TaskDialogPython.cpp +++ b/src/Gui/TaskView/TaskDialogPython.cpp @@ -128,7 +128,7 @@ Py::Object ControlPy::activeDialog(const Py::Tuple& args) if (!PyArg_ParseTuple(args.ptr(), "")) throw Py::Exception(); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - return Py::Boolean(dlg!=nullptr); + return Py::Boolean(dlg != nullptr); } Py::Object ControlPy::closeDialog(const Py::Tuple& args) @@ -478,7 +478,7 @@ void TaskDialogPython::helpRequested() } } -QDialogButtonBox::StandardButtons TaskDialogPython::getStandardButtons(void) const +QDialogButtonBox::StandardButtons TaskDialogPython::getStandardButtons() const { Base::PyGILStateLocker lock; try { @@ -518,7 +518,7 @@ void TaskDialogPython::modifyStandardButtons(QDialogButtonBox *buttonBox) } } -bool TaskDialogPython::isAllowedAlterDocument(void) const +bool TaskDialogPython::isAllowedAlterDocument() const { Base::PyGILStateLocker lock; try { @@ -537,7 +537,7 @@ bool TaskDialogPython::isAllowedAlterDocument(void) const return TaskDialog::isAllowedAlterDocument(); } -bool TaskDialogPython::isAllowedAlterView(void) const +bool TaskDialogPython::isAllowedAlterView() const { Base::PyGILStateLocker lock; try { @@ -556,7 +556,7 @@ bool TaskDialogPython::isAllowedAlterView(void) const return TaskDialog::isAllowedAlterView(); } -bool TaskDialogPython::isAllowedAlterSelection(void) const +bool TaskDialogPython::isAllowedAlterSelection() const { Base::PyGILStateLocker lock; try { diff --git a/src/Gui/TaskView/TaskDialogPython.h b/src/Gui/TaskView/TaskDialogPython.h index 178f562c7e..fb08258fe2 100644 --- a/src/Gui/TaskView/TaskDialogPython.h +++ b/src/Gui/TaskView/TaskDialogPython.h @@ -34,13 +34,13 @@ namespace TaskView { class ControlPy : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods static ControlPy* getInstance(); ControlPy(); - ~ControlPy(); + ~ControlPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object showDialog(const Py::Tuple&); Py::Object activeDialog(const Py::Tuple&); Py::Object closeDialog(const Py::Tuple&); @@ -59,9 +59,9 @@ private: class GuiExport TaskWatcherPython : public TaskWatcher { public: - TaskWatcherPython(const Py::Object&); - ~TaskWatcherPython(); - bool shouldShow(); + explicit TaskWatcherPython(const Py::Object&); + ~TaskWatcherPython() override; + bool shouldShow() override; private: Py::Object watcher; @@ -70,40 +70,40 @@ private: class GuiExport TaskDialogPython : public TaskDialog { public: - TaskDialogPython(const Py::Object&); - ~TaskDialogPython(); + explicit TaskDialogPython(const Py::Object&); + ~TaskDialogPython() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const; - virtual void modifyStandardButtons(QDialogButtonBox*); + QDialogButtonBox::StandardButtons getStandardButtons() const override; + void modifyStandardButtons(QDialogButtonBox*) override; /*! Indicates whether this task dialog allows other commands to modify the document while it is open. */ - virtual bool isAllowedAlterDocument(void) const; + bool isAllowedAlterDocument() const override; /*! Indicates whether this task dialog allows other commands to modify the 3d view while it is open. */ - virtual bool isAllowedAlterView(void) const; + bool isAllowedAlterView() const override; /*! Indicates whether this task dialog allows other commands to modify the selection while it is open. */ - virtual bool isAllowedAlterSelection(void) const; - virtual bool needsFullSpace() const; + bool isAllowedAlterSelection() const override; + bool needsFullSpace() const override; public: /// is called by the framework when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if a button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; private: void clearForm(); diff --git a/src/Gui/TaskView/TaskEditControl.h b/src/Gui/TaskView/TaskEditControl.h index f0997673d2..2f51cb53ec 100644 --- a/src/Gui/TaskView/TaskEditControl.h +++ b/src/Gui/TaskView/TaskEditControl.h @@ -46,8 +46,8 @@ class TaskEditControl : public TaskWidget Q_OBJECT public: - TaskEditControl(QWidget *parent = nullptr); - ~TaskEditControl(); + explicit TaskEditControl(QWidget *parent = nullptr); + ~TaskEditControl() override; QDialogButtonBox* standardButtons() const; friend class TaskView; diff --git a/src/Gui/TaskView/TaskSelectLinkProperty.cpp b/src/Gui/TaskView/TaskSelectLinkProperty.cpp index f15e9e7534..93f03e51cc 100644 --- a/src/Gui/TaskView/TaskSelectLinkProperty.cpp +++ b/src/Gui/TaskView/TaskSelectLinkProperty.cpp @@ -102,7 +102,7 @@ bool TaskSelectLinkProperty::setFilter(const char * sFilter) } -void TaskSelectLinkProperty::activate(void) +void TaskSelectLinkProperty::activate() { // first clear the selection Gui::Selection().clearSelection(); @@ -140,7 +140,7 @@ void TaskSelectLinkProperty::activate(void) checkSelectionStatus(); } -bool TaskSelectLinkProperty::accept(void) +bool TaskSelectLinkProperty::accept() { // set the proptery with the selection sendSelection2Property(); @@ -151,7 +151,7 @@ bool TaskSelectLinkProperty::accept(void) return true; } -bool TaskSelectLinkProperty::reject(void) +bool TaskSelectLinkProperty::reject() { if(LinkSub){ // restore the old values @@ -164,7 +164,7 @@ bool TaskSelectLinkProperty::reject(void) return true; } -void TaskSelectLinkProperty::sendSelection2Property(void) +void TaskSelectLinkProperty::sendSelection2Property() { if (LinkSub) { std::vector temp = Gui::Selection().getSelectionEx(); @@ -182,7 +182,7 @@ void TaskSelectLinkProperty::sendSelection2Property(void) } -void TaskSelectLinkProperty::checkSelectionStatus(void) +void TaskSelectLinkProperty::checkSelectionStatus() { QPalette palette(QApplication::palette()); diff --git a/src/Gui/TaskView/TaskSelectLinkProperty.h b/src/Gui/TaskView/TaskSelectLinkProperty.h index 2abd6aa0fb..497b30c661 100644 --- a/src/Gui/TaskView/TaskSelectLinkProperty.h +++ b/src/Gui/TaskView/TaskSelectLinkProperty.h @@ -57,25 +57,25 @@ class GuiExport TaskSelectLinkProperty : public TaskBox, public Gui::SelectionSi public: TaskSelectLinkProperty(const char *,App::Property *,QWidget *parent = nullptr); - ~TaskSelectLinkProperty(); + ~TaskSelectLinkProperty() override; /// Observer message from the Selection void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason); + Gui::SelectionSingleton::MessageType Reason) override; /// set the filter criterion (same as in constructor) bool setFilter(const char*); /// set the TaskSelectLinkProperty active, means setting the selection and control it - void activate(void); + void activate(); /// call this to accept the changes the user has made and send back to the Property (Ok) - bool accept(void); + bool accept(); /// This discards the changes of the user and leaves the Property untouched (Cancel) - bool reject(void); + bool reject(); /// send the selection to the Property for e.g. forced recomputation of a feature - void sendSelection2Property(void); + void sendSelection2Property(); /// checks if the filter is currently met - inline bool isSelectionValid(void) const {return Filter->match();} + inline bool isSelectionValid() const {return Filter->match();} private Q_SLOTS: void on_Remove_clicked(bool); @@ -84,15 +84,15 @@ private Q_SLOTS: void on_Help_clicked(bool); Q_SIGNALS: - void emitSelectionFit(void); - void emitSelectionMisfit(void); + void emitSelectionFit(); + void emitSelectionMisfit(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: // checks for selection and set background color and signals - void checkSelectionStatus(void); + void checkSelectionStatus(); QWidget* proxy; Ui_TaskSelectLinkProperty* ui; diff --git a/src/Gui/TaskView/TaskView.cpp b/src/Gui/TaskView/TaskView.cpp index 1cd46d7c47..28bed5fc13 100644 --- a/src/Gui/TaskView/TaskView.cpp +++ b/src/Gui/TaskView/TaskView.cpp @@ -523,7 +523,7 @@ void TaskView::showDialog(TaskDialog *dlg) getMainWindow()->updateActions(); } -void TaskView::removeDialog(void) +void TaskView::removeDialog() { getMainWindow()->updateActions(); @@ -561,7 +561,7 @@ void TaskView::removeDialog(void) } } -void TaskView::updateWatcher(void) +void TaskView::updateWatcher() { // In case a child of the TaskView has the focus and get hidden we have // to make sure to set the focus on a widget that won't be hidden or @@ -608,7 +608,7 @@ void TaskView::addTaskWatcher(const std::vector &Watcher) addTaskWatcher(); } -void TaskView::clearTaskWatcher(void) +void TaskView::clearTaskWatcher() { std::vector watcher; removeTaskWatcher(); @@ -616,7 +616,7 @@ void TaskView::clearTaskWatcher(void) addTaskWatcher(watcher); } -void TaskView::addTaskWatcher(void) +void TaskView::addTaskWatcher() { // add all widgets for all watcher to the task view for (std::vector::iterator it=ActiveWatcher.begin();it!=ActiveWatcher.end();++it){ @@ -646,7 +646,7 @@ void TaskView::addTaskWatcher(void) taskPanel->setScheme(QSint::FreeCADPanelScheme::defaultScheme()); } -void TaskView::removeTaskWatcher(void) +void TaskView::removeTaskWatcher() { // In case a child of the TaskView has the focus and get hidden we have // to make sure that set the focus on a widget that won't be hidden or diff --git a/src/Gui/TaskView/TaskView.h b/src/Gui/TaskView/TaskView.h index 5f1c0b9064..c30ba52e9c 100644 --- a/src/Gui/TaskView/TaskView.h +++ b/src/Gui/TaskView/TaskView.h @@ -64,10 +64,10 @@ public: explicit TaskGroup(QWidget *parent = nullptr); explicit TaskGroup(const QString & headerText, QWidget *parent = nullptr); explicit TaskGroup(const QPixmap & icon, const QString & headerText, QWidget *parent = nullptr); - ~TaskGroup(); + ~TaskGroup() override; protected: - void actionEvent (QActionEvent*); + void actionEvent (QActionEvent*) override; }; /// Father class of content with header and Icon @@ -98,15 +98,15 @@ public: const QString& title, bool expandable = true, QWidget *parent = nullptr); - virtual QSize minimumSizeHint() const; + QSize minimumSizeHint() const override; - ~TaskBox(); + ~TaskBox() override; void hideGroupBox(); bool isGroupVisible() const; protected: - void showEvent(QShowEvent*); - void actionEvent (QActionEvent*); + void showEvent(QShowEvent*) override; + void actionEvent (QActionEvent*) override; private: bool wasShown; @@ -118,8 +118,8 @@ class GuiExport TaskPanel : public QSint::ActionPanel public: explicit TaskPanel(QWidget *parent = nullptr); - virtual ~TaskPanel(); - virtual QSize minimumSizeHint() const; + ~TaskPanel() override; + QSize minimumSizeHint() const override; }; /// Father class of content of a Free widget (without header and Icon), shut be an exception! @@ -128,8 +128,8 @@ class GuiExport TaskWidget : public QWidget, public TaskContent Q_OBJECT public: - TaskWidget(QWidget *parent=nullptr); - ~TaskWidget(); + explicit TaskWidget(QWidget *parent=nullptr); + ~TaskWidget() override; }; /** TaskView class @@ -142,18 +142,18 @@ class GuiExport TaskView : public QScrollArea, public Gui::SelectionSingleton::O Q_OBJECT public: - TaskView(QWidget *parent = nullptr); - ~TaskView(); + explicit TaskView(QWidget *parent = nullptr); + ~TaskView() override; /// Observer message from the Selection - virtual void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason); + void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, + Gui::SelectionSingleton::MessageType Reason) override; friend class Gui::DockWnd::ComboView; friend class Gui::ControlSingleton; void addTaskWatcher(const std::vector &Watcher); - void clearTaskWatcher(void); + void clearTaskWatcher(); void clearActionStyle(); void restoreActionStyle(); @@ -165,17 +165,17 @@ protected Q_SLOTS: void clicked (QAbstractButton * button); protected: - virtual void keyPressEvent(QKeyEvent*); - virtual bool event(QEvent*); + void keyPressEvent(QKeyEvent*) override; + bool event(QEvent*) override; - void addTaskWatcher(void); - void removeTaskWatcher(void); + void addTaskWatcher(); + void removeTaskWatcher(); /// update the visibility of the TaskWatcher accordant to the selection - void updateWatcher(void); + void updateWatcher(); /// used by Gui::Control to register Dialogs void showDialog(TaskDialog *dlg); // removes the running dialog after accept() or reject() from the TaskView - void removeDialog(void); + void removeDialog(); void slotActiveDocument(const App::Document&); void slotDeletedDocument(); diff --git a/src/Gui/TaskView/TaskWatcher.cpp b/src/Gui/TaskView/TaskWatcher.cpp index 14ae2f6f76..014e9c32f7 100644 --- a/src/Gui/TaskView/TaskWatcher.cpp +++ b/src/Gui/TaskView/TaskWatcher.cpp @@ -59,7 +59,7 @@ TaskWatcher::~TaskWatcher() //==== implementer =========================================================================== -std::vector &TaskWatcher::getWatcherContent(void) +std::vector &TaskWatcher::getWatcherContent() { return Content; } diff --git a/src/Gui/TaskView/TaskWatcher.h b/src/Gui/TaskView/TaskWatcher.h index a4a5b1bcfd..147fe71dba 100644 --- a/src/Gui/TaskView/TaskWatcher.h +++ b/src/Gui/TaskView/TaskWatcher.h @@ -41,14 +41,14 @@ class GuiExport TaskWatcher : public QObject, public Gui::SelectionFilter Q_OBJECT public: - TaskWatcher(const char* Filter); - virtual ~TaskWatcher(); + explicit TaskWatcher(const char* Filter); + ~TaskWatcher() override; - std::vector &getWatcherContent(void); + std::vector &getWatcherContent(); public: /// is called wenn the document or the Selection changes. - virtual bool shouldShow(void); + virtual bool shouldShow(); protected: /// List of TaskBoxes of that dialog @@ -68,7 +68,7 @@ public: public: /// is called wenn the document or the Selection changes. - virtual bool shouldShow(void); + bool shouldShow() override; }; @@ -84,7 +84,7 @@ public: public: /// is called wenn the document or the Selection changes. - virtual bool shouldShow(void); + bool shouldShow() override; }; @@ -97,11 +97,11 @@ class GuiExport TaskWatcherCommandsEmptySelection : public TaskWatcherCommands public: TaskWatcherCommandsEmptySelection(const char* commands[], const char* name, const char* pixmap); - ~TaskWatcherCommandsEmptySelection(); + ~TaskWatcherCommandsEmptySelection() override; public: /// is called wenn the document or the Selection changes. - virtual bool shouldShow(void); + bool shouldShow() override; }; diff --git a/src/Gui/TextDocumentEditorView.h b/src/Gui/TextDocumentEditorView.h index 28ac3b90fc..0ba1d6f165 100644 --- a/src/Gui/TextDocumentEditorView.h +++ b/src/Gui/TextDocumentEditorView.h @@ -40,7 +40,7 @@ public: TextDocumentEditorView( App::TextDocument* textDocument, QPlainTextEdit* editor, QWidget* parent); - ~TextDocumentEditorView(); + ~TextDocumentEditorView() override; const char *getName() const override { return "TextDocumentEditorView"; } bool onMsg(const char* msg, const char**) override; bool onHasMsg(const char* msg) const override; diff --git a/src/Gui/TextEdit.h b/src/Gui/TextEdit.h index 26a1025ec2..8e1f7d9fb0 100644 --- a/src/Gui/TextEdit.h +++ b/src/Gui/TextEdit.h @@ -57,8 +57,8 @@ class GuiExport TextEdit : public QPlainTextEdit Q_OBJECT public: - TextEdit(QWidget *parent = nullptr); - virtual ~TextEdit(); + explicit TextEdit(QWidget *parent = nullptr); + ~TextEdit() override; private Q_SLOTS: void complete(); @@ -69,7 +69,7 @@ Q_SIGNALS: void findPrevious(); protected: - void keyPressEvent(QKeyEvent *); + void keyPressEvent(QKeyEvent *) override; private: void createListBox(); @@ -86,11 +86,11 @@ class GuiExport TextEditor : public TextEdit, public WindowParameter Q_OBJECT public: - TextEditor(QWidget *parent = nullptr); - ~TextEditor(); + explicit TextEditor(QWidget *parent = nullptr); + ~TextEditor() override; void setSyntaxHighlighter(SyntaxHighlighter*); - void OnChange(Base::Subject &rCaller,const char* rcReason); + void OnChange(Base::Subject &rCaller,const char* rcReason) override; void lineNumberAreaPaintEvent(QPaintEvent* ); int lineNumberAreaWidth(); @@ -101,10 +101,10 @@ private Q_SLOTS: void highlightCurrentLine(); protected: - void keyPressEvent (QKeyEvent * e); + void keyPressEvent (QKeyEvent * e) override; /** Draw a beam in the line where the cursor is. */ - void paintEvent (QPaintEvent * e); - void resizeEvent(QResizeEvent* e); + void paintEvent (QPaintEvent * e) override; + void resizeEvent(QResizeEvent* e) override; QWidget* getMarker() const { return lineNumberArea; } virtual void drawMarker(int line, int x, int y, QPainter*); @@ -122,13 +122,13 @@ class LineMarker : public QWidget Q_OBJECT public: - LineMarker(TextEditor* editor); - virtual ~LineMarker(); + explicit LineMarker(TextEditor* editor); + ~LineMarker() override; - QSize sizeHint() const; + QSize sizeHint() const override; protected: - void paintEvent (QPaintEvent *); + void paintEvent (QPaintEvent *) override; private: TextEditor *textEditor; @@ -145,14 +145,14 @@ class CompletionList : public QListWidget public: /// Construction - CompletionList(QPlainTextEdit* parent); + explicit CompletionList(QPlainTextEdit* parent); /// Destruction - ~CompletionList(); + ~CompletionList() override; void findCurrentWord(const QString&); protected: - bool eventFilter(QObject *, QEvent *); + bool eventFilter(QObject *, QEvent *) override; private Q_SLOTS: void completionItem(QListWidgetItem *item); diff --git a/src/Gui/TextureMapping.h b/src/Gui/TextureMapping.h index 482dd44625..a3ec51ac9c 100644 --- a/src/Gui/TextureMapping.h +++ b/src/Gui/TextureMapping.h @@ -39,7 +39,7 @@ class GuiExport TextureMapping : public QDialog Q_OBJECT public: - TextureMapping(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + explicit TextureMapping(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); ~TextureMapping(); void accept(); void reject(); @@ -66,13 +66,13 @@ class TaskTextureMapping : public Gui::TaskView::TaskDialog public: TaskTextureMapping(); - ~TaskTextureMapping(); + ~TaskTextureMapping() override; public: - bool accept(); - bool reject(); + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Close; } private: diff --git a/src/Gui/Thumbnail.cpp b/src/Gui/Thumbnail.cpp index 50709df7ac..aa41e9686b 100644 --- a/src/Gui/Thumbnail.cpp +++ b/src/Gui/Thumbnail.cpp @@ -65,7 +65,7 @@ void Thumbnail::setFileName(const char* fn) this->uri = QUrl::fromLocalFile(QString::fromUtf8(fn)); } -unsigned int Thumbnail::getMemSize (void) const +unsigned int Thumbnail::getMemSize () const { return 0; } diff --git a/src/Gui/Thumbnail.h b/src/Gui/Thumbnail.h index 5bd487ff81..2563ef30df 100644 --- a/src/Gui/Thumbnail.h +++ b/src/Gui/Thumbnail.h @@ -36,7 +36,7 @@ class Thumbnail : public Base::Persistence { public: Thumbnail(int s = 128); - ~Thumbnail(); + ~Thumbnail() override; void setViewer(View3DInventorViewer*); void setSize(int); @@ -44,15 +44,15 @@ public: /** @name I/O of the document */ //@{ - unsigned int getMemSize (void) const; + unsigned int getMemSize () const override; /// This method is used to save properties or very small amounts of data to an XML document. - void Save (Base::Writer &writer) const; + void Save (Base::Writer &writer) const override; /// This method is used to restore properties from an XML document. - void Restore(Base::XMLReader &reader); + void Restore(Base::XMLReader &reader) override; /// This method is used to save large amounts of data to a binary file. - void SaveDocFile (Base::Writer &writer) const; + void SaveDocFile (Base::Writer &writer) const override; /// This method is used to restore large amounts of data from a binary file. - void RestoreDocFile(Base::Reader &reader); + void RestoreDocFile(Base::Reader &reader) override; //@} private: diff --git a/src/Gui/TransactionObject.h b/src/Gui/TransactionObject.h index 155ec36dc3..c5a00c6859 100644 --- a/src/Gui/TransactionObject.h +++ b/src/Gui/TransactionObject.h @@ -30,14 +30,14 @@ namespace Gui { class TransactionViewProvider : public App::TransactionObject { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: TransactionViewProvider(); - virtual ~TransactionViewProvider(); + ~TransactionViewProvider() override; - void applyNew(App::Document& Doc, App::TransactionalObject* pcObj); - void applyDel(App::Document& Doc, App::TransactionalObject* pcObj); + void applyNew(App::Document& Doc, App::TransactionalObject* pcObj) override; + void applyDel(App::Document& Doc, App::TransactionalObject* pcObj) override; }; } //namespace Gui diff --git a/src/Gui/Transform.h b/src/Gui/Transform.h index 7c1a49f977..88ed66e417 100644 --- a/src/Gui/Transform.h +++ b/src/Gui/Transform.h @@ -56,11 +56,11 @@ class GuiExport DefaultTransformStrategy : public TransformStrategy, { public: DefaultTransformStrategy(QWidget* widget); - virtual ~DefaultTransformStrategy(); - std::set transformObjects() const; + ~DefaultTransformStrategy() override; + std::set transformObjects() const override; private: - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: std::set selection; @@ -74,15 +74,15 @@ class GuiExport Transform : public Gui::LocationDialog public: Transform(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~Transform(); - void accept(); - void reject(); + ~Transform() override; + void accept() override; + void reject() override; void showStandardButtons(bool); void setTransformStrategy(TransformStrategy* ts); protected: - Base::Vector3d getDirection() const; - void changeEvent(QEvent *e); + Base::Vector3d getDirection() const override; + void changeEvent(QEvent *e) override; public Q_SLOTS: void on_applyButton_clicked(); @@ -92,7 +92,7 @@ private Q_SLOTS: private: Base::Placement getPlacementData() const; - void directionActivated(int); + void directionActivated(int) override; Q_SIGNALS: void directionChanged(); @@ -111,15 +111,15 @@ class GuiExport TaskTransform : public Gui::TaskView::TaskDialog public: TaskTransform(); - ~TaskTransform(); + ~TaskTransform() override; public: - bool accept(); - bool reject(); - void clicked(int); + bool accept() override; + bool reject() override; + void clicked(int) override; void setTransformStrategy(TransformStrategy* ts); - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; } diff --git a/src/Gui/Tree.cpp b/src/Gui/Tree.cpp index 869b511e32..f9e5eff402 100644 --- a/src/Gui/Tree.cpp +++ b/src/Gui/Tree.cpp @@ -203,7 +203,7 @@ struct TimingInfo { bool timed = false; FC_TIME_POINT t; FC_DURATION& d; - TimingInfo(FC_DURATION& d) + explicit TimingInfo(FC_DURATION& d) :d(d) { _FC_TIME_INIT(t); @@ -629,7 +629,7 @@ static bool _DisableCheckTopParent; void TreeWidget::checkTopParent(App::DocumentObject*& obj, std::string& subname) { if (_DisableCheckTopParent) return; - if (Instances.size() && obj && obj->getNameInDocument()) { + if (!Instances.empty() && obj && obj->getNameInDocument()) { auto tree = *Instances.begin(); auto it = tree->DocumentMap.find(Application::Instance->getDocument(obj->getDocument())); if (it != tree->DocumentMap.end()) { @@ -679,9 +679,9 @@ void TreeWidget::startItemSearch(QLineEdit* edit) { searchDoc = Application::Instance->activeDocument(); App::DocumentObject* obj = nullptr; - if (searchContextDoc && searchContextDoc->getDocument()->getObjects().size()) + if (searchContextDoc && !searchContextDoc->getDocument()->getObjects().empty()) obj = searchContextDoc->getDocument()->getObjects().front(); - else if (searchDoc && searchDoc->getDocument()->getObjects().size()) + else if (searchDoc && !searchDoc->getDocument()->getObjects().empty()) obj = searchDoc->getDocument()->getObjects().front(); if (obj) @@ -810,7 +810,7 @@ void TreeWidget::updateStatus(bool delay) { void TreeWidget::_updateStatus(bool delay) { if (!delay) { - if (ChangedObjects.size() || NewObjects.size()) + if (!ChangedObjects.empty() || !NewObjects.empty()) onUpdateStatus(); return; } @@ -968,28 +968,10 @@ void TreeWidget::contextMenuEvent(QContextMenuEvent* e) } void TreeWidget::hideEvent(QHideEvent* ev) { - // No longer required. Visibility is now handled inside onUpdateStatus() by - // UpdateDisabler. -#if 0 - TREE_TRACE("detaching selection observer"); - this->detachSelection(); - selectTimer->stop(); -#endif QTreeWidget::hideEvent(ev); } void TreeWidget::showEvent(QShowEvent* ev) { - // No longer required. Visibility is now handled inside onUpdateStatus() by - // UpdateDisabler. -#if 0 - TREE_TRACE("attaching selection observer"); - this->attachSelection(); - int timeout = TreeParams::Instance()->SelectionTimeout(); - if (timeout <= 0) - timeout = 1; - selectTimer->start(timeout); - _updateStatus(); -#endif QTreeWidget::showEvent(ev); } @@ -1042,22 +1024,9 @@ void TreeWidget::onStartEditing() MDIView* view = doc->getActiveView(); if (view) getMainWindow()->setActiveWindow(view); - // Always open a transaction here doesn't make much sense because: - // - many objects open transactions when really changing some properties - // - this leads to certain inconsistencies with the doubleClicked() method - // So, only the view provider class should decide what to do -#if 0 - // open a transaction before starting edit mode - std::string cmd("Edit "); - cmd += obj->Label.getValue(); - doc->openCommand(cmd.c_str()); - bool ok = doc->setEdit(objitem->object(), edit); - if (!ok) doc->abortCommand(); -#else editingItem = objitem; if (!doc->setEdit(objitem->object(), edit)) editingItem = nullptr; -#endif } } } @@ -1093,7 +1062,7 @@ bool TreeWidget::CheckForDependents() App::DocumentObject* obj = objitem->object()->getObject(); // get dependents auto subObjectList = obj->getOutList(); - if (subObjectList.size() > 0) + if (!subObjectList.empty()) return true; } } @@ -1189,7 +1158,8 @@ void TreeWidget::onMarkRecompute() void TreeWidget::onRecomputeObject() { std::vector objs; - for (auto ti : selectedItems()) { + const auto items = selectedItems(); + for (auto ti : items) { if (ti->type() == ObjectType) { DocumentObjectItem* objitem = static_cast(ti); objs.push_back(objitem->object()->getObject()); @@ -1255,8 +1225,10 @@ std::vector TreeWidget::getSelection(App::Document* doc) else tree->_updateStatus(false); - for (auto ti : tree->selectedItems()) { - if (ti->type() != ObjectType) continue; + const auto items = tree->selectedItems(); + for (auto ti : items) { + if (ti->type() != ObjectType) + continue; auto item = static_cast(ti); auto vp = item->object(); auto obj = vp->getObject(); @@ -1345,15 +1317,6 @@ Qt::DropActions TreeWidget::supportedDropActions() const bool TreeWidget::event(QEvent* e) { -#if 0 - if (e->type() == QEvent::ShortcutOverride) { - QKeyEvent* ke = static_cast(e); - switch (ke->key()) { - case Qt::Key_Delete: - ke->accept(); - } - } -#endif return QTreeWidget::event(e); } @@ -1380,11 +1343,6 @@ bool TreeWidget::eventFilter(QObject*, QEvent* ev) { void TreeWidget::keyPressEvent(QKeyEvent* event) { -#if 0 - if (event && event->matches(QKeySequence::Delete)) { - event->ignore(); - } -#endif if (event->matches(QKeySequence::Find)) { event->accept(); onSearchObjects(); @@ -1533,19 +1491,6 @@ void TreeWidget::startDrag(Qt::DropActions supportedActions) QMimeData* TreeWidget::mimeData(const QList items) const { -#if 0 - // all selected items must reference an object from the same document - App::Document* doc = 0; - for (QList::ConstIterator it = items.begin(); it != items.end(); ++it) { - if ((*it)->type() != TreeWidget::ObjectType) - return 0; - App::DocumentObject* obj = static_cast(*it)->object()->getObject(); - if (!doc) - doc = obj->getDocument(); - else if (doc != obj->getDocument()) - return 0; - } -#endif return QTreeWidget::mimeData(items); } @@ -1910,7 +1855,7 @@ void TreeWidget::dropEvent(QDropEvent* event) } ViewProviderDocumentObject* vpp = nullptr; - if (da != Qt::LinkAction && info.parentDoc.size()) { + if (da != Qt::LinkAction && !info.parentDoc.empty()) { auto parentDoc = App::GetApplication().getDocument(info.parentDoc.c_str()); if (parentDoc) { auto parent = parentDoc->getObject(info.parent.c_str()); @@ -1924,7 +1869,7 @@ void TreeWidget::dropEvent(QDropEvent* event) } App::DocumentObject* owner = nullptr; - if (info.ownerDoc.size()) { + if (!info.ownerDoc.empty()) { auto ownerDoc = App::GetApplication().getDocument(info.ownerDoc.c_str()); if (ownerDoc) owner = ownerDoc->getObject(info.owner.c_str()); @@ -1937,7 +1882,7 @@ void TreeWidget::dropEvent(QDropEvent* event) Base::Matrix4D mat; App::PropertyPlacement* propPlacement = nullptr; if (syncPlacement) { - if (info.topObj.size()) { + if (!info.topObj.empty()) { auto doc = App::GetApplication().getDocument(info.topDoc.c_str()); if (doc) { auto topObj = doc->getObject(info.topObj.c_str()); @@ -2048,7 +1993,7 @@ void TreeWidget::dropEvent(QDropEvent* event) dropName = vp->dropObjectEx(obj, owner, subname.c_str(), info.subs); if (manager->getLines() == lines) manager->addLine(MacroManager::Gui, ss.str().c_str()); - if (dropName.size()) + if (!dropName.empty()) dropName = targetSubname.str() + dropName; } @@ -2090,7 +2035,7 @@ void TreeWidget::dropEvent(QDropEvent* event) droppedObjects.emplace_back(dropParent, dropName); } Base::FlagToggler<> guard(_DisableCheckTopParent); - if (setSelection && droppedObjects.size()) { + if (setSelection && !droppedObjects.empty()) { Selection().selStackPush(); Selection().clearCompleteSelection(); for (auto& v : droppedObjects) @@ -2111,7 +2056,7 @@ void TreeWidget::dropEvent(QDropEvent* event) FC_ERR("Unknown exception"); errMsg = "Unknown exception"; } - if (errMsg.size()) { + if (!errMsg.empty()) { committer.close(true); QMessageBox::critical(getMainWindow(), QObject::tr("Drag & drop failed"), QString::fromUtf8(errMsg.c_str())); @@ -2195,7 +2140,7 @@ void TreeWidget::dropEvent(QDropEvent* event) Base::Matrix4D mat; App::PropertyPlacement* propPlacement = nullptr; if (syncPlacement) { - if (info.topObj.size()) { + if (!info.topObj.empty()) { auto doc = App::GetApplication().getDocument(info.topDoc.c_str()); if (doc) { auto topObj = doc->getObject(info.topObj.c_str()); @@ -2229,7 +2174,7 @@ void TreeWidget::dropEvent(QDropEvent* event) propPlacement->setValueIfChanged(Base::Placement(mat)); droppedObjs.push_back(link); } - else if (info.parent.size()) { + else if (!info.parent.empty()) { auto parentDoc = App::GetApplication().getDocument(info.parentDoc.c_str()); if (!parentDoc) { FC_WARN("Canont find document " << info.parentDoc); @@ -2275,7 +2220,7 @@ void TreeWidget::dropEvent(QDropEvent* event) App::DocumentObject* res = nullptr; if (da == Qt::CopyAction) { auto copied = thisDoc->copyObject({ obj }, true); - if (copied.size()) + if (!copied.empty()) res = copied.back(); } else @@ -2307,7 +2252,7 @@ void TreeWidget::dropEvent(QDropEvent* event) FC_ERR("Unknown exception"); errMsg = "Unknown exception"; } - if (errMsg.size()) { + if (!errMsg.empty()) { committer.close(true); QMessageBox::critical(getMainWindow(), QObject::tr("Drag & drop failed"), QString::fromUtf8(errMsg.c_str())); @@ -2501,7 +2446,7 @@ struct UpdateDisabler { } }; -void TreeWidget::onUpdateStatus(void) +void TreeWidget::onUpdateStatus() { if (this->state() == DraggingState || App::GetApplication().isRestoring()) { _updateStatus(); @@ -2563,7 +2508,7 @@ void TreeWidget::onUpdateStatus(void) if (v.second.test(CS_Error) && obj->isError()) errors.push_back(obj); - if (iter->second.size()) { + if (!iter->second.empty()) { auto data = *iter->second.begin(); bool itemHidden = !data->viewObject->showInTree(); if (data->itemHidden != itemHidden) { @@ -2621,7 +2566,7 @@ void TreeWidget::onUpdateStatus(void) continue; if (iter->second->rootItem) docItem->restoreItemExpansion(entry.second, iter->second->rootItem); - else if (legacy && iter->second->items.size()) { + else if (legacy && !iter->second->items.empty()) { auto item = *iter->second->items.begin(); item->setExpanded(true); } @@ -2661,7 +2606,7 @@ void TreeWidget::onUpdateStatus(void) } if (data) { auto item = data->rootItem; - if (!item && data->items.size()) { + if (!item && !data->items.empty()) { item = *data->items.begin(); data->docItem->showItem(item, false, true); } @@ -2794,7 +2739,8 @@ void TreeWidget::expandSelectedItems(TreeItemMode mode) if (!isSelectionAttached()) return; - for (auto item : selectedItems()) { + const auto items = selectedItems(); + for (auto item : items) { switch (mode) { case TreeItemMode::ExpandPath: { QTreeWidgetItem* parentItem = item->parent(); @@ -2926,7 +2872,7 @@ void TreeWidget::onItemSelectionChanged() auto selItems = selectedItems(); // do not allow document item multi-selection - if (selItems.size()) { + if (!selItems.empty()) { auto firstType = selItems.back()->type(); for (auto it = selItems.begin(); it != selItems.end();) { auto item = *it; @@ -2950,7 +2896,7 @@ void TreeWidget::onItemSelectionChanged() // DocumentObject::redirectSubName() Selection().clearCompleteSelection(); DocumentObjectItem* item = nullptr; - if (selItems.size()) { + if (!selItems.empty()) { if (selItems.front()->type() == ObjectType) item = static_cast(selItems.front()); else if (selItems.front()->type() == DocumentType) { @@ -3150,7 +3096,7 @@ void TreePanel::hideEditor() this->searchBox->hide(); this->treeWidget->resetItemSearch(); auto sels = this->treeWidget->selectedItems(); - if (sels.size()) + if (!sels.empty()) this->treeWidget->scrollToItem(sels.front()); } @@ -3358,13 +3304,13 @@ bool DocumentItem::createNewItem(const Gui::ViewProviderDocumentObject& obj, pdata = std::make_shared( this, const_cast(&obj)); auto& entry = getTree()->ObjectTable[obj.getObject()]; - if (entry.size()) + if (!entry.empty()) pdata->updateChildren(*entry.begin()); else pdata->updateChildren(true); entry.insert(pdata); } - else if (pdata->rootItem && parent == nullptr) { + else if (pdata->rootItem && !parent) { Base::Console().Warning("DocumentItem::slotNewObject: Cannot add view provider twice.\n"); return false; } @@ -3384,7 +3330,7 @@ bool DocumentItem::createNewItem(const Gui::ViewProviderDocumentObject& obj, parent->insertChild(index, item); assert(item->parent() == parent); item->setText(0, QString::fromUtf8(data->label.c_str())); - if (data->label2.size()) + if (!data->label2.empty()) item->setText(1, QString::fromUtf8(data->label2.c_str())); if (!obj.showInTree() && !showHidden()) item->setHidden(true); @@ -3445,7 +3391,7 @@ void TreeWidget::_slotDeleteObject(const Gui::ViewProviderDocumentObject& view, bool needUpdate = false; - for (auto data : itEntry->second) { + for (const auto& data : itEntry->second) { DocumentItem* docItem = data->docItem; if (docItem == deletingDoc) continue; @@ -3759,7 +3705,7 @@ void TreeWidget::slotChangeObject( const char* label = obj->Label.getValue(); auto firstData = *itEntry->second.begin(); if (firstData->label != label) { - for (auto data : itEntry->second) { + for (const auto& data : itEntry->second) { data->label = label; auto displayName = QString::fromUtf8(label); for (auto item : data->items) @@ -3773,7 +3719,7 @@ void TreeWidget::slotChangeObject( const char* label = obj->Label2.getValue(); auto firstData = *itEntry->second.begin(); if (firstData->label2 != label) { - for (auto data : itEntry->second) { + for (const auto& data : itEntry->second) { data->label2 = label; auto displayName = QString::fromUtf8(label); for (auto item : data->items) @@ -3898,7 +3844,7 @@ static unsigned int countExpandedItem(const QTreeWidgetItem* item) { return size; } -unsigned int DocumentItem::getMemSize(void) const { +unsigned int DocumentItem::getMemSize() const { return countExpandedItem(this); } @@ -4076,7 +4022,7 @@ void DocumentItem::slotRecomputed(const App::Document&, const std::vectorisValid()) tree->ChangedObjects[obj].set(TreeWidget::CS_Error); } - if (tree->ChangedObjects.size()) + if (!tree->ChangedObjects.empty()) tree->_updateStatus(); } @@ -4100,7 +4046,7 @@ Gui::Document* DocumentItem::document() const // } //} -void DocumentItem::testStatus(void) +void DocumentItem::testStatus() { for (const auto& v : ObjectMap) v.second->testStatus(); @@ -4201,7 +4147,7 @@ void DocumentItem::updateItemSelection(DocumentObjectItem* item) { const char* docname = obj->getDocument()->getName(); const auto& subname = str.str(); - if (subname.size()) { + if (!subname.empty()) { auto parentItem = item->getParentItem(); assert(parentItem); if (selected && parentItem->selected) { @@ -4237,7 +4183,7 @@ void DocumentItem::updateItemSelection(DocumentObjectItem* item) { return; } selected = false; - if (item->mySubs.size()) { + if (!item->mySubs.empty()) { for (auto& sub : item->mySubs) { if (Gui::Selection().addSelection(docname, objname, (subname + sub).c_str())) selected = true; @@ -4362,7 +4308,7 @@ DocumentObjectItem* DocumentItem::findItem( if (select) { item->selected += 2; if (std::find(item->mySubs.begin(), item->mySubs.end(), subname) == item->mySubs.end()) - item->mySubs.push_back(subname); + item->mySubs.emplace_back(subname); } return item; } @@ -4376,7 +4322,7 @@ DocumentObjectItem* DocumentItem::findItem( if (select) { item->selected += 2; if (std::find(item->mySubs.begin(), item->mySubs.end(), subname) == item->mySubs.end()) - item->mySubs.push_back(subname); + item->mySubs.emplace_back(subname); } return item; } @@ -4421,7 +4367,7 @@ DocumentObjectItem* DocumentItem::findItem( TREE_TRACE("element " << subname << " not found"); item->selected += 2; if (std::find(item->mySubs.begin(), item->mySubs.end(), subname) == item->mySubs.end()) - item->mySubs.push_back(subname); + item->mySubs.emplace_back(subname); } return res; } @@ -4619,7 +4565,7 @@ DocumentObjectItem::~DocumentObjectItem() if (myOwner && myData->items.empty()) { auto it = myOwner->_ParentMap.find(object()->getObject()); - if (it != myOwner->_ParentMap.end() && it->second.size()) { + if (it != myOwner->_ParentMap.end() && !it->second.empty()) { myOwner->PopulateObjects.push_back(*it->second.begin()); myOwner->getTree()->_updateStatus(); } diff --git a/src/Gui/Tree.h b/src/Gui/Tree.h index e69f1f5352..6b8fe56965 100644 --- a/src/Gui/Tree.h +++ b/src/Gui/Tree.h @@ -56,8 +56,8 @@ class TreeWidget : public QTreeWidget, public SelectionObserver Q_OBJECT public: - TreeWidget(const char *name, QWidget* parent=nullptr); - ~TreeWidget(); + explicit TreeWidget(const char *name, QWidget* parent=nullptr); + ~TreeWidget() override; static void scrollItemToTop(); void selectAllInstances(const ViewProviderDocumentObject &vpd); @@ -88,7 +88,7 @@ public: void markItem(const App::DocumentObject* Obj,bool mark); void syncView(ViewProviderDocumentObject *vp); - virtual void selectAll() override; + void selectAll() override; const char *getTreeName() const; @@ -160,12 +160,12 @@ protected Q_SLOTS: void onSearchObjects(); private Q_SLOTS: - void onItemSelectionChanged(void); + void onItemSelectionChanged(); void onItemChanged(QTreeWidgetItem*, int); void onItemEntered(QTreeWidgetItem * item); void onItemCollapsed(QTreeWidgetItem * item); void onItemExpanded(QTreeWidgetItem * item); - void onUpdateStatus(void); + void onUpdateStatus(); Q_SIGNALS: void emitSearchObjects(); @@ -259,7 +259,7 @@ class DocumentItem : public QTreeWidgetItem, public Base::Persistence { public: DocumentItem(const Gui::Document* doc, QTreeWidgetItem * parent); - ~DocumentItem(); + ~DocumentItem() override; Gui::Document* document() const; void clearSelection(DocumentObjectItem *exclude=nullptr); @@ -274,7 +274,7 @@ public: }; void selectItems(SelectionReason reason=SR_SELECT); - void testStatus(void); + void testStatus(); void setData(int column, int role, const QVariant & value) override; void populateItem(DocumentObjectItem *item, bool refresh=false, bool delayUpdate=true); bool populateObject(App::DocumentObject *obj); @@ -292,9 +292,9 @@ public: bool isObjectShowable(App::DocumentObject *obj); - virtual unsigned int getMemSize (void) const override; - virtual void Save (Base::Writer &) const override; - virtual void Restore(Base::XMLReader &) override; + unsigned int getMemSize () const override; + void Save (Base::Writer &) const override; + void Restore(Base::XMLReader &) override; class ExpandInfo; typedef std::shared_ptr ExpandInfoPtr; @@ -372,14 +372,14 @@ class DocumentObjectItem : public QTreeWidgetItem { public: DocumentObjectItem(DocumentItem *ownerDocItem, DocumentObjectDataPtr data); - ~DocumentObjectItem(); + ~DocumentObjectItem() override; Gui::ViewProviderDocumentObject* object() const; void testStatus(bool resetStatus, QIcon &icon1, QIcon &icon2); void testStatus(bool resetStatus); void displayStatusInfo(); void setExpandedStatus(bool); - void setData(int column, int role, const QVariant & value); + void setData(int column, int role, const QVariant & value) override; bool isChildOfItem(DocumentObjectItem*); void restoreBackground(); @@ -446,10 +446,10 @@ class TreePanel : public QWidget Q_OBJECT public: - TreePanel(const char *name, QWidget* parent=nullptr); - virtual ~TreePanel(); + explicit TreePanel(const char *name, QWidget* parent=nullptr); + ~TreePanel() override; - bool eventFilter(QObject *obj, QEvent *ev); + bool eventFilter(QObject *obj, QEvent *ev) override; private Q_SLOTS: void accept(); @@ -471,8 +471,8 @@ class TreeDockWidget : public Gui::DockWindow Q_OBJECT public: - TreeDockWidget(Gui::Document* pcDocument,QWidget *parent=nullptr); - ~TreeDockWidget(); + explicit TreeDockWidget(Gui::Document* pcDocument,QWidget *parent=nullptr); + ~TreeDockWidget() override; }; @@ -482,9 +482,9 @@ public: class TreeWidgetEditDelegate: public QStyledItemDelegate { Q_OBJECT public: - TreeWidgetEditDelegate(QObject* parent=nullptr); - virtual QWidget* createEditor(QWidget *parent, - const QStyleOptionViewItem &, const QModelIndex &index) const; + explicit TreeWidgetEditDelegate(QObject* parent=nullptr); + QWidget* createEditor(QWidget *parent, + const QStyleOptionViewItem &, const QModelIndex &index) const override; }; @@ -508,7 +508,7 @@ public: class GuiExport TreeParams : public ParameterGrp::ObserverType { public: TreeParams(); - void OnChange(Base::Subject &, const char* sReason); + void OnChange(Base::Subject &, const char* sReason) override; static TreeParams *Instance(); bool getTreeViewStretchDescription() const; diff --git a/src/Gui/UiLoader.h b/src/Gui/UiLoader.h index 3d33db681d..5f8ae0e6cc 100644 --- a/src/Gui/UiLoader.h +++ b/src/Gui/UiLoader.h @@ -90,7 +90,7 @@ class PySideUicModule : public Py::ExtensionModule public: PySideUicModule(); - virtual ~PySideUicModule() {} + ~PySideUicModule() override {} private: Py::Object loadUiType(const Py::Tuple& args); @@ -107,15 +107,15 @@ private: class UiLoader : public QUiLoader { public: - UiLoader(QObject* parent=nullptr); - virtual ~UiLoader(); + explicit UiLoader(QObject* parent=nullptr); + ~UiLoader() override; /** * Creates a widget of the type \a className with the parent \a parent. * For more details see the documentation to QWidgetFactory. */ QWidget* createWidget(const QString & className, QWidget * parent=nullptr, - const QString& name = QString()); + const QString& name = QString()) override; private: QStringList cw; @@ -129,9 +129,9 @@ public: static void init_type(); // announce properties and methods UiLoaderPy(); - ~UiLoaderPy(); + ~UiLoaderPy() override; - Py::Object repr(); + Py::Object repr() override; Py::Object createWidget(const Py::Tuple&); Py::Object load(const Py::Tuple&); diff --git a/src/Gui/Utilities.cpp b/src/Gui/Utilities.cpp index d3cb77af7b..d9abd84f8d 100644 --- a/src/Gui/Utilities.cpp +++ b/src/Gui/Utilities.cpp @@ -133,7 +133,7 @@ std::vector Tessellator::tessellate() const class ItemViewSelection::MatchName { public: - MatchName(const QString& n) : name(n) + explicit MatchName(const QString& n) : name(n) {} bool operator() (const App::DocumentObject* obj) { return name == QLatin1String(obj->getNameInDocument()); diff --git a/src/Gui/Utilities.h b/src/Gui/Utilities.h index 2ba37b6a39..0787a0bee7 100644 --- a/src/Gui/Utilities.h +++ b/src/Gui/Utilities.h @@ -43,7 +43,7 @@ template <> struct vec_traits { typedef SbVec3f vec_type; typedef float float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v[0], v[1], v[2]); } @@ -56,7 +56,7 @@ template <> struct vec_traits { typedef SbVec3d vec_type; typedef double float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v[0], v[1], v[2]); } @@ -69,7 +69,7 @@ template <> struct vec_traits { typedef SbRotation vec_type; typedef float float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { float_type q1,q2,q3,q4; v.getValue(q1,q2,q3,q4); @@ -84,7 +84,7 @@ template <> struct vec_traits { typedef SbColor vec_type; typedef float float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v[0], v[1], v[2]); } @@ -97,7 +97,7 @@ template <> struct vec_traits { typedef App::Color vec_type; typedef float float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.r, v.g, v.b); } @@ -114,15 +114,15 @@ namespace Gui { class GuiExport ViewVolumeProjection : public Base::ViewProjMethod { public: - ViewVolumeProjection (const SbViewVolume &vv); - virtual ~ViewVolumeProjection(){} + explicit ViewVolumeProjection (const SbViewVolume &vv); + ~ViewVolumeProjection() override{} - Base::Vector3f operator()(const Base::Vector3f &rclPt) const; - Base::Vector3d operator()(const Base::Vector3d &rclPt) const; - Base::Vector3f inverse (const Base::Vector3f &rclPt) const; - Base::Vector3d inverse (const Base::Vector3d &rclPt) const; + Base::Vector3f operator()(const Base::Vector3f &rclPt) const override; + Base::Vector3d operator()(const Base::Vector3d &rclPt) const override; + Base::Vector3f inverse (const Base::Vector3f &rclPt) const override; + Base::Vector3d inverse (const Base::Vector3d &rclPt) const override; - Base::Matrix4D getProjectionMatrix () const; + Base::Matrix4D getProjectionMatrix () const override; protected: SbViewVolume viewVolume; @@ -133,7 +133,7 @@ protected: class GuiExport Tessellator { public: - Tessellator(const std::vector&); + explicit Tessellator(const std::vector&); std::vector tessellate() const; private: @@ -146,7 +146,7 @@ private: class GuiExport ItemViewSelection { public: - ItemViewSelection(QAbstractItemView* view); + explicit ItemViewSelection(QAbstractItemView* view); void applyFrom(const std::vector objs); private: diff --git a/src/Gui/VectorListEditor.cpp b/src/Gui/VectorListEditor.cpp index b12d203308..6a27bcaf99 100644 --- a/src/Gui/VectorListEditor.cpp +++ b/src/Gui/VectorListEditor.cpp @@ -76,7 +76,7 @@ bool VectorTableModel::setData(const QModelIndex &index, const QVariant &value, if (role == Qt::EditRole && r < vectors.size()) { if (value.canConvert()) { vectors[r] = value.value(); - dataChanged(index, index.sibling(index.row(), 2)); + Q_EMIT dataChanged(index, index.sibling(index.row(), 2)); return true; } else if (c < 3) { @@ -87,7 +87,7 @@ bool VectorTableModel::setData(const QModelIndex &index, const QVariant &value, vectors[r].y = d; else if (c == 2) vectors[r].z = d; - dataChanged(index, index); + Q_EMIT dataChanged(index, index); return true; } } diff --git a/src/Gui/VectorListEditor.h b/src/Gui/VectorListEditor.h index 82705e1878..875bc47ef1 100644 --- a/src/Gui/VectorListEditor.h +++ b/src/Gui/VectorListEditor.h @@ -39,19 +39,19 @@ class VectorTableModel : public QAbstractTableModel Q_OBJECT public: - VectorTableModel(int decimals, QObject *parent = nullptr); + explicit VectorTableModel(int decimals, QObject *parent = nullptr); - QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - virtual int columnCount(const QModelIndex &parent = QModelIndex()) const; - virtual int rowCount(const QModelIndex &parent = QModelIndex()) const; - Qt::ItemFlags flags (const QModelIndex & index) const; - bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole); - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - virtual QModelIndex parent(const QModelIndex &index) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + Qt::ItemFlags flags (const QModelIndex & index) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QModelIndex parent(const QModelIndex &index) const override; void setValues(const QList& d); const QList& values() const; - virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()); - virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); + bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; + bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) override; private: QList vectors; @@ -63,17 +63,17 @@ class VectorTableDelegate : public QItemDelegate Q_OBJECT public: - VectorTableDelegate(int decimals, QObject *parent = nullptr); + explicit VectorTableDelegate(int decimals, QObject *parent = nullptr); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const; + const QModelIndex &index) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const; + const QModelIndex &index) const override; void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const; + const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: int decimals; @@ -85,14 +85,14 @@ class VectorListEditor : public QDialog Q_OBJECT public: - VectorListEditor(int decimals, QWidget* parent = nullptr); - ~VectorListEditor(); + explicit VectorListEditor(int decimals, QWidget* parent = nullptr); + ~VectorListEditor() override; void setValues(const QList&); const QList& getValues() const; - void accept(); - void reject(); + void accept() override; + void reject() override; private Q_SLOTS: void addRow(); diff --git a/src/Gui/View.cpp b/src/Gui/View.cpp index b7856323b7..486f7e3f4f 100644 --- a/src/Gui/View.cpp +++ b/src/Gui/View.cpp @@ -54,7 +54,7 @@ BaseView::~BaseView() onClose(); } -void BaseView::onClose(void) +void BaseView::onClose() { if (bIsDetached) return; diff --git a/src/Gui/View.h b/src/Gui/View.h index 35e7f3095e..fd588e6145 100644 --- a/src/Gui/View.h +++ b/src/Gui/View.h @@ -25,6 +25,7 @@ #define GUI_VIEW_H #include +#include namespace App { @@ -49,7 +50,7 @@ class ViewProvider; */ class GuiExport BaseView : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** View constructor @@ -61,7 +62,7 @@ public: /** View destructor * Detach the view from the document, if attached! */ - virtual ~BaseView(); + ~BaseView() override; /** @name methods used by the Application and the GuiDocument @@ -70,7 +71,7 @@ public: /// sets the view to another document (called by Application) void setDocument(Gui::Document* pcDocument); /// is sent from the document in order to close the document - void onClose(void); + void onClose(); //@} /// returns the document the view is attached to @@ -78,26 +79,26 @@ public: /// returns the document the view is attached to App::Document* getAppDocument() const; /// indicates if the view is in passive mode - bool isPassive(void) const {return bIsPassive;} + bool isPassive() const {return bIsPassive;} /** @name methods to override */ //@{ /// get called when the document is updated - virtual void onUpdate(void){} + virtual void onUpdate(){} /// get called when the document is relabeled (change of its user name) virtual void onRelabel(Gui::Document *){} /// get called when the document is renamed (change of its internal name) virtual void onRename(Gui::Document *){} /// returns the name of the view (important for messages) - virtual const char *getName(void) const + virtual const char *getName() const { return "Base view"; } /// Message handler virtual bool onMsg(const char* pMsg, const char** ppReturn)=0; /// Message handler test virtual bool onHasMsg(const char* pMsg) const=0; /// overwrite when checking on close state - virtual bool canClose(void){return true;} + virtual bool canClose(){return true;} /// delete itself virtual void deleteSelf(); //@} diff --git a/src/Gui/View3DInventor.cpp b/src/Gui/View3DInventor.cpp index 4d429c720a..8fc2c42840 100644 --- a/src/Gui/View3DInventor.cpp +++ b/src/Gui/View3DInventor.cpp @@ -98,6 +98,10 @@ View3DInventor::View3DInventor(Gui::Document* pcDocument, QWidget* parent, hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); hGrp->Attach(this); + hGrpNavi = + App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/NaviCube"); + hGrpNavi->Attach(this); + //anti-aliasing settings bool smoothing = false; bool glformat = false; @@ -145,7 +149,7 @@ View3DInventor::View3DInventor(Gui::Document* pcDocument, QWidget* parent, OnChange(*hGrp,"UseBackgroundColorMid"); OnChange(*hGrp,"ShowFPS"); OnChange(*hGrp,"ShowNaviCube"); - OnChange(*hGrp,"CornerNaviCube"); + OnChange(*hGrpNavi, "CornerNaviCube"); OnChange(*hGrp,"UseVBO"); OnChange(*hGrp,"RenderCache"); OnChange(*hGrp,"Orthographic"); @@ -178,6 +182,7 @@ View3DInventor::~View3DInventor() _pcDocument->saveCameraSettings(SoFCDB::writeNodesToString(Cam).c_str()); } hGrp->Detach(this); + hGrpNavi->Detach(this); //If we destroy this viewer by calling 'delete' directly the focus proxy widget which is defined //by a widget in SoQtViewer isn't reset. This widget becomes a dangling pointer and makes @@ -212,7 +217,7 @@ void View3DInventor::deleteSelf() MDIView::deleteSelf(); } -PyObject *View3DInventor::getPyObject(void) +PyObject *View3DInventor::getPyObject() { if (!_viewerPy) _viewerPy = new View3DInventorPy(this); @@ -369,8 +374,8 @@ void View3DInventor::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M else if (strcmp(Reason,"ShowNaviCube") == 0) { _viewer->setEnabledNaviCube(rGrp.GetBool("ShowNaviCube",true)); } - else if (strcmp(Reason,"CornerNaviCube") == 0) { - _viewer->setNaviCubeCorner(rGrp.GetInt("CornerNaviCube",1)); + else if (strcmp(Reason, "CornerNaviCube") == 0) { + _viewer->setNaviCubeCorner(rGrp.GetInt("CornerNaviCube", 1)); } else if (strcmp(Reason,"UseVBO") == 0) { _viewer->setEnabledVBO(rGrp.GetBool("UseVBO",false)); @@ -418,10 +423,10 @@ void View3DInventor::OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::M } } else { - unsigned long col1 = rGrp.GetUnsigned("BackgroundColor",3940932863UL); - unsigned long col2 = rGrp.GetUnsigned("BackgroundColor2",859006463UL); // default color (dark blue) - unsigned long col3 = rGrp.GetUnsigned("BackgroundColor3",2880160255UL); // default color (blue/grey) - unsigned long col4 = rGrp.GetUnsigned("BackgroundColor4",1869583359UL); // default color (blue/grey) + unsigned long col1 = rGrp.GetUnsigned("BackgroundColor", 3940932863UL); + unsigned long col2 = rGrp.GetUnsigned("BackgroundColor2", 2526456575UL); // default color (blue/grey) + unsigned long col3 = rGrp.GetUnsigned("BackgroundColor3", 3570714879UL); // default color (light yellow/bluey) + unsigned long col4 = rGrp.GetUnsigned("BackgroundColor4", 1869583359UL); // default color (blue/grey) float r1,g1,b1,r2,g2,b2,r3,g3,b3,r4,g4,b4; r1 = ((col1 >> 24) & 0xff) / 255.0; g1 = ((col1 >> 16) & 0xff) / 255.0; b1 = ((col1 >> 8) & 0xff) / 255.0; r2 = ((col2 >> 24) & 0xff) / 255.0; g2 = ((col2 >> 16) & 0xff) / 255.0; b2 = ((col2 >> 8) & 0xff) / 255.0; @@ -443,7 +448,7 @@ void View3DInventor::onRename(Gui::Document *pDoc) cAct.apply(_viewer->getSceneGraph()); } -void View3DInventor::onUpdate(void) +void View3DInventor::onUpdate() { #ifdef FC_LOGUPDATECHAIN Base::Console().Log("Acti: Gui::View3DInventor::onUpdate()"); @@ -457,7 +462,7 @@ void View3DInventor::viewAll() _viewer->viewAll(); } -const char *View3DInventor::getName(void) const +const char *View3DInventor::getName() const { return "View3DInventor"; } diff --git a/src/Gui/View3DInventor.h b/src/Gui/View3DInventor.h index 4a7719aade..1e9fed65b3 100644 --- a/src/Gui/View3DInventor.h +++ b/src/Gui/View3DInventor.h @@ -45,13 +45,13 @@ class GuiExport GLOverlayWidget : public QWidget Q_OBJECT public: - GLOverlayWidget(QWidget* parent=nullptr) : QWidget(parent) + explicit GLOverlayWidget(QWidget* parent=nullptr) : QWidget(parent) {} - ~GLOverlayWidget() + ~GLOverlayWidget() override {} virtual void setImage(const QImage& img) { image = img; } - void paintEvent(QPaintEvent*); + void paintEvent(QPaintEvent*) override; protected: QImage image; @@ -65,31 +65,31 @@ class GuiExport View3DInventor : public MDIView, public ParameterGrp::ObserverTy { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: View3DInventor(Gui::Document* pcDocument, QWidget* parent, const QtGLWidget* sharewidget = nullptr, Qt::WindowFlags wflags=Qt::WindowFlags()); - ~View3DInventor(); + ~View3DInventor() override; /// Message handler - virtual bool onMsg(const char* pMsg, const char** ppReturn); - virtual bool onHasMsg(const char* pMsg) const; - virtual void deleteSelf(); + bool onMsg(const char* pMsg, const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; + void deleteSelf() override; /// Observer message from the ParameterGrp - virtual void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason); + void OnChange(ParameterGrp::SubjectType &rCaller,ParameterGrp::MessageType Reason) override; /// get called when the document is updated - virtual void onRename(Gui::Document *pDoc); - virtual void onUpdate(void); - virtual void viewAll(); - virtual const char *getName(void) const; + void onRename(Gui::Document *pDoc) override; + void onUpdate() override; + void viewAll() override; + const char *getName() const override; /// print function of the view - virtual void print(); - virtual void printPdf(); - virtual void printPreview(); - virtual void print(QPrinter*); + void print() override; + void printPdf() override; + void printPreview() override; + void print(QPrinter*) override; - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; /** * If \a b is set to \a FullScreen the MDI view is displayed in full screen mode, if \a b * is set to \a TopLevel then it is displayed as an own top-level window, otherwise (\a Normal) @@ -97,7 +97,7 @@ public: * This method is reimplemented from MDIView to set the this widget as the proxy of the embedded * GL widget to get all key events in \a TopLevel or \a Fullscreen mode. */ - void setCurrentViewMode(ViewMode b); + void setCurrentViewMode(ViewMode b) override; bool setCamera(const char* pCamera); void toggleClippingPlane(); bool hasClippingPlane() const; @@ -105,13 +105,13 @@ public: void setOverlayWidget(QWidget*); void removeOverlayWidget(); - View3DInventorViewer *getViewer(void) const {return _viewer;} - virtual bool containsViewProvider(const ViewProvider*) const; + View3DInventorViewer *getViewer() const {return _viewer;} + bool containsViewProvider(const ViewProvider*) const override; public Q_SLOTS: /// override the cursor in this view - void setOverrideCursor(const QCursor&); - void restoreOverrideCursor(); + void setOverrideCursor(const QCursor&) override; + void restoreOverrideCursor() override; void dump(const char* filename, bool onlyVisible=false); @@ -119,20 +119,21 @@ protected Q_SLOTS: void stopAnimating(); public: - bool eventFilter(QObject*, QEvent* ); + bool eventFilter(QObject*, QEvent* ) override; protected: - void windowStateChanged(MDIView* ); - void dropEvent (QDropEvent * e); - void dragEnterEvent (QDragEnterEvent * e); - void keyPressEvent (QKeyEvent * e); - void keyReleaseEvent (QKeyEvent * e); - void focusInEvent (QFocusEvent * e); - void customEvent (QEvent * e); - void contextMenuEvent (QContextMenuEvent*e); + void windowStateChanged(MDIView* ) override; + void dropEvent (QDropEvent * e) override; + void dragEnterEvent (QDragEnterEvent * e) override; + void keyPressEvent (QKeyEvent * e) override; + void keyReleaseEvent (QKeyEvent * e) override; + void focusInEvent (QFocusEvent * e) override; + void customEvent (QEvent * e) override; + void contextMenuEvent (QContextMenuEvent*e) override; /// handle to the viewer parameter group ParameterGrp::handle hGrp; + ParameterGrp::handle hGrpNavi; private: View3DInventorViewer * _viewer; diff --git a/src/Gui/View3DInventorExamples.cpp b/src/Gui/View3DInventorExamples.cpp index efb48ef4bd..df8b4904a7 100644 --- a/src/Gui/View3DInventorExamples.cpp +++ b/src/Gui/View3DInventorExamples.cpp @@ -276,7 +276,7 @@ void LightManip(SoSeparator * root) SoInput in; in.setBuffer((void *)scenegraph, std::strlen(scenegraph)); SoSeparator * _root = SoDB::readAll( &in ); - if ( _root == nullptr ) // Shouldn't happen. + if (!_root) // Shouldn't happen. return; root->addChild(_root); root->ref(); @@ -290,7 +290,7 @@ void LightManip(SoSeparator * root) sa.setSearchingAll( false ); sa.apply( root ); SoPath * path = sa.getPath(); - if ( path == nullptr) // Shouldn't happen. + if (!path) // Shouldn't happen. return; SoPointLightManip * manip = new SoPointLightManip; @@ -396,7 +396,7 @@ timersensorcallback(void * data, SoSensor *) void AnimationTexture(SoSeparator * root) { // Scene graph - if ( root == nullptr ) // Shouldn't happen. + if (!root) // Shouldn't happen. return; // Generate a julia set to use as a texturemap diff --git a/src/Gui/View3DInventorViewer.cpp b/src/Gui/View3DInventorViewer.cpp index 84cda465b0..18bdeb2f25 100644 --- a/src/Gui/View3DInventorViewer.cpp +++ b/src/Gui/View3DInventorViewer.cpp @@ -200,9 +200,9 @@ class Gui::ViewerEventFilter : public QObject { public: ViewerEventFilter() {} - ~ViewerEventFilter() {} + ~ViewerEventFilter() override {} - bool eventFilter(QObject* obj, QEvent* event) { + bool eventFilter(QObject* obj, QEvent* event) override { // Bug #0000607: Some mice also support horizontal scrolling which however might // lead to some unwanted zooming when pressing the MMB for panning. // Thus, we filter out horizontal scrolling. @@ -242,9 +242,9 @@ public: class SpaceNavigatorDevice : public Quarter::InputDevice { public: - SpaceNavigatorDevice(void) {} - virtual ~SpaceNavigatorDevice() {} - virtual const SoEvent* translateEvent(QEvent* event) { + SpaceNavigatorDevice() {} + ~SpaceNavigatorDevice() override {} + const SoEvent* translateEvent(QEvent* event) override { if (event->type() == Spaceball::MotionEvent::MotionEventType) { Spaceball::MotionEvent* motionEvent = static_cast(event); @@ -389,36 +389,16 @@ void View3DInventorViewer::init() cam->nearDistance = 0; cam->farDistance = 10; - // dragger - //SoSeparator * dragSep = new SoSeparator(); - //SoScale *scale = new SoScale(); - //scale->scaleFactor = SbVec3f (0.2,0.2,0.2); - //dragSep->addChild(scale); - //SoCenterballDragger *dragger = new SoCenterballDragger(); - //dragger->center = SbVec3f (0.8,0.8,0); - ////dragger->rotation = SbRotation(rrot[0],rrot[1],rrot[2],rrot[3]); - //dragSep->addChild(dragger); - this->foregroundroot->addChild(cam); this->foregroundroot->addChild(lm); this->foregroundroot->addChild(bc); - //this->foregroundroot->addChild(dragSep); -#if 0 - // NOTE: For every mouse click event the SoSelection searches for the picked - // point which causes a certain slow-down because for all objects the primitives - // must be created. Using an SoSeparator avoids this drawback. - SoSelection* selectionRoot = new SoSelection(); - selectionRoot->addSelectionCallback(View3DInventorViewer::selectCB, this); - selectionRoot->addDeselectionCallback(View3DInventorViewer::deselectCB, this); - selectionRoot->setPickFilterCallback(View3DInventorViewer::pickFilterCB, this); -#else // NOTE: For every mouse click event the SoFCUnifiedSelection searches for the picked // point which causes a certain slow-down because for all objects the primitives // must be created. Using an SoSeparator avoids this drawback. selectionRoot = new Gui::SoFCUnifiedSelection(); selectionRoot->applySettings(); -#endif + // set the ViewProvider root node pcViewProviderRoot = selectionRoot; @@ -453,7 +433,6 @@ void View3DInventorViewer::init() auto pcGroupOnTopPickStyle = new SoPickStyle; pcGroupOnTopPickStyle->style = SoPickStyle::UNPICKABLE; - // pcGroupOnTopPickStyle->style = SoPickStyle::SHAPE_ON_TOP; pcGroupOnTopPickStyle->setOverride(true); pcGroupOnTop->addChild(pcGroupOnTopPickStyle); @@ -503,9 +482,7 @@ void View3DInventorViewer::init() this->getSoRenderManager()->getGLRenderAction()->setCacheContext(id); // set the transparency and antialiasing settings -// getGLRenderAction()->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_BLEND); getSoRenderManager()->getGLRenderAction()->setTransparencyType(SoGLRenderAction::SORTED_OBJECT_SORTED_TRIANGLE_BLEND); -// getGLRenderAction()->setSmoothing(true); // Settings setSeekTime(0.4f); @@ -688,7 +665,7 @@ void View3DInventorViewer::initialize() } void View3DInventorViewer::clearGroupOnTop() { - if(objectsOnTop.size() || objectsOnTopPreSel.size()) { + if(!objectsOnTop.empty() || !objectsOnTopPreSel.empty()) { objectsOnTop.clear(); objectsOnTopPreSel.clear(); SoSelectionElementAction action(SoSelectionElementAction::None,true); @@ -1396,7 +1373,7 @@ void View3DInventorViewer::setEnabledNaviCube(bool on) naviCubeEnabled = on; } -bool View3DInventorViewer::isEnabledNaviCube(void) const +bool View3DInventorViewer::isEnabledNaviCube() const { return naviCubeEnabled; } @@ -1440,7 +1417,7 @@ void View3DInventorViewer::setAxisCross(bool on) } } -bool View3DInventorViewer::hasAxisCross(void) +bool View3DInventorViewer::hasAxisCross() { return axisGroup; } @@ -1474,7 +1451,7 @@ NavigationStyle* View3DInventorViewer::navigationStyle() const return this->navigation; } -SoDirectionalLight* View3DInventorViewer::getBacklight(void) const +SoDirectionalLight* View3DInventorViewer::getBacklight() const { return this->backlight; } @@ -1484,7 +1461,7 @@ void View3DInventorViewer::setBacklight(SbBool on) this->backlight->on = on; } -SbBool View3DInventorViewer::isBacklight(void) const +SbBool View3DInventorViewer::isBacklight() const { return this->backlight->on.getValue(); } @@ -1733,7 +1710,7 @@ void View3DInventorViewer::setSelectionEnabled(const SbBool enable) static_cast(root)->selectionRole.setValue(enable); } -SbBool View3DInventorViewer::isSelectionEnabled(void) const +SbBool View3DInventorViewer::isSelectionEnabled() const { SoNode* root = getSceneGraph(); return static_cast(root)->selectionRole.getValue(); @@ -1787,33 +1764,33 @@ SbVec2f View3DInventorViewer::screenCoordsOfPath(SoPath* path) const std::vector View3DInventorViewer::getGLPolygon(const std::vector& pnts) const { - const SbViewportRegion& vp = this->getSoRenderManager()->getViewportRegion(); - const SbVec2s& sz = vp.getWindowSize(); - short w,h; - sz.getValue(w,h); - const SbVec2s& sp = vp.getViewportSizePixels(); - const SbVec2s& op = vp.getViewportOriginPixels(); - const SbVec2f& siz = vp.getViewportSize(); + const SbViewportRegion &vp = this->getSoRenderManager()->getViewportRegion(); + const SbVec2s &winSize = vp.getWindowSize(); + short w, h; + winSize.getValue(w, h); + const SbVec2s &sp = vp.getViewportSizePixels(); + const SbVec2s &op = vp.getViewportOriginPixels(); + const SbVec2f &vpSize = vp.getViewportSize(); float dX, dY; - siz.getValue(dX, dY); + vpSize.getValue(dX, dY); float fRatio = vp.getViewportAspectRatio(); std::vector poly; for (std::vector::const_iterator it = pnts.begin(); it != pnts.end(); ++it) { SbVec2s loc = *it - op; - SbVec2f pos((float)loc[0]/(float)sp[0], (float)loc[1]/(float)sp[1]); - float pX,pY; - pos.getValue(pX,pY); + SbVec2f pos((float)loc[0] / (float)sp[0], (float)loc[1] / (float)sp[1]); + float pX, pY; + pos.getValue(pX, pY); // now calculate the real points respecting aspect ratio information // if (fRatio > 1.0f) { - pX = (pX - 0.5f*dX) * fRatio + 0.5f*dX; - pos.setValue(pX,pY); + pX = (pX - 0.5f * dX) * fRatio + 0.5f * dX; + pos.setValue(pX, pY); } else if (fRatio < 1.0f) { - pY = (pY - 0.5f*dY) / fRatio + 0.5f*dY; - pos.setValue(pX,pY); + pY = (pY - 0.5f * dY) / fRatio + 0.5f * dY; + pos.setValue(pX, pY); } poly.push_back(pos); @@ -2165,9 +2142,6 @@ void View3DInventorViewer::renderToFramebuffer(QtGLFramebufferObject* fbo) glClearColor(col.redF(), col.greenF(), col.blueF(), col.alphaF()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - // If on then transparent areas may shine through opaque areas - //glDepthRange(0.1,1.0); - SoBoxSelectionRenderAction gl(SbViewportRegion(width, height)); // When creating a new GL render action we have to copy over the cache context id // For further details see init(). @@ -2291,7 +2265,7 @@ void View3DInventorViewer::renderGLImage() // Documented in superclass. Overrides this method to be able to draw // the axis cross, if selected, and to keep a continuous animation // upon spin. -void View3DInventorViewer::renderScene(void) +void View3DInventorViewer::renderScene() { // Must set up the OpenGL viewport manually, as upon resize // operations, Coin won't set it up until the SoGLRenderAction is @@ -2368,11 +2342,6 @@ void View3DInventorViewer::renderScene(void) this->getSoRenderManager()->scheduleRedraw(); } -#if 0 // this breaks highlighting of edges - glDisable(GL_LIGHTING); - glDisable(GL_DEPTH_TEST); -#endif - printDimension(); navigation->redraw(); @@ -2390,11 +2359,6 @@ void View3DInventorViewer::renderScene(void) if (naviCubeEnabled) naviCube->drawNaviCube(); - -#if 0 // this breaks highlighting of edges - glEnable(GL_LIGHTING); - glEnable(GL_DEPTH_TEST); -#endif } void View3DInventorViewer::setSeekMode(SbBool on) @@ -2775,7 +2739,7 @@ const SoPickedPoint* View3DInventorViewer::getPickedPoint(SoEventCallback* n) co { if (selectionRoot) { auto ret = selectionRoot->getPickedList(n->getAction(), true); - if(ret.size()) + if(!ret.empty()) return ret[0].pp; return nullptr; } @@ -2808,7 +2772,7 @@ void View3DInventorViewer::setCameraType(SoType t) // close camera but we don't have this other ugly effect. SoCamera* cam = this->getSoRenderManager()->getCamera(); - if(cam == nullptr) + if(!cam) return; static_cast(cam)->heightAngle = (float)(M_PI / 4.0); @@ -2829,11 +2793,11 @@ namespace Gui { startPos = camera->position.getValue(); startRot = camera->orientation.getValue(); } - virtual ~CameraAnimation() + ~CameraAnimation() override { } protected: - void updateCurrentValue(const QVariant & value) + void updateCurrentValue(const QVariant & value) override { int steps = endValue().toInt(); int curr = value.toInt(); @@ -2850,7 +2814,7 @@ namespace Gui { void View3DInventorViewer::moveCameraTo(const SbRotation& rot, const SbVec3f& pos, int steps, int ms) { SoCamera* cam = this->getSoRenderManager()->getCamera(); - if (cam == nullptr) + if (!cam) return; CameraAnimation anim(cam, rot, pos); @@ -2941,7 +2905,7 @@ extern void oculusStop (void); void oculusSetTestScene(View3DInventorRiftViewer *window); #endif -void View3DInventorViewer::viewVR(void) +void View3DInventorViewer::viewVR() { #if BUILD_VR if (oculusUp()) { @@ -3136,7 +3100,7 @@ View3DInventorViewer::setAnimationEnabled(const SbBool enable) */ SbBool -View3DInventorViewer::isAnimationEnabled(void) const +View3DInventorViewer::isAnimationEnabled() const { return navigation->isAnimationEnabled(); } @@ -3145,7 +3109,7 @@ View3DInventorViewer::isAnimationEnabled(void) const Query if the model in the viewer is currently in spinning mode after a user drag. */ -SbBool View3DInventorViewer::isAnimating(void) const +SbBool View3DInventorViewer::isAnimating() const { return navigation->isAnimating(); } @@ -3159,7 +3123,7 @@ void View3DInventorViewer::startAnimating(const SbVec3f& axis, float velocity) navigation->startAnimating(axis, velocity); } -void View3DInventorViewer::stopAnimating(void) +void View3DInventorViewer::stopAnimating() { navigation->stopAnimating(); } @@ -3169,7 +3133,7 @@ void View3DInventorViewer::setPopupMenuEnabled(const SbBool on) navigation->setPopupMenuEnabled(on); } -SbBool View3DInventorViewer::isPopupMenuEnabled(void) const +SbBool View3DInventorViewer::isPopupMenuEnabled() const { return navigation->isPopupMenuEnabled(); } @@ -3197,7 +3161,7 @@ View3DInventorViewer::setFeedbackVisibility(const SbBool enable) */ SbBool -View3DInventorViewer::isFeedbackVisible(void) const +View3DInventorViewer::isFeedbackVisible() const { return this->axiscrossEnabled; } @@ -3226,7 +3190,7 @@ View3DInventorViewer::setFeedbackSize(const int size) */ int -View3DInventorViewer::getFeedbackSize(void) const +View3DInventorViewer::getFeedbackSize() const { return this->axiscrossSize; } @@ -3240,7 +3204,7 @@ void View3DInventorViewer::setCursorEnabled(SbBool /*enable*/) this->setCursorRepresentation(navigation->getViewingMode()); } -void View3DInventorViewer::afterRealizeHook(void) +void View3DInventorViewer::afterRealizeHook() { inherited::afterRealizeHook(); this->setCursorRepresentation(navigation->getViewingMode()); @@ -3259,7 +3223,7 @@ void View3DInventorViewer::setViewing(SbBool enable) inherited::setViewing(enable); } -void View3DInventorViewer::drawAxisCross(void) +void View3DInventorViewer::drawAxisCross() { // FIXME: convert this to a superimposition scenegraph instead of // OpenGL calls. 20020603 mortene. @@ -3282,14 +3246,8 @@ void View3DInventorViewer::drawAxisCross(void) // Set the viewport in the OpenGL canvas. Dimensions are calculated // as a percentage of the total canvas size. SbVec2s view = this->getSoRenderManager()->getSize(); - const int pixelarea = - int(float(this->axiscrossSize)/100.0f * std::min(view[0], view[1])); -#if 0 // middle of canvas - SbVec2s origin(view[0]/2 - pixelarea/2, view[1]/2 - pixelarea/2); -#endif // middle of canvas -#if 1 // lower right of canvas + const int pixelarea = int(float(this->axiscrossSize)/100.0f * std::min(view[0], view[1])); SbVec2s origin(view[0] - pixelarea, 0); -#endif // lower right of canvas glViewport(origin[0], origin[1], pixelarea, pixelarea); // Set up the projection matrix. @@ -3325,7 +3283,7 @@ void View3DInventorViewer::drawAxisCross(void) // Find unit vector end points. SbMatrix px; glGetFloatv(GL_PROJECTION_MATRIX, (float*)px); - SbMatrix comb = mx.multRight(px); + SbMatrix comb = mx.multRight(px); // clazy:exclude=rule-of-two-soft SbVec3f xpos; comb.multVecMatrix(SbVec3f(1,0,0), xpos); @@ -3440,7 +3398,7 @@ void View3DInventorViewer::drawAxisCross(void) } // Draw an arrow for the axis representation directly through OpenGL. -void View3DInventorViewer::drawArrow(void) +void View3DInventorViewer::drawArrow() { glDisable(GL_CULL_FACE); glBegin(GL_QUADS); @@ -3700,7 +3658,7 @@ void View3DInventorViewer::turnDeltaDimensionsOff() static_cast(dimensionRoot->getChild(1))->whichChild = SO_SWITCH_NONE; } -PyObject *View3DInventorViewer::getPyObject(void) +PyObject *View3DInventorViewer::getPyObject() { if (!_viewerPy) _viewerPy = new View3DInventorViewerPy(this); @@ -3751,3 +3709,4 @@ void View3DInventorViewer::dragLeaveEvent(QDragLeaveEvent *e) inherited::dragLeaveEvent(e); } +#include "moc_View3DInventorViewer.cpp" diff --git a/src/Gui/View3DInventorViewer.h b/src/Gui/View3DInventorViewer.h index 7e3f79cab5..efa4ef281c 100644 --- a/src/Gui/View3DInventorViewer.h +++ b/src/Gui/View3DInventorViewer.h @@ -80,6 +80,7 @@ class ViewerEventFilter; class GuiExport View3DInventorViewer : public Quarter::SoQTQuarterAdaptor, public SelectionObserver { typedef Quarter::SoQTQuarterAdaptor inherited; + Q_OBJECT public: /// Pick modes for picking points in the scene @@ -130,38 +131,38 @@ public: }; //@} - View3DInventorViewer (QWidget *parent, const QtGLWidget* sharewidget = nullptr); + explicit View3DInventorViewer (QWidget *parent, const QtGLWidget* sharewidget = nullptr); View3DInventorViewer (const QtGLFormat& format, QWidget *parent, const QtGLWidget* sharewidget = nullptr); - virtual ~View3DInventorViewer(); + ~View3DInventorViewer() override; void init(); /// Observer message from the Selection - virtual void onSelectionChanged(const SelectionChanges &Reason); + void onSelectionChanged(const SelectionChanges &Reason) override; void checkGroupOnTop(const SelectionChanges &Reason); void clearGroupOnTop(); - SoDirectionalLight* getBacklight(void) const; + SoDirectionalLight* getBacklight() const; void setBacklight(SbBool on); - SbBool isBacklight(void) const; - void setSceneGraph (SoNode *root); + SbBool isBacklight() const; + void setSceneGraph (SoNode *root) override; SbBool searchNode(SoNode*) const; void setAnimationEnabled(const SbBool enable); - SbBool isAnimationEnabled(void) const; + SbBool isAnimationEnabled() const; void setPopupMenuEnabled(const SbBool on); - SbBool isPopupMenuEnabled(void) const; + SbBool isPopupMenuEnabled() const; void startAnimating(const SbVec3f& axis, float velocity); - void stopAnimating(void); - SbBool isAnimating(void) const; + void stopAnimating(); + SbBool isAnimating() const; void setFeedbackVisibility(const SbBool enable); - SbBool isFeedbackVisible(void) const; + SbBool isFeedbackVisible() const; void setFeedbackSize(const int size); - int getFeedbackSize(void) const; + int getFeedbackSize() const; /// Get the preferred samples from the user settings static int getNumSamples(); @@ -172,7 +173,7 @@ public: void imageFromFramebuffer(int width, int height, int samples, const QColor& bgcolor, QImage& img); - virtual void setViewing(SbBool enable); + void setViewing(SbBool enable) override; virtual void setCursorEnabled(SbBool enable); void addGraphicsItem(GLGraphicsItem*); @@ -245,7 +246,7 @@ public: std::vector getGLPolygon(const std::vector&) const; const std::vector& getPolygon(SelectionRole* role=nullptr) const; void setSelectionEnabled(const SbBool enable); - SbBool isSelectionEnabled(void) const; + SbBool isSelectionEnabled() const; //@} /// Returns the screen coordinates of the origin of the path's tail object @@ -261,7 +262,7 @@ public: void setRedirectToSceneGraph(SbBool redirect) { this->redirected = redirect; } SbBool isRedirectedToSceneGraph() const { return this->redirected; } void setRedirectToSceneGraphEnabled(SbBool enable) { this->allowredir = enable; } - SbBool isRedirectToSceneGraphEnabled(void) const { return this->allowredir; } + SbBool isRedirectToSceneGraphEnabled() const { return this->allowredir; } //@} /** @name Pick actions */ @@ -342,7 +343,7 @@ public: * set. */ void setCameraOrientation(const SbRotation& rot, SbBool moveTocenter=false); - void setCameraType(SoType t); + void setCameraType(SoType t) override; void moveCameraTo(const SbRotation& rot, const SbVec3f& pos, int steps, int ms); /** * Zooms the viewport to the size of the bounding box. @@ -351,11 +352,11 @@ public: /** * Reposition the current camera so we can see the complete scene. */ - void viewAll(); + void viewAll() override; void viewAll(float factor); /// Breaks out a VR window for a Rift - void viewVR(void); + void viewVR(); /** * Returns the bounding box of the scene graph. @@ -379,11 +380,11 @@ public: void setNavigationType(Base::Type); void setAxisCross(bool b); - bool hasAxisCross(void); + bool hasAxisCross(); void setEnabledFPSCounter(bool b); void setEnabledNaviCube(bool b); - bool isEnabledNaviCube(void) const; + bool isEnabledNaviCube() const; void setNaviCubeCorner(int); NaviCube* getNavigationCube() const; void setEnabledVBO(bool b); @@ -395,7 +396,7 @@ public: void setDocument(Gui::Document *pcDocument); Gui::Document* getDocument(); - virtual PyObject *getPyObject(void); + virtual PyObject *getPyObject(); protected: GLenum getInternalTextureFormat() const; @@ -403,14 +404,14 @@ protected: void renderFramebuffer(); void renderGLImage(); void animatedViewAll(int steps, int ms); - virtual void actualRedraw(void); - virtual void setSeekMode(SbBool enable); - virtual void afterRealizeHook(void); - virtual bool processSoEvent(const SoEvent * ev); - void dropEvent (QDropEvent * e); - void dragEnterEvent (QDragEnterEvent * e); - void dragMoveEvent(QDragMoveEvent *e); - void dragLeaveEvent(QDragLeaveEvent *e); + void actualRedraw() override; + void setSeekMode(SbBool enable) override; + void afterRealizeHook() override; + bool processSoEvent(const SoEvent * ev) override; + void dropEvent (QDropEvent * e) override; + void dragEnterEvent (QDragEnterEvent * e) override; + void dragMoveEvent(QDragMoveEvent *e) override; + void dragLeaveEvent(QDragLeaveEvent *e) override; SbBool processSoEventBase(const SoEvent * const ev); void printDimension(); void selectAll(); @@ -429,10 +430,10 @@ private: static void deselectCB(void * closure, SoPath * p); static SoPath * pickFilterCB(void * data, const SoPickedPoint * pick); void initialize(); - void drawAxisCross(void); - static void drawArrow(void); + void drawAxisCross(); + static void drawArrow(); void setCursorRepresentation(int mode); - void aboutToDestroyGLContext(); + void aboutToDestroyGLContext() override; void createStandardCursors(double); private: diff --git a/src/Gui/View3DPy.cpp b/src/Gui/View3DPy.cpp index 5b3c862df4..d5fe267162 100644 --- a/src/Gui/View3DPy.cpp +++ b/src/Gui/View3DPy.cpp @@ -282,7 +282,7 @@ Py::Object View3DInventorPy::getattribute(const char * attr) if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); - for (auto it : dict_base) { + for (const auto& it : dict_base) { dict_self.setItem(it.first, it.second); } return dict_self; @@ -1483,7 +1483,7 @@ Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args) auto obj = vpd->getObject(); if (!obj) return ret; - if (subname.size()) { + if (!subname.empty()) { std::pair elementName; auto sobj = App::GeoFeature::resolveElement(obj,subname.c_str(),elementName); if (!sobj) @@ -1493,7 +1493,7 @@ Py::Object View3DInventorPy::getObjectInfo(const Py::Tuple& args) dict.setItem("SubName",Py::String(subname)); obj = sobj; } - subname = elementName.second.size()?elementName.second:elementName.first; + subname = !elementName.second.empty()?elementName.second:elementName.first; } dict.setItem("Document", Py::String(obj->getDocument()->getName())); @@ -1595,7 +1595,7 @@ Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args) auto obj = vpd->getObject(); if (!obj) continue; - if (subname.size()) { + if (!subname.empty()) { std::pair elementName; auto sobj = App::GeoFeature::resolveElement(obj,subname.c_str(),elementName); if (!sobj) @@ -1605,7 +1605,7 @@ Py::Object View3DInventorPy::getObjectsInfo(const Py::Tuple& args) dict.setItem("SubName",Py::String(subname)); obj = sobj; } - subname = elementName.second.size()?elementName.second:elementName.first; + subname = !elementName.second.empty()?elementName.second:elementName.first; } dict.setItem("Document", Py::String(obj->getDocument()->getName())); diff --git a/src/Gui/View3DPy.h b/src/Gui/View3DPy.h index 3ce99980e0..11ea92f5e7 100644 --- a/src/Gui/View3DPy.h +++ b/src/Gui/View3DPy.h @@ -59,13 +59,13 @@ public: using BaseType = Py::PythonExtension; static void init_type(); // announce properties and methods - View3DInventorPy(View3DInventor *vi); - ~View3DInventorPy(); + explicit View3DInventorPy(View3DInventor *vi); + ~View3DInventorPy() override; View3DInventor* getView3DIventorPtr(); - Py::Object repr(); - Py::Object getattr(const char *); - int setattr(const char *, const Py::Object &); + Py::Object repr() override; + Py::Object getattr(const char *) override; + int setattr(const char *, const Py::Object &) override; Py::Object cast_to_base(const Py::Tuple&); Py::Object fitAll(const Py::Tuple&); diff --git a/src/Gui/View3DViewerPy.h b/src/Gui/View3DViewerPy.h index e33292bb8b..0f2e275c1a 100644 --- a/src/Gui/View3DViewerPy.h +++ b/src/Gui/View3DViewerPy.h @@ -42,14 +42,14 @@ class View3DInventorViewer; class View3DInventorViewerPy : public Py::PythonExtension { public: - static void init_type(void); // announce properties and methods + static void init_type(); // announce properties and methods - View3DInventorViewerPy(View3DInventorViewer *vi); - ~View3DInventorViewerPy(); + explicit View3DInventorViewerPy(View3DInventorViewer *vi); + ~View3DInventorViewerPy() override; - Py::Object repr(); - Py::Object getattr(const char *); - int setattr(const char *, const Py::Object &); + Py::Object repr() override; + Py::Object getattr(const char *) override; + int setattr(const char *, const Py::Object &) override; //exposed methods Py::Object getSoEventManager(const Py::Tuple&); diff --git a/src/Gui/ViewParams.h b/src/Gui/ViewParams.h index b679f129fa..654af67bb9 100644 --- a/src/Gui/ViewParams.h +++ b/src/Gui/ViewParams.h @@ -35,8 +35,8 @@ namespace Gui { class GuiExport ViewParams: public ParameterGrp::ObserverType { public: ViewParams(); - virtual ~ViewParams(); - void OnChange(Base::Subject &, const char* sReason); + ~ViewParams() override; + void OnChange(Base::Subject &, const char* sReason) override; static ViewParams *instance(); ParameterGrp::handle getHandle() { diff --git a/src/Gui/ViewProvider.cpp b/src/Gui/ViewProvider.cpp index 2b651d96b4..a2371108cc 100644 --- a/src/Gui/ViewProvider.cpp +++ b/src/Gui/ViewProvider.cpp @@ -291,7 +291,7 @@ void ViewProvider::eventCallback(void * ud, SoEventCallback * node) } } -SoSeparator* ViewProvider::getAnnotation(void) +SoSeparator* ViewProvider::getAnnotation() { if (!pcAnnotation) { pcAnnotation = new SoSeparator(); @@ -312,7 +312,7 @@ void ViewProvider::update(const App::Property* prop) if (vis) ViewProvider::show(); } -QIcon ViewProvider::getIcon(void) const +QIcon ViewProvider::getIcon() const { return mergeGreyableOverlayIcons (Gui::BitmapFactory().pixmap(sPixmap)); } @@ -436,7 +436,7 @@ const char* ViewProvider::getDefaultDisplayMode() const { return nullptr; } -vector ViewProvider::getDisplayModes(void) const { +vector ViewProvider::getDisplayModes() const { std::vector< std::string > modes; auto vector = getExtensionsDerivedFromType(); @@ -447,12 +447,12 @@ vector ViewProvider::getDisplayModes(void) const { return modes; } -std::string ViewProvider::getActiveDisplayMode(void) const +std::string ViewProvider::getActiveDisplayMode() const { return _sCurrentMode; } -void ViewProvider::hide(void) +void ViewProvider::hide() { auto exts = getExtensionsDerivedFromType(); @@ -467,7 +467,7 @@ void ViewProvider::hide(void) ext->extensionHide(); } -void ViewProvider::show(void) +void ViewProvider::show() { setModeSwitch(); @@ -477,7 +477,7 @@ void ViewProvider::show(void) ext->extensionShow(); } -bool ViewProvider::isShow(void) const +bool ViewProvider::isShow() const { return pcModeSwitch->whichChild.getValue() != -1; } @@ -846,7 +846,7 @@ void ViewProvider::updateData(const App::Property* prop) ext->extensionUpdateData(prop); } -SoSeparator* ViewProvider::getBackRoot(void) const +SoSeparator* ViewProvider::getBackRoot() const { auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { @@ -857,7 +857,7 @@ SoSeparator* ViewProvider::getBackRoot(void) const return nullptr; } -SoGroup* ViewProvider::getChildRoot(void) const +SoGroup* ViewProvider::getChildRoot() const { auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { @@ -868,7 +868,7 @@ SoGroup* ViewProvider::getChildRoot(void) const return nullptr; } -SoSeparator* ViewProvider::getFrontRoot(void) const +SoSeparator* ViewProvider::getFrontRoot() const { auto vector = getExtensionsDerivedFromType(); for (Gui::ViewProviderExtension* ext : vector) { @@ -879,7 +879,7 @@ SoSeparator* ViewProvider::getFrontRoot(void) const return nullptr; } -std::vector< App::DocumentObject* > ViewProvider::claimChildren(void) const +std::vector< App::DocumentObject* > ViewProvider::claimChildren() const { std::vector< App::DocumentObject* > vec; auto vector = getExtensionsDerivedFromType(); @@ -891,7 +891,7 @@ std::vector< App::DocumentObject* > ViewProvider::claimChildren(void) const return vec; } -std::vector< App::DocumentObject* > ViewProvider::claimChildren3D(void) const +std::vector< App::DocumentObject* > ViewProvider::claimChildren3D() const { std::vector< App::DocumentObject* > vec; auto vector = getExtensionsDerivedFromType(); @@ -1009,7 +1009,7 @@ Base::BoundBox3d ViewProvider::getBoundingBox(const char *subname, bool transfor auto doc = Application::Instance->activeDocument(); if(doc) { auto views = doc->getMDIViewsOfType(View3DInventor::getClassTypeId()); - if(views.size()) + if(!views.empty()) iview = dynamic_cast(views.front()); } if(!iview) { diff --git a/src/Gui/ViewProvider.h b/src/Gui/ViewProvider.h index ed7682e52e..ba5284ed7f 100644 --- a/src/Gui/ViewProvider.h +++ b/src/Gui/ViewProvider.h @@ -100,7 +100,7 @@ public: operator T *() const { return this->get(); - } + }//explicit bombs }; /** Helper function to deal with bug in SoNode::removeAllChildren() @@ -118,28 +118,28 @@ void GuiExport coinRemoveAllChildren(SoGroup *node); */ class GuiExport ViewProvider : public App::TransactionalObject { - PROPERTY_HEADER(Gui::ViewProvider); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProvider); public: /// constructor. ViewProvider(); /// destructor. - virtual ~ViewProvider(); + ~ViewProvider() override; // returns the root node of the Provider (3D) - virtual SoSeparator* getRoot(void) const {return pcRoot;} + virtual SoSeparator* getRoot() const {return pcRoot;} // return the mode switch node of the Provider (3D) - SoSwitch *getModeSwitch(void) const {return pcModeSwitch;} + SoSwitch *getModeSwitch() const {return pcModeSwitch;} SoTransform *getTransformNode() const {return pcTransform;} // returns the root for the Annotations. - SoSeparator* getAnnotation(void); + SoSeparator* getAnnotation(); // returns the root node of the Provider (3D) - virtual SoSeparator* getFrontRoot(void) const; + virtual SoSeparator* getFrontRoot() const; // returns the root node where the children gets collected(3D) - virtual SoGroup* getChildRoot(void) const; + virtual SoGroup* getChildRoot() const; // returns the root node of the Provider (3D) - virtual SoSeparator* getBackRoot(void) const; + virtual SoSeparator* getBackRoot() const; ///Indicate whether to be added to scene graph or not virtual bool canAddToSceneGraph() const {return true;} @@ -149,7 +149,7 @@ public: * scene graph. This affects the visibility and the 3D * position of the object. */ - virtual std::vector claimChildren3D(void) const; + virtual std::vector claimChildren3D() const; /** @name Selection handling * This group of methods do the selection handling. @@ -159,8 +159,8 @@ public: //@{ /// indicates if the ViewProvider use the new Selection model - virtual bool useNewSelectionModel(void) const; - virtual bool isSelectable(void) const {return true;} + virtual bool useNewSelectionModel() const; + virtual bool isSelectable() const {return true;} /// return a hit element given the picked point which contains the full node path virtual bool getElementPicked(const SoPickedPoint *, std::string &subname) const; /// return a hit element to the selection path or 0 @@ -187,7 +187,7 @@ public: /** partial rendering setup * * @param subelements: a list of dot separated string refer to the sub element - * @param clear: if true, remove the the subelement from partial rendering. + * @param clear: if true, remove the subelement from partial rendering. * If else, add the subelement for rendering. * * @return Return the number of subelement found @@ -241,7 +241,7 @@ public: */ //@{ /// deliver the icon shown in the tree view - virtual QIcon getIcon(void) const; + virtual QIcon getIcon() const; /** @name Methods used by the Tree * If you want to take control over the @@ -258,7 +258,7 @@ public: * be used for any kind of grouping needed for a special * purpose. */ - virtual std::vector claimChildren(void) const; + virtual std::vector claimChildren() const; //@} /** @name Drag and drop @@ -374,24 +374,24 @@ public: void setStatus(ViewStatus pos, bool on) {StatusBits.set((size_t)pos, on);} std::string toString() const; - PyObject* getPyObject(); + PyObject* getPyObject() override; /** @name Display mode methods */ //@{ - std::string getActiveDisplayMode(void) const; + std::string getActiveDisplayMode() const; /// set the display mode virtual void setDisplayMode(const char* ModeName); /// get the default display mode virtual const char* getDefaultDisplayMode() const; /// returns a list of all possible display modes - virtual std::vector getDisplayModes(void) const; + virtual std::vector getDisplayModes() const; /// Hides the view provider - virtual void hide(void); + virtual void hide(); /// Shows the view provider - virtual void show(void); + virtual void show(); /// checks whether the view provider is visible or not - virtual bool isShow(void) const; + virtual bool isShow() const; void setVisible(bool); bool isVisible() const; void setLinkVisible(bool); @@ -462,7 +462,7 @@ public: /// If null is returned then no transaction will be opened. virtual const char* getTransactionText() const { return nullptr; } /// is called by the tree if the user double clicks on the object - virtual bool doubleClicked(void) { return false; } + virtual bool doubleClicked() { return false; } /// is called when the provider is in edit and the mouse is moved virtual bool mouseMove(const SbVec2s &cursorPos, View3DInventorViewer* viewer); /// is called when the Provider is in edit and the mouse is clicked @@ -497,7 +497,7 @@ public: //restoring the object from document: //this may be of interest to extensions, hence call them - virtual void Restore(Base::XMLReader& reader); + void Restore(Base::XMLReader& reader) override; bool isRestoring() {return testStatus(Gui::isRestoring);} @@ -539,9 +539,9 @@ protected: SoPickedPoint* getPointOnRay(const SbVec3f& pos, const SbVec3f& dir, const View3DInventorViewer* viewer) const; /// Reimplemented from subclass - void onBeforeChange(const App::Property* prop); + void onBeforeChange(const App::Property* prop) override; /// Reimplemented from subclass - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; /** @name Methods used by the Tree * If you want to take control over the diff --git a/src/Gui/ViewProviderAnnotation.cpp b/src/Gui/ViewProviderAnnotation.cpp index f1df4531e2..bf2d3b159e 100644 --- a/src/Gui/ViewProviderAnnotation.cpp +++ b/src/Gui/ViewProviderAnnotation.cpp @@ -163,12 +163,12 @@ void ViewProviderAnnotation::onChanged(const App::Property* prop) } } -std::vector ViewProviderAnnotation::getDisplayModes(void) const +std::vector ViewProviderAnnotation::getDisplayModes() const { // add modes std::vector StrList; - StrList.push_back("Screen"); - StrList.push_back("World"); + StrList.emplace_back("Screen"); + StrList.emplace_back("World"); return StrList; } @@ -333,12 +333,12 @@ void ViewProviderAnnotationLabel::onChanged(const App::Property* prop) } } -std::vector ViewProviderAnnotationLabel::getDisplayModes(void) const +std::vector ViewProviderAnnotationLabel::getDisplayModes() const { // add modes std::vector StrList; - StrList.push_back("Line"); - StrList.push_back("Object"); + StrList.emplace_back("Line"); + StrList.emplace_back("Object"); return StrList; } @@ -399,7 +399,7 @@ void ViewProviderAnnotationLabel::updateData(const App::Property* prop) ViewProviderDocumentObject::updateData(prop); } -bool ViewProviderAnnotationLabel::doubleClicked(void) +bool ViewProviderAnnotationLabel::doubleClicked() { Gui::Application::Instance->activeDocument()->setEdit(this); return true; diff --git a/src/Gui/ViewProviderAnnotation.h b/src/Gui/ViewProviderAnnotation.h index f986bb9c08..1d2d5e7923 100644 --- a/src/Gui/ViewProviderAnnotation.h +++ b/src/Gui/ViewProviderAnnotation.h @@ -42,12 +42,12 @@ namespace Gui class GuiExport ViewProviderAnnotation : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderAnnotation); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderAnnotation); public: /// Constructor - ViewProviderAnnotation(void); - virtual ~ViewProviderAnnotation(); + ViewProviderAnnotation(); + ~ViewProviderAnnotation() override; // Display properties App::PropertyColor TextColor; @@ -58,13 +58,13 @@ public: App::PropertyAngle Rotation; App::PropertyEnumeration RotationAxis; - void attach(App::DocumentObject *); - void updateData(const App::Property*); - std::vector getDisplayModes(void) const; - void setDisplayMode(const char* ModeName); + void attach(App::DocumentObject *) override; + void updateData(const App::Property*) override; + std::vector getDisplayModes() const override; + void setDisplayMode(const char* ModeName) override; protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: SoFont * pFont; @@ -86,12 +86,12 @@ private: */ class GuiExport ViewProviderAnnotationLabel : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderAnnotationLabel); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderAnnotationLabel); public: /// Constructor - ViewProviderAnnotationLabel(void); - virtual ~ViewProviderAnnotationLabel(); + ViewProviderAnnotationLabel(); + ~ViewProviderAnnotationLabel() override; // Display properties App::PropertyColor TextColor; @@ -101,22 +101,22 @@ public: App::PropertyFont FontName; App::PropertyBool Frame; - void attach(App::DocumentObject *); - void updateData(const App::Property*); - std::vector getDisplayModes(void) const; - void setDisplayMode(const char* ModeName); + void attach(App::DocumentObject *) override; + void updateData(const App::Property*) override; + std::vector getDisplayModes() const override; + void setDisplayMode(const char* ModeName) override; /** @name Edit methods */ //@{ - bool doubleClicked(void); - void setupContextMenu(QMenu*, QObject*, const char*); + bool doubleClicked() override; + void setupContextMenu(QMenu*, QObject*, const char*) override; protected: - bool setEdit(int ModNum); - void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; //@} protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; void drawImage(const std::vector&); private: diff --git a/src/Gui/ViewProviderBuilder.h b/src/Gui/ViewProviderBuilder.h index ec27ac9f01..9a10276b47 100644 --- a/src/Gui/ViewProviderBuilder.h +++ b/src/Gui/ViewProviderBuilder.h @@ -43,7 +43,7 @@ class GuiExport ViewProviderBuilder { public: /// Constructor - ViewProviderBuilder(void); + ViewProviderBuilder(); virtual ~ViewProviderBuilder(); virtual void buildNodes(const App::Property*, std::vector&) const = 0; @@ -59,9 +59,9 @@ class GuiExport ViewProviderColorBuilder : public ViewProviderBuilder { public: /// Constructor - ViewProviderColorBuilder(void); - virtual ~ViewProviderColorBuilder(); - virtual void buildNodes(const App::Property*, std::vector&) const; + ViewProviderColorBuilder(); + ~ViewProviderColorBuilder() override; + void buildNodes(const App::Property*, std::vector&) const override; }; } //namespace Gui diff --git a/src/Gui/ViewProviderDocumentObject.cpp b/src/Gui/ViewProviderDocumentObject.cpp index 3886b2de48..08fa38ea32 100644 --- a/src/Gui/ViewProviderDocumentObject.cpp +++ b/src/Gui/ViewProviderDocumentObject.cpp @@ -224,7 +224,7 @@ void ViewProviderDocumentObject::onChanged(const App::Property* prop) ViewProvider::onChanged(prop); } -void ViewProviderDocumentObject::hide(void) +void ViewProviderDocumentObject::hide() { ViewProvider::hide(); // use this bit to check whether 'Visibility' must be adjusted @@ -280,7 +280,7 @@ void ViewProviderDocumentObject::setModeSwitch() { ViewProvider::setModeSwitch(); } -void ViewProviderDocumentObject::show(void) +void ViewProviderDocumentObject::show() { if(TreeWidget::isObjectShowable(getObject())) ViewProvider::show(); @@ -339,7 +339,7 @@ void ViewProviderDocumentObject::attach(App::DocumentObject *pcObj) aDisplayModesArray = this->getDisplayModes(); if (aDisplayModesArray.empty()) - aDisplayModesArray.push_back(""); + aDisplayModesArray.emplace_back(""); // We must collect the const char* of the strings and give it to PropertyEnumeration, // but we are still responsible for them, i.e. the property class must not delete the literals. diff --git a/src/Gui/ViewProviderDocumentObject.h b/src/Gui/ViewProviderDocumentObject.h index f18c4fed03..f01c808069 100644 --- a/src/Gui/ViewProviderDocumentObject.h +++ b/src/Gui/ViewProviderDocumentObject.h @@ -55,7 +55,7 @@ public: ViewProviderDocumentObject(); /// destructor. - virtual ~ViewProviderDocumentObject(); + ~ViewProviderDocumentObject() override; // Display properties App::PropertyEnumeration DisplayMode; @@ -66,43 +66,43 @@ public: virtual void attach(App::DocumentObject *pcObject); virtual void reattach(App::DocumentObject *); - virtual void update(const App::Property*) override; + void update(const App::Property*) override; /// Set the active mode, i.e. the first item of the 'Display' property. void setActiveMode(); /// Hide the object in the view - virtual void hide(void) override; + void hide() override; /// Show the object in the view - virtual void show(void) override; + void show() override; /// Is called by the tree if the user double clicks on the object. It returns the string /// for the transaction that will be shown in the undo/redo dialog. /// If null is returned then no transaction will be opened. - virtual const char* getTransactionText() const override; + const char* getTransactionText() const override; - virtual bool canDropObjectEx(App::DocumentObject *, App::DocumentObject *, + bool canDropObjectEx(App::DocumentObject *, App::DocumentObject *, const char *, const std::vector &) const override; - virtual int replaceObject(App::DocumentObject*, App::DocumentObject*) override; + int replaceObject(App::DocumentObject*, App::DocumentObject*) override; - virtual bool showInTree() const override; + bool showInTree() const override; /// Get a list of TaskBoxes associated with this object - virtual void getTaskViewContent(std::vector&) const override; + void getTaskViewContent(std::vector&) const override; /// Run a redraw void updateView(); /// Get the object of this ViewProvider object - App::DocumentObject *getObject(void) const {return pcObject;} + App::DocumentObject *getObject() const {return pcObject;} /// Asks the view provider if the given object can be deleted. - virtual bool canDelete(App::DocumentObject* obj) const override; + bool canDelete(App::DocumentObject* obj) const override; /// Get the GUI document to this ViewProvider object Gui::Document* getDocument() const; /// Get the python wrapper for that ViewProvider PyObject* getPyObject() override; /// return a hit element given the picked point which contains the full node path - virtual bool getElementPicked(const SoPickedPoint *, std::string &subname) const override; + bool getElementPicked(const SoPickedPoint *, std::string &subname) const override; /// return the coin node detail and path to the node of the subname - virtual bool getDetailPath(const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const override; + bool getDetailPath(const char *subname, SoFullPath *pPath, bool append, SoDetail *&det) const override; /* Force update visual * @@ -121,9 +121,9 @@ public: virtual void finishRestoring(); //@} - virtual bool removeDynamicProperty(const char* prop) override; + bool removeDynamicProperty(const char* prop) override; - virtual App::Property* addDynamicProperty( + App::Property* addDynamicProperty( const char* type, const char* name=nullptr, const char* group=nullptr, const char* doc=nullptr, short attr=0, bool ro=false, bool hidden=false) override; @@ -142,7 +142,7 @@ public: virtual ViewProviderDocumentObject *getLinkedViewProvider( std::string *subname=nullptr, bool recursive=false) const; - virtual std::string getFullName() const override; + std::string getFullName() const override; /** Allow this class to be used as an override for the original view provider of the given object * @@ -181,9 +181,9 @@ protected: */ Gui::MDIView* getViewOfNode(SoNode* node) const; /// get called before the value is changed - virtual void onBeforeChange(const App::Property* prop) override; + void onBeforeChange(const App::Property* prop) override; /// Gets called by the container whenever a property has been changed - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; /** Searches in all view providers that are attached to an object that * is part of the same document as the object this view provider is * attached to for an front root of \a type. @@ -196,15 +196,15 @@ protected: /** @name Transaction handling */ //@{ - virtual bool isAttachedToDocument() const override; - virtual const char* detachFromDocument() override; + bool isAttachedToDocument() const override; + const char* detachFromDocument() override; /// get called when a property status has changed - virtual void onPropertyStatusChanged(const App::Property &prop, unsigned long oldStatus) override; + void onPropertyStatusChanged(const App::Property &prop, unsigned long oldStatus) override; //@} - virtual void setModeSwitch() override; + void setModeSwitch() override; /** Adds a menu item and bind it with \ref startDefaultEditMode(). */ void addDefaultAction(QMenu*, const QString&); diff --git a/src/Gui/ViewProviderDocumentObjectGroup.cpp b/src/Gui/ViewProviderDocumentObjectGroup.cpp index d5bb582816..986f129c21 100644 --- a/src/Gui/ViewProviderDocumentObjectGroup.cpp +++ b/src/Gui/ViewProviderDocumentObjectGroup.cpp @@ -41,9 +41,6 @@ PROPERTY_SOURCE_WITH_EXTENSIONS(Gui::ViewProviderDocumentObjectGroup, Gui::ViewP */ ViewProviderDocumentObjectGroup::ViewProviderDocumentObjectGroup() { -#if 0 - setDefaultMode(SO_SWITCH_ALL); -#endif ViewProviderGroupExtension::initExtension(this); sPixmap = "folder"; @@ -53,18 +50,18 @@ ViewProviderDocumentObjectGroup::~ViewProviderDocumentObjectGroup() { } -std::vector ViewProviderDocumentObjectGroup::getDisplayModes(void) const +std::vector ViewProviderDocumentObjectGroup::getDisplayModes() const { // empty return std::vector(); } -bool ViewProviderDocumentObjectGroup::isShow(void) const +bool ViewProviderDocumentObjectGroup::isShow() const { return Visibility.getValue(); } -QIcon ViewProviderDocumentObjectGroup::getIcon(void) const +QIcon ViewProviderDocumentObjectGroup::getIcon() const { return mergeGreyableOverlayIcons (Gui::BitmapFactory().iconFromTheme(sPixmap)); } diff --git a/src/Gui/ViewProviderDocumentObjectGroup.h b/src/Gui/ViewProviderDocumentObjectGroup.h index 5bcf7a5aa8..b61dad9232 100644 --- a/src/Gui/ViewProviderDocumentObjectGroup.h +++ b/src/Gui/ViewProviderDocumentObjectGroup.h @@ -39,14 +39,14 @@ public: /// constructor. ViewProviderDocumentObjectGroup(); /// destructor. - virtual ~ViewProviderDocumentObjectGroup(); + ~ViewProviderDocumentObjectGroup() override; /// returns a list of all possible modes - std::vector getDisplayModes(void) const override; - bool isShow(void) const override; + std::vector getDisplayModes() const override; + bool isShow() const override; /// deliver the icon shown in the tree view - virtual QIcon getIcon(void) const override; + QIcon getIcon() const override; protected: void getViewProviders(std::vector&) const; diff --git a/src/Gui/ViewProviderDocumentObjectPyImp.cpp b/src/Gui/ViewProviderDocumentObjectPyImp.cpp index 2a2aaa8c07..41a7030d6f 100644 --- a/src/Gui/ViewProviderDocumentObjectPyImp.cpp +++ b/src/Gui/ViewProviderDocumentObjectPyImp.cpp @@ -37,7 +37,7 @@ using namespace Gui; // returns a string which represents the object e.g. when printed in python -std::string ViewProviderDocumentObjectPy::representation(void) const +std::string ViewProviderDocumentObjectPy::representation() const { std::stringstream str; str << ""; @@ -55,7 +55,7 @@ PyObject* ViewProviderDocumentObjectPy::update(PyObject *args) } PY_CATCH; } -Py::Object ViewProviderDocumentObjectPy::getObject(void) const +Py::Object ViewProviderDocumentObjectPy::getObject() const { App::DocumentObject* obj = getViewProviderDocumentObjectPtr()->getObject(); return Py::Object(obj->getPyObject(), true); // do not inc'ref twice @@ -82,7 +82,7 @@ void ViewProviderDocumentObjectPy::setForceUpdate(Py::Boolean arg) getViewProviderDocumentObjectPtr()->forceUpdate(arg); } -Py::Object ViewProviderDocumentObjectPy::getDocument(void) const +Py::Object ViewProviderDocumentObjectPy::getDocument() const { Document* doc = getViewProviderDocumentObjectPtr()->getDocument(); return Py::asObject(doc->getPyObject()); // do not inc'ref twice diff --git a/src/Gui/ViewProviderDragger.cpp b/src/Gui/ViewProviderDragger.cpp index 91e50ded7f..1d3ed1c713 100644 --- a/src/Gui/ViewProviderDragger.cpp +++ b/src/Gui/ViewProviderDragger.cpp @@ -76,7 +76,7 @@ void ViewProviderDragger::updateData(const App::Property* prop) ViewProviderDocumentObject::updateData(prop); } -bool ViewProviderDragger::doubleClicked(void) +bool ViewProviderDragger::doubleClicked() { Gui::Application::Instance->activeDocument()->setEdit(this, (int)ViewProvider::Default); return true; diff --git a/src/Gui/ViewProviderDragger.h b/src/Gui/ViewProviderDragger.h index e8f247ff35..e0c7f221de 100644 --- a/src/Gui/ViewProviderDragger.h +++ b/src/Gui/ViewProviderDragger.h @@ -50,15 +50,15 @@ public: ViewProviderDragger(); /// destructor. - virtual ~ViewProviderDragger(); + ~ViewProviderDragger() override; /** @name Edit methods */ //@{ - bool doubleClicked(void) override; + bool doubleClicked() override; void setupContextMenu(QMenu*, QObject*, const char*) override; void updateData(const App::Property*) override; - virtual ViewProvider *startEditing(int ModNum=0) override; + ViewProvider *startEditing(int ModNum=0) override; /*! synchronize From FC placement to Coin placement*/ static void updateTransform(const Base::Placement &from, SoTransform *to); diff --git a/src/Gui/ViewProviderExtension.cpp b/src/Gui/ViewProviderExtension.cpp index 1f422134df..e9fb56c0ca 100644 --- a/src/Gui/ViewProviderExtension.cpp +++ b/src/Gui/ViewProviderExtension.cpp @@ -63,7 +63,7 @@ void ViewProviderExtension::extensionUpdateData(const App::Property*) { } -PyObject* ViewProviderExtension::getExtensionPyObject(void) { +PyObject* ViewProviderExtension::getExtensionPyObject() { if (ExtensionPythonObject.is(Py::_None())){ // ref counter is set to 1 diff --git a/src/Gui/ViewProviderExtension.h b/src/Gui/ViewProviderExtension.h index 8ba57142ee..2b68a6e8f5 100644 --- a/src/Gui/ViewProviderExtension.h +++ b/src/Gui/ViewProviderExtension.h @@ -51,23 +51,23 @@ class GuiExport ViewProviderExtension : public App::Extension //The cass does not have properties itself, but it is important to provide the property access //functions. - EXTENSION_PROPERTY_HEADER(Gui::ViewProviderExtension); + EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderExtension); public: ViewProviderExtension (); - virtual ~ViewProviderExtension (); + ~ViewProviderExtension () override; Gui::ViewProviderDocumentObject* getExtendedViewProvider(); const Gui::ViewProviderDocumentObject* getExtendedViewProvider() const; - virtual std::vector extensionClaimChildren3D(void) const { + virtual std::vector extensionClaimChildren3D() const { return std::vector(); } virtual bool extensionOnDelete(const std::vector &){ return true;} virtual void extensionBeforeDelete(){} - virtual std::vector extensionClaimChildren(void) const { + virtual std::vector extensionClaimChildren() const { return std::vector(); } virtual bool extensionCanDragObjects() const { return false; } @@ -88,24 +88,24 @@ public: { return -1; } /// Hides the view provider - virtual void extensionHide(void) { } + virtual void extensionHide() { } /// Shows the view provider - virtual void extensionShow(void) { } + virtual void extensionShow() { } - virtual void extensionModeSwitchChange(void) { } + virtual void extensionModeSwitchChange() { } - virtual SoSeparator* extensionGetFrontRoot(void) const {return nullptr;} - virtual SoGroup* extensionGetChildRoot(void) const {return nullptr;} - virtual SoSeparator* extensionGetBackRoot(void) const {return nullptr;} + virtual SoSeparator* extensionGetFrontRoot() const {return nullptr;} + virtual SoGroup* extensionGetChildRoot() const {return nullptr;} + virtual SoSeparator* extensionGetBackRoot() const {return nullptr;} virtual void extensionAttach(App::DocumentObject* ) { } virtual void extensionReattach(App::DocumentObject* ) { } virtual void extensionSetDisplayMode(const char* ) { } - virtual std::vector extensionGetDisplayModes(void) const {return std::vector();} + virtual std::vector extensionGetDisplayModes() const {return std::vector();} virtual void extensionSetupContextMenu(QMenu*, QObject*, const char*) {} - //update data of extended opject + // update data of extended object virtual void extensionUpdateData(const App::Property*); - virtual PyObject* getExtensionPyObject(); + PyObject* getExtensionPyObject() override; void setIgnoreOverlayIcon(bool on) { m_ignoreOverlayIcon = on; diff --git a/src/Gui/ViewProviderExtensionPyImp.cpp b/src/Gui/ViewProviderExtensionPyImp.cpp index 3bb08a0392..0c5f8052fc 100644 --- a/src/Gui/ViewProviderExtensionPyImp.cpp +++ b/src/Gui/ViewProviderExtensionPyImp.cpp @@ -35,7 +35,7 @@ using namespace Gui; // returns a string which represent the object e.g. when printed in python -std::string ViewProviderExtensionPy::representation(void) const +std::string ViewProviderExtensionPy::representation() const { return std::string(""); } diff --git a/src/Gui/ViewProviderExtern.cpp b/src/Gui/ViewProviderExtern.cpp index e14caf0240..c169f381b9 100644 --- a/src/Gui/ViewProviderExtern.cpp +++ b/src/Gui/ViewProviderExtern.cpp @@ -97,7 +97,7 @@ void ViewProviderExtern::setModeBySoInput(const char* name, SoInput &ivFileInput ::iterator,string>(modes.begin(),modes.end(),string(name)); if (pos == modes.end()) { // new mode - modes.push_back(name); + modes.emplace_back(name); addDisplayMaskMode(root, name); setDisplayMaskMode(name); } @@ -143,7 +143,7 @@ const char* ViewProviderExtern::getDefaultDisplayMode() const return (modes.empty() ? "" : modes.front().c_str()); } -std::vector ViewProviderExtern::getDisplayModes(void) const +std::vector ViewProviderExtern::getDisplayModes() const { return modes; } diff --git a/src/Gui/ViewProviderExtern.h b/src/Gui/ViewProviderExtern.h index 6be47c868c..0cbc917d03 100644 --- a/src/Gui/ViewProviderExtern.h +++ b/src/Gui/ViewProviderExtern.h @@ -35,23 +35,23 @@ namespace Gui { class GuiExport ViewProviderExtern:public ViewProvider { - PROPERTY_HEADER(Gui::ViewProviderExtern); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderExtern); public: /// constructor. ViewProviderExtern(); /// destructor. - virtual ~ViewProviderExtern(); + ~ViewProviderExtern() override; void setModeByString(const char* name, const char* ivFragment); void setModeByFile(const char* name, const char* ivFileName); void setModeBySoInput(const char* name, SoInput &ivFileInput); void adjustDocumentName(const char* docname); - virtual const char* getDefaultDisplayMode() const; - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*){} + const char* getDefaultDisplayMode() const override; + std::vector getDisplayModes() const override; + void updateData(const App::Property*) override{} private: void adjustRecursiveDocumentName(SoNode*, const char* docname); diff --git a/src/Gui/ViewProviderFeature.h b/src/Gui/ViewProviderFeature.h index c6494ee2ce..cc9968215e 100644 --- a/src/Gui/ViewProviderFeature.h +++ b/src/Gui/ViewProviderFeature.h @@ -34,21 +34,21 @@ class View3DInventorViewer; class GuiExport ViewProviderFeature:public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderFeature); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderFeature); public: /// constructor. ViewProviderFeature(); /// destructor. - virtual ~ViewProviderFeature(); + ~ViewProviderFeature() override; App::PropertyColorList ColourList; /** * Attaches the document object to this view provider. */ - virtual void attach(App::DocumentObject *pcObj); + void attach(App::DocumentObject *pcObj) override; }; } // namespace Gui diff --git a/src/Gui/ViewProviderGeoFeatureGroup.h b/src/Gui/ViewProviderGeoFeatureGroup.h index bcb3c1ac9c..5b65739569 100644 --- a/src/Gui/ViewProviderGeoFeatureGroup.h +++ b/src/Gui/ViewProviderGeoFeatureGroup.h @@ -41,7 +41,7 @@ public: /// constructor. ViewProviderGeoFeatureGroup(); /// destructor. - virtual ~ViewProviderGeoFeatureGroup(); + ~ViewProviderGeoFeatureGroup() override; }; typedef ViewProviderPythonFeatureT ViewProviderGeoFeatureGroupPython; diff --git a/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp b/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp index ffff8894bf..35012dff48 100644 --- a/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp +++ b/src/Gui/ViewProviderGeoFeatureGroupExtension.cpp @@ -64,7 +64,7 @@ ViewProviderGeoFeatureGroupExtension::~ViewProviderGeoFeatureGroupExtension() } -std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren3D(void) const { +std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren3D() const { //all object in the group must be claimed in 3D, as we are a coordinate system for all of them auto* ext = getExtendedViewProvider()->getObject()->getExtensionByType(); @@ -75,7 +75,7 @@ std::vector ViewProviderGeoFeatureGroupExtension::extensio return std::vector(); } -std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren(void) const { +std::vector ViewProviderGeoFeatureGroupExtension::extensionClaimChildren() const { auto* group = getExtendedViewProvider()->getObject()->getExtensionByType(); const std::vector &model = group->Group.getValues (); @@ -129,13 +129,13 @@ void ViewProviderGeoFeatureGroupExtension::extensionSetDisplayMode(const char* M ViewProviderGroupExtension::extensionSetDisplayMode( ModeName ); } -std::vector ViewProviderGeoFeatureGroupExtension::extensionGetDisplayModes(void) const +std::vector ViewProviderGeoFeatureGroupExtension::extensionGetDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderGroupExtension::extensionGetDisplayModes(); // add your own modes - StrList.push_back("Group"); + StrList.emplace_back("Group"); return StrList; } diff --git a/src/Gui/ViewProviderGeoFeatureGroupExtension.h b/src/Gui/ViewProviderGeoFeatureGroupExtension.h index 0a9171b8a8..b0aa469ee4 100644 --- a/src/Gui/ViewProviderGeoFeatureGroupExtension.h +++ b/src/Gui/ViewProviderGeoFeatureGroupExtension.h @@ -37,29 +37,29 @@ class GuiExport ViewProviderGeoFeatureGroupExtension : public ViewProviderGroupE public: /// Constructor - ViewProviderGeoFeatureGroupExtension(void); - virtual ~ViewProviderGeoFeatureGroupExtension(); + ViewProviderGeoFeatureGroupExtension(); + ~ViewProviderGeoFeatureGroupExtension() override; - virtual std::vector extensionClaimChildren3D(void)const override; - virtual std::vector< App::DocumentObject* > extensionClaimChildren(void) const override; - virtual SoSeparator* extensionGetFrontRoot() const override {return pcGroupFront;} - virtual SoSeparator* extensionGetBackRoot() const override {return pcGroupBack;} - virtual SoGroup* extensionGetChildRoot(void) const override {return pcGroupChildren;} - virtual void extensionAttach(App::DocumentObject* pcObject) override; - virtual void extensionSetDisplayMode(const char* ModeName) override; - virtual std::vector extensionGetDisplayModes(void) const override; - virtual void extensionFinishRestoring() override; + std::vector extensionClaimChildren3D()const override; + std::vector< App::DocumentObject* > extensionClaimChildren() const override; + SoSeparator* extensionGetFrontRoot() const override {return pcGroupFront;} + SoSeparator* extensionGetBackRoot() const override {return pcGroupBack;} + SoGroup* extensionGetChildRoot() const override {return pcGroupChildren;} + void extensionAttach(App::DocumentObject* pcObject) override; + void extensionSetDisplayMode(const char* ModeName) override; + std::vector extensionGetDisplayModes() const override; + void extensionFinishRestoring() override; /// Show the object in the view: suppresses behavior of DocumentObjectGroup - virtual void extensionShow(void) override { + void extensionShow() override { ViewProviderExtension::extensionShow(); // clazy:exclude=skipped-base-method } /// Hide the object in the view: suppresses behavior of DocumentObjectGroup - virtual void extensionHide(void) override { + void extensionHide() override { ViewProviderExtension::extensionHide(); // clazy:exclude=skipped-base-method } - virtual void extensionUpdateData(const App::Property*) override; + void extensionUpdateData(const App::Property*) override; protected: SoSeparator *pcGroupFront; diff --git a/src/Gui/ViewProviderGeometryObject.h b/src/Gui/ViewProviderGeometryObject.h index e0da40eef6..0b16849284 100644 --- a/src/Gui/ViewProviderGeometryObject.h +++ b/src/Gui/ViewProviderGeometryObject.h @@ -45,14 +45,14 @@ class View3DInventorViewer; */ class GuiExport ViewProviderGeometryObject : public ViewProviderDragger { - PROPERTY_HEADER(Gui::ViewProviderGeometryObject); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderGeometryObject); public: /// constructor. ViewProviderGeometryObject(); /// destructor. - virtual ~ViewProviderGeometryObject(); + ~ViewProviderGeometryObject() override; // Display properties App::PropertyColor ShapeColor; @@ -64,10 +64,10 @@ public: /** * Attaches the document object to this view provider. */ - void attach(App::DocumentObject *pcObject); - void updateData(const App::Property*); + void attach(App::DocumentObject *pcObject) override; + void updateData(const App::Property*) override; - bool isSelectable(void) const {return Selectable.getValue();} + bool isSelectable() const override {return Selectable.getValue();} /** * Returns a list of picked points from the geometry under \a getRoot(). @@ -89,7 +89,7 @@ public: protected: /// get called by the container whenever a property has been changed - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; void setSelectable(bool Selectable=true); virtual unsigned long getBoundColor() const; diff --git a/src/Gui/ViewProviderGroupExtension.cpp b/src/Gui/ViewProviderGroupExtension.cpp index e69ef437ec..3653896784 100644 --- a/src/Gui/ViewProviderGroupExtension.cpp +++ b/src/Gui/ViewProviderGroupExtension.cpp @@ -108,13 +108,13 @@ void ViewProviderGroupExtension::extensionDropObject(App::DocumentObject* obj) { Gui::Command::doCommand(Gui::Command::App, cmd.toUtf8()); } -std::vector< App::DocumentObject* > ViewProviderGroupExtension::extensionClaimChildren(void) const { +std::vector< App::DocumentObject* > ViewProviderGroupExtension::extensionClaimChildren() const { auto* group = getExtendedViewProvider()->getObject()->getExtensionByType(); return std::vector(group->Group.getValues()); } -void ViewProviderGroupExtension::extensionShow(void) { +void ViewProviderGroupExtension::extensionShow() { // avoid possible infinite recursion if (guard) @@ -134,7 +134,7 @@ void ViewProviderGroupExtension::extensionShow(void) { ViewProviderExtension::extensionShow(); } -void ViewProviderGroupExtension::extensionHide(void) { +void ViewProviderGroupExtension::extensionHide() { // avoid possible infinite recursion if (guard) diff --git a/src/Gui/ViewProviderGroupExtension.h b/src/Gui/ViewProviderGroupExtension.h index 77f5b0931c..1ae880a04a 100644 --- a/src/Gui/ViewProviderGroupExtension.h +++ b/src/Gui/ViewProviderGroupExtension.h @@ -35,21 +35,21 @@ class GuiExport ViewProviderGroupExtension : public ViewProviderExtension public: /// Constructor - ViewProviderGroupExtension(void); - virtual ~ViewProviderGroupExtension(); + ViewProviderGroupExtension(); + ~ViewProviderGroupExtension() override; - virtual std::vector extensionClaimChildren(void)const override; - virtual bool extensionCanDragObjects() const override; - virtual bool extensionCanDragObject(App::DocumentObject*) const override; - virtual void extensionDragObject(App::DocumentObject*) override; - virtual bool extensionCanDropObjects() const override; - virtual bool extensionCanDropObject(App::DocumentObject*) const override; - virtual void extensionDropObject(App::DocumentObject*) override; + std::vector extensionClaimChildren()const override; + bool extensionCanDragObjects() const override; + bool extensionCanDragObject(App::DocumentObject*) const override; + void extensionDragObject(App::DocumentObject*) override; + bool extensionCanDropObjects() const override; + bool extensionCanDropObject(App::DocumentObject*) const override; + void extensionDropObject(App::DocumentObject*) override; - virtual void extensionHide(void) override; - virtual void extensionShow(void) override; + void extensionHide() override; + void extensionShow() override; - virtual bool extensionOnDelete(const std::vector &) override; + bool extensionOnDelete(const std::vector &) override; private: bool guard; diff --git a/src/Gui/ViewProviderInventorObject.cpp b/src/Gui/ViewProviderInventorObject.cpp index e7a9f4187c..46b8778cbe 100644 --- a/src/Gui/ViewProviderInventorObject.cpp +++ b/src/Gui/ViewProviderInventorObject.cpp @@ -77,12 +77,12 @@ void ViewProviderInventorObject::setDisplayMode(const char* ModeName) ViewProviderDocumentObject::setDisplayMode(ModeName); } -std::vector ViewProviderInventorObject::getDisplayModes(void) const +std::vector ViewProviderInventorObject::getDisplayModes() const { std::vector StrList; - StrList.push_back("File+Buffer"); - StrList.push_back("Buffer"); - StrList.push_back("File"); + StrList.emplace_back("File+Buffer"); + StrList.emplace_back("Buffer"); + StrList.emplace_back("File"); return StrList; } diff --git a/src/Gui/ViewProviderInventorObject.h b/src/Gui/ViewProviderInventorObject.h index 7d9b0066b1..57b7c3356d 100644 --- a/src/Gui/ViewProviderInventorObject.h +++ b/src/Gui/ViewProviderInventorObject.h @@ -32,20 +32,20 @@ namespace Gui class GuiExport ViewProviderInventorObject : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderInventorObject); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderInventorObject); public: /// constructor. ViewProviderInventorObject(); /// destructor. - ~ViewProviderInventorObject(); + ~ViewProviderInventorObject() override; - void attach(App::DocumentObject *pcObject); - void setDisplayMode(const char* ModeName); - std::vector getDisplayModes() const; - void updateData(const App::Property*); - bool useNewSelectionModel(void) const {return true;} + void attach(App::DocumentObject *pcObject) override; + void setDisplayMode(const char* ModeName) override; + std::vector getDisplayModes() const override; + void updateData(const App::Property*) override; + bool useNewSelectionModel() const override {return true;} private: void adjustSelectionNodes(SoNode* child, const char* docname, const char* objname); diff --git a/src/Gui/ViewProviderLine.h b/src/Gui/ViewProviderLine.h index f45e4baf65..95fa60f3d0 100644 --- a/src/Gui/ViewProviderLine.h +++ b/src/Gui/ViewProviderLine.h @@ -31,13 +31,13 @@ namespace Gui { class GuiExport ViewProviderLine : public ViewProviderOriginFeature { - PROPERTY_HEADER(Gui::ViewProviderLine); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderLine); public: /// Constructor - ViewProviderLine(void); - virtual ~ViewProviderLine(); + ViewProviderLine(); + ~ViewProviderLine() override; - virtual void attach ( App::DocumentObject * ); + void attach ( App::DocumentObject * ) override; }; } //namespace Gui diff --git a/src/Gui/ViewProviderLink.cpp b/src/Gui/ViewProviderLink.cpp index 60d2268e78..4c54226980 100644 --- a/src/Gui/ViewProviderLink.cpp +++ b/src/Gui/ViewProviderLink.cpp @@ -245,7 +245,7 @@ public: FC_LOG("link detach " << getLinkedNameSafe()); auto me = LinkInfoPtr(this); if(unlink) { - while(links.size()) { + while(!links.empty()) { auto link = *links.begin(); links.erase(links.begin()); link->unlink(me); @@ -646,7 +646,7 @@ public: dot = next; } - for(auto v : nodeMap) { + for(const auto& v : nodeMap) { if(v.second->getDetail(true,type,subname,det,path)) return true; } @@ -739,15 +739,7 @@ void ViewProviderLinkObserver::extensionReattach(App::DocumentObject *) { } void ViewProviderLinkObserver::extensionOnChanged(const App::Property *prop) { -#if 0 - auto owner = freecad_dynamic_cast(getExtendedContainer()); - if(!owner || !linkInfo) - return; - if(prop != &owner->Visibility && prop != &owner->DisplayMode) - linkInfo->update(); -#else (void)prop; -#endif } void ViewProviderLinkObserver::extensionModeSwitchChange() { @@ -785,7 +777,7 @@ public: pcNode->addChild(pcTransform); } - ~SubInfo() { + ~SubInfo() override { unlink(); auto root = handle.getLinkRoot(); if(root) { @@ -795,12 +787,12 @@ public: } } - virtual void onLinkedIconChange(LinkInfoPtr) override { + void onLinkedIconChange(LinkInfoPtr) override { if(handle.autoSubLink && handle.subInfo.size()==1) handle.onLinkedIconChange(handle.linkInfo); } - virtual void unlink(LinkInfoPtr info=LinkInfoPtr()) override { + void unlink(LinkInfoPtr info=LinkInfoPtr()) override { (void)info; if(linkInfo) { linkInfo->remove(this); @@ -846,7 +838,7 @@ public: pcSwitch->whichChild = 0; } - ~Element() { + ~Element() override { unlink(); auto root = handle.getLinkRoot(); if(root) { @@ -856,7 +848,7 @@ public: } } - virtual void unlink(LinkInfoPtr info=LinkInfoPtr()) override{ + void unlink(LinkInfoPtr info=LinkInfoPtr()) override{ (void)info; if(linkInfo) { linkInfo->remove(this); @@ -895,14 +887,14 @@ LinkView::~LinkView() { unlink(linkOwner); } -PyObject *LinkView::getPyObject(void) +PyObject *LinkView::getPyObject() { if (PythonObject.is(Py::_None())) PythonObject = Py::Object(new LinkViewPy(this),true); return Py::new_reference_to(PythonObject); } -void LinkView::setInvalid(void) { +void LinkView::setInvalid() { if (!PythonObject.is(Py::_None())){ Base::PyObjectBase* obj = (Base::PyObjectBase*)PythonObject.ptr(); obj->setInvalid(); @@ -1053,68 +1045,12 @@ void LinkView::setLinkViewObject(ViewProviderDocumentObject *vpd, } void LinkView::setTransform(SoTransform *pcTransform, const Base::Matrix4D &mat) { -#if 1 double dMtrx[16]; mat.getGLMatrix(dMtrx); pcTransform->setMatrix(SbMatrix(dMtrx[0], dMtrx[1], dMtrx[2], dMtrx[3], dMtrx[4], dMtrx[5], dMtrx[6], dMtrx[7], dMtrx[8], dMtrx[9], dMtrx[10], dMtrx[11], dMtrx[12],dMtrx[13],dMtrx[14], dMtrx[15])); -#else - // extract scale factor from column vector length - double sx = Base::Vector3d(mat[0][0],mat[1][0],mat[2][0]).Sqr(); - double sy = Base::Vector3d(mat[0][1],mat[1][1],mat[2][1]).Sqr(); - double sz = Base::Vector3d(mat[0][2],mat[1][2],mat[2][2]).Sqr(); - bool bx,by,bz; - if((bx=fabs(sx-1.0)>=1e-10)) - sx = sqrt(sx); - else - sx = 1.0; - if((by=fabs(sy-1.0)>=1e-10)) - sy = sqrt(sy); - else - sy = 1.0; - if((bz=fabs(sz-1.0)>=1e-10)) - sz = sqrt(sz); - else - sz = 1.0; - // TODO: how to deal with negative scale? - pcTransform->scaleFactor.setValue(sx,sy,sz); - - Base::Matrix4D matRotate; - if(bx) { - matRotate[0][0] = mat[0][0]/sx; - matRotate[1][0] = mat[1][0]/sx; - matRotate[2][0] = mat[2][0]/sx; - }else{ - matRotate[0][0] = mat[0][0]; - matRotate[1][0] = mat[1][0]; - matRotate[2][0] = mat[2][0]; - } - if(by) { - matRotate[0][1] = mat[0][1]/sy; - matRotate[1][1] = mat[1][1]/sy; - matRotate[2][1] = mat[2][1]/sy; - }else{ - matRotate[0][1] = mat[0][1]; - matRotate[1][1] = mat[1][1]; - matRotate[2][1] = mat[2][1]; - } - if(bz) { - matRotate[0][2] = mat[0][2]/sz; - matRotate[1][2] = mat[1][2]/sz; - matRotate[2][2] = mat[2][2]/sz; - }else{ - matRotate[0][2] = mat[0][2]; - matRotate[1][2] = mat[1][2]; - matRotate[2][2] = mat[2][2]; - } - - Base::Rotation rot(matRotate); - pcTransform->rotation.setValue(rot[0],rot[1],rot[2],rot[3]); - pcTransform->translation.setValue(mat[0][3],mat[1][3],mat[2][3]); - pcTransform->center.setValue(0.0f,0.0f,0.0f); -#endif } void LinkView::setSize(int _size) { @@ -1165,7 +1101,7 @@ void LinkView::setChildren(const std::vector &children, const boost::dynamic_bitset<> &vis, SnapshotType type) { if(children.empty()) { - if(nodeArray.size()) { + if(!nodeArray.empty()) { nodeArray.clear(); nodeMap.clear(); childType = SnapshotContainer; @@ -1210,7 +1146,7 @@ void LinkView::setChildren(const std::vector &children, for(size_t i=0;ipcLinked->getObject())); if(iter != groups.end()) { @@ -1397,7 +1333,7 @@ void LinkView::updateLink() { linkedRoot->addChild(sub.pcNode); setTransform(sub.pcTransform,mat); - if(sub.subElements.size()) { + if(!sub.subElements.empty()) { path.truncate(1); appendPath(&path,sub.pcNode); SoSelectionElementAction action(SoSelectionElementAction::Append,true); @@ -1420,7 +1356,7 @@ bool LinkView::linkGetElementPicked(const SoPickedPoint *pp, std::string &subnam { std::ostringstream ss; CoinPtr path = pp->getPath(); - if(nodeArray.size()) { + if(!nodeArray.empty()) { auto idx = path->findNode(pcLinkRoot); if(idx<0 || idx+2>=path->getLength()) return false; @@ -1477,7 +1413,7 @@ bool LinkView::linkGetElementPicked(const SoPickedPoint *pp, std::string &subnam if(!sub.linkInfo->getElementPicked(false,SnapshotTransform,pp,ss2)) return false; const std::string &element = ss2.str(); - if(sub.subElements.size()) { + if(!sub.subElements.empty()) { if(sub.subElements.find(element)==sub.subElements.end()) { auto pos = element.find('.'); if(pos==std::string::npos || @@ -1592,7 +1528,7 @@ bool LinkView::linkGetDetailPath(const char *subname, SoFullPath *path, SoDetail continue; ++nextsub; } - if(*nextsub && sub.subElements.size() && + if(*nextsub && !sub.subElements.empty() && sub.subElements.find(nextsub)==sub.subElements.end()) break; appendPath(path,sub.pcNode); @@ -1648,7 +1584,7 @@ QIcon LinkView::getLinkedIcon(QPixmap px) const { } bool LinkView::hasSubs() const { - return isLinked() && subInfo.size(); + return isLinked() && !subInfo.empty(); } /////////////////////////////////////////////////////////////////////////////////// @@ -1736,11 +1672,11 @@ void ViewProviderLink::reattach(App::DocumentObject *obj) { ViewProviderDocumentObject::reattach(obj); } -std::vector ViewProviderLink::getDisplayModes(void) const +std::vector ViewProviderLink::getDisplayModes() const { std::vector StrList = inherited::getDisplayModes(); - StrList.push_back("Link"); - StrList.push_back("ChildView"); + StrList.emplace_back("Link"); + StrList.emplace_back("ChildView"); return StrList; } @@ -1883,7 +1819,7 @@ void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension *ext, const App: if(canScale(v)) pcTransform->scaleFactor.setValue(v.x,v.y,v.z); SbMatrix matrix = convert(ext->getTransform(false)); - linkView->renderDoubleSide(matrix.det3() < 0); + linkView->renderDoubleSide(matrix.det3() < 1e-7); } }else if(prop == ext->getPlacementProperty() || prop == ext->getLinkPlacementProperty()) { auto propLinkPlacement = ext->getLinkPlacementProperty(); @@ -1894,7 +1830,7 @@ void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension *ext, const App: if(canScale(v)) pcTransform->scaleFactor.setValue(v.x,v.y,v.z); SbMatrix matrix = convert(ext->getTransform(false)); - linkView->renderDoubleSide(matrix.det3() < 0); + linkView->renderDoubleSide(matrix.det3() < 1e-7); } }else if(prop == ext->getLinkCopyOnChangeGroupProperty()) { if (auto group = ext->getLinkCopyOnChangeGroupValue()) { @@ -1920,7 +1856,7 @@ void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension *ext, const App: subs.push_back(sub+s); } - if(subs.empty() && sub.size()) + if(subs.empty() && !sub.empty()) subs.push_back(sub); hasSubName = !subs.empty(); @@ -1955,7 +1891,7 @@ void ViewProviderLink::updateDataPrivate(App::LinkBaseExtension *ext, const App: const auto &elements = ext->_getElementListValue(); // elements is about to be collapsed, preserve the materials - if(elements.size()) { + if(!elements.empty()) { std::vector materials; boost::dynamic_bitset<> overrideMaterials; overrideMaterials.resize(elements.size(),false); @@ -2139,7 +2075,7 @@ bool ViewProviderLink::hasElements(const App::LinkBaseExtension *ext) const { return false; } const auto &elements = ext->getElementListValue(); - return elements.size() && (int)elements.size()==ext->_getElementCountValue(); + return !elements.empty() && (int)elements.size()==ext->_getElementCountValue(); } bool ViewProviderLink::isGroup(const App::LinkBaseExtension *ext, bool plainGroup) const { @@ -2164,7 +2100,7 @@ ViewProvider *ViewProviderLink::getLinkedView( return nullptr; } -std::vector ViewProviderLink::claimChildren(void) const { +std::vector ViewProviderLink::claimChildren() const { auto ext = getLinkExtension(); std::vector ret; @@ -2306,11 +2242,11 @@ std::string ViewProviderLink::dropObjectEx(App::DocumentObject* obj, return linked->dropObjectEx(obj,owner,subname,subElements); } if(owner) { - if(ext->getSubElements().size()) + if(!ext->getSubElements().empty()) ext->setLink(-1,owner,subname,subElements); else ext->setLink(-1,owner,subname); - } else if(ext->getSubElements().size()) + } else if(!ext->getSubElements().empty()) ext->setLink(-1,obj,nullptr,subElements); else ext->setLink(-1,obj,nullptr); @@ -2646,7 +2582,8 @@ void ViewProviderLink::_setupContextMenu( || (ext->getLinkPlacementProperty() && !ext->getLinkPlacementProperty()->isReadOnly())) { bool found = false; - for(auto action : menu->actions()) { + const auto actions = menu->actions(); + for(auto action : actions) { if(action->data().toInt() == ViewProvider::Transform) { found = true; break; @@ -2662,7 +2599,8 @@ void ViewProviderLink::_setupContextMenu( if(ext->getColoredElementsProperty()) { bool found = false; - for(auto action : menu->actions()) { + const auto actions = menu->actions(); + for(auto action : actions) { if(action->data().toInt() == ViewProvider::Color) { action->setText(QObject::tr("Override colors...")); found = true; @@ -2938,19 +2876,25 @@ void ViewProviderLink::unsetEditViewer(Gui::View3DInventorViewer* viewer) Gui::Control().closeDialog(); } -Base::Placement ViewProviderLink::currentDraggingPlacement() const{ - assert(pcDragger); +Base::Placement ViewProviderLink::currentDraggingPlacement() const +{ + // if there isn't an active dragger return a default placement + if (!pcDragger) + return Base::Placement(); + SbVec3f v; SbRotation r; - if(useCenterballDragger) { + if (useCenterballDragger) { SoCenterballDragger *dragger = static_cast(pcDragger.get()); v = dragger->center.getValue(); r = dragger->rotation.getValue(); - }else{ + } + else { SoFCCSysDragger *dragger = static_cast(pcDragger.get()); v = dragger->translation.getValue(); r = dragger->rotation.getValue(); } + float q1,q2,q3,q4; r.getValue(q1,q2,q3,q4); return Base::Placement(Base::Vector3d(v[0],v[1],v[2]),Base::Rotation(q1,q2,q3,q4)); @@ -3102,7 +3046,7 @@ std::map ViewProviderLink::getElementColors(const char if(wildcard.size()==4) return colors; } - if(wildcard.size()) + if(!wildcard.empty()) wildcard.resize(4); }else if(wildcard == "Edge*") wildcard.resize(4); @@ -3114,7 +3058,7 @@ std::map ViewProviderLink::getElementColors(const char wildcard.clear(); int i=-1; - if(wildcard.size()) { + if(!wildcard.empty()) { for(const auto &sub : subs) { if(++i >= size) break; @@ -3178,7 +3122,7 @@ std::map ViewProviderLink::getElementColors(const char int offset = 0; - if(sub.second.size() && element_count && !std::isdigit(sub.second[0])) { + if(!sub.second.empty() && element_count && !std::isdigit(sub.second[0])) { // For checking and expanding color override of array base if(!subname[0]) { std::ostringstream ss; @@ -3263,7 +3207,7 @@ void ViewProviderLink::setElementColors(const std::map continue; } - if(element_count && v.first.size() && std::isdigit(v.first[0])) { + if(element_count && !v.first.empty() && std::isdigit(v.first[0])) { // In case of array, check if there are override of the same // sub-element for every array element. And collapse those overrides // into one without the index. @@ -3359,7 +3303,7 @@ void ViewProviderLink::applyColors() { for(const auto &sub : hideList) { SoDetail *det=nullptr; path.truncate(0); - if(sub.size() && getDetailPath(sub.c_str(), &path, false, det)) + if(!sub.empty() && getDetailPath(sub.c_str(), &path, false, det)) action.apply(&path); delete det; } @@ -3463,6 +3407,30 @@ ViewProviderDocumentObject *ViewProviderLink::getLinkedViewProvider( return self; } +void ViewProviderLink::setTransformation(const Base::Matrix4D &rcMatrix) +{ + inherited::setTransformation(rcMatrix); + auto ext = getLinkExtension(); + if(ext) { + if (ext->getScaleVectorProperty()) + updateDataPrivate(getLinkExtension(),ext->getScaleVectorProperty()); + else + updateDataPrivate(getLinkExtension(),ext->getScaleProperty()); + } +} + +void ViewProviderLink::setTransformation(const SbMatrix &rcMatrix) +{ + inherited::setTransformation(rcMatrix); + auto ext = getLinkExtension(); + if(ext) { + if (ext->getScaleVectorProperty()) + updateDataPrivate(getLinkExtension(),ext->getScaleVectorProperty()); + else + updateDataPrivate(getLinkExtension(),ext->getScaleProperty()); + } +} + //////////////////////////////////////////////////////////////////////////////////////// namespace Gui { diff --git a/src/Gui/ViewProviderLink.h b/src/Gui/ViewProviderLink.h index 85f9c8a310..6ed6b97d11 100644 --- a/src/Gui/ViewProviderLink.h +++ b/src/Gui/ViewProviderLink.h @@ -44,7 +44,7 @@ class GuiExport ViewProviderLinkObserver: public ViewProviderExtension { EXTENSION_TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: ViewProviderLinkObserver(); - virtual ~ViewProviderLinkObserver(); + ~ViewProviderLinkObserver() override; void extensionReattach(App::DocumentObject *) override; void extensionBeforeDelete() override; void extensionOnChanged(const App::Property *) override; @@ -52,7 +52,7 @@ public: void extensionFinishRestoring() override; bool extensionCanDragObject(App::DocumentObject*) const override { return false; } bool extensionCanDropObject(App::DocumentObject*) const override { return false; } - void extensionModeSwitchChange(void) override; + void extensionModeSwitchChange() override; bool isLinkVisible() const; void setLinkVisible(bool); @@ -74,15 +74,15 @@ class GuiExport LinkView : public Base::BaseClass, public LinkOwner { public: LinkView(); - ~LinkView(); + ~LinkView() override; LinkView &operator=(const LinkView&) = delete; LinkView(const LinkView&) = delete; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void unlink(LinkInfoPtr) override; - virtual void onLinkedIconChange(LinkInfoPtr) override; - virtual void onLinkedUpdateData(LinkInfoPtr, const App::Property *) override; + void unlink(LinkInfoPtr) override; + void onLinkedIconChange(LinkInfoPtr) override; + void onLinkedUpdateData(LinkInfoPtr, const App::Property *) override; bool isLinked() const; @@ -196,24 +196,24 @@ public: App::PropertyPersistentObject ChildViewProvider; ViewProviderLink(); - virtual ~ViewProviderLink(); + ~ViewProviderLink() override; void attach(App::DocumentObject *pcObj) override; void reattach(App::DocumentObject *pcObj) override; - bool isSelectable(void) const override; + bool isSelectable() const override; - bool useNewSelectionModel(void) const override {return true;} + bool useNewSelectionModel() const override {return true;} void updateData(const App::Property*) override; void onChanged(const App::Property* prop) override; - std::vector claimChildren(void) const override; + std::vector claimChildren() const override; bool getElementPicked(const SoPickedPoint *, std::string &) const override; bool getDetailPath(const char *, SoFullPath *, bool, SoDetail *&) const override; void finishRestoring() override; - QIcon getIcon(void) const override; + QIcon getIcon() const override; bool canDragObjects() const override; bool canDragObject(App::DocumentObject*) const override; @@ -228,7 +228,7 @@ public: bool onDelete(const std::vector &) override; bool canDelete(App::DocumentObject* obj) const override; - std::vector getDisplayModes(void) const override; + std::vector getDisplayModes() const override; void setupContextMenu(QMenu*, QObject*, const char*) override; @@ -252,22 +252,25 @@ public: void setOverrideMode(const std::string &mode) override; - virtual void onBeforeChange(const App::Property*) override; + void onBeforeChange(const App::Property*) override; ViewProviderDocumentObject *getChildViewProvider() const { return childVp; } - virtual App::Property *getPropertyByName(const char* name) const override; - virtual void getPropertyMap(std::map &Map) const override; - virtual void getPropertyList(std::vector &List) const override; + App::Property *getPropertyByName(const char* name) const override; + void getPropertyMap(std::map &Map) const override; + void getPropertyList(std::vector &List) const override; - virtual ViewProviderDocumentObject *getLinkedViewProvider( + ViewProviderDocumentObject *getLinkedViewProvider( std::string *subname=nullptr, bool recursive=false) const override; - virtual bool allowOverride(const App::DocumentObject &) const override { + bool allowOverride(const App::DocumentObject &) const override { return true; } + void setTransformation(const Base::Matrix4D &rcMatrix) override; + void setTransformation(const SbMatrix &rcMatrix) override; + protected: bool setEdit(int ModNum) override; void setEditViewer(View3DInventorViewer*, int ModNum) override; diff --git a/src/Gui/ViewProviderLinkPyImp.cpp b/src/Gui/ViewProviderLinkPyImp.cpp index 7b19ada206..a81a25fb7a 100644 --- a/src/Gui/ViewProviderLinkPyImp.cpp +++ b/src/Gui/ViewProviderLinkPyImp.cpp @@ -36,7 +36,7 @@ using namespace Gui; // returns a string which represents the object e.g. when printed in python -std::string ViewProviderLinkPy::representation(void) const +std::string ViewProviderLinkPy::representation() const { std::stringstream str; str << ""; diff --git a/src/Gui/ViewProviderMaterialObject.cpp b/src/Gui/ViewProviderMaterialObject.cpp index ed31857564..51415a8ac9 100644 --- a/src/Gui/ViewProviderMaterialObject.cpp +++ b/src/Gui/ViewProviderMaterialObject.cpp @@ -50,7 +50,7 @@ ViewProviderMaterialObject::~ViewProviderMaterialObject() { } -bool ViewProviderMaterialObject::doubleClicked(void) +bool ViewProviderMaterialObject::doubleClicked() { Gui::Application::Instance->activeDocument()->setEdit(this, (int)ViewProvider::Default); return true; diff --git a/src/Gui/ViewProviderMaterialObject.h b/src/Gui/ViewProviderMaterialObject.h index 76e890b5aa..7562727bb0 100644 --- a/src/Gui/ViewProviderMaterialObject.h +++ b/src/Gui/ViewProviderMaterialObject.h @@ -32,20 +32,20 @@ namespace Gui { class GuiExport ViewProviderMaterialObject : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderMaterialObject); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderMaterialObject); public: /// constructor. ViewProviderMaterialObject(); /// destructor. - virtual ~ViewProviderMaterialObject(); + ~ViewProviderMaterialObject() override; - QIcon getIcon(void) const; + QIcon getIcon() const override; - bool doubleClicked(void); + bool doubleClicked() override; // shows solid in the tree - virtual bool isShow(void) const{return true;} + bool isShow() const override{return true;} }; diff --git a/src/Gui/ViewProviderMeasureDistance.cpp b/src/Gui/ViewProviderMeasureDistance.cpp index 8a25195df4..b965ff7fa4 100644 --- a/src/Gui/ViewProviderMeasureDistance.cpp +++ b/src/Gui/ViewProviderMeasureDistance.cpp @@ -141,11 +141,11 @@ void ViewProviderMeasureDistance::onChanged(const App::Property* prop) } } -std::vector ViewProviderMeasureDistance::getDisplayModes(void) const +std::vector ViewProviderMeasureDistance::getDisplayModes() const { // add modes std::vector StrList; - StrList.push_back("Base"); + StrList.emplace_back("Base"); return StrList; } @@ -337,7 +337,7 @@ void ViewProviderMeasureDistance::measureDistanceCallback(void * ud, SoEventCall if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No point picked.\n"); return; } diff --git a/src/Gui/ViewProviderMeasureDistance.h b/src/Gui/ViewProviderMeasureDistance.h index 149246306e..73b015876f 100644 --- a/src/Gui/ViewProviderMeasureDistance.h +++ b/src/Gui/ViewProviderMeasureDistance.h @@ -44,14 +44,14 @@ class ViewProviderPointMarker; class PointMarker : public QObject { public: - PointMarker(View3DInventorViewer* view); - ~PointMarker(); + explicit PointMarker(View3DInventorViewer* view); + ~PointMarker() override; void addPoint(const SbVec3f&); int countPoints() const; protected: - void customEvent(QEvent* e); + void customEvent(QEvent* e) override; private: View3DInventorViewer *view; @@ -61,11 +61,11 @@ private: class GuiExport ViewProviderPointMarker : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderPointMarker); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderPointMarker); public: ViewProviderPointMarker(); - virtual ~ViewProviderPointMarker(); + ~ViewProviderPointMarker() override; protected: SoCoordinate3 * pCoords; @@ -75,12 +75,12 @@ protected: class GuiExport ViewProviderMeasureDistance : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderMeasureDistance); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderMeasureDistance); public: /// Constructor - ViewProviderMeasureDistance(void); - virtual ~ViewProviderMeasureDistance(); + ViewProviderMeasureDistance(); + ~ViewProviderMeasureDistance() override; // Display properties App::PropertyColor TextColor; @@ -89,16 +89,16 @@ public: App::PropertyFloat DistFactor; App::PropertyBool Mirror; - void attach(App::DocumentObject *); - void updateData(const App::Property*); - bool useNewSelectionModel(void) const {return true;} - std::vector getDisplayModes(void) const; - void setDisplayMode(const char* ModeName); + void attach(App::DocumentObject *) override; + void updateData(const App::Property*) override; + bool useNewSelectionModel() const override {return true;} + std::vector getDisplayModes() const override; + void setDisplayMode(const char* ModeName) override; static void measureDistanceCallback(void * ud, SoEventCallback * n); protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: SoFontStyle * pFont; diff --git a/src/Gui/ViewProviderOrigin.cpp b/src/Gui/ViewProviderOrigin.cpp index a04e063a6f..129043a574 100644 --- a/src/Gui/ViewProviderOrigin.cpp +++ b/src/Gui/ViewProviderOrigin.cpp @@ -66,11 +66,11 @@ ViewProviderOrigin::~ViewProviderOrigin() { pcGroupChildren = nullptr; } -std::vector ViewProviderOrigin::claimChildren(void) const { +std::vector ViewProviderOrigin::claimChildren() const { return static_cast( getObject() )->OriginFeatures.getValues (); } -std::vector ViewProviderOrigin::claimChildren3D(void) const { +std::vector ViewProviderOrigin::claimChildren3D() const { return claimChildren (); } @@ -80,7 +80,7 @@ void ViewProviderOrigin::attach(App::DocumentObject* pcObject) addDisplayMaskMode(pcGroupChildren, "Base"); } -std::vector ViewProviderOrigin::getDisplayModes(void) const +std::vector ViewProviderOrigin::getDisplayModes() const { return { "Base" }; } diff --git a/src/Gui/ViewProviderOrigin.h b/src/Gui/ViewProviderOrigin.h index eedf442733..9400f4c0e7 100644 --- a/src/Gui/ViewProviderOrigin.h +++ b/src/Gui/ViewProviderOrigin.h @@ -35,7 +35,7 @@ class Document; class GuiExport ViewProviderOrigin : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderOrigin); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderOrigin); public: /// Size of the origin as set by the part. @@ -44,18 +44,18 @@ public: /// constructor. ViewProviderOrigin(); /// destructor. - virtual ~ViewProviderOrigin(); + ~ViewProviderOrigin() override; /// @name Override methods ///@{ - virtual std::vector claimChildren(void) const; - virtual std::vector claimChildren3D(void) const; + std::vector claimChildren() const override; + std::vector claimChildren3D() const override; - virtual SoGroup* getChildRoot(void) const {return pcGroupChildren;}; + SoGroup* getChildRoot() const override {return pcGroupChildren;} - virtual void attach(App::DocumentObject* pcObject); - virtual std::vector getDisplayModes(void) const; - virtual void setDisplayMode(const char* ModeName); + void attach(App::DocumentObject* pcObject) override; + std::vector getDisplayModes() const override; + void setDisplayMode(const char* ModeName) override; ///@} /** @name Temporary visibility mode @@ -70,15 +70,15 @@ public: void resetTemporaryVisibility (); ///@} - virtual bool canDragObjects() const { + bool canDragObjects() const override { return false; } /// Returns default size. Use this if it is not possible to determine appropriate size by other means static double defaultSize(); protected: - virtual void onChanged(const App::Property* prop); - virtual bool onDelete(const std::vector &); + void onChanged(const App::Property* prop) override; + bool onDelete(const std::vector &) override; private: SoGroup *pcGroupChildren; diff --git a/src/Gui/ViewProviderOriginFeature.cpp b/src/Gui/ViewProviderOriginFeature.cpp index b2ddf3dbf1..a0fb33c50d 100644 --- a/src/Gui/ViewProviderOriginFeature.cpp +++ b/src/Gui/ViewProviderOriginFeature.cpp @@ -160,7 +160,7 @@ std::vector ViewProviderOriginFeature::getDisplayModes () const { // add modes std::vector StrList; - StrList.push_back("Base"); + StrList.emplace_back("Base"); return StrList; } diff --git a/src/Gui/ViewProviderOriginFeature.h b/src/Gui/ViewProviderOriginFeature.h index 7bdde15680..525496541d 100644 --- a/src/Gui/ViewProviderOriginFeature.h +++ b/src/Gui/ViewProviderOriginFeature.h @@ -35,14 +35,14 @@ namespace Gui * View provider associated with an App::OriginFeature. */ class GuiExport ViewProviderOriginFeature: public ViewProviderGeometryObject { - PROPERTY_HEADER(Gui::ViewProviderOriginFeature); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderOriginFeature); public: /// The display size of the feature App::PropertyFloat Size; ViewProviderOriginFeature (); - virtual ~ViewProviderOriginFeature (); + ~ViewProviderOriginFeature () override; /// Get point derived classes will add their specific stuff SoSeparator * getOriginFeatureRoot () { return pOriginFeatureRoot; } @@ -50,22 +50,22 @@ public: /// Get pointer to the text label associated with the feature SoAsciiText * getLabel () { return pLabel; } - virtual void attach(App::DocumentObject *); - virtual void updateData(const App::Property *); - virtual std::vector getDisplayModes () const; - virtual void setDisplayMode (const char* ModeName); + void attach(App::DocumentObject *) override; + void updateData(const App::Property *) override; + std::vector getDisplayModes () const override; + void setDisplayMode (const char* ModeName) override; /// @name Suppress ViewProviderGeometryObject's behaviour ///@{ - virtual bool setEdit ( int ) + bool setEdit ( int ) override { return false; } - virtual void unsetEdit ( int ) + void unsetEdit ( int ) override { } ///@} protected: - virtual void onChanged ( const App::Property* prop ); - virtual bool onDelete ( const std::vector & ); + void onChanged ( const App::Property* prop ) override; + bool onDelete ( const std::vector & ) override; protected: SoSeparator * pOriginFeatureRoot; SoScale * pScale; diff --git a/src/Gui/ViewProviderOriginGroup.h b/src/Gui/ViewProviderOriginGroup.h index d27611236f..d10f93f688 100644 --- a/src/Gui/ViewProviderOriginGroup.h +++ b/src/Gui/ViewProviderOriginGroup.h @@ -33,7 +33,7 @@ class GuiExport ViewProviderOriginGroup: public ViewProviderDocumentObject, PROPERTY_HEADER_WITH_EXTENSIONS(Gui::ViewProviderOriginGroup); public: ViewProviderOriginGroup (); - virtual ~ViewProviderOriginGroup (); + ~ViewProviderOriginGroup () override; }; } /* Gui */ diff --git a/src/Gui/ViewProviderOriginGroupExtension.h b/src/Gui/ViewProviderOriginGroupExtension.h index 23b0c181cc..330df8a64c 100644 --- a/src/Gui/ViewProviderOriginGroupExtension.h +++ b/src/Gui/ViewProviderOriginGroupExtension.h @@ -36,14 +36,14 @@ class GuiExport ViewProviderOriginGroupExtension : public ViewProviderGeoFeature public: /// Constructor - ViewProviderOriginGroupExtension(void); - virtual ~ViewProviderOriginGroupExtension(); + ViewProviderOriginGroupExtension(); + ~ViewProviderOriginGroupExtension() override; - virtual std::vector extensionClaimChildren(void)const override; - virtual std::vector extensionClaimChildren3D(void)const override; + std::vector extensionClaimChildren()const override; + std::vector extensionClaimChildren3D()const override; - virtual void extensionAttach(App::DocumentObject *pcObject) override; - virtual void extensionUpdateData(const App::Property* prop) override; + void extensionAttach(App::DocumentObject *pcObject) override; + void extensionUpdateData(const App::Property* prop) override; void updateOriginSize(); diff --git a/src/Gui/ViewProviderPart.cpp b/src/Gui/ViewProviderPart.cpp index ad8a9c97db..bcac0fc3b1 100644 --- a/src/Gui/ViewProviderPart.cpp +++ b/src/Gui/ViewProviderPart.cpp @@ -76,7 +76,7 @@ void ViewProviderPart::setupContextMenu(QMenu* menu, QObject* receiver, const ch ViewProviderDragger::setupContextMenu(menu, receiver, member); } -bool ViewProviderPart::doubleClicked(void) +bool ViewProviderPart::doubleClicked() { //make the part the active one @@ -108,7 +108,7 @@ bool ViewProviderPart::doubleClicked(void) return true; } -QIcon ViewProviderPart::getIcon(void) const +QIcon ViewProviderPart::getIcon() const { // the original Part object for this ViewProviderPart App::Part* part = static_cast(this->getObject()); diff --git a/src/Gui/ViewProviderPart.h b/src/Gui/ViewProviderPart.h index 55c4b5043c..dc546f01f4 100644 --- a/src/Gui/ViewProviderPart.h +++ b/src/Gui/ViewProviderPart.h @@ -39,18 +39,18 @@ public: /// constructor. ViewProviderPart(); /// destructor. - virtual ~ViewProviderPart(); + ~ViewProviderPart() override; - virtual bool doubleClicked(void) override; - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool doubleClicked() override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; /// deliver the icon shown in the tree view /// override from ViewProvider.h - virtual QIcon getIcon(void) const override; + QIcon getIcon() const override; protected: /// get called by the container whenever a property has been changed - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; /// a second icon for the Assembly type const char* aPixmap; diff --git a/src/Gui/ViewProviderPlacement.cpp b/src/Gui/ViewProviderPlacement.cpp index ab0d8eb394..c1ef25044a 100644 --- a/src/Gui/ViewProviderPlacement.cpp +++ b/src/Gui/ViewProviderPlacement.cpp @@ -67,7 +67,7 @@ std::vector ViewProviderPlacement::getDisplayModes(void) const { // add modes std::vector StrList; - StrList.push_back("Base"); + StrList.emplace_back("Base"); return StrList; } diff --git a/src/Gui/ViewProviderPlacement.h b/src/Gui/ViewProviderPlacement.h index aaeea64815..72c4c21521 100644 --- a/src/Gui/ViewProviderPlacement.h +++ b/src/Gui/ViewProviderPlacement.h @@ -46,21 +46,21 @@ class GuiExport ViewProviderPlacement : public ViewProviderGeometryObject public: /// Constructor - ViewProviderPlacement(void); - virtual ~ViewProviderPlacement(); + ViewProviderPlacement(); + ~ViewProviderPlacement() override; void attach(App::DocumentObject *) override; void updateData(const App::Property*) override; - std::vector getDisplayModes(void) const override; + std::vector getDisplayModes() const override; void setDisplayMode(const char* ModeName) override; /// indicates if the ViewProvider use the new Selection model - virtual bool useNewSelectionModel(void) const override {return true;} + bool useNewSelectionModel() const override {return true;} /// indicates if the ViewProvider can be selected - virtual bool isSelectable(void) const override; + bool isSelectable() const override; - virtual bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const override; - virtual bool getDetailPath(const char *, SoFullPath *, bool, SoDetail *&) const override; + bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const override; + bool getDetailPath(const char *, SoFullPath *, bool, SoDetail *&) const override; protected: void onChanged(const App::Property* prop) override; diff --git a/src/Gui/ViewProviderPlane.h b/src/Gui/ViewProviderPlane.h index 76b60ec0a7..68a809955c 100644 --- a/src/Gui/ViewProviderPlane.h +++ b/src/Gui/ViewProviderPlane.h @@ -32,13 +32,13 @@ namespace Gui class GuiExport ViewProviderPlane : public ViewProviderOriginFeature { - PROPERTY_HEADER(Gui::ViewProviderPlane); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderPlane); public: /// Constructor - ViewProviderPlane(void); - virtual ~ViewProviderPlane(); + ViewProviderPlane(); + ~ViewProviderPlane() override; - virtual void attach ( App::DocumentObject * ); + void attach ( App::DocumentObject * ) override; }; } //namespace Gui diff --git a/src/Gui/ViewProviderPyImp.cpp b/src/Gui/ViewProviderPyImp.cpp index ce00d8b3f6..f795203e7e 100644 --- a/src/Gui/ViewProviderPyImp.cpp +++ b/src/Gui/ViewProviderPyImp.cpp @@ -54,7 +54,7 @@ using namespace Gui; // returns a string which represent the object e.g. when printed in python -std::string ViewProviderPy::representation(void) const +std::string ViewProviderPy::representation() const { return ""; } @@ -641,19 +641,11 @@ Py::String ViewProviderPy::getIV() const Py::Object ViewProviderPy::getIcon() const { -#if 0 - QByteArray ba; - QDataStream str(&ba, QIODevice::WriteOnly); - QIcon icon = getViewProviderPtr()->getIcon(); - str << icon; - return Py::String(ba.constData(), ba.size()); -#else PythonWrapper wrap; wrap.loadGuiModule(); wrap.loadWidgetsModule(); QIcon icon = getViewProviderPtr()->getIcon(); return wrap.fromQIcon(new QIcon(icon)); -#endif } Py::Int ViewProviderPy::getDefaultMode() const diff --git a/src/Gui/ViewProviderPythonFeature.cpp b/src/Gui/ViewProviderPythonFeature.cpp index e7251ba741..9416d90d33 100644 --- a/src/Gui/ViewProviderPythonFeature.cpp +++ b/src/Gui/ViewProviderPythonFeature.cpp @@ -52,219 +52,6 @@ FC_LOG_LEVEL_INIT("ViewProviderPythonFeature", true, true) using namespace Gui; namespace bp = boost::placeholders; -// #0003564: Python objects: updateData calls to proxy instance that should have been deleted -// See https://forum.freecadweb.org/viewtopic.php?f=22&t=30429&p=252429#p252429 -#if 0 -namespace Gui { - -struct ProxyInfo { - Py::Object viewObject; - Py::Object proxy; - - ~ProxyInfo() { - Base::PyGILStateLocker lock; - viewObject = Py::Object(); - proxy = Py::Object(); - } -}; - -class PropertyEvent : public QEvent -{ -public: - PropertyEvent(const Gui::ViewProviderDocumentObject* vp, const ProxyInfo &info) - : QEvent(QEvent::Type(QEvent::User)), view(vp), info(info) - { - } - - const Gui::ViewProviderDocumentObject* view; - ProxyInfo info; -}; - -class ViewProviderPythonFeatureObserver : public QObject -{ -public: - /// The one and only instance. - static ViewProviderPythonFeatureObserver* instance(); - /// Destructs the sole instance. - static void destruct (); - void slotAppendObject(const Gui::ViewProvider&); - void slotDeleteObject(const Gui::ViewProvider&); - void slotDeleteDocument(const Gui::Document&); - -private: - void customEvent(QEvent* e) - { - PropertyEvent* pe = static_cast(e); - std::set::iterator it = viewMap.find(pe->view); - // Make sure that the object hasn't been deleted in the meantime (#0001522) - if (it != viewMap.end()) { - viewMap.erase(it); - - // We check below the python object of the view provider to make - // sure that the view provider is actually the owner of the proxy - // object we cached before. This step is necessary to prevent a - // very obscure bug described here. - // - // The proxy caching is only effective when an object is deleted in - // an event of undo, and we restore the proxy in the event of redo. - // The object is not really freed while inside undo/redo stack. It - // gets really deleted from memory when either the user clears the - // undo/redo stack manually, or the redo stack gets automatically - // cleared when new transaction is created. FC has no explicit - // signaling of when the object is really deleted from the memory. - // This ViewProviderPythonFeatureObserver uses a heuristic to - // decide when to flush the cache in slotAppendObject(), that is, - // it sees any cache miss event as the signaling of an redo clear. - // The bug happens in the very rare event, when the redo stack is - // cleared when new transaction is added, and the freed object's - // memory gets immediately reused by c++ allocator for the new - // object created in the new transaction. This creates a cache - // false hit event, where the old deleted view provider's proxy - // gets mistakenly assigned to the newly created object, which - // happens to have the exact same memory location. This situation - // is very rare and really depends on the system's allocator - // implementation. However, tests show that it happens regularly - // in Linux debug build. To prevent this, we use the trick of - // checking the python object pointer of the view provider to make - // sure the view provider are in fact the same. We hold the python - // object reference count, so it never gets freed and reused like - // its owner view provider. - // - // Side note: the original implementation uses property copy and - // paste to store the proxy object, which is fine, but has the - // trouble of having to manually freed the copied property. And the - // original implementation didn't do that in every case, causing - // memory leak. We now simply stores the python object with - // reference counting, so no need to worry about deleting - - Py::Object viewObject(const_cast(pe->view)->getPyObject(),true); - if(viewObject.ptr() != pe->info.viewObject.ptr()) { - if(FC_LOG_INSTANCE.isEnabled(FC_LOGLEVEL_LOG)) - FC_WARN("invalid proxy cache " << viewObject.ptr() << ", " << - pe->info.viewObject.ptr() << ", " << pe->info.proxy.ptr()); - }else{ - App::Property* prop = pe->view->getPropertyByName("Proxy"); - if (prop && prop->isDerivedFrom(App::PropertyPythonObject::getClassTypeId())) { - prop->setPyObject(pe->info.proxy.ptr()); - } - } - } - } - static ViewProviderPythonFeatureObserver* _singleton; - - ViewProviderPythonFeatureObserver(); - ~ViewProviderPythonFeatureObserver(); - typedef std::map< - const App::DocumentObject*, - ProxyInfo - > ObjectProxy; - - std::map proxyMap; - std::set viewMap; -}; - -} - -ViewProviderPythonFeatureObserver* ViewProviderPythonFeatureObserver::_singleton = 0; - -ViewProviderPythonFeatureObserver* ViewProviderPythonFeatureObserver::instance() -{ - if (!_singleton) - _singleton = new ViewProviderPythonFeatureObserver; - return _singleton; -} - -void ViewProviderPythonFeatureObserver::destruct () -{ - delete _singleton; - _singleton = 0; -} - -void ViewProviderPythonFeatureObserver::slotDeleteDocument(const Gui::Document& d) -{ - App::Document* doc = d.getDocument(); - std::map::iterator it = proxyMap.find(doc); - if (it != proxyMap.end()) { - Base::PyGILStateLocker lock; - proxyMap.erase(it); - } -} - -void ViewProviderPythonFeatureObserver::slotAppendObject(const Gui::ViewProvider& obj) -{ - if (!obj.isDerivedFrom(Gui::ViewProviderDocumentObject::getClassTypeId())) - return; - const Gui::ViewProviderDocumentObject& vp = static_cast(obj); - const App::DocumentObject* docobj = vp.getObject(); - App::Document* doc = docobj->getDocument(); - std::map::iterator it = proxyMap.find(doc); - if (it != proxyMap.end()) { - ObjectProxy::iterator jt = it->second.find(docobj); - if (jt != it->second.end()) { - Base::PyGILStateLocker lock; - try { - App::Property* prop = vp.getPropertyByName("Proxy"); - if (prop && prop->isDerivedFrom(App::PropertyPythonObject::getClassTypeId())) { - // make this delayed so that the corresponding item in the tree view is accessible - QApplication::postEvent(this, new PropertyEvent(&vp, jt->second)); - // needed in customEvent() - viewMap.insert(&vp); - it->second.erase(jt); - } - } - catch (Py::Exception& e) { - e.clear(); - } - } - // all cached objects of the documents are already destroyed - else { - it->second.clear(); - } - } -} - -void ViewProviderPythonFeatureObserver::slotDeleteObject(const Gui::ViewProvider& obj) -{ - // check this in customEvent() if the object is still there - std::set::iterator it = viewMap.find(&obj); - if (it != viewMap.end()) - viewMap.erase(it); - if (!obj.isDerivedFrom(Gui::ViewProviderDocumentObject::getClassTypeId())) - return; - const Gui::ViewProviderDocumentObject& vp = static_cast(obj); - const App::DocumentObject* docobj = vp.getObject(); - App::Document* doc = docobj->getDocument(); - if (!doc->getUndoMode()) - return; // object will be deleted immediately, thus we don't need to store anything - Base::PyGILStateLocker lock; - try { - App::Property* prop = vp.getPropertyByName("Proxy"); - if (prop && prop->isDerivedFrom(App::PropertyPythonObject::getClassTypeId())) { - auto &info = proxyMap[doc][docobj]; - info.viewObject = Py::asObject(const_cast(vp).getPyObject()); - info.proxy = Py::asObject(prop->getPyObject()); - FC_LOG("proxy cache " << info.viewObject.ptr() << ", " << info.proxy.ptr()); - } - } - catch (Py::Exception& e) { - e.clear(); - } -} - -ViewProviderPythonFeatureObserver::ViewProviderPythonFeatureObserver() -{ - Gui::Application::Instance->signalDeletedObject.connect(boost::bind - (&ViewProviderPythonFeatureObserver::slotDeleteObject, this, bp::_1)); - Gui::Application::Instance->signalNewObject.connect(boost::bind - (&ViewProviderPythonFeatureObserver::slotAppendObject, this, bp::_1)); - Gui::Application::Instance->signalDeleteDocument.connect(boost::bind - (&ViewProviderPythonFeatureObserver::slotDeleteDocument, this, bp::_1)); -} - -ViewProviderPythonFeatureObserver::~ViewProviderPythonFeatureObserver() -{ -} -#endif // ---------------------------------------------------------------------------- @@ -272,9 +59,6 @@ ViewProviderPythonFeatureImp::ViewProviderPythonFeatureImp( ViewProviderDocumentObject* vp, App::PropertyPythonObject &proxy) : object(vp), Proxy(proxy), has__object__(false) { -#if 0 - (void)ViewProviderPythonFeatureObserver::instance(); -#endif } ViewProviderPythonFeatureImp::~ViewProviderPythonFeatureImp() @@ -307,9 +91,6 @@ QIcon ViewProviderPythonFeatureImp::getIcon() const { _FC_PY_CALL_CHECK(getIcon,return(QIcon())); - // default icon - //static QPixmap px = BitmapFactory().pixmap("Tree_Python"); - // Run the getIcon method of the proxy object. Base::PyGILStateLocker lock; try { @@ -698,7 +479,7 @@ ViewProviderPythonFeatureImp::unsetEditViewer(View3DInventorViewer *viewer) } ViewProviderPythonFeatureImp::ValueT -ViewProviderPythonFeatureImp::doubleClicked(void) +ViewProviderPythonFeatureImp::doubleClicked() { FC_PY_CALL_CHECK(doubleClicked) @@ -966,8 +747,6 @@ bool ViewProviderPythonFeatureImp::getDefaultDisplayMode(std::string &mode) cons Base::PyGILStateLocker lock; try { Py::String str(Base::pyCall(py_getDefaultDisplayMode.ptr())); - //if (str.isUnicode()) - // str = str.encode("ascii"); // json converts strings into unicode mode = str.as_std_string("ascii"); return true; } @@ -983,7 +762,7 @@ bool ViewProviderPythonFeatureImp::getDefaultDisplayMode(std::string &mode) cons return true; } -std::vector ViewProviderPythonFeatureImp::getDisplayModes(void) const +std::vector ViewProviderPythonFeatureImp::getDisplayModes() const { std::vector modes; _FC_PY_CALL_CHECK(getDisplayModes,return(modes)); diff --git a/src/Gui/ViewProviderPythonFeature.h b/src/Gui/ViewProviderPythonFeature.h index ed2aeb0bfc..405437d13a 100644 --- a/src/Gui/ViewProviderPythonFeature.h +++ b/src/Gui/ViewProviderPythonFeature.h @@ -64,7 +64,7 @@ public: ValueT unsetEdit(int ModNum); ValueT setEditViewer(View3DInventorViewer*, int ModNum); ValueT unsetEditViewer(View3DInventorViewer*); - ValueT doubleClicked(void); + ValueT doubleClicked(); bool setupContextMenu(QMenu* menu); /** @name Update data methods*/ @@ -85,7 +85,7 @@ public: /// get the default display mode bool getDefaultDisplayMode(std::string &mode) const; /// returns a list of all possible modes - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const; /// set the display mode std::string setDisplayMode(const char* ModeName); //@} @@ -227,21 +227,21 @@ public: /** @name Nodes */ //@{ - virtual SoSeparator* getRoot() const override { + SoSeparator* getRoot() const override { return ViewProviderT::getRoot(); } - virtual SoSeparator* getFrontRoot() const override { + SoSeparator* getFrontRoot() const override { return ViewProviderT::getFrontRoot(); } // returns the root node of the Provider (3D) - virtual SoSeparator* getBackRoot() const override { + SoSeparator* getBackRoot() const override { return ViewProviderT::getBackRoot(); } //@} /** @name Selection handling */ //@{ - virtual bool useNewSelectionModel() const override { + bool useNewSelectionModel() const override { switch(imp->useNewSelectionModel()) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -251,7 +251,7 @@ public: return ViewProviderT::useNewSelectionModel(); } } - virtual bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const override { + bool getElementPicked(const SoPickedPoint *pp, std::string &subname) const override { auto ret = imp->getElementPicked(pp,subname); if(ret == ViewProviderPythonFeatureImp::NotImplemented) return ViewProviderT::getElementPicked(pp,subname); @@ -259,44 +259,44 @@ public: return true; return false; } - virtual std::string getElement(const SoDetail *det) const override { + std::string getElement(const SoDetail *det) const override { std::string name; if(!imp->getElement(det,name)) return ViewProviderT::getElement(det); return name; } - virtual SoDetail* getDetail(const char* name) const override { + SoDetail* getDetail(const char* name) const override { SoDetail *det = nullptr; if(imp->getDetail(name,det)) return det; return ViewProviderT::getDetail(name); } - virtual bool getDetailPath(const char *name, SoFullPath *path, bool append,SoDetail *&det) const override { + bool getDetailPath(const char *name, SoFullPath *path, bool append,SoDetail *&det) const override { auto ret = imp->getDetailPath(name,path,append,det); if(ret == ViewProviderPythonFeatureImp::NotImplemented) return ViewProviderT::getDetailPath(name,path,append,det); return ret == ViewProviderPythonFeatureImp::Accepted; } - virtual std::vector getSelectionShape(const char* Element) const override { + std::vector getSelectionShape(const char* Element) const override { return ViewProviderT::getSelectionShape(Element); }; //@} /** @name Update data methods*/ //@{ - virtual void attach(App::DocumentObject *obj) override { + void attach(App::DocumentObject *obj) override { // delay loading of the actual attach() method because the Python // view provider class is not attached yet ViewProviderT::pcObject = obj; } - virtual void updateData(const App::Property* prop) override { + void updateData(const App::Property* prop) override { imp->updateData(prop); ViewProviderT::updateData(prop); } - virtual void getTaskViewContent(std::vector& c) const override { + void getTaskViewContent(std::vector& c) const override { ViewProviderT::getTaskViewContent(c); } - virtual bool onDelete(const std::vector & sub) override { + bool onDelete(const std::vector & sub) override { switch(imp->onDelete(sub)) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -306,7 +306,7 @@ public: return ViewProviderT::onDelete(sub); } } - virtual bool canDelete(App::DocumentObject *obj) const override { + bool canDelete(App::DocumentObject *obj) const override { switch(imp->canDelete(obj)) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -320,11 +320,11 @@ public: /** @name Restoring view provider from document load */ //@{ - virtual void startRestoring() override { + void startRestoring() override { ViewProviderT::startRestoring(); imp->startRestoring(); } - virtual void finishRestoring() override { + void finishRestoring() override { imp->finishRestoring(); ViewProviderT::finishRestoring(); } @@ -333,7 +333,7 @@ public: /** @name Drag and drop */ //@{ /// Returns true if the view provider generally supports dragging objects - virtual bool canDragObjects() const override { + bool canDragObjects() const override { switch (imp->canDragObjects()) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -344,7 +344,7 @@ public: } } /// Check whether the object can be removed from the view provider by drag and drop - virtual bool canDragObject(App::DocumentObject* obj) const override { + bool canDragObject(App::DocumentObject* obj) const override { switch (imp->canDragObject(obj)) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -355,7 +355,7 @@ public: } } /// Starts to drag the object - virtual void dragObject(App::DocumentObject* obj) override { + void dragObject(App::DocumentObject* obj) override { App::AutoTransaction committer; switch (imp->dragObject(obj)) { case ViewProviderPythonFeatureImp::Accepted: @@ -366,7 +366,7 @@ public: } } /// Returns true if the view provider generally accepts dropping of objects - virtual bool canDropObjects() const override { + bool canDropObjects() const override { switch (imp->canDropObjects()) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -377,7 +377,7 @@ public: } } /// Check whether the object can be dropped to the view provider by drag and drop - virtual bool canDropObject(App::DocumentObject* obj) const override { + bool canDropObject(App::DocumentObject* obj) const override { switch (imp->canDropObject(obj)) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -388,7 +388,7 @@ public: } } /// If the dropped object type is accepted the object will be added as child - virtual void dropObject(App::DocumentObject* obj) override { + void dropObject(App::DocumentObject* obj) override { App::AutoTransaction committer; switch (imp->dropObject(obj)) { case ViewProviderPythonFeatureImp::Accepted: @@ -399,7 +399,7 @@ public: } } /** Return false to force drop only operation for a give object*/ - virtual bool canDragAndDropObject(App::DocumentObject *obj) const override { + bool canDragAndDropObject(App::DocumentObject *obj) const override { switch (imp->canDragAndDropObject(obj)) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -409,7 +409,7 @@ public: return ViewProviderT::canDragAndDropObject(obj); } } - virtual bool canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, + bool canDropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, const char *subname, const std::vector &elements) const override { switch (imp->canDropObjectEx(obj,owner,subname,elements)) { @@ -422,7 +422,7 @@ public: } } /** Add an object with full qualified name to the view provider by drag and drop */ - virtual std::string dropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, + std::string dropObjectEx(App::DocumentObject *obj, App::DocumentObject *owner, const char *subname, const std::vector &elements) override { App::AutoTransaction committer; @@ -436,7 +436,7 @@ public: /** @name Display methods */ //@{ /// Returns true if the icon must always appear enabled in the tree view - virtual bool isShow() const override { + bool isShow() const override { switch(imp->isShow()) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -447,28 +447,28 @@ public: } } /// get the default display mode - virtual const char* getDefaultDisplayMode() const override { + const char* getDefaultDisplayMode() const override { defaultMode.clear(); if(imp->getDefaultDisplayMode(defaultMode)) return defaultMode.c_str(); return ViewProviderT::getDefaultDisplayMode(); } /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const override { + std::vector getDisplayModes() const override { std::vector modes = ViewProviderT::getDisplayModes(); std::vector more_modes = imp->getDisplayModes(); modes.insert(modes.end(), more_modes.begin(), more_modes.end()); return modes; } /// set the display mode - virtual void setDisplayMode(const char* ModeName) override { + void setDisplayMode(const char* ModeName) override { std::string mask = imp->setDisplayMode(ModeName); ViewProviderT::setDisplayMaskMode(mask.c_str()); ViewProviderT::setDisplayMode(ModeName); } //@} - virtual bool canRemoveChildrenFromRoot() const override { + bool canRemoveChildrenFromRoot() const override { switch(imp->canRemoveChildrenFromRoot()) { case ViewProviderPythonFeatureImp::NotImplemented: return ViewProviderT::canRemoveChildrenFromRoot(); @@ -483,7 +483,7 @@ public: return ViewProviderT::getPyObject(); } - virtual bool canAddToSceneGraph() const override { + bool canAddToSceneGraph() const override { switch(imp->canAddToSceneGraph()) { case ViewProviderPythonFeatureImp::Accepted: return true; @@ -495,7 +495,7 @@ public: } protected: - virtual void onChanged(const App::Property* prop) override { + void onChanged(const App::Property* prop) override { if (prop == &Proxy) { imp->init(Proxy.getValue().ptr()); if (ViewProviderT::pcObject && !Proxy.getValue().is(Py::_None())) { @@ -519,7 +519,7 @@ protected: ViewProviderT::onChanged(prop); } /// is called by the document when the provider goes in edit mode - virtual bool setEdit(int ModNum) override + bool setEdit(int ModNum) override { switch (imp->setEdit(ModNum)) { case ViewProviderPythonFeatureImp::Accepted: @@ -531,7 +531,7 @@ protected: } } /// is called when you lose the edit mode - virtual void unsetEdit(int ModNum) override + void unsetEdit(int ModNum) override { switch (imp->unsetEdit(ModNum)) { case ViewProviderPythonFeatureImp::Accepted: @@ -541,23 +541,23 @@ protected: return ViewProviderT::unsetEdit(ModNum); } } - virtual void setEditViewer(View3DInventorViewer *viewer, int ModNum) override { + void setEditViewer(View3DInventorViewer *viewer, int ModNum) override { if (imp->setEditViewer(viewer,ModNum) == ViewProviderPythonFeatureImp::NotImplemented) ViewProviderT::setEditViewer(viewer,ModNum); } - virtual void unsetEditViewer(View3DInventorViewer *viewer) override { + void unsetEditViewer(View3DInventorViewer *viewer) override { if (imp->unsetEditViewer(viewer) == ViewProviderPythonFeatureImp::NotImplemented) ViewProviderT::unsetEditViewer(viewer); } - virtual std::string getDropPrefix() const override { + std::string getDropPrefix() const override { std::string prefix; if(!imp->getDropPrefix(prefix)) return ViewProviderT::getDropPrefix(); return prefix; } - virtual int replaceObject(App::DocumentObject *oldObj, App::DocumentObject *newObj) override { + int replaceObject(App::DocumentObject *oldObj, App::DocumentObject *newObj) override { App::AutoTransaction committer; switch (imp->replaceObject(oldObj,newObj)) { case ViewProviderPythonFeatureImp::Accepted: @@ -569,7 +569,7 @@ protected: } } - virtual ViewProviderDocumentObject *getLinkedViewProvider( + ViewProviderDocumentObject *getLinkedViewProvider( std::string *subname=nullptr, bool recursive=false) const override{ ViewProviderDocumentObject *res = nullptr; if(!imp->getLinkedViewProvider(res, subname, recursive)) @@ -577,20 +577,20 @@ protected: return res; } - virtual void editProperty(const char *propName) override { + void editProperty(const char *propName) override { if (!imp->editProperty(propName)) ViewProviderT::editProperty(propName); } public: - virtual void setupContextMenu(QMenu* menu, QObject* recipient, const char* member) override + void setupContextMenu(QMenu* menu, QObject* recipient, const char* member) override { if(!imp->setupContextMenu(menu)) ViewProviderT::setupContextMenu(menu, recipient, member); } protected: - virtual bool doubleClicked(void) override + bool doubleClicked() override { App::AutoTransaction committer; switch (imp->doubleClicked()) { @@ -602,7 +602,7 @@ protected: return ViewProviderT::doubleClicked(); } } - virtual void setOverrideMode(const std::string &mode) override + void setOverrideMode(const std::string &mode) override { ViewProviderT::setOverrideMode(mode); viewerMode = mode; diff --git a/src/Gui/ViewProviderTextDocument.h b/src/Gui/ViewProviderTextDocument.h index 0a1efc38e9..61505dbed6 100644 --- a/src/Gui/ViewProviderTextDocument.h +++ b/src/Gui/ViewProviderTextDocument.h @@ -32,23 +32,23 @@ class QPlainTextEdit; namespace Gui { class GuiExport ViewProviderTextDocument : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderTextDocument); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderTextDocument); public: ViewProviderTextDocument(); - ~ViewProviderTextDocument() {} + ~ViewProviderTextDocument() override {} App::PropertyBool ReadOnly; App::PropertyFloat FontSize; App::PropertyFont FontName; App::PropertyEnumeration SyntaxHighlighter; - bool doubleClicked(); - void setupContextMenu(QMenu* menu, QObject* receiver, const char* member); - bool isShow() const { return true; } + bool doubleClicked() override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool isShow() const override { return true; } - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; - virtual MDIView *getMDIView() const; + MDIView *getMDIView() const override; private: bool activateView() const; diff --git a/src/Gui/ViewProviderVRMLObject.cpp b/src/Gui/ViewProviderVRMLObject.cpp index 963b9fa8f2..40f9ce9188 100644 --- a/src/Gui/ViewProviderVRMLObject.cpp +++ b/src/Gui/ViewProviderVRMLObject.cpp @@ -86,10 +86,10 @@ void ViewProviderVRMLObject::setDisplayMode(const char* ModeName) ViewProviderDocumentObject::setDisplayMode( ModeName ); } -std::vector ViewProviderVRMLObject::getDisplayModes(void) const +std::vector ViewProviderVRMLObject::getDisplayModes() const { std::vector StrList; - StrList.push_back("VRML"); + StrList.emplace_back("VRML"); return StrList; } @@ -165,7 +165,7 @@ void ViewProviderVRMLObject::addResource(const SbString& url, std::list 0) { // add the resource file if not yet listed if (std::find(resources.begin(), resources.end(), url.getString()) == resources.end()) { - resources.push_back(url.getString()); + resources.emplace_back(url.getString()); } // if the resource file could be loaded check if it references further resources diff --git a/src/Gui/ViewProviderVRMLObject.h b/src/Gui/ViewProviderVRMLObject.h index 39a0244910..944e429b1a 100644 --- a/src/Gui/ViewProviderVRMLObject.h +++ b/src/Gui/ViewProviderVRMLObject.h @@ -34,19 +34,19 @@ namespace Gui class SoFCSelection; class GuiExport ViewProviderVRMLObject : public ViewProviderDocumentObject { - PROPERTY_HEADER(Gui::ViewProviderVRMLObject); + PROPERTY_HEADER_WITH_OVERRIDE(Gui::ViewProviderVRMLObject); public: /// constructor. ViewProviderVRMLObject(); /// destructor. - ~ViewProviderVRMLObject(); + ~ViewProviderVRMLObject() override; - void attach(App::DocumentObject *pcObject); - void setDisplayMode(const char* ModeName); - std::vector getDisplayModes() const; - void updateData(const App::Property*); + void attach(App::DocumentObject *pcObject) override; + void setDisplayMode(const char* ModeName) override; + std::vector getDisplayModes() const override; + void updateData(const App::Property*) override; void getLocalResources(SoNode*, std::list&); void addResource(const SbString&, std::list&); template void getResourceFile(SoNode*, std::list&); diff --git a/src/Gui/WaitCursor.cpp b/src/Gui/WaitCursor.cpp index 44d0262a55..593801043a 100644 --- a/src/Gui/WaitCursor.cpp +++ b/src/Gui/WaitCursor.cpp @@ -47,7 +47,7 @@ public: void setIgnoreEvents(WaitCursor::FilterEventsFlags flags); protected: - bool eventFilter(QObject*, QEvent*); + bool eventFilter(QObject*, QEvent*) override; bool isModalDialog(QObject* o) const; private: diff --git a/src/Gui/WhatsThis.cpp b/src/Gui/WhatsThis.cpp index 64ceefb705..0db2264abd 100644 --- a/src/Gui/WhatsThis.cpp +++ b/src/Gui/WhatsThis.cpp @@ -54,7 +54,7 @@ StdCmdDescription::~StdCmdDescription() { } -Action * StdCmdDescription::createAction(void) +Action * StdCmdDescription::createAction() { Action *pcAction = Command::createAction(); pcAction->setCheckable( true ); diff --git a/src/Gui/WhatsThis.h b/src/Gui/WhatsThis.h index c55c26391c..8a0b4965cd 100644 --- a/src/Gui/WhatsThis.h +++ b/src/Gui/WhatsThis.h @@ -36,7 +36,7 @@ class StdCmdDescription : public Command { public: StdCmdDescription(); - ~StdCmdDescription(); + ~StdCmdDescription() override; static bool inDescriptionMode(); static void enterDescriptionMode(); @@ -45,8 +45,8 @@ public: static void setSource( const QString& ); protected: - Action* createAction(void); - void activated(int iMsg); + Action* createAction() override; + void activated(int iMsg) override; private: static bool _descrMode; diff --git a/src/Gui/WidgetFactory.cpp b/src/Gui/WidgetFactory.cpp index 860bf22c60..83d76281f8 100644 --- a/src/Gui/WidgetFactory.cpp +++ b/src/Gui/WidgetFactory.cpp @@ -53,14 +53,14 @@ Gui::WidgetFactoryInst* Gui::WidgetFactoryInst::_pcSingleton = nullptr; WidgetFactoryInst& WidgetFactoryInst::instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) _pcSingleton = new WidgetFactoryInst; return *_pcSingleton; } void WidgetFactoryInst::destruct () { - if (_pcSingleton != nullptr) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } diff --git a/src/Gui/WidgetFactory.h b/src/Gui/WidgetFactory.h index 8e958d693b..4f840d836f 100644 --- a/src/Gui/WidgetFactory.h +++ b/src/Gui/WidgetFactory.h @@ -62,7 +62,7 @@ private: static WidgetFactoryInst* _pcSingleton; WidgetFactoryInst(){} - ~WidgetFactoryInst(){} + ~WidgetFactoryInst() override{} }; inline WidgetFactoryInst& WidgetFactory() @@ -90,12 +90,12 @@ public: WidgetFactoryInst::instance().AddProducer(cname, this); } - virtual ~WidgetProducer (){} + ~WidgetProducer () override{} /** * Creates an instance of the specified widget. */ - virtual void* Produce () const + void* Produce () const override { return (new CLASS); } @@ -129,12 +129,12 @@ public: } } - virtual ~PrefPageProducer (){} + ~PrefPageProducer () override{} /** * Creates an instance of the specified widget. */ - virtual void* Produce () const + void* Produce () const override { return (new CLASS); } @@ -152,11 +152,11 @@ public: * Register a special type of preference page to the WidgetFactoryInst. */ PrefPageUiProducer (const char* filename, const char* group); - virtual ~PrefPageUiProducer (); + ~PrefPageUiProducer () override; /** * Creates an instance of the specified widget. */ - virtual void* Produce () const; + void* Produce () const override; private: QString fn; @@ -174,11 +174,11 @@ public: * Register a special type of preference page to the WidgetFactoryInst. */ PrefPagePyProducer (const Py::Object&, const char* group); - virtual ~PrefPagePyProducer (); + ~PrefPagePyProducer () override; /** * Creates an instance of the specified widget. */ - virtual void* Produce () const; + void* Produce () const override; private: Py::Object type; @@ -212,12 +212,12 @@ public: } } - virtual ~CustomPageProducer (){} + ~CustomPageProducer () override{} /** * Creates an instance of the specified widget. */ - virtual void* Produce () const + void* Produce () const override { return (new CLASS); } @@ -262,7 +262,7 @@ class ContainerDialog : public QDialog public: ContainerDialog( QWidget* templChild ); - ~ContainerDialog(); + ~ContainerDialog() override; QPushButton* buttonOk; /**< The Ok button. */ QPushButton* buttonCancel; /**< The cancel button. */ @@ -332,12 +332,12 @@ public: static void init_type(); // announce properties and methods PyResource(); - ~PyResource(); + ~PyResource() override; void load(const char* name); bool connect(const char* sender, const char* signal, PyObject* cb); - Py::Object repr(); + Py::Object repr() override; Py::Object value(const Py::Tuple&); Py::Object setValue(const Py::Tuple&); @@ -361,7 +361,7 @@ class SignalConnect : public QObject public: SignalConnect(PyObject* res, PyObject* cb); - ~SignalConnect(); + ~SignalConnect() override; public Q_SLOTS: void onExecute(); @@ -383,13 +383,13 @@ class GuiExport PreferencePagePython : public PreferencePage public: PreferencePagePython(const Py::Object& dlg, QWidget* parent = nullptr); - virtual ~PreferencePagePython(); + ~PreferencePagePython() override; - void loadSettings(); - void saveSettings(); + void loadSettings() override; + void saveSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: Py::Object page; diff --git a/src/Gui/Widgets.cpp b/src/Gui/Widgets.cpp index aedf846d95..ace41e8ba3 100644 --- a/src/Gui/Widgets.cpp +++ b/src/Gui/Widgets.cpp @@ -652,10 +652,8 @@ ColorButton::ColorButton(QWidget* parent) d->col = palette().color(QPalette::Active,QPalette::Midlight); connect(this, SIGNAL(clicked()), SLOT(onChooseColor())); -#if 1 int e = style()->pixelMetric(QStyle::PM_ButtonIconSize); setIconSize(QSize(2*e, e)); -#endif } /** @@ -744,36 +742,6 @@ bool ColorButton::autoChangeColor() const */ void ColorButton::paintEvent (QPaintEvent * e) { -#if 0 - // first paint the complete button - QPushButton::paintEvent(e); - - // repaint the rectangle area - QPalette::ColorGroup group = isEnabled() ? hasFocus() ? QPalette::Active : QPalette::Inactive : QPalette::Disabled; - QColor pen = palette().color(group,QPalette::ButtonText); - { - QPainter paint(this); - paint.setPen(pen); - - if (d->drawFrame) { - paint.setBrush(QBrush(d->col)); - paint.drawRect(5, 5, width()-10, height()-10); - } - else { - paint.fillRect(5, 5, width()-10, height()-10, QBrush(d->col)); - } - } - - // overpaint the rectangle to paint icon and text - QStyleOptionButton opt; - opt.init(this); - opt.text = text(); - opt.icon = icon(); - opt.iconSize = iconSize(); - - QStylePainter p(this); - p.drawControl(QStyle::CE_PushButtonLabel, opt); -#else if (d->dirty) { QSize isize = iconSize(); QPixmap pix(isize); @@ -797,7 +765,6 @@ void ColorButton::paintEvent (QPaintEvent * e) } QPushButton::paintEvent(e); -#endif } /** @@ -1222,7 +1189,6 @@ bool ToolTip::eventFilter(QObject* o, QEvent*e) StatusWidget::StatusWidget(QWidget* parent) : QDialog(parent, Qt::Dialog | Qt::FramelessWindowHint) { - //setWindowModality(Qt::ApplicationModal); label = new QLabel(this); label->setAlignment(Qt::AlignCenter); @@ -1275,12 +1241,12 @@ public: codeEditor = editor; } - QSize sizeHint() const { + QSize sizeHint() const override { return QSize(codeEditor->lineNumberAreaWidth(), 0); } protected: - void paintEvent(QPaintEvent *event) { + void paintEvent(QPaintEvent *event) override { codeEditor->lineNumberAreaPaintEvent(event); } @@ -1393,7 +1359,7 @@ public: { } - void accept() + void accept() override { PropertyListEditor* edit = this->findChild(); QStringList lines; @@ -1705,7 +1671,8 @@ ButtonGroup::ButtonGroup(QObject *parent) connect(this, qOverload(&QButtonGroup::buttonClicked), [=](QAbstractButton *button) { if (exclusive()) { - for (auto btn : buttons()) { + const auto btns = buttons(); + for (auto btn : btns) { if (btn && btn != button && btn->isCheckable()) btn->setChecked(false); } diff --git a/src/Gui/Widgets.h b/src/Gui/Widgets.h index 37cfc637e4..0963952e42 100644 --- a/src/Gui/Widgets.h +++ b/src/Gui/Widgets.h @@ -64,10 +64,10 @@ class CommandIconView : public QListWidget public: CommandIconView (QWidget * parent = nullptr); - virtual ~CommandIconView (); + ~CommandIconView () override; protected: - void startDrag ( Qt::DropActions supportedActions ); + void startDrag ( Qt::DropActions supportedActions ) override; protected Q_SLOTS: void onSelectionChanged( QListWidgetItem * item, QListWidgetItem * ); @@ -85,7 +85,7 @@ class GuiExport ActionSelector : public QWidget public: ActionSelector(QWidget* parent=nullptr); - ~ActionSelector(); + ~ActionSelector() override; QTreeWidget* availableTreeWidget() const { return availableWidget; } @@ -97,8 +97,8 @@ public: QString availableLabel() const; private: - void keyPressEvent(QKeyEvent *); - void changeEvent(QEvent*); + void keyPressEvent(QKeyEvent *) override; + void changeEvent(QEvent*) override; void retranslateUi(); void setButtonsEnabled(); @@ -141,7 +141,7 @@ public: bool isNone() const; protected: - void keyPressEvent(QKeyEvent * e); + void keyPressEvent(QKeyEvent * e) override; private: int keyPressedCount; @@ -160,7 +160,7 @@ public: ModifierLineEdit(QWidget * parent=nullptr); protected: - void keyPressEvent(QKeyEvent * e); + void keyPressEvent(QKeyEvent * e) override; }; // ------------------------------------------------------------------------------ @@ -177,7 +177,7 @@ public: ClearLineEdit (QWidget * parent=nullptr); protected: - void resizeEvent(QResizeEvent *); + void resizeEvent(QResizeEvent *) override; private Q_SLOTS: void updateClearButton(const QString &text); @@ -203,13 +203,13 @@ class GuiExport CheckListDialog : public QDialog public: CheckListDialog( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~CheckListDialog(); + ~CheckListDialog() override; void setCheckableItems( const QStringList& items ); void setCheckableItems( const QList& items ); QStringList getCheckedItems() const; - void accept (); + void accept () override; private: QStringList checked; @@ -226,14 +226,14 @@ class GuiExport ColorButton : public QPushButton { Q_OBJECT - Q_PROPERTY( QColor color READ color WRITE setColor ) - Q_PROPERTY( bool allowChangeColor READ allowChangeColor WRITE setAllowChangeColor ) - Q_PROPERTY( bool drawFrame READ drawFrame WRITE setDrawFrame ) - Q_PROPERTY( bool allowTransparency READ allowTransparency WRITE setAllowTransparency) + Q_PROPERTY( QColor color READ color WRITE setColor NOTIFY changed) + Q_PROPERTY( bool allowChangeColor READ allowChangeColor WRITE setAllowChangeColor ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( bool drawFrame READ drawFrame WRITE setDrawFrame ) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( bool allowTransparency READ allowTransparency WRITE setAllowTransparency) // clazy:exclude=qproperty-without-notify public: ColorButton(QWidget* parent = nullptr); - ~ColorButton(); + ~ColorButton() override; void setColor(const QColor&); QColor color() const; @@ -265,7 +265,7 @@ Q_SIGNALS: void changed(); protected: - void paintEvent (QPaintEvent*); + void paintEvent (QPaintEvent*) override; private: struct ColorButtonP *d; @@ -284,12 +284,12 @@ private: class GuiExport UrlLabel : public QLabel { Q_OBJECT - Q_PROPERTY( QString url READ url WRITE setUrl) - Q_PROPERTY( bool launchExternal READ launchExternal WRITE setLaunchExternal) + Q_PROPERTY( QString url READ url WRITE setUrl) // clazy:exclude=qproperty-without-notify + Q_PROPERTY( bool launchExternal READ launchExternal WRITE setLaunchExternal) // clazy:exclude=qproperty-without-notify public: UrlLabel ( QWidget * parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags() ); - virtual ~UrlLabel(); + ~UrlLabel() override; QString url() const; bool launchExternal() const; @@ -302,7 +302,7 @@ public Q_SLOTS: void setLaunchExternal(bool l); protected: - void mouseReleaseEvent ( QMouseEvent * ); + void mouseReleaseEvent ( QMouseEvent * ) override; private: QString _url; @@ -343,7 +343,7 @@ class GuiExport StatefulLabel : public QLabel, public Base::Observer& rCaller, const char* rcReason); + void OnChange(Base::Subject& rCaller, const char* rcReason) override; public Q_SLOTS: void setState(QString state); @@ -398,11 +398,11 @@ class GuiExport LabelButton : public QWidget { Q_OBJECT - Q_PROPERTY(QVariant value READ value WRITE setValue) + Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) public: LabelButton (QWidget * parent = nullptr); - virtual ~LabelButton(); + ~LabelButton() override; QVariant value() const; @@ -414,7 +414,7 @@ public Q_SLOTS: protected: virtual void showValue(const QVariant& data); - void resizeEvent(QResizeEvent*); + void resizeEvent(QResizeEvent*) override; protected Q_SLOTS: virtual void browse(); @@ -447,10 +447,10 @@ protected: static ToolTip* instance(); ToolTip(); - virtual ~ToolTip(); + ~ToolTip() override; - void timerEvent(QTimerEvent *e); - bool eventFilter(QObject* o, QEvent*e); + void timerEvent(QTimerEvent *e) override; + bool eventFilter(QObject* o, QEvent*e) override; void installEventFilter(); void removeEventFilter(); @@ -473,14 +473,14 @@ class GuiExport StatusWidget : public QDialog public: StatusWidget(QWidget* parent); - ~StatusWidget(); + ~StatusWidget() override; void setStatusText(const QString&); - QSize sizeHint () const; + QSize sizeHint () const override; void showText(int ms); protected: - void showEvent(QShowEvent*); - void hideEvent(QHideEvent*); + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; private: QLabel* label; @@ -499,7 +499,7 @@ public: int lineNumberAreaWidth(); protected: - void resizeEvent(QResizeEvent *event); + void resizeEvent(QResizeEvent *event) override; private Q_SLOTS: void updateLineNumberAreaWidth(int newBlockCount); @@ -516,14 +516,14 @@ class GuiExport LabelEditor : public QWidget { Q_OBJECT - Q_PROPERTY(QString text READ text WRITE setText ) - Q_PROPERTY(QString buttonText READ buttonText WRITE setButtonText) + Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged) + Q_PROPERTY(QString buttonText READ buttonText WRITE setButtonText) // clazy:exclude=qproperty-without-notify public: enum InputType {String, Float, Integer}; LabelEditor (QWidget * parent = nullptr); - virtual ~LabelEditor(); + ~LabelEditor() override; /** * Returns the text. @@ -552,7 +552,7 @@ private Q_SLOTS: void changeText(); protected: - void resizeEvent(QResizeEvent*); + void resizeEvent(QResizeEvent*) override; private: InputType type; @@ -572,17 +572,17 @@ class GuiExport ExpLineEdit : public QLineEdit, public ExpressionBinding public: ExpLineEdit ( QWidget * parent=nullptr, bool expressionOnly=false ); - void setExpression(std::shared_ptr expr); - void bind(const App::ObjectIdentifier &_path); - bool apply(const std::string &propName); + void setExpression(std::shared_ptr expr) override; + void bind(const App::ObjectIdentifier &_path) override; + bool apply(const std::string &propName) override; - void keyPressEvent(QKeyEvent *event); - void resizeEvent(QResizeEvent *event); + void keyPressEvent(QKeyEvent *event) override; + void resizeEvent(QResizeEvent *event) override; private Q_SLOTS: void finishFormulaDialog(); void openFormulaDialog(); - virtual void onChange(); + void onChange() override; private: bool autoClose; diff --git a/src/Gui/Window.cpp b/src/Gui/Window.cpp index 6fcd71e64a..58a03bfdae 100644 --- a/src/Gui/Window.cpp +++ b/src/Gui/Window.cpp @@ -78,7 +78,7 @@ void WindowParameter::OnChange(Base::Subject &rCaller, const char * Base::Console().Log("Parameter has changed and window (%s) has not overridden this function!",_handle->GetGroupName()); } -ParameterGrp::handle WindowParameter::getWindowParameter(void) +ParameterGrp::handle WindowParameter::getWindowParameter() { return _handle; } @@ -87,7 +87,7 @@ ParameterGrp::handle WindowParameter::getWindowParameter(void) * Returns a handle to the parameter group to the user parameter * under BaseApp/Preferences. */ -ParameterGrp::handle WindowParameter::getDefaultParameter(void) +ParameterGrp::handle WindowParameter::getDefaultParameter() { return App::GetApplication().GetUserParameter().GetGroup("BaseApp")->GetGroup("Preferences"); } diff --git a/src/Gui/Window.h b/src/Gui/Window.h index 6a85101d16..8bc2960691 100644 --- a/src/Gui/Window.h +++ b/src/Gui/Window.h @@ -36,15 +36,15 @@ class GuiExport WindowParameter : public ParameterGrp::ObserverType { public: WindowParameter(const char *name); - virtual ~WindowParameter(); + ~WindowParameter() override; bool setGroupName( const char* name ); - void OnChange(Base::Subject &rCaller, const char * sReason); + void OnChange(Base::Subject &rCaller, const char * sReason) override; /// get the parameters - static ParameterGrp::handle getDefaultParameter(void); + static ParameterGrp::handle getDefaultParameter(); /// return the parameter group of this window - ParameterGrp::handle getWindowParameter(void); + ParameterGrp::handle getWindowParameter(); private: ParameterGrp::handle _handle; diff --git a/src/Gui/Workbench.cpp b/src/Gui/Workbench.cpp index b59f9d4cb3..d545611a7a 100644 --- a/src/Gui/Workbench.cpp +++ b/src/Gui/Workbench.cpp @@ -205,7 +205,6 @@ using namespace Gui; TYPESYSTEM_SOURCE_ABSTRACT(Gui::Workbench, Base::BaseClass) Workbench::Workbench() - : _name("") { } @@ -456,7 +455,7 @@ void Workbench::addTaskWatcher(const std::vector &W taskView->addTaskWatcher(Watcher); } -void Workbench::removeTaskWatcher(void) +void Workbench::removeTaskWatcher() { Gui::TaskView::TaskView* taskView = Control().taskPanel(); if (taskView) @@ -468,7 +467,7 @@ std::list Workbench::listToolbars() const std::unique_ptr tb(setupToolBars()); std::list bars; QList items = tb->getItems(); - for (QList::ConstIterator item = items.begin(); item != items.end(); ++item) + for (QList::ConstIterator item = items.cbegin(); item != items.cend(); ++item) bars.push_back((*item)->command()); return bars; } @@ -479,10 +478,10 @@ std::list>> Workbench::getToolbarI std::list>> itemsList; QList items = tb->getItems(); - for (QList::ConstIterator it = items.begin(); it != items.end(); ++it) { + for (QList::ConstIterator it = items.cbegin(); it != items.cend(); ++it) { QList sub = (*it)->getItems(); std::list cmds; - for (QList::ConstIterator jt = sub.begin(); jt != sub.end(); ++jt) { + for (QList::ConstIterator jt = sub.cbegin(); jt != sub.cend(); ++jt) { cmds.push_back((*jt)->command()); } @@ -496,7 +495,7 @@ std::list Workbench::listMenus() const std::unique_ptr mb(setupMenuBar()); std::list menus; QList items = mb->getItems(); - for ( QList::ConstIterator it = items.begin(); it != items.end(); ++it ) + for ( QList::ConstIterator it = items.cbegin(); it != items.cend(); ++it ) menus.push_back((*it)->command()); return menus; } @@ -506,7 +505,7 @@ std::list Workbench::listCommandbars() const std::unique_ptr cb(setupCommandBars()); std::list bars; QList items = cb->getItems(); - for (QList::ConstIterator item = items.begin(); item != items.end(); ++item) + for (QList::ConstIterator item = items.cbegin(); item != items.cend(); ++item) bars.push_back((*item)->command()); return bars; } diff --git a/src/Gui/Workbench.h b/src/Gui/Workbench.h index a56ee2d7de..6e40ae6abd 100644 --- a/src/Gui/Workbench.h +++ b/src/Gui/Workbench.h @@ -51,12 +51,12 @@ class WorkbenchManager; */ class GuiExport Workbench : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** Constructs a workbench object. */ Workbench(); - virtual ~Workbench(); + ~Workbench() override; /** * Returns the name of the workbench object. */ @@ -68,7 +68,7 @@ public: /** * The default implementation returns an instance of @ref WorkbenchPy. */ - PyObject* getPyObject(); + PyObject* getPyObject() override; /** Sets up the contextmenu for this workbench. * The default implementation does nothing. */ @@ -93,7 +93,7 @@ public: /// helper to add TaskWatcher to the TaskView void addTaskWatcher(const std::vector &Watcher); /// remove the added TaskWatcher - void removeTaskWatcher(void); + void removeTaskWatcher(); static void createLinkMenu(MenuItem *); @@ -146,26 +146,26 @@ private: */ class GuiExport StdWorkbench : public Workbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: StdWorkbench(); - virtual ~StdWorkbench(); + ~StdWorkbench() override; public: /** Defines the standard context menu. */ - virtual void setupContextMenu(const char* recipient, MenuItem*) const; - virtual void createMainWindowPopupMenu(MenuItem*) const; + void setupContextMenu(const char* recipient, MenuItem*) const override; + void createMainWindowPopupMenu(MenuItem*) const override; protected: /** Defines the standard menus. */ - virtual MenuItem* setupMenuBar() const; + MenuItem* setupMenuBar() const override; /** Defines the standard toolbars. */ - virtual ToolBarItem* setupToolBars() const; + ToolBarItem* setupToolBars() const override; /** Defines the standard command bars. */ - virtual ToolBarItem* setupCommandBars() const; + ToolBarItem* setupCommandBars() const override; /** Returns a DockWindowItems structure of dock windows this workbench. */ - virtual DockWindowItems* setupDockWindows() const; + DockWindowItems* setupDockWindows() const override; friend class PythonWorkbench; }; @@ -176,28 +176,28 @@ protected: */ class GuiExport BlankWorkbench : public Workbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: BlankWorkbench(); - virtual ~BlankWorkbench(); + ~BlankWorkbench() override; /** Defines the standard context menu. */ - virtual void setupContextMenu(const char* recipient,MenuItem*) const; + void setupContextMenu(const char* recipient,MenuItem*) const override; /** Run some actions when the workbench gets activated. */ - virtual void activated(); + void activated() override; /** Run some actions when the workbench gets deactivated. */ - virtual void deactivated(); + void deactivated() override; protected: /** Defines the standard menus. */ - virtual MenuItem* setupMenuBar() const; + MenuItem* setupMenuBar() const override; /** Defines the standard toolbars. */ - virtual ToolBarItem* setupToolBars() const; + ToolBarItem* setupToolBars() const override; /** Defines the standard command bars. */ - virtual ToolBarItem* setupCommandBars() const; + ToolBarItem* setupCommandBars() const override; /** Returns a DockWindowItems structure of dock windows this workbench. */ - virtual DockWindowItems* setupDockWindows() const; + DockWindowItems* setupDockWindows() const override; }; /** @@ -206,38 +206,38 @@ protected: */ class GuiExport NoneWorkbench : public StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: NoneWorkbench(); - virtual ~NoneWorkbench(); + ~NoneWorkbench() override; /** Defines the standard context menu. */ - virtual void setupContextMenu(const char* recipient,MenuItem*) const; + void setupContextMenu(const char* recipient,MenuItem*) const override; protected: /** Defines the standard menus. */ - virtual MenuItem* setupMenuBar() const; + MenuItem* setupMenuBar() const override; /** Defines the standard toolbars. */ - virtual ToolBarItem* setupToolBars() const; + ToolBarItem* setupToolBars() const override; /** Defines the standard command bars. */ - virtual ToolBarItem* setupCommandBars() const; + ToolBarItem* setupCommandBars() const override; /** Returns a DockWindowItems structure of dock windows this workbench. */ - virtual DockWindowItems* setupDockWindows() const; + DockWindowItems* setupDockWindows() const override; }; class GuiExport TestWorkbench : public StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: TestWorkbench(); - ~TestWorkbench(); + ~TestWorkbench() override; protected: - MenuItem* setupMenuBar() const; - ToolBarItem* setupToolBars() const; - ToolBarItem* setupCommandBars() const; + MenuItem* setupMenuBar() const override; + ToolBarItem* setupToolBars() const override; + ToolBarItem* setupCommandBars() const override; }; /** @@ -247,15 +247,15 @@ protected: */ class GuiExport PythonBaseWorkbench : public Workbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PythonBaseWorkbench(); - ~PythonBaseWorkbench(); + ~PythonBaseWorkbench() override; /** * Creates and returns immediately the corresponding Python workbench object. */ - PyObject* getPyObject(); + PyObject* getPyObject() override; /** @name Manipulation methods */ //@{ @@ -268,7 +268,7 @@ public: void appendContextMenu(const std::list& menu, const std::list& items) const; /// Removes a context menu void removeContextMenu(const std::string& menu ) const; - void setupContextMenu(const char* recipient,MenuItem*) const; + void setupContextMenu(const char* recipient,MenuItem*) const override; void clearContextMenu(); /// Appends a new toolbar @@ -283,10 +283,10 @@ public: //@} protected: - MenuItem* setupMenuBar() const; - ToolBarItem* setupToolBars() const; - ToolBarItem* setupCommandBars() const; - DockWindowItems* setupDockWindows() const; + MenuItem* setupMenuBar() const override; + ToolBarItem* setupToolBars() const override; + ToolBarItem* setupCommandBars() const override; + DockWindowItems* setupDockWindows() const override; protected: MenuItem* _menuBar; @@ -298,11 +298,11 @@ protected: class GuiExport PythonBlankWorkbench : public PythonBaseWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PythonBlankWorkbench(); - ~PythonBlankWorkbench(); + ~PythonBlankWorkbench() override; }; /** @@ -312,21 +312,21 @@ public: */ class GuiExport PythonWorkbench : public PythonBaseWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PythonWorkbench(); - ~PythonWorkbench(); + ~PythonWorkbench() override; /** Defines the standard context menu. */ - virtual void setupContextMenu(const char* recipient, MenuItem*) const; - virtual void createMainWindowPopupMenu(MenuItem*) const; + void setupContextMenu(const char* recipient, MenuItem*) const override; + void createMainWindowPopupMenu(MenuItem*) const override; protected: - MenuItem* setupMenuBar() const; - ToolBarItem* setupToolBars() const; - ToolBarItem* setupCommandBars() const; - DockWindowItems* setupDockWindows() const; + MenuItem* setupMenuBar() const override; + ToolBarItem* setupToolBars() const override; + ToolBarItem* setupCommandBars() const override; + DockWindowItems* setupDockWindows() const override; }; } // namespace Gui diff --git a/src/Gui/WorkbenchFactory.cpp b/src/Gui/WorkbenchFactory.cpp index 3a1b9e8270..f8a364c2fa 100644 --- a/src/Gui/WorkbenchFactory.cpp +++ b/src/Gui/WorkbenchFactory.cpp @@ -32,14 +32,14 @@ Gui::WorkbenchFactoryInst* Gui::WorkbenchFactoryInst::_pcSingleton = nullptr; WorkbenchFactoryInst& WorkbenchFactoryInst::instance() { - if (_pcSingleton == nullptr) + if (!_pcSingleton) _pcSingleton = new WorkbenchFactoryInst; return *_pcSingleton; } void WorkbenchFactoryInst::destruct () { - if ( _pcSingleton != nullptr ) + if (_pcSingleton) delete _pcSingleton; _pcSingleton = nullptr; } diff --git a/src/Gui/WorkbenchFactory.h b/src/Gui/WorkbenchFactory.h index 7b2ed02a9d..979292cdb5 100644 --- a/src/Gui/WorkbenchFactory.h +++ b/src/Gui/WorkbenchFactory.h @@ -57,7 +57,7 @@ private: static WorkbenchFactoryInst* _pcSingleton; WorkbenchFactoryInst(){} - ~WorkbenchFactoryInst(){} + ~WorkbenchFactoryInst() override{} }; inline GuiExport WorkbenchFactoryInst& WorkbenchFactory() @@ -80,9 +80,9 @@ public: { } - virtual ~WorkbenchProducer (){} + ~WorkbenchProducer () override{} - virtual void* Produce () const + void* Produce () const override { return (new CLASS); } diff --git a/src/Gui/WorkbenchManager.cpp b/src/Gui/WorkbenchManager.cpp index 5de48db826..6830f7275b 100644 --- a/src/Gui/WorkbenchManager.cpp +++ b/src/Gui/WorkbenchManager.cpp @@ -37,7 +37,7 @@ WorkbenchManager* WorkbenchManager::_instance = nullptr; WorkbenchManager* WorkbenchManager::instance() { - if (_instance == nullptr) + if (!_instance) _instance = new WorkbenchManager; return _instance; } diff --git a/src/Gui/WorkbenchPyImp.cpp b/src/Gui/WorkbenchPyImp.cpp index 9136fced82..a9beff4a50 100644 --- a/src/Gui/WorkbenchPyImp.cpp +++ b/src/Gui/WorkbenchPyImp.cpp @@ -43,7 +43,7 @@ using namespace Gui; */ // returns a string which represent the object e.g. when printed in python -std::string WorkbenchPy::representation(void) const +std::string WorkbenchPy::representation() const { return std::string(""); } diff --git a/src/Gui/propertyeditor/PropertyEditor.cpp b/src/Gui/propertyeditor/PropertyEditor.cpp index fb12f727dd..e256a232d9 100644 --- a/src/Gui/propertyeditor/PropertyEditor.cpp +++ b/src/Gui/propertyeditor/PropertyEditor.cpp @@ -624,13 +624,14 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { auto contextIndex = currentIndex(); std::unordered_set props; - for(auto index : selectedIndexes()) { + const auto indexes = selectedIndexes(); + for(const auto& index : indexes) { auto item = static_cast(index.internalPointer()); if(item->isSeparator()) continue; for(auto parent=item;parent;parent=parent->parent()) { const auto &ps = parent->getPropertyData(); - if(ps.size()) { + if(!ps.empty()) { props.insert(ps.begin(),ps.end()); break; } @@ -654,7 +655,7 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { } if(PropertyView::showAll()) { - if(props.size()) { + if(!props.empty()) { menu.addAction(tr("Add property"))->setData(QVariant(MA_AddProp)); if (std::all_of(props.begin(), props.end(), [](auto prop) { return prop->testStatus(App::Property::PropDynamic) @@ -680,7 +681,7 @@ void PropertyEditor::contextMenuEvent(QContextMenuEvent *) { if(canRemove) menu.addAction(tr("Remove property"))->setData(QVariant(MA_RemoveProp)); - if(props.size()) { + if(!props.empty()) { menu.addSeparator(); QAction *action; diff --git a/src/Gui/propertyeditor/PropertyEditor.h b/src/Gui/propertyeditor/PropertyEditor.h index 3e6c3c9585..f8b21ca329 100644 --- a/src/Gui/propertyeditor/PropertyEditor.h +++ b/src/Gui/propertyeditor/PropertyEditor.h @@ -62,12 +62,12 @@ class PropertyEditor : public QTreeView { Q_OBJECT - Q_PROPERTY(QBrush groupBackground READ groupBackground WRITE setGroupBackground DESIGNABLE true SCRIPTABLE true) - Q_PROPERTY(QColor groupTextColor READ groupTextColor WRITE setGroupTextColor DESIGNABLE true SCRIPTABLE true) + Q_PROPERTY(QBrush groupBackground READ groupBackground WRITE setGroupBackground DESIGNABLE true SCRIPTABLE true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor groupTextColor READ groupTextColor WRITE setGroupTextColor DESIGNABLE true SCRIPTABLE true) // clazy:exclude=qproperty-without-notify public: PropertyEditor(QWidget *parent = nullptr); - ~PropertyEditor(); + ~PropertyEditor() override; /** Builds up the list view with the properties. */ void buildUp(PropertyModel::PropertyList &&props = PropertyModel::PropertyList(), bool checkDocument=false); @@ -78,7 +78,7 @@ public: void setAutomaticDocumentUpdate(bool); bool isAutomaticDocumentUpdate(bool) const; /*! Reset the internal state of the view. */ - virtual void reset(); + void reset() override; QBrush groupBackground() const; void setGroupBackground(const QBrush& c); @@ -97,16 +97,16 @@ protected Q_SLOTS: void onRowsRemoved(const QModelIndex &parent, int start, int end); protected: - virtual void closeEditor (QWidget * editor, QAbstractItemDelegate::EndEditHint hint); - virtual void commitData (QWidget * editor); - virtual void editorDestroyed (QObject * editor); - virtual void currentChanged (const QModelIndex & current, const QModelIndex & previous); - virtual void rowsInserted (const QModelIndex & parent, int start, int end); - virtual void rowsAboutToBeRemoved (const QModelIndex & parent, int start, int end); - virtual void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const; - virtual QStyleOptionViewItem viewOptions() const; - virtual void contextMenuEvent(QContextMenuEvent *event); - virtual bool event(QEvent*); + void closeEditor (QWidget * editor, QAbstractItemDelegate::EndEditHint hint) override; + void commitData (QWidget * editor) override; + void editorDestroyed (QObject * editor) override; + void currentChanged (const QModelIndex & current, const QModelIndex & previous) override; + void rowsInserted (const QModelIndex & parent, int start, int end) override; + void rowsAboutToBeRemoved (const QModelIndex & parent, int start, int end) override; + void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override; + QStyleOptionViewItem viewOptions() const override; + void contextMenuEvent(QContextMenuEvent *event) override; + bool event(QEvent*) override; private: void setEditorMode(const QModelIndex & parent, int start, int end); diff --git a/src/Gui/propertyeditor/PropertyItem.cpp b/src/Gui/propertyeditor/PropertyItem.cpp index 31eecf44a8..4a3696cab5 100644 --- a/src/Gui/propertyeditor/PropertyItem.cpp +++ b/src/Gui/propertyeditor/PropertyItem.cpp @@ -69,7 +69,7 @@ Gui::PropertyEditor::PropertyItemFactory* Gui::PropertyEditor::PropertyItemFacto PropertyItemFactory& PropertyItemFactory::instance() { - if (_singleton == nullptr) + if (!_singleton) _singleton = new PropertyItemFactory; return *_singleton; } @@ -123,7 +123,7 @@ void PropertyItem::reset() void PropertyItem::onChange() { if(hasExpression()) { - for(auto child : childItems) { + for(auto child : qAsConst(childItems)) { if(child && child->hasExpression()) child->setExpression(std::shared_ptr()); } @@ -1040,7 +1040,7 @@ void PropertyFloatItem::setValue(const QVariant& value) if (!value.canConvert(QVariant::Double)) return; double val = value.toDouble(); - QString data = QString::fromLatin1("%1").arg(val,0,'f',decimals()); + QString data = QString::fromLatin1("%1").arg(val, 0, 'f', decimals()); setPropertyValue(data); } } @@ -1216,7 +1216,7 @@ void PropertyFloatConstraintItem::setValue(const QVariant& value) if (!value.canConvert(QVariant::Double)) return; double val = value.toDouble(); - QString data = QString::fromLatin1("%1").arg(val,0,'f',decimals()); + QString data = QString::fromLatin1("%1").arg(val, 0, 'f', decimals()); setPropertyValue(data); } } @@ -1349,22 +1349,22 @@ class VectorLineEdit : public Gui::ExpLineEdit { int decimals; public: - VectorLineEdit (int decimals, QWidget * parent=nullptr, bool expressionOnly=false) + explicit VectorLineEdit (int decimals, QWidget * parent=nullptr, bool expressionOnly=false) : Gui::ExpLineEdit(parent, expressionOnly) , decimals(decimals) { } - bool apply(const std::string &propName) { - if (!ExpressionBinding::apply(propName)) { + bool apply(const std::string &propName) override { + if (!ExpressionBinding::apply(propName)) { // clazy:exclude=skipped-base-method QVariant data = property("coords"); if (data.canConvert()) { const Base::Vector3d& value = data.value(); QString str = QString::fromLatin1("(%1, %2, %3)") - .arg(value.x,0,'f',decimals) - .arg(value.y,0,'f',decimals) - .arg(value.z,0,'f',decimals); + .arg(value.x, 0, 'f', decimals) + .arg(value.y, 0, 'f', decimals) + .arg(value.z, 0, 'f', decimals); Gui::Command::doCommand(Gui::Command::Doc, "%s = %s", propName.c_str(), str.toLatin1().constData()); return true; @@ -1554,7 +1554,7 @@ void PropertyEditorWidget::setValue(const QVariant& val) { variant = val; showValue(variant); - valueChanged(variant); + Q_EMIT valueChanged(variant); } // --------------------------------------------------------------- @@ -1643,9 +1643,9 @@ void PropertyVectorListItem::setValue(const QVariant& value) str << "["; for (const auto& it : val) { str << QString::fromLatin1("(%1, %2, %3), ") - .arg(it.x,0,'f',decimals()) - .arg(it.y,0,'f',decimals()) - .arg(it.z,0,'f',decimals()); + .arg(it.x, 0, 'f', decimals()) + .arg(it.y, 0, 'f', decimals()) + .arg(it.z, 0, 'f', decimals()); } str << "]"; setPropertyValue(data); @@ -1724,9 +1724,9 @@ void PropertyVectorDistanceItem::setValue(const QVariant& variant) Base::QuantityFormat format(Base::QuantityFormat::Fixed, decimals()); QString data = QString::fromLatin1("(%1, %2, %3)") - .arg(Base::UnitsApi::toNumber(x, format)) - .arg(Base::UnitsApi::toNumber(y, format)) - .arg(Base::UnitsApi::toNumber(z, format)); + .arg(Base::UnitsApi::toNumber(x, format), + Base::UnitsApi::toNumber(y, format), + Base::UnitsApi::toNumber(z, format)); setPropertyValue(data); } @@ -2374,10 +2374,10 @@ QVariant PropertyRotationItem::toolTip(const App::Property* prop) const QLocale loc; QString data = QString::fromUtf8("Axis: (%1 %2 %3)\n" "Angle: %4") - .arg(loc.toString(dir.x,'f',decimals()), - loc.toString(dir.y,'f',decimals()), - loc.toString(dir.z,'f',decimals()), - Base::Quantity(angle, Base::Unit::Angle).getUserString()); + .arg(loc.toString(dir.x, 'f', decimals()), + loc.toString(dir.y, 'f', decimals()), + loc.toString(dir.z, 'f', decimals()), + Base::Quantity(angle, Base::Unit::Angle).getUserString()); return QVariant(data); } @@ -2391,10 +2391,10 @@ QVariant PropertyRotationItem::toString(const QVariant& prop) const QLocale loc; QString data = QString::fromUtf8("[(%1 %2 %3); %4]") - .arg(loc.toString(dir.x,'f',2), - loc.toString(dir.y,'f',2), - loc.toString(dir.z,'f',2), - Base::Quantity(angle, Base::Unit::Angle).getUserString()); + .arg(loc.toString(dir.x, 'f', 2), + loc.toString(dir.y, 'f', 2), + loc.toString(dir.z, 'f', 2), + Base::Quantity(angle, Base::Unit::Angle).getUserString()); return QVariant(data); } @@ -2412,10 +2412,10 @@ void PropertyRotationItem::setValue(const QVariant& value) h.getValue(axis, angle); Base::QuantityFormat format(Base::QuantityFormat::Fixed, decimals()); QString data = QString::fromLatin1("App.Rotation(App.Vector(%1,%2,%3),%4)") - .arg(Base::UnitsApi::toNumber(axis.x, format)) - .arg(Base::UnitsApi::toNumber(axis.y, format)) - .arg(Base::UnitsApi::toNumber(axis.z, format)) - .arg(Base::UnitsApi::toNumber(angle, format)); + .arg(Base::UnitsApi::toNumber(axis.x, format), + Base::UnitsApi::toNumber(axis.y, format), + Base::UnitsApi::toNumber(axis.z, format), + Base::UnitsApi::toNumber(angle, format)); setPropertyValue(data); } @@ -2498,13 +2498,13 @@ void PlacementEditor::showValue(const QVariant& d) QLocale loc; QString data = QString::fromUtf8("[(%1 %2 %3);%4 \xc2\xb0;(%5 %6 %7)]") - .arg(loc.toString(dir.x,'f',2), - loc.toString(dir.y,'f',2), - loc.toString(dir.z,'f',2), - loc.toString(angle,'f',2), - loc.toString(pos.x,'f',2), - loc.toString(pos.y,'f',2), - loc.toString(pos.z,'f',2)); + .arg(loc.toString(dir.x, 'f', 2), + loc.toString(dir.y, 'f', 2), + loc.toString(dir.z, 'f', 2), + loc.toString(angle, 'f', 2), + loc.toString(pos.x, 'f', 2), + loc.toString(pos.y, 'f', 2), + loc.toString(pos.z, 'f', 2)); getLabel()->setText(data); } @@ -2673,13 +2673,13 @@ QVariant PropertyPlacementItem::toolTip(const App::Property* prop) const QString data = QString::fromUtf8("Axis: (%1 %2 %3)\n" "Angle: %4\n" "Position: (%5 %6 %7)") - .arg(loc.toString(dir.x,'f',decimals()), - loc.toString(dir.y,'f',decimals()), - loc.toString(dir.z,'f',decimals()), - Base::Quantity(angle, Base::Unit::Angle).getUserString(), - Base::Quantity(pos.x, Base::Unit::Length).getUserString(), - Base::Quantity(pos.y, Base::Unit::Length).getUserString(), - Base::Quantity(pos.z, Base::Unit::Length).getUserString()); + .arg(loc.toString(dir.x, 'f', decimals()), + loc.toString(dir.y, 'f', decimals()), + loc.toString(dir.z, 'f', decimals()), + Base::Quantity(angle, Base::Unit::Angle).getUserString(), + Base::Quantity(pos.x, Base::Unit::Length).getUserString(), + Base::Quantity(pos.y, Base::Unit::Length).getUserString(), + Base::Quantity(pos.z, Base::Unit::Length).getUserString()); return QVariant(data); } @@ -2694,13 +2694,13 @@ QVariant PropertyPlacementItem::toString(const QVariant& prop) const QLocale loc; QString data = QString::fromUtf8("[(%1 %2 %3); %4; (%5 %6 %7)]") - .arg(loc.toString(dir.x,'f',2), - loc.toString(dir.y,'f',2), - loc.toString(dir.z,'f',2), - Base::Quantity(angle, Base::Unit::Angle).getUserString(), - Base::Quantity(pos.x, Base::Unit::Length).getUserString(), - Base::Quantity(pos.y, Base::Unit::Length).getUserString(), - Base::Quantity(pos.z, Base::Unit::Length).getUserString()); + .arg(loc.toString(dir.x, 'f', 2), + loc.toString(dir.y, 'f', 2), + loc.toString(dir.z, 'f', 2), + Base::Quantity(angle, Base::Unit::Angle).getUserString(), + Base::Quantity(pos.x, Base::Unit::Length).getUserString(), + Base::Quantity(pos.y, Base::Unit::Length).getUserString(), + Base::Quantity(pos.z, Base::Unit::Length).getUserString()); return QVariant(data); } @@ -2724,13 +2724,13 @@ void PropertyPlacementItem::setValue(const QVariant& value) QString data = QString::fromLatin1("App.Placement(" "App.Vector(%1,%2,%3)," "App.Rotation(App.Vector(%4,%5,%6),%7))") - .arg(Base::UnitsApi::toNumber(pos.x, format)) - .arg(Base::UnitsApi::toNumber(pos.y, format)) - .arg(Base::UnitsApi::toNumber(pos.z, format)) - .arg(Base::UnitsApi::toNumber(axis.x, format)) - .arg(Base::UnitsApi::toNumber(axis.y, format)) - .arg(Base::UnitsApi::toNumber(axis.z, format)) - .arg(Base::UnitsApi::toNumber(angle, format)); + .arg(Base::UnitsApi::toNumber(pos.x, format), + Base::UnitsApi::toNumber(pos.y, format), + Base::UnitsApi::toNumber(pos.z, format), + Base::UnitsApi::toNumber(axis.x, format), + Base::UnitsApi::toNumber(axis.y, format), + Base::UnitsApi::toNumber(axis.z, format), + Base::UnitsApi::toNumber(angle, format)); setPropertyValue(data); } @@ -2856,7 +2856,7 @@ struct EnumItem { QString text; QString fullText; std::shared_ptr children; - EnumItem(const QString &t = QString(), const QString &f = QString()) + explicit EnumItem(const QString &t = QString(), const QString &f = QString()) :text(t), fullText(f) {} void populate(QMenu *menu); @@ -2971,7 +2971,7 @@ QWidget* PropertyEnumItem::createEditor(QWidget* parent, const QObject* receiver }); QObject::connect(menu, &QMenu::triggered, this, [=](QAction *action) { button->setText(action->data().toString()); - button->picked(); + Q_EMIT button->picked(); }); QObject::connect(button, SIGNAL(picked()), receiver, method); return button; @@ -3264,9 +3264,9 @@ void PropertyColorItem::setValue(const QVariant& value) QColor col = value.value(); App::Color val; val.setValue(col); QString data = QString::fromLatin1("(%1,%2,%3)") - .arg(val.r,0,'f',decimals()) - .arg(val.g,0,'f',decimals()) - .arg(val.b,0,'f',decimals()); + .arg(val.r, 0, 'f', decimals()) + .arg(val.g, 0, 'f', decimals()) + .arg(val.b, 0, 'f', decimals()); setPropertyValue(data); } @@ -4339,7 +4339,7 @@ void LinkLabel::updatePropertyLink() linkcolor, DlgPropertyLink::formatObject( owner->getDocument(), sobj.getObject(), sobj.getSubName().c_str())); - } else if (links.size()) { + } else if (!links.empty()) { text = DlgPropertyLink::formatLinks(owner->getDocument(), links); } } @@ -4396,7 +4396,7 @@ PropertyLinkItem::PropertyLinkItem() QVariant PropertyLinkItem::toString(const QVariant& prop) const { QString res; - if(propertyItems.size()) { + if(!propertyItems.empty()) { App::DocumentObjectT owner(propertyItems[0]); res = DlgPropertyLink::formatLinks(owner.getDocument(), qvariant_cast >(prop)); @@ -4405,7 +4405,7 @@ QVariant PropertyLinkItem::toString(const QVariant& prop) const } QVariant PropertyLinkItem::data(int column, int role) const { - if(propertyItems.size() && column == 1 + if(!propertyItems.empty() && column == 1 && (role == Qt::ForegroundRole || role == Qt::ToolTipRole)) { auto propLink = Base::freecad_dynamic_cast(propertyItems[0]); diff --git a/src/Gui/propertyeditor/PropertyItem.h b/src/Gui/propertyeditor/PropertyItem.h index 480d2e6a67..0f2da7cfbe 100644 --- a/src/Gui/propertyeditor/PropertyItem.h +++ b/src/Gui/propertyeditor/PropertyItem.h @@ -98,19 +98,19 @@ private: static PropertyItemFactory* _singleton; PropertyItemFactory(){} - ~PropertyItemFactory(){} + ~PropertyItemFactory() override{} }; template class PropertyItemProducer : public Base::AbstractProducer { public: - PropertyItemProducer(const char* className) { + explicit PropertyItemProducer(const char* className) { PropertyItemFactory::instance().AddProducer(className, this); } - virtual ~PropertyItemProducer() { + ~PropertyItemProducer() override { } - virtual void* Produce () const { + void* Produce () const override { return CLASS::create(); } }; @@ -126,7 +126,7 @@ class GuiExport PropertyItem : public QObject, public ExpressionBinding PROPERTYITEM_HEADER public: - ~PropertyItem(); + ~PropertyItem() override; /** Sets the current property objects. */ void setPropertyData( const std::vector& ); @@ -152,8 +152,8 @@ public: /**override the bind functions to ensure we issue the propertyBound() call, which is then overloaded by childs which like to be informed of a binding*/ - virtual void bind(const App::Property& prop); - virtual void bind(const App::ObjectIdentifier& _path); + void bind(const App::Property& prop) override; + void bind(const App::ObjectIdentifier& _path) override; virtual void propertyBound() {} QString expressionAsString() const; @@ -203,7 +203,7 @@ protected: virtual void initialize(); //gets called when the bound expression is changed - virtual void onChange(); + void onChange() override; protected: QString propName; @@ -228,13 +228,13 @@ class GuiExport PropertyStringItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyStringItem(); @@ -249,13 +249,13 @@ class GuiExport PropertyFontItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyFontItem(); @@ -270,10 +270,10 @@ class GuiExport PropertySeparatorItem : public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - bool isSeparator() const { return true; } - QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; + bool isSeparator() const override { return true; } + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; - virtual int row() const { + int row() const override { return _row<0?PropertyItem::row():_row; } @@ -291,14 +291,14 @@ class GuiExport PropertyIntegerItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyIntegerItem(); @@ -313,14 +313,14 @@ class GuiExport PropertyIntegerConstraintItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyIntegerConstraintItem(); @@ -335,14 +335,14 @@ class GuiExport PropertyFloatItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyFloatItem(); @@ -357,14 +357,14 @@ class GuiExport PropertyUnitItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; PropertyUnitItem(); }; @@ -378,7 +378,7 @@ class GuiExport PropertyUnitConstraintItem: public PropertyUnitItem Q_OBJECT PROPERTYITEM_HEADER - virtual void setEditorData(QWidget *editor, const QVariant& data) const; + void setEditorData(QWidget *editor, const QVariant& data) const override; protected: PropertyUnitConstraintItem(); @@ -393,14 +393,14 @@ class GuiExport PropertyFloatConstraintItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyFloatConstraintItem(); @@ -427,8 +427,8 @@ class GuiExport PropertyAngleItem : public PropertyUnitConstraintItem PROPERTYITEM_HEADER protected: - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant toString(const QVariant&) const; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant toString(const QVariant&) const override; protected: PropertyAngleItem(); @@ -443,13 +443,13 @@ class GuiExport PropertyBoolItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyBoolItem(); @@ -463,14 +463,14 @@ class PropertyFloatItem; class GuiExport PropertyVectorItem: public PropertyItem { Q_OBJECT - Q_PROPERTY(double x READ x WRITE setX DESIGNABLE true USER true) - Q_PROPERTY(double y READ y WRITE setY DESIGNABLE true USER true) - Q_PROPERTY(double z READ z WRITE setZ DESIGNABLE true USER true) + Q_PROPERTY(double x READ x WRITE setX DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double y READ y WRITE setY DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double z READ z WRITE setZ DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; double x() const; void setX(double x); @@ -480,13 +480,13 @@ class GuiExport PropertyVectorItem: public PropertyItem void setZ(double z); protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyVectorItem(); - virtual void propertyBound(); + void propertyBound() override; private: PropertyFloatItem* m_x; @@ -499,8 +499,8 @@ class PropertyEditorWidget : public QWidget Q_OBJECT public: - PropertyEditorWidget (QWidget * parent = nullptr); - virtual ~PropertyEditorWidget(); + explicit PropertyEditorWidget (QWidget * parent = nullptr); + ~PropertyEditorWidget() override; QVariant value() const; @@ -509,7 +509,7 @@ public Q_SLOTS: protected: virtual void showValue(const QVariant& data); - void resizeEvent(QResizeEvent*); + void resizeEvent(QResizeEvent*) override; Q_SIGNALS: void buttonClick(); @@ -526,10 +526,10 @@ class VectorListWidget : public PropertyEditorWidget Q_OBJECT public: - VectorListWidget (int decimals, QWidget * parent = nullptr); + explicit VectorListWidget (int decimals, QWidget * parent = nullptr); protected: - virtual void showValue(const QVariant& data) override; + void showValue(const QVariant& data) override; private Q_SLOTS: void buttonClicked(); @@ -547,14 +547,14 @@ class GuiExport PropertyVectorListItem : public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyVectorListItem(); @@ -568,16 +568,16 @@ class PropertyUnitItem; class GuiExport PropertyVectorDistanceItem: public PropertyItem { Q_OBJECT - Q_PROPERTY(Base::Quantity x READ x WRITE setX DESIGNABLE true USER true) - Q_PROPERTY(Base::Quantity y READ y WRITE setY DESIGNABLE true USER true) - Q_PROPERTY(Base::Quantity z READ z WRITE setZ DESIGNABLE true USER true) + Q_PROPERTY(Base::Quantity x READ x WRITE setX DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(Base::Quantity y READ y WRITE setY DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(Base::Quantity z READ z WRITE setZ DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; - virtual void propertyBound(); + void propertyBound() override; Base::Quantity x() const; void setX(Base::Quantity x); @@ -587,9 +587,9 @@ class GuiExport PropertyVectorDistanceItem: public PropertyItem void setZ(Base::Quantity z); protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; PropertyVectorDistanceItem(); @@ -615,27 +615,27 @@ class GuiExport PropertyDirectionItem: public PropertyVectorDistanceItem class GuiExport PropertyMatrixItem: public PropertyItem { Q_OBJECT - Q_PROPERTY(double A11 READ getA11 WRITE setA11 DESIGNABLE true USER true) - Q_PROPERTY(double A12 READ getA12 WRITE setA12 DESIGNABLE true USER true) - Q_PROPERTY(double A13 READ getA13 WRITE setA13 DESIGNABLE true USER true) - Q_PROPERTY(double A14 READ getA14 WRITE setA14 DESIGNABLE true USER true) - Q_PROPERTY(double A21 READ getA21 WRITE setA21 DESIGNABLE true USER true) - Q_PROPERTY(double A22 READ getA22 WRITE setA22 DESIGNABLE true USER true) - Q_PROPERTY(double A23 READ getA23 WRITE setA23 DESIGNABLE true USER true) - Q_PROPERTY(double A24 READ getA24 WRITE setA24 DESIGNABLE true USER true) - Q_PROPERTY(double A31 READ getA31 WRITE setA31 DESIGNABLE true USER true) - Q_PROPERTY(double A32 READ getA32 WRITE setA32 DESIGNABLE true USER true) - Q_PROPERTY(double A33 READ getA33 WRITE setA33 DESIGNABLE true USER true) - Q_PROPERTY(double A34 READ getA34 WRITE setA34 DESIGNABLE true USER true) - Q_PROPERTY(double A41 READ getA41 WRITE setA41 DESIGNABLE true USER true) - Q_PROPERTY(double A42 READ getA42 WRITE setA42 DESIGNABLE true USER true) - Q_PROPERTY(double A43 READ getA43 WRITE setA43 DESIGNABLE true USER true) - Q_PROPERTY(double A44 READ getA44 WRITE setA44 DESIGNABLE true USER true) + Q_PROPERTY(double A11 READ getA11 WRITE setA11 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A12 READ getA12 WRITE setA12 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A13 READ getA13 WRITE setA13 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A14 READ getA14 WRITE setA14 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A21 READ getA21 WRITE setA21 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A22 READ getA22 WRITE setA22 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A23 READ getA23 WRITE setA23 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A24 READ getA24 WRITE setA24 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A31 READ getA31 WRITE setA31 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A32 READ getA32 WRITE setA32 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A33 READ getA33 WRITE setA33 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A34 READ getA34 WRITE setA34 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A41 READ getA41 WRITE setA41 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A42 READ getA42 WRITE setA42 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A43 READ getA43 WRITE setA43 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(double A44 READ getA44 WRITE setA44 DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; double getA11() const; void setA11(double A11); @@ -671,13 +671,13 @@ class GuiExport PropertyMatrixItem: public PropertyItem void setA44(double A44); protected: - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyMatrixItem(); - virtual QVariant toolTip(const App::Property*) const; + QVariant toolTip(const App::Property*) const override; private: PropertyFloatItem* m_a11; @@ -727,16 +727,16 @@ private: class GuiExport PropertyRotationItem: public PropertyItem { Q_OBJECT - Q_PROPERTY(Base::Quantity Angle READ getAngle WRITE setAngle DESIGNABLE true USER true) - Q_PROPERTY(Base::Vector3d Axis READ getAxis WRITE setAxis DESIGNABLE true USER true) + Q_PROPERTY(Base::Quantity Angle READ getAngle WRITE setAngle DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(Base::Vector3d Axis READ getAxis WRITE setAxis DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; - virtual void propertyBound(); - virtual void assignProperty(const App::Property*); + void propertyBound() override; + void assignProperty(const App::Property*) override; Base::Quantity getAngle() const; void setAngle(Base::Quantity); @@ -745,11 +745,11 @@ class GuiExport PropertyRotationItem: public PropertyItem protected: PropertyRotationItem(); - ~PropertyRotationItem(); - virtual QVariant toolTip(const App::Property*) const; - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + ~PropertyRotationItem() override; + QVariant toolTip(const App::Property*) const override; + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; private: mutable RotationHelper h; @@ -762,15 +762,15 @@ class PlacementEditor : public Gui::LabelButton Q_OBJECT public: - PlacementEditor(const QString& name, QWidget * parent = nullptr); - ~PlacementEditor(); + explicit PlacementEditor(const QString& name, QWidget * parent = nullptr); + ~PlacementEditor() override; private Q_SLOTS: void updateValue(const QVariant& v, bool, bool); private: - void browse(); - void showValue(const QVariant& d); + void browse() override; + void showValue(const QVariant& d) override; private: QPointer _task; @@ -784,17 +784,17 @@ private: class GuiExport PropertyPlacementItem: public PropertyItem { Q_OBJECT - Q_PROPERTY(Base::Quantity Angle READ getAngle WRITE setAngle DESIGNABLE true USER true) - Q_PROPERTY(Base::Vector3d Axis READ getAxis WRITE setAxis DESIGNABLE true USER true) - Q_PROPERTY(Base::Vector3d Position READ getPosition WRITE setPosition DESIGNABLE true USER true) + Q_PROPERTY(Base::Quantity Angle READ getAngle WRITE setAngle DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(Base::Vector3d Axis READ getAxis WRITE setAxis DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(Base::Vector3d Position READ getPosition WRITE setPosition DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; - virtual void propertyBound(); - virtual void assignProperty(const App::Property*); + void propertyBound() override; + void assignProperty(const App::Property*) override; Base::Quantity getAngle() const; void setAngle(Base::Quantity); @@ -805,11 +805,11 @@ class GuiExport PropertyPlacementItem: public PropertyItem protected: PropertyPlacementItem(); - ~PropertyPlacementItem(); - virtual QVariant toolTip(const App::Property*) const; - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + ~PropertyPlacementItem() override; + QVariant toolTip(const App::Property*) const override; + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; private: mutable RotationHelper h; @@ -827,20 +827,20 @@ class PropertyStringListItem; class GuiExport PropertyEnumItem: public PropertyItem { Q_OBJECT - Q_PROPERTY(QStringList Enum READ getEnum WRITE setEnum DESIGNABLE true USER true) + Q_PROPERTY(QStringList Enum READ getEnum WRITE setEnum DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; QStringList getEnum() const; void setEnum(QStringList); protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); - virtual void propertyBound(); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; + void propertyBound() override; protected: PropertyEnumItem(); @@ -853,7 +853,7 @@ class PropertyEnumButton : public QPushButton { Q_OBJECT public: - PropertyEnumButton(QWidget *parent = nullptr) + explicit PropertyEnumButton(QWidget *parent = nullptr) :QPushButton(parent) {} @@ -870,14 +870,14 @@ class GuiExport PropertyStringListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyStringListItem(); @@ -892,14 +892,14 @@ class GuiExport PropertyFloatListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyFloatListItem(); @@ -914,14 +914,14 @@ class GuiExport PropertyIntegerListItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyIntegerListItem(); @@ -936,15 +936,15 @@ class GuiExport PropertyColorItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant decoration(const QVariant&) const; - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant decoration(const QVariant&) const override; + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyColorItem(); @@ -957,19 +957,19 @@ protected: class GuiExport PropertyMaterialItem : public PropertyItem { Q_OBJECT - Q_PROPERTY(QColor AmbientColor READ getAmbientColor WRITE setAmbientColor DESIGNABLE true USER true) - Q_PROPERTY(QColor DiffuseColor READ getDiffuseColor WRITE setDiffuseColor DESIGNABLE true USER true) - Q_PROPERTY(QColor SpecularColor READ getSpecularColor WRITE setSpecularColor DESIGNABLE true USER true) - Q_PROPERTY(QColor EmissiveColor READ getEmissiveColor WRITE setEmissiveColor DESIGNABLE true USER true) - Q_PROPERTY(float Shininess READ getShininess WRITE setShininess DESIGNABLE true USER true) - Q_PROPERTY(float Transparency READ getTransparency WRITE setTransparency DESIGNABLE true USER true) + Q_PROPERTY(QColor AmbientColor READ getAmbientColor WRITE setAmbientColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor DiffuseColor READ getDiffuseColor WRITE setDiffuseColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor SpecularColor READ getSpecularColor WRITE setSpecularColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor EmissiveColor READ getEmissiveColor WRITE setEmissiveColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(float Shininess READ getShininess WRITE setShininess DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(float Transparency READ getTransparency WRITE setTransparency DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; - virtual void propertyBound(); + void propertyBound() override; QColor getAmbientColor() const; void setAmbientColor(const QColor&); @@ -986,13 +986,13 @@ class GuiExport PropertyMaterialItem : public PropertyItem protected: PropertyMaterialItem(); - virtual ~PropertyMaterialItem(); + ~PropertyMaterialItem() override; - virtual QVariant decoration(const QVariant&) const; - virtual QVariant toolTip(const App::Property*) const; - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant decoration(const QVariant&) const override; + QVariant toolTip(const App::Property*) const override; + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; private: PropertyColorItem* ambient; @@ -1006,19 +1006,19 @@ private: class GuiExport PropertyMaterialListItem : public PropertyItem { Q_OBJECT - Q_PROPERTY(QColor AmbientColor READ getAmbientColor WRITE setAmbientColor DESIGNABLE true USER true) - Q_PROPERTY(QColor DiffuseColor READ getDiffuseColor WRITE setDiffuseColor DESIGNABLE true USER true) - Q_PROPERTY(QColor SpecularColor READ getSpecularColor WRITE setSpecularColor DESIGNABLE true USER true) - Q_PROPERTY(QColor EmissiveColor READ getEmissiveColor WRITE setEmissiveColor DESIGNABLE true USER true) - Q_PROPERTY(float Shininess READ getShininess WRITE setShininess DESIGNABLE true USER true) - Q_PROPERTY(float Transparency READ getTransparency WRITE setTransparency DESIGNABLE true USER true) + Q_PROPERTY(QColor AmbientColor READ getAmbientColor WRITE setAmbientColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor DiffuseColor READ getDiffuseColor WRITE setDiffuseColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor SpecularColor READ getSpecularColor WRITE setSpecularColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(QColor EmissiveColor READ getEmissiveColor WRITE setEmissiveColor DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(float Shininess READ getShininess WRITE setShininess DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify + Q_PROPERTY(float Transparency READ getTransparency WRITE setTransparency DESIGNABLE true USER true) // clazy:exclude=qproperty-without-notify PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; - virtual void propertyBound(); + void propertyBound() override; QColor getAmbientColor() const; void setAmbientColor(const QColor&); @@ -1035,13 +1035,13 @@ class GuiExport PropertyMaterialListItem : public PropertyItem protected: PropertyMaterialListItem(); - virtual ~PropertyMaterialListItem(); + ~PropertyMaterialListItem() override; - virtual QVariant decoration(const QVariant&) const; - virtual QVariant toolTip(const App::Property*) const; - virtual QVariant toString(const QVariant&) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant decoration(const QVariant&) const override; + QVariant toolTip(const App::Property*) const override; + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; private: PropertyColorItem* ambient; @@ -1061,17 +1061,17 @@ class GuiExport PropertyFileItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyFileItem(); - virtual QVariant toolTip(const App::Property*) const; + QVariant toolTip(const App::Property*) const override; }; /** @@ -1083,17 +1083,17 @@ class GuiExport PropertyPathItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyPathItem(); - virtual QVariant toolTip(const App::Property*) const; + QVariant toolTip(const App::Property*) const override; }; /** @@ -1105,17 +1105,17 @@ class GuiExport PropertyTransientFileItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyTransientFileItem(); - virtual QVariant toolTip(const App::Property*) const; + QVariant toolTip(const App::Property*) const override; }; class LinkSelection : public QObject @@ -1123,8 +1123,8 @@ class LinkSelection : public QObject Q_OBJECT public: - LinkSelection(const App::SubObjectT &); - ~LinkSelection(); + explicit LinkSelection(const App::SubObjectT &); + ~LinkSelection() override; public Q_SLOTS: void select(); @@ -1140,12 +1140,12 @@ class LinkLabel : public QWidget public: LinkLabel (QWidget * parent, const App::Property *prop); - virtual ~LinkLabel(); + ~LinkLabel() override; void updatePropertyLink(); QVariant propertyLink() const; protected: - void resizeEvent(QResizeEvent*); + void resizeEvent(QResizeEvent*) override; protected Q_SLOTS: void onLinkActivated(const QString&); @@ -1173,15 +1173,15 @@ class GuiExport PropertyLinkItem: public PropertyItem Q_OBJECT PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; - virtual void setEditorData(QWidget *editor, const QVariant& data) const override; - virtual QVariant editorData(QWidget *editor) const override; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; protected: - virtual QVariant toString(const QVariant&) const override; - virtual QVariant value(const App::Property*) const override; - virtual void setValue(const QVariant&) override; - virtual QVariant data(int column, int role) const override; + QVariant toString(const QVariant&) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; + QVariant data(int column, int role) const override; protected: PropertyLinkItem(); @@ -1204,10 +1204,10 @@ class PropertyItemEditorFactory : public QItemEditorFactory { public: PropertyItemEditorFactory(); - virtual ~PropertyItemEditorFactory(); + ~PropertyItemEditorFactory() override; - virtual QWidget *createEditor(int userType, QWidget *parent) const; - virtual QByteArray valuePropertyName(int userType) const; + QWidget *createEditor(int userType, QWidget *parent) const override; + QByteArray valuePropertyName(int userType) const override; }; } // namespace PropertyEditor diff --git a/src/Gui/propertyeditor/PropertyItemDelegate.cpp b/src/Gui/propertyeditor/PropertyItemDelegate.cpp index f0288c3972..41539dbae2 100644 --- a/src/Gui/propertyeditor/PropertyItemDelegate.cpp +++ b/src/Gui/propertyeditor/PropertyItemDelegate.cpp @@ -130,38 +130,13 @@ bool PropertyItemDelegate::eventFilter(QObject *o, QEvent *ev) PropertyEditor *parentEditor = qobject_cast(this->parent()); auto widget = qobject_cast(o); if (widget && parentEditor && parentEditor->activeEditor - && widget != parentEditor->activeEditor) - { -#if 1 + && widget != parentEditor->activeEditor) { // All the attempts to ignore the focus-out event has been approved to not work // reliably because there are still cases that cannot be handled. // So, the best for now is to always ignore this event. // See https://forum.freecadweb.org/viewtopic.php?p=579530#p579530 why this is not // possible. return false; -#else - // We event filter child QAbstractButton and QLabel of an editor, - // which requires special focus change in order to not mess up with - // QItemDelegate's logic. - QWidget *w = QApplication::focusWidget(); - // For some reason, Qt (5.15) on Windows will remove current focus - // before bringing up a modal dialog. - if (!w) - return false; - while (w) { // don't worry about focus changes internally in the editor - if (w == widget || w == parentEditor->activeEditor) - return false; - - // ignore focus change to 3D view or tree view, because, for - // example DlgPropertyLink is implemented as modeless dialog - // to allow selection in 3D and tree view. - if (qobject_cast(w)) - return false; - if (qobject_cast(w)) - return false; - w = w->parentWidget(); - } -#endif } } return QItemDelegate::eventFilter(o, ev); @@ -218,7 +193,8 @@ QWidget * PropertyItemDelegate::createEditor (QWidget * parent, const QStyleOpti this->pressed = false; if (editor) { - for (auto w : editor->findChildren()) { + const auto widgets = editor->findChildren(); + for (auto w : widgets) { if (qobject_cast(w) || qobject_cast(w)) { diff --git a/src/Gui/propertyeditor/PropertyItemDelegate.h b/src/Gui/propertyeditor/PropertyItemDelegate.h index 1b543902b7..f5db047406 100644 --- a/src/Gui/propertyeditor/PropertyItemDelegate.h +++ b/src/Gui/propertyeditor/PropertyItemDelegate.h @@ -36,18 +36,18 @@ class PropertyItemDelegate : public QItemDelegate Q_OBJECT public: - PropertyItemDelegate(QObject* parent); - ~PropertyItemDelegate(); + explicit PropertyItemDelegate(QObject* parent); + ~PropertyItemDelegate() override; - virtual void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const; - virtual QWidget * createEditor (QWidget *, const QStyleOptionViewItem&, const QModelIndex&) const; - virtual void setEditorData(QWidget *editor, const QModelIndex &index) const; - virtual void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex& index ) const; - virtual QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const; - virtual bool editorEvent (QEvent *event, QAbstractItemModel *model, - const QStyleOptionViewItem& option, const QModelIndex& index); + void paint(QPainter *painter, const QStyleOptionViewItem &opt, const QModelIndex &index) const override; + QWidget * createEditor (QWidget *, const QStyleOptionViewItem&, const QModelIndex&) const override; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; + void setModelData (QWidget *editor, QAbstractItemModel *model, const QModelIndex& index ) const override; + QSize sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const override; + bool editorEvent (QEvent *event, QAbstractItemModel *model, + const QStyleOptionViewItem& option, const QModelIndex& index) override; protected: - bool eventFilter(QObject *, QEvent *); + bool eventFilter(QObject *, QEvent *) override; public Q_SLOTS: void valueChanged(); diff --git a/src/Gui/propertyeditor/PropertyModel.cpp b/src/Gui/propertyeditor/PropertyModel.cpp index 1b6e837b04..3bbc507617 100644 --- a/src/Gui/propertyeditor/PropertyModel.cpp +++ b/src/Gui/propertyeditor/PropertyModel.cpp @@ -493,15 +493,6 @@ void PropertyModel::updateChildren(PropertyItem* item, int column, const QModelI QModelIndex topLeft = this->index(0, column, parent); QModelIndex bottomRight = this->index(numChild, column, parent); Q_EMIT dataChanged(topLeft, bottomRight); -#if 0 // It seems we don't have to inform grand children - for (int row=0; rowchild(row); - QModelIndex data = this->index(row, column, parent); - if (data.isValid()) { - updateChildren(child, column, data); - } - } -#endif } } diff --git a/src/Gui/propertyeditor/PropertyModel.h b/src/Gui/propertyeditor/PropertyModel.h index 37d06d2596..f23ef9d57a 100644 --- a/src/Gui/propertyeditor/PropertyModel.h +++ b/src/Gui/propertyeditor/PropertyModel.h @@ -46,21 +46,21 @@ public: typedef std::vector< std::pair< std::string, std::vector > > PropertyList; PropertyModel(QObject* parent); - virtual ~PropertyModel(); + ~PropertyModel() override; - QModelIndex buddy (const QModelIndex & index) const; - int columnCount (const QModelIndex & parent = QModelIndex()) const; - QVariant data (const QModelIndex & index, int role = Qt::DisplayRole) const; - bool setData (const QModelIndex & idx, const QVariant & value, int role); - Qt::ItemFlags flags(const QModelIndex &index) const; - QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex()) const; - QModelIndex parent (const QModelIndex & index) const; - int rowCount (const QModelIndex & parent = QModelIndex()) const; - QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; - bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole); + QModelIndex buddy (const QModelIndex & index) const override; + int columnCount (const QModelIndex & parent = QModelIndex()) const override; + QVariant data (const QModelIndex & index, int role = Qt::DisplayRole) const override; + bool setData (const QModelIndex & idx, const QVariant & value, int role) override; + Qt::ItemFlags flags(const QModelIndex &index) const override; + QModelIndex index (int row, int column, const QModelIndex & parent = QModelIndex()) const override; + QModelIndex parent (const QModelIndex & index) const override; + int rowCount (const QModelIndex & parent = QModelIndex()) const override; + QVariant headerData (int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; + bool setHeaderData (int section, Qt::Orientation orientation, const QVariant & value, int role = Qt::EditRole) override; void buildUp(const PropertyList& props); - bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()); + bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()) override; void updateProperty(const App::Property&); void appendProperty(const App::Property&); diff --git a/src/Gui/resource.cpp b/src/Gui/resource.cpp index 45bdb4bb2e..ac2b8ae313 100644 --- a/src/Gui/resource.cpp +++ b/src/Gui/resource.cpp @@ -40,7 +40,6 @@ #include "DlgSettingsMacroImp.h" #include "DlgSettingsUnitsImp.h" #include "DlgSettingsDocumentImp.h" -//#include "DlgOnlineHelpImp.h" #include "DlgReportViewImp.h" #include "DlgSettingsLazyLoadedImp.h" @@ -68,7 +67,6 @@ WidgetFactorySupplier::WidgetFactorySupplier() // // new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","General") ); - //new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","General") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","General") ); new PrefPageProducer ( QT_TRANSLATE_NOOP("QObject","General") ); new PrefPageProducer( QT_TRANSLATE_NOOP("QObject","General") ); @@ -89,7 +87,6 @@ WidgetFactorySupplier::WidgetFactorySupplier() new CustomPageProducer; new CustomPageProducer; new CustomPageProducer; - //new CustomPageProducer; new CustomPageProducer; new CustomPageProducer; new CustomPageProducer; diff --git a/src/Mod/AddonManager/Addon.py b/src/Mod/AddonManager/Addon.py index 6a69dbe0ec..1393adc91a 100644 --- a/src/Mod/AddonManager/Addon.py +++ b/src/Mod/AddonManager/Addon.py @@ -20,15 +20,19 @@ # * * # *************************************************************************** -import FreeCAD +""" Defines the Addon class to encapsulate information about FreeCAD Addons """ import os from urllib.parse import urlparse from typing import Dict, Set from threading import Lock +from enum import IntEnum + +import FreeCAD from addonmanager_macro import Macro import addonmanager_utilities as utils +from addonmanager_utilities import construct_git_url translate = FreeCAD.Qt.translate @@ -51,11 +55,11 @@ INTERNAL_WORKBENCHES["techdraw"] = "TechDraw" class Addon: - "Encapsulate information about a FreeCAD addon" - - from enum import IntEnum + """Encapsulates information about a FreeCAD addon""" class Kind(IntEnum): + """The type of Addon: Workbench, macro, or package""" + WORKBENCH = 1 MACRO = 2 PACKAGE = 3 @@ -63,12 +67,15 @@ class Addon: def __str__(self) -> str: if self.value == 1: return "Workbench" - elif self.value == 2: + if self.value == 2: return "Macro" - elif self.value == 3: + if self.value == 3: return "Package" + return "ERROR_TYPE" class Status(IntEnum): + """The installation status of an Addon""" + NOT_INSTALLED = 0 UNCHECKED = 1 NO_UPDATE_AVAILABLE = 2 @@ -82,20 +89,26 @@ class Addon: return NotImplemented def __str__(self) -> str: + result = "" if self.value == 0: - return "Not installed" + result = "Not installed" elif self.value == 1: - return "Unchecked" + result = "Unchecked" elif self.value == 2: - return "No update available" + result = "No update available" elif self.value == 3: - return "Update available" + result = "Update available" elif self.value == 4: - return "Restart required" + result = "Restart required" elif self.value == 5: - return "Can't check" + result = "Can't check" + else: + result = "ERROR_STATUS" + return result class Dependencies: + """Addon dependency information""" + def __init__(self): self.required_external_addons = [] # A list of Addons self.blockers = [] # A list of Addons @@ -105,8 +118,13 @@ class Addon: self.python_optional: Set[str] = set() class ResolutionFailed(RuntimeError): - def __init__(self, msg): - super().__init__(msg) + """An exception type for dependency resolution failure.""" + + # The location of Addon Manager cache files: overridden by testing code + cache_directory = os.path.join(FreeCAD.getUserCachePath(), "AddonManager") + + # The location of the Mod directory: overridden by testing code + mod_directory = os.path.join(FreeCAD.getUserAppDataDir(), "Mod") def __init__(self, name: str, url: str, status: Status, branch: str): self.name = name.strip() @@ -127,8 +145,6 @@ class Addon: self.status_lock = Lock() self.set_status(status) - from addonmanager_utilities import construct_git_url - # The url should never end in ".git", so strip it if it's there parsed_url = urlparse(self.url) if parsed_url.path.endswith(".git"): @@ -172,7 +188,9 @@ class Addon: return result @classmethod - def from_macro(self, macro: Macro): + def from_macro(cls, macro: Macro): + """Create an Addon object from a Macro wrapper object""" + if macro.is_installed(): status = Addon.Status.UNCHECKED else: @@ -184,10 +202,10 @@ class Addon: return instance @classmethod - def from_cache(self, cache_dict: Dict): + def from_cache(cls, cache_dict: Dict): """Load basic data from cached dict data. Does not include Macro or Metadata information, which must be populated separately.""" - mod_dir = os.path.join(FreeCAD.getUserAppDataDir(), "Mod", cache_dict["name"]) + mod_dir = os.path.join(cls.mod_directory, cache_dict["name"]) if os.path.isdir(mod_dir): status = Addon.Status.UNCHECKED else: @@ -203,8 +221,7 @@ class Addon: if instance.repo_type == Addon.Kind.PACKAGE: # There must be a cached metadata file, too cached_package_xml_file = os.path.join( - FreeCAD.getUserCachePath(), - "AddonManager", + instance.cache_directory, "PackageMetadata", instance.name, ) @@ -240,13 +257,18 @@ class Addon: } def load_metadata_file(self, file: str) -> None: + """Read a given metadata file and set it as this object's metadata""" + if os.path.exists(file): metadata = FreeCAD.Metadata(file) self.set_metadata(metadata) else: - FreeCAD.Console.PrintLog("Internal error: {} does not exist".format(file)) + FreeCAD.Console.PrintLog(f"Internal error: {file} does not exist") def set_metadata(self, metadata: FreeCAD.Metadata) -> None: + """Set the given metadata object as this object's metadata, updating the object's display name + and package type information to match, as well as updating any dependency information, etc.""" + self.metadata = metadata self.display_name = metadata.Name self.repo_type = Addon.Kind.PACKAGE @@ -262,6 +284,9 @@ class Addon: self.extract_metadata_dependencies(self.metadata) def version_is_ok(self, metadata) -> bool: + """Checks to see if the current running version of FreeCAD meets the requirements set by + the passed-in metadata parameter.""" + dep_fc_min = metadata.FreeCADMin dep_fc_max = metadata.FreeCADMax @@ -273,7 +298,7 @@ class Addon: required_version = dep_fc_min.split(".") if fc_major < int(required_version[0]): return False # Major version is too low - elif fc_major == int(required_version[0]): + if fc_major == int(required_version[0]): if len(required_version) > 1 and fc_minor < int( required_version[1] ): @@ -288,7 +313,7 @@ class Addon: required_version = dep_fc_max.split(".") if fc_major > int(required_version[0]): return False # Major version is too high - elif fc_major == int(required_version[0]): + if fc_major == int(required_version[0]): if len(required_version) > 1 and fc_minor > int( required_version[1] ): @@ -301,6 +326,7 @@ class Addon: return True def extract_metadata_dependencies(self, metadata): + """Read dependency information from a metadata object and store it in this Addon""" # Version check: if this piece of metadata doesn't apply to this version of # FreeCAD, just skip it. @@ -345,6 +371,7 @@ class Addon: ) def extract_tags(self, metadata: FreeCAD.Metadata) -> None: + """Read the tags from the metadata object""" # Version check: if this piece of metadata doesn't apply to this version of # FreeCAD, just skip it. @@ -355,7 +382,7 @@ class Addon: self.tags.add(new_tag) content = metadata.Content - for key, value in content.items(): + for _, value in content.items(): for item in value: self.extract_tags(item) @@ -364,7 +391,7 @@ class Addon: if self.repo_type == Addon.Kind.WORKBENCH: return True - elif self.repo_type == Addon.Kind.PACKAGE: + if self.repo_type == Addon.Kind.PACKAGE: if self.metadata is None: FreeCAD.Console.PrintLog( f"Addon Manager internal error: lost metadata for package {self.name}\n" @@ -377,15 +404,14 @@ class Addon: ) return False return "workbench" in content - else: - return False + return False def contains_macro(self) -> bool: """Determine if this package contains (or is) a macro""" if self.repo_type == Addon.Kind.MACRO: return True - elif self.repo_type == Addon.Kind.PACKAGE: + if self.repo_type == Addon.Kind.PACKAGE: if self.metadata is None: FreeCAD.Console.PrintLog( f"Addon Manager internal error: lost metadata for package {self.name}\n" @@ -393,8 +419,7 @@ class Addon: return False content = self.metadata.Content return "macro" in content - else: - return False + return False def contains_preference_pack(self) -> bool: """Determine if this package contains a preference pack""" @@ -407,8 +432,7 @@ class Addon: return False content = self.metadata.Content return "preferencepack" in content - else: - return False + return False def get_cached_icon_filename(self) -> str: """Get the filename for the locally-cached copy of the icon""" @@ -438,9 +462,7 @@ class Addon: ) # Required path separator in the metadata.xml file to local separator _, file_extension = os.path.splitext(real_icon) - store = os.path.join( - FreeCAD.getUserCachePath(), "AddonManager", "PackageMetadata" - ) + store = os.path.join(self.cache_directory, "PackageMetadata") self.cached_icon_filename = os.path.join( store, self.name, "cached_icon" + file_extension ) @@ -481,37 +503,35 @@ class Addon: deps.blockers[dep] = all_repos[dep] def status(self): + """Threadsafe access to the current update status""" with self.status_lock: return self.update_status def set_status(self, status): + """Threadsafe setting of the update status""" with self.status_lock: self.update_status = status def is_disabled(self): - # Check for existence of disabling stopfile: - stopfile = os.path.join( - FreeCAD.getUserAppDataDir(), "Mod", self.name, "ADDON_DISABLED" - ) - if os.path.exists(stopfile): - return True - else: - return False + """Check to see if the disabling stopfile exists""" + + stopfile = os.path.join(self.mod_directory, self.name, "ADDON_DISABLED") + return os.path.exists(stopfile) def disable(self): - stopfile = os.path.join( - FreeCAD.getUserAppDataDir(), "Mod", self.name, "ADDON_DISABLED" - ) - with open(stopfile, "w") as f: + """Disable this addon from loading when FreeCAD starts up by creating a stopfile""" + + stopfile = os.path.join(mod_directory, self.name, "ADDON_DISABLED") + with open(stopfile, "w", encoding="utf-8") as f: f.write( "The existence of this file prevents FreeCAD from loading this Addon. To re-enable, delete the file." ) def enable(self): - stopfile = os.path.join( - FreeCAD.getUserAppDataDir(), "Mod", self.name, "ADDON_DISABLED" - ) + """Re-enable loading this addon by deleting the stopfile""" + + stopfile = os.path.join(self.mod_directory, self.name, "ADDON_DISABLED") try: os.unlink(stopfile) - except Exception: + except FileNotFoundError: pass diff --git a/src/Mod/AddonManager/AddonManager.py b/src/Mod/AddonManager/AddonManager.py index 7732042f72..5b50968101 100644 --- a/src/Mod/AddonManager/AddonManager.py +++ b/src/Mod/AddonManager/AddonManager.py @@ -25,17 +25,36 @@ # *************************************************************************** import os +import functools import shutil import stat import tempfile import hashlib +import threading +import json from datetime import date, timedelta from typing import Dict, List from PySide2 import QtGui, QtCore, QtWidgets +import FreeCAD import FreeCADGui -from addonmanager_workers import * +from addonmanager_workers_startup import ( + CreateAddonListWorker, + LoadPackagesFromCacheWorker, + LoadMacrosFromCacheWorker, + CheckWorkbenchesForUpdatesWorker, + CacheMacroCodeWorker, + GetMacroDetailsWorker, +) +from addonmanager_workers_installation import ( + InstallWorkbenchWorker, + DependencyInstallationWorker, + UpdateMetadataCacheWorker, + UpdateAllWorker, + UpdateSingleWorker, +) +from addonmanager_workers_utility import ConnectionChecker import addonmanager_utilities as utils import AddonManager_rc from package_list import PackageList, PackageListItemModel @@ -45,8 +64,13 @@ from install_to_toolbar import ( ask_to_install_toolbar_button, remove_custom_toolbar_button, ) +from manage_python_dependencies import ( + check_for_python_package_updates, + CheckForPythonPackageUpdatesWorker, + PythonPackageManager, +) -from NetworkManager import HAVE_QTNETWORK, InitializeNetworkManager +import NetworkManager translate = FreeCAD.Qt.translate @@ -77,6 +101,7 @@ installed. def QT_TRANSLATE_NOOP(ctx, txt): return txt + ADDON_MANAGER_DEVELOPER_MODE = False @@ -85,7 +110,7 @@ class CommandAddonManager: workers = [ "connection_checker", - "update_worker", + "create_addon_list_worker", "check_worker", "show_worker", "showmacro_worker", @@ -95,6 +120,7 @@ class CommandAddonManager: "load_macro_metadata_worker", "update_all_worker", "dependency_installation_worker", + "check_for_python_package_updates_worker", ] lock = threading.Lock() @@ -103,7 +129,7 @@ class CommandAddonManager: def __init__(self): FreeCADGui.addPreferencePage( os.path.join(os.path.dirname(__file__), "AddonManagerOptions.ui"), - translate("AddonsInstaller","Addon Manager"), + translate("AddonsInstaller", "Addon Manager"), ) self.allowed_packages = set() @@ -125,6 +151,12 @@ class CommandAddonManager: + "\n" ) + # Silence some pylint errors: + self.check_worker = None + self.check_for_python_package_updates_worker = None + self.install_worker = None + self.update_all_worker = None + def GetResources(self) -> Dict[str, str]: return { "Pixmap": "AddonManager", @@ -138,7 +170,7 @@ class CommandAddonManager: def Activated(self) -> None: - InitializeNetworkManager() + NetworkManager.InitializeNetworkManager() # display first use dialog if needed pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") @@ -325,6 +357,9 @@ class CommandAddonManager: translate("AddonsInstaller", "Starting up...") ) + # Only shown if there are available Python package updates + self.dialog.buttonUpdateDependencies.hide() + # connect slots self.dialog.rejected.connect(self.reject) self.dialog.buttonUpdateAll.clicked.connect(self.update_all) @@ -334,6 +369,9 @@ class CommandAddonManager: self.dialog.buttonCheckForUpdates.clicked.connect( lambda: self.force_check_updates(standalone=True) ) + self.dialog.buttonUpdateDependencies.clicked.connect( + self.show_python_updates_dialog + ) self.packageList.itemSelected.connect(self.table_row_activated) self.packageList.setEnabled(False) self.packageDetails.execute.connect(self.executemacro) @@ -435,7 +473,7 @@ class CommandAddonManager: self.update_cache = True elif not os.path.isdir(am_path): self.update_cache = True - stopfile = self.get_cache_file_name("CACHE_UPDATE_INTERRUPTED") + stopfile = utils.get_cache_file_name("CACHE_UPDATE_INTERRUPTED") if os.path.exists(stopfile): self.update_cache = True os.remove(stopfile) @@ -493,8 +531,8 @@ class CommandAddonManager: thread = getattr(self, worker) if thread: thread.wait(25) - if not thread.isFinished(): - oktoclose = False + if not thread.isFinished(): + oktoclose = False QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) # Write the cache data if it's safe to do so: @@ -567,13 +605,14 @@ class CommandAddonManager: self.populate_macros, self.update_metadata_cache, self.check_updates, + self.check_python_updates, ] pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") if pref.GetBool("DownloadMacros", False): self.startup_sequence.append(self.load_macro_metadata) selection = pref.GetString("SelectedAddon", "") if selection: - self.startup_sequence.insert(2, lambda: self.select_addon(selection)) + self.startup_sequence.insert(2, functools.partial(self.select_addon, selection)) pref.SetString("SelectedAddon", "") if ADDON_MANAGER_DEVELOPER_MODE: self.startup_sequence.append(self.validate) @@ -599,19 +638,13 @@ class CommandAddonManager: pref.SetString("LastCacheUpdate", date.today().isoformat()) self.packageList.item_filter.invalidateFilter() - def get_cache_file_name(self, file: str) -> str: - cache_path = FreeCAD.getUserCachePath() - am_path = os.path.join(cache_path, "AddonManager") - os.makedirs(am_path, exist_ok=True) - return os.path.join(am_path, file) - def populate_packages_table(self) -> None: self.item_model.clear() use_cache = not self.update_cache if use_cache: - if os.path.isfile(self.get_cache_file_name("package_cache.json")): - with open(self.get_cache_file_name("package_cache.json"), "r") as f: + if os.path.isfile(utils.get_cache_file_name("package_cache.json")): + with open(utils.get_cache_file_name("package_cache.json"), "r") as f: data = f.read() try: from_json = json.loads(data) @@ -624,24 +657,24 @@ class CommandAddonManager: if not use_cache: self.update_cache = True # Make sure to trigger the other cache updates, if the json file was missing - self.update_worker = UpdateWorker() - self.update_worker.status_message.connect(self.show_information) - self.update_worker.addon_repo.connect(self.add_addon_repo) + self.create_addon_list_worker = CreateAddonListWorker() + self.create_addon_list_worker.status_message.connect(self.show_information) + self.create_addon_list_worker.addon_repo.connect(self.add_addon_repo) self.update_progress_bar(10, 100) - self.update_worker.finished.connect( + self.create_addon_list_worker.finished.connect( self.do_next_startup_phase ) # Link to step 2 - self.update_worker.start() + self.create_addon_list_worker.start() else: - self.update_worker = LoadPackagesFromCacheWorker( - self.get_cache_file_name("package_cache.json") + self.create_addon_list_worker = LoadPackagesFromCacheWorker( + utils.get_cache_file_name("package_cache.json") ) - self.update_worker.addon_repo.connect(self.add_addon_repo) + self.create_addon_list_worker.addon_repo.connect(self.add_addon_repo) self.update_progress_bar(10, 100) - self.update_worker.finished.connect( + self.create_addon_list_worker.finished.connect( self.do_next_startup_phase ) # Link to step 2 - self.update_worker.start() + self.create_addon_list_worker.start() def cache_package(self, repo: Addon): if not hasattr(self, "package_cache"): @@ -650,7 +683,7 @@ class CommandAddonManager: def write_package_cache(self): if hasattr(self, "package_cache"): - package_cache_path = self.get_cache_file_name("package_cache.json") + package_cache_path = utils.get_cache_file_name("package_cache.json") with open(package_cache_path, "w") as f: f.write(json.dumps(self.package_cache, indent=" ")) @@ -660,23 +693,31 @@ class CommandAddonManager: self.do_next_startup_phase() def populate_macros(self) -> None: - macro_cache_file = self.get_cache_file_name("macro_cache.json") + macro_cache_file = utils.get_cache_file_name("macro_cache.json") cache_is_bad = True if os.path.isfile(macro_cache_file): size = os.path.getsize(macro_cache_file) if size > 1000: # Make sure there is actually data in there cache_is_bad = False - if self.update_cache or cache_is_bad: - self.update_cache = True - self.macro_worker = FillMacroListWorker(self.get_cache_file_name("Macros")) - self.macro_worker.status_message_signal.connect(self.show_information) - self.macro_worker.progress_made.connect(self.update_progress_bar) - self.macro_worker.add_macro_signal.connect(self.add_addon_repo) - self.macro_worker.finished.connect(self.do_next_startup_phase) - self.macro_worker.start() + if cache_is_bad: + if not self.update_cache: + self.update_cache = True # Make sure to trigger the other cache updates, if the json file was missing + self.create_addon_list_worker = CreateAddonListWorker() + self.create_addon_list_worker.status_message.connect( + self.show_information + ) + self.create_addon_list_worker.addon_repo.connect(self.add_addon_repo) + self.update_progress_bar(10, 100) + self.create_addon_list_worker.finished.connect( + self.do_next_startup_phase + ) # Link to step 2 + self.create_addon_list_worker.start() + else: + # It's already been done in the previous step (TODO: Refactor to eliminate this step) + self.do_next_startup_phase() else: self.macro_worker = LoadMacrosFromCacheWorker( - self.get_cache_file_name("macro_cache.json") + utils.get_cache_file_name("macro_cache.json") ) self.macro_worker.add_macro_signal.connect(self.add_addon_repo) self.macro_worker.finished.connect(self.do_next_startup_phase) @@ -695,7 +736,7 @@ class CommandAddonManager: def write_macro_cache(self): if not hasattr(self, "macro_cache"): return - macro_cache_path = self.get_cache_file_name("macro_cache.json") + macro_cache_path = utils.get_cache_file_name("macro_cache.json") with open(macro_cache_path, "w") as f: f.write(json.dumps(self.macro_cache, indent=" ")) self.macro_cache = [] @@ -748,7 +789,9 @@ class CommandAddonManager: def load_macro_metadata(self) -> None: if self.update_cache: - self.load_macro_metadata_worker = CacheMacroCode(self.item_model.repos) + self.load_macro_metadata_worker = CacheMacroCodeWorker( + self.item_model.repos + ) self.load_macro_metadata_worker.status_message.connect( self.show_information ) @@ -850,6 +893,29 @@ class CommandAddonManager: self.enable_updates(len(self.packages_with_updates)) self.dialog.buttonCheckForUpdates.setEnabled(True) + def check_python_updates(self) -> None: + if hasattr(self, "check_for_python_package_updates_worker"): + thread = self.check_for_python_package_updates_worker + if thread: + if not thread.isFinished(): + self.do_next_startup_phase() + return + self.check_for_python_package_updates_worker = ( + CheckForPythonPackageUpdatesWorker() + ) + self.check_for_python_package_updates_worker.python_package_updates_available.connect( + lambda: self.dialog.buttonUpdateDependencies.show() + ) + self.check_for_python_package_updates_worker.finished.connect( + self.do_next_startup_phase + ) + self.check_for_python_package_updates_worker.start() + + def show_python_updates_dialog(self) -> None: + if not hasattr(self, "manage_python_packages_dialog"): + self.manage_python_packages_dialog = PythonPackageManager() + self.manage_python_packages_dialog.show() + def add_addon_repo(self, addon_repo: Addon) -> None: """adds a workbench to the list""" @@ -857,7 +923,7 @@ class CommandAddonManager: addon_repo.icon = self.get_icon(addon_repo) for repo in self.item_model.repos: if repo.name == addon_repo.name: - #self.item_model.reload_item(repo) # If we want to have later additions supersede earlier + # self.item_model.reload_item(repo) # If we want to have later additions supersede earlier return self.item_model.append_item(addon_repo) @@ -954,16 +1020,17 @@ class CommandAddonManager: def __init__(self, repo: Addon, all_repos: List[Addon]): deps = Addon.Dependencies() - repo_name_dict = dict() + repo_name_dict = {} for r in all_repos: - repo_name_dict[repo.name] = r - repo_name_dict[repo.display_name] = r + repo_name_dict[r.name] = r + repo_name_dict[r.display_name] = r + repo.walk_dependency_tree(repo_name_dict, deps) self.external_addons = [] for dep in deps.required_external_addons: if dep.status() == Addon.Status.NOT_INSTALLED: - self.external_addons.append(dep) + self.external_addons.append(dep.name) # Now check the loaded addons to see if we are missing an internal workbench: wbs = [wb.lower() for wb in FreeCADGui.listWorkbenches()] @@ -1009,20 +1076,26 @@ class CommandAddonManager: ] def update_allowed_packages_list(self) -> None: - FreeCAD.Console.PrintLog("Attempting to fetch remote copy of ALLOWED_PYTHON_PACKAGES.txt...\n") + FreeCAD.Console.PrintLog( + "Attempting to fetch remote copy of ALLOWED_PYTHON_PACKAGES.txt...\n" + ) p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( "https://raw.githubusercontent.com/FreeCAD/FreeCAD-addons/master/ALLOWED_PYTHON_PACKAGES.txt" ) if p: - FreeCAD.Console.PrintLog("Remote ALLOWED_PYTHON_PACKAGES.txt file located, overriding locally-installed copy\n") + FreeCAD.Console.PrintLog( + "Remote ALLOWED_PYTHON_PACKAGES.txt file located, overriding locally-installed copy\n" + ) p = p.data().decode("utf8") lines = p.split("\n") - self.allowed_packages.clear() # Unset the locally-defined list + self.allowed_packages.clear() # Unset the locally-defined list for line in lines: if line and len(line) > 0 and line[0] != "#": self.allowed_packages.add(line.strip()) else: - FreeCAD.Console.PrintLog("Could not fetch remote ALLOWED_PYTHON_PACKAGES.txt, using local copy\n") + FreeCAD.Console.PrintLog( + "Could not fetch remote ALLOWED_PYTHON_PACKAGES.txt, using local copy\n" + ) def handle_disallowed_python(self, python_required: List[str]) -> bool: """Determine if we are missing any required Python packages that are not in the allowed @@ -1131,10 +1204,10 @@ class CommandAddonManager: self.dependency_dialog.buttonBox.button( QtWidgets.QDialogButtonBox.Yes - ).clicked.connect(lambda: self.dependency_dialog_yes_clicked(repo)) + ).clicked.connect(functools.partial(self.dependency_dialog_yes_clicked, repo)) self.dependency_dialog.buttonBox.button( QtWidgets.QDialogButtonBox.Ignore - ).clicked.connect(lambda: self.dependency_dialog_ignore_clicked(repo)) + ).clicked.connect(functools.partial(self.dependency_dialog_ignore_clicked, repo)) self.dependency_dialog.buttonBox.button( QtWidgets.QDialogButtonBox.Cancel ).setDefault(True) @@ -1176,7 +1249,7 @@ class CommandAddonManager: # No missing deps, just install self.install(repo) - def dependency_dialog_yes_clicked(self, repo: Addon) -> None: + def dependency_dialog_yes_clicked(self, installing_repo: Addon) -> None: # Get the lists out of the dialog: addons = [] for row in range(self.dependency_dialog.listWidgetAddons.count()): @@ -1201,15 +1274,15 @@ class CommandAddonManager: addons, python_required, python_optional ) self.dependency_installation_worker.no_python_exe.connect( - lambda: self.no_python_exe(repo) + functools.partial(self.no_python_exe, installing_repo) ) self.dependency_installation_worker.no_pip.connect( - lambda command: self.no_pip(command, repo) + functools.partial(self.no_pip, repo=installing_repo) ) self.dependency_installation_worker.failure.connect( self.dependency_installation_failure ) - self.dependency_installation_worker.success.connect(lambda: self.install(repo)) + self.dependency_installation_worker.success.connect(functools.partial(self.install,installing_repo)) self.dependency_installation_dialog = QtWidgets.QMessageBox( QtWidgets.QMessageBox.Information, translate("AddonsInstaller", "Installing dependencies"), @@ -1373,10 +1446,10 @@ class CommandAddonManager: self.update_all_worker.progress_made.connect(self.update_progress_bar) self.update_all_worker.status_message.connect(self.show_information) self.update_all_worker.success.connect( - lambda repo: self.subupdates_succeeded.append(repo) + self.subupdates_succeeded.append ) self.update_all_worker.failure.connect( - lambda repo: self.subupdates_failed.append(repo) + self.subupdates_failed.append ) self.update_all_worker.finished.connect(self.on_update_all_completed) self.update_all_worker.start() @@ -1502,7 +1575,7 @@ class CommandAddonManager: ) def write_cache_stopfile(self) -> None: - stopfile = self.get_cache_file_name("CACHE_UPDATE_INTERRUPTED") + stopfile = utils.get_cache_file_name("CACHE_UPDATE_INTERRUPTED") with open(stopfile, "w", encoding="utf8") as f: f.write( "This file indicates that a cache operation was interrupted, and " @@ -1692,14 +1765,18 @@ class CommandAddonManager: elif addon.repo_type == Addon.Kind.MACRO: if addon.macro.parsed: if len(addon.macro.icon) == 0 and len(addon.macro.xpm) == 0: - FreeCAD.Console.PrintLog(f"Macro '{addon.name}' does not have an icon\n") + FreeCAD.Console.PrintLog( + f"Macro '{addon.name}' does not have an icon\n" + ) else: - FreeCAD.Console.PrintLog(f"Addon '{addon.name}' does not have a package.xml file\n") - + FreeCAD.Console.PrintLog( + f"Addon '{addon.name}' does not have a package.xml file\n" + ) + FreeCAD.Console.PrintLog(f"-----------------------------------\n\n") self.do_next_startup_phase() - def validate_package_xml(self, addon:Addon): + def validate_package_xml(self, addon: Addon): if addon.metadata is None: return @@ -1711,20 +1788,28 @@ class CommandAddonManager: # Top-level required elements if not addon.metadata.Name or len(addon.metadata.Name) == 0: - errors.append(f"No top-level element found, or element is empty") + errors.append( + f"No top-level element found, or element is empty" + ) if not addon.metadata.Version or addon.metadata.Version == "0.0.0": - errors.append(f"No top-level element found, or element is invalid") - #if not addon.metadata.Date or len(addon.metadata.Date) == 0: + errors.append( + f"No top-level element found, or element is invalid" + ) + # if not addon.metadata.Date or len(addon.metadata.Date) == 0: # errors.append(f"No top-level element found, or element is invalid") if not addon.metadata.Description or len(addon.metadata.Description) == 0: - errors.append(f"No top-level element found, or element is invalid") + errors.append( + f"No top-level element found, or element is invalid" + ) maintainers = addon.metadata.Maintainer if len(maintainers) == 0: errors.append(f"No top-level found, at least one is required") for maintainer in maintainers: - if len(maintainer['email']) == 0: - errors.append(f"No email address specified for maintainer '{maintainer['name']}'") + if len(maintainer["email"]) == 0: + errors.append( + f"No email address specified for maintainer '{maintainer['name']}'" + ) licenses = addon.metadata.License if len(licenses) == 0: @@ -1732,7 +1817,9 @@ class CommandAddonManager: urls = addon.metadata.Urls if len(urls) == 0: - errors.append(f"No elements found, at least a repo url must be provided") + errors.append( + f"No elements found, at least a repo url must be provided" + ) else: found_repo = False found_readme = False @@ -1740,23 +1827,31 @@ class CommandAddonManager: if url["type"] == "repository": found_repo = True if len(url["branch"]) == 0: - errors.append(" element is missing the 'branch' attribute") + errors.append( + " element is missing the 'branch' attribute" + ) elif url["type"] == "readme": found_readme = True location = url["location"] p = NetworkManager.AM_NETWORK_MANAGER.blocking_get(location) if not p: - errors.append(f"Could not access specified readme at {location}") + errors.append( + f"Could not access specified readme at {location}" + ) else: p = p.data().decode("utf8") if "" in p: pass else: - errors.append(f"Readme data found at {location} does not appear to be rendered HTML") + errors.append( + f"Readme data found at {location} does not appear to be rendered HTML" + ) if not found_repo: errors.append("No repo url specified") if not found_readme: - errors.append("No readme url specified (not required, but highly recommended)") + errors.append( + "No readme url specified (not required, but highly recommended)" + ) contents = addon.metadata.Content if not contents or len(contents) == 0: @@ -1769,20 +1864,22 @@ class CommandAddonManager: if "workbench" in contents: wb = contents["workbench"][0] if wb.Icon: - missing_icon = False + missing_icon = False if missing_icon: errors.append(f"No element found, or element is invalid") if "workbench" in contents: for wb in contents["workbench"]: - errors.extend (self.validate_workbench_metadata(wb)) + errors.extend(self.validate_workbench_metadata(wb)) if "preferencepack" in contents: for wb in contents["preferencepack"]: - errors.extend (self.validate_preference_pack_metadata(wb)) + errors.extend(self.validate_preference_pack_metadata(wb)) if len(errors) > 0: - FreeCAD.Console.PrintLog(f"Errors found in package.xml file for '{addon.name}'\n") + FreeCAD.Console.PrintLog( + f"Errors found in package.xml file for '{addon.name}'\n" + ) for error in errors: FreeCAD.Console.PrintLog(f" * {error}\n") @@ -1798,4 +1895,5 @@ class CommandAddonManager: errors.append("No specified for preference pack") return errors + # @} diff --git a/src/Mod/AddonManager/AddonManager.ui b/src/Mod/AddonManager/AddonManager.ui index c6f6c66fa0..463c82e7e4 100644 --- a/src/Mod/AddonManager/AddonManager.ui +++ b/src/Mod/AddonManager/AddonManager.ui @@ -121,6 +121,19 @@ + + + + true + + + View and update Python package dependencies + + + Update dependencies + + + diff --git a/src/Mod/AddonManager/AddonManagerOptions.ui b/src/Mod/AddonManager/AddonManagerOptions.ui index 0e412b8c3f..51c0cf551d 100644 --- a/src/Mod/AddonManager/AddonManagerOptions.ui +++ b/src/Mod/AddonManager/AddonManagerOptions.ui @@ -22,7 +22,7 @@ installed addons will be checked for available updates (this requires the GitPython package installed on your system) - Automatically check for updates at start (requires GitPython) + Automatically check for updates at start (requires git) false @@ -249,16 +249,16 @@ of the line after a space (e.g. https://github.com/FreeCAD/FreeCAD master). - - + + Python executable (optional): - - + + 0 @@ -282,6 +282,38 @@ of the line after a space (e.g. https://github.com/FreeCAD/FreeCAD master). + + + + git executable (optional): + + + + + + + + 0 + 0 + + + + + 300 + 0 + + + + The path to the git executable. Autodetected if needed and not specified. + + + GitExecutable + + + Addons + + + @@ -299,7 +331,7 @@ of the line after a space (e.g. https://github.com/FreeCAD/FreeCAD master). - Show option to change branches (Requires GitPython) + Show option to change branches (requires git) ShowBranchSwitcher @@ -309,6 +341,13 @@ of the line after a space (e.g. https://github.com/FreeCAD/FreeCAD master). + + + + Disable git (fall back to ZIP downloads only) + + + diff --git a/src/Mod/AddonManager/AddonManagerTest/app/test_git.py b/src/Mod/AddonManager/AddonManagerTest/app/test_git.py new file mode 100644 index 0000000000..e70822e8d8 --- /dev/null +++ b/src/Mod/AddonManager/AddonManagerTest/app/test_git.py @@ -0,0 +1,174 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 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 unittest +import os +import shutil +import stat +import tempfile +import time +from zipfile import ZipFile +import FreeCAD + +from addonmanager_git import GitManager, NoGitFound, GitFailed + + +class TestGit(unittest.TestCase): + + MODULE = "test_git" # file name without extension + + def setUp(self): + """Set up the test case: called by the unit test system""" + self.cwd = os.getcwd() + test_data_dir = os.path.join( + FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data" + ) + git_repo_zip = os.path.join(test_data_dir, "test_repo.zip") + self.test_dir = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "AddonManagerTests", "Git" + ) + os.makedirs(self.test_dir, exist_ok=True) + self.test_repo_remote = os.path.join(self.test_dir, "TEST_REPO_REMOTE") + if os.path.exists(self.test_repo_remote): + # Make sure any old copy that got left around is deleted + self._rmdir(self.test_repo_remote) + + if not os.path.exists(git_repo_zip): + self.skipTest("Can't find test repo") + return + + with ZipFile(git_repo_zip, "r") as zip_repo: + zip_repo.extractall(self.test_repo_remote) + self.test_repo_remote = os.path.join(self.test_repo_remote, "test_repo") + + try: + self.git = GitManager() + except NoGitFound: + self.skipTest("No git found") + + def tearDown(self): + """Clean up after the test""" + os.chdir(self.cwd) + #self._rmdir(self.test_dir) + os.rename(self.test_dir, self.test_dir + ".old." + str(time.time())) + + def test_clone(self): + """Test git clone""" + checkout_dir = self._clone_test_repo() + self.assertTrue(os.path.exists(checkout_dir)) + self.assertTrue(os.path.exists(os.path.join(checkout_dir, ".git"))) + self.assertEqual(os.getcwd(),self.cwd, "We should be left in the same CWD we started") + + def test_checkout(self): + """Test git checkout""" + checkout_dir = self._clone_test_repo() + + self.git.checkout(checkout_dir, "HEAD~1") + status = self.git.status(checkout_dir).strip() + expected_status = "## HEAD (no branch)" + self.assertEqual(status, expected_status) + + self.assertEqual(os.getcwd(),self.cwd, "We should be left in the same CWD we started") + + def test_update(self): + """Test using git to update the local repo""" + checkout_dir = self._clone_test_repo() + + self.git.reset(checkout_dir, ["--hard", "HEAD~1"]) + self.assertTrue(self.git.update_available(checkout_dir)) + self.git.update(checkout_dir) + self.assertFalse(self.git.update_available(checkout_dir)) + self.assertEqual(os.getcwd(),self.cwd, "We should be left in the same CWD we started") + + def test_tag_and_branch(self): + """Test checking the currently checked-out tag""" + checkout_dir = self._clone_test_repo() + + expected_tag = "TestTag" + self.git.checkout(checkout_dir, expected_tag) + found_tag = self.git.current_tag(checkout_dir) + self.assertEqual(found_tag, expected_tag) + self.assertFalse(self.git.update_available(checkout_dir)) + + expected_branch = "TestBranch" + self.git.checkout(checkout_dir, expected_branch) + found_branch = self.git.current_branch(checkout_dir) + self.assertEqual(found_branch, expected_branch) + self.assertFalse(self.git.update_available(checkout_dir)) + + expected_branch = "main" + self.git.checkout(checkout_dir, expected_branch) + found_branch = self.git.current_branch(checkout_dir) + self.assertEqual(found_branch, expected_branch) + self.assertFalse(self.git.update_available(checkout_dir)) + + self.assertEqual(os.getcwd(),self.cwd, "We should be left in the same CWD we started") + + def test_get_remote(self): + """ Test getting the remote location """ + checkout_dir = self._clone_test_repo() + expected_remote = self.test_repo_remote + returned_remote = self.git.get_remote(checkout_dir) + self.assertEqual(expected_remote, returned_remote) + self.assertEqual(os.getcwd(),self.cwd, "We should be left in the same CWD we started") + + def test_repair(self): + """ Test the repair feature (and some exception throwing) """ + checkout_dir = self._clone_test_repo() + remote = self.git.get_remote(checkout_dir) + git_dir = os.path.join(checkout_dir,".git") + self.assertTrue(os.path.exists(git_dir)) + self._rmdir(git_dir) + + # Make sure that we've truly broken the install + with self.assertRaises(GitFailed): + self.git.status(checkout_dir) + + self.git.repair(remote, checkout_dir) + status = self.git.status(checkout_dir) + self.assertEqual(status,"## main...origin/main\n") + self.assertEqual(os.getcwd(),self.cwd, "We should be left in the same CWD we started") + + + def _rmdir(self, path): + try: + shutil.rmtree(path, onerror=self._remove_readonly) + except Exception as e: + print(e) + + def _remove_readonly(self, func, path, _) -> None: + """Remove a read-only file.""" + + os.chmod(path, stat.S_IWRITE) + func(path) + + def _clone_test_repo(self) -> str: + checkout_dir = os.path.join(self.test_dir, "test_repo") + try: + # Git won't clone to an existing directory, so make sure to remove it first + if os.path.exists(checkout_dir): + self._rmdir(checkout_dir) + self.git.clone(self.test_repo_remote, checkout_dir) + except GitFailed as e: + self.fail(str(e)) + return checkout_dir diff --git a/src/Mod/AddonManager/AddonManagerTest/data/TestWorkbench.zip b/src/Mod/AddonManager/AddonManagerTest/data/TestWorkbench.zip new file mode 100644 index 0000000000..187c9b6c34 Binary files /dev/null and b/src/Mod/AddonManager/AddonManagerTest/data/TestWorkbench.zip differ diff --git a/src/Mod/AddonManager/AddonManagerTest/data/test_repo.zip b/src/Mod/AddonManager/AddonManagerTest/data/test_repo.zip new file mode 100644 index 0000000000..6449777ab5 Binary files /dev/null and b/src/Mod/AddonManager/AddonManagerTest/data/test_repo.zip differ diff --git a/src/Mod/AddonManager/AddonManagerTest/gui/test_gui.py b/src/Mod/AddonManager/AddonManagerTest/gui/test_gui.py index bfc0676585..e78896939d 100644 --- a/src/Mod/AddonManager/AddonManagerTest/gui/test_gui.py +++ b/src/Mod/AddonManager/AddonManagerTest/gui/test_gui.py @@ -25,9 +25,10 @@ import unittest import FreeCAD + class TestGui(unittest.TestCase): - MODULE = 'test_gui' # file name without extension + MODULE = "test_gui" # file name without extension def setUp(self): - pass \ No newline at end of file + pass diff --git a/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_installation.py b/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_installation.py new file mode 100644 index 0000000000..637cf1cd93 --- /dev/null +++ b/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_installation.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- + +# *************************************************************************** +# * Copyright (c) 2022 FreeCAD Project Association * +# * * +# * 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 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +import json +import os +import shutil +import stat +import tempfile +import unittest +import FreeCAD +from addonmanager_git import initialize_git + +from PySide2 import QtCore + +import NetworkManager +from Addon import Addon +from addonmanager_workers_startup import ( + CreateAddonListWorker, + UpdateChecker, +) +from addonmanager_workers_installation import InstallWorkbenchWorker + + +class TestWorkersInstallation(unittest.TestCase): + + MODULE = "test_workers_installation" # file name without extension + + addon_list = ( + [] + ) # Cache at the class level so only the first test has to download it + + def setUp(self): + """Set up the test""" + self.test_dir = os.path.join( + FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data" + ) + + self.saved_mod_directory = Addon.mod_directory + self.saved_cache_directory = Addon.cache_directory + Addon.mod_directory = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "Mod" + ) + Addon.cache_directory = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "Cache" + ) + + os.makedirs(Addon.mod_directory, mode=0o777, exist_ok=True) + os.makedirs(Addon.cache_directory, mode=0o777, exist_ok=True) + + url = "https://api.github.com/zen" + NetworkManager.InitializeNetworkManager() + result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) + if result is None: + self.skipTest("No active internet connection detected") + + self.macro_counter = 0 + self.workbench_counter = 0 + self.prefpack_counter = 0 + self.addon_from_cache_counter = 0 + self.macro_from_cache_counter = 0 + + self.package_cache = {} + self.macro_cache = [] + + self.package_cache_filename = os.path.join( + Addon.cache_directory, "packages.json" + ) + self.macro_cache_filename = os.path.join(Addon.cache_directory, "macros.json") + + if not TestWorkersInstallation.addon_list: + self._create_addon_list() + + # Workbench: use the FreeCAD-Help workbench for testing purposes + self.help_addon = None + for addon in self.addon_list: + if addon.name == "Help": + self.help_addon = addon + break + if not self.help_addon: + print("Unable to locate the FreeCAD-Help addon to test with") + self.skipTest("No active internet connection detected") + + # Store the user's preference for whether git is enabled or disabled + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + self.saved_git_disabled_status = pref.GetBool("disableGit", False) + + def tearDown(self): + mod_dir = os.path.join(tempfile.gettempdir(), "FreeCADTesting", "Mod") + if os.path.exists(mod_dir): + self._rmdir(mod_dir) + macro_dir = os.path.join(tempfile.gettempdir(), "FreeCADTesting", "Mod") + if os.path.exists(macro_dir): + self._rmdir(macro_dir) + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + pref.SetBool("disableGit", self.saved_git_disabled_status) + + def test_workbench_installation(self): + addon_location = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "Mod", self.help_addon.name + ) + worker = InstallWorkbenchWorker(self.help_addon, addon_location) + worker.run() # Synchronous call, blocks until complete + self.assertTrue(os.path.exists(addon_location)) + self.assertTrue(os.path.exists(os.path.join(addon_location, "package.xml"))) + + def test_workbench_installation_git_disabled(self): + """If the testing user has git enabled, also test the addon manager with git disabled""" + if self.saved_git_disabled_status: + self.skipTest("Git is disabled, this test is redundant") + + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + pref.SetBool("disableGit", True) + + self.test_workbench_installation() + + pref.SetBool("disableGit", False) + + def test_workbench_update_checker(self): + + git_manager = initialize_git() + + if not git_manager: + return + + # Workbench: use the FreeCAD-Help workbench for testing purposes + help_addon = None + for addon in self.addon_list: + if addon.name == "Help": + help_addon = addon + break + if not help_addon: + print("Unable to locate the FreeCAD-Help addon to test with") + return + + addon_location = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "Mod", self.help_addon.name + ) + worker = InstallWorkbenchWorker(addon, addon_location) + worker.run() # Synchronous call, blocks until complete + self.assertEqual(help_addon.status(), Addon.Status.PENDING_RESTART) + + # Back up one revision + git_manager.reset(addon_location, ["--hard", "HEAD~1"]) + + # At this point the addon should be "out of date", checked out to one revision behind + # the most recent. + + worker = UpdateChecker() + worker.override_mod_directory( + os.path.join(tempfile.gettempdir(), "FreeCADTesting", "Mod") + ) + worker.check_workbench(help_addon) # Synchronous call + self.assertEqual(help_addon.status(), Addon.Status.UPDATE_AVAILABLE) + + # Now try to "update" it (which is really done via the install worker) + worker = InstallWorkbenchWorker(addon, addon_location) + worker.run() # Synchronous call, blocks until complete + self.assertEqual(help_addon.status(), Addon.Status.PENDING_RESTART) + + def _rmdir(self, path): + try: + shutil.rmtree(path, onerror=self._remove_readonly) + except Exception as e: + print(e) + + def _remove_readonly(self, func, path, _) -> None: + """Remove a read-only file.""" + + os.chmod(path, stat.S_IWRITE) + func(path) + + def _create_addon_list(self): + """Create the list of addons""" + worker = CreateAddonListWorker() + worker.addon_repo.connect(self._addon_added) + worker.start() + while worker.isRunning(): + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + + def _addon_added(self, addon: Addon): + """Callback for adding an Addon: tracks the list, and counts the various types""" + print(f"Addon added: {addon.name}") + TestWorkersInstallation.addon_list.append(addon) + if addon.contains_workbench(): + self.workbench_counter += 1 + if addon.contains_macro(): + self.macro_counter += 1 + if addon.contains_preference_pack(): + self.prefpack_counter += 1 diff --git a/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_startup.py b/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_startup.py new file mode 100644 index 0000000000..0043741529 --- /dev/null +++ b/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_startup.py @@ -0,0 +1,214 @@ +# -*- coding: utf-8 -*- + +# *************************************************************************** +# * Copyright (c) 2022 FreeCAD Project Association * +# * * +# * 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 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +import json +import unittest +import os +import tempfile + +from addonmanager_git import initialize_git + +import FreeCAD + +from PySide2 import QtCore + +import NetworkManager +from Addon import Addon +from addonmanager_workers_startup import ( + CreateAddonListWorker, + LoadPackagesFromCacheWorker, + LoadMacrosFromCacheWorker, + CheckSingleUpdateWorker, +) + +from addonmanager_workers_installation import ( + InstallWorkbenchWorker, +) + + +class TestWorkersStartup(unittest.TestCase): + + MODULE = "test_workers_startup" # file name without extension + + def setUp(self): + """Set up the test""" + self.test_dir = os.path.join( + FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data" + ) + + self.saved_mod_directory = Addon.mod_directory + self.saved_cache_directory = Addon.cache_directory + Addon.mod_directory = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "Mod" + ) + Addon.cache_directory = os.path.join( + tempfile.gettempdir(), "FreeCADTesting", "Cache" + ) + + os.makedirs(Addon.mod_directory, mode=0o777, exist_ok=True) + os.makedirs(Addon.cache_directory, mode=0o777, exist_ok=True) + + url = "https://api.github.com/zen" + NetworkManager.InitializeNetworkManager() + result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) + if result is None: + self.skipTest("No active internet connection detected") + + self.addon_list = [] + self.macro_counter = 0 + self.workbench_counter = 0 + self.prefpack_counter = 0 + self.addon_from_cache_counter = 0 + self.macro_from_cache_counter = 0 + + self.package_cache = {} + self.macro_cache = [] + + self.package_cache_filename = os.path.join( + Addon.cache_directory, "packages.json" + ) + self.macro_cache_filename = os.path.join(Addon.cache_directory, "macros.json") + + # Store the user's preference for whether git is enabled or disabled + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + self.saved_git_disabled_status = pref.GetBool("disableGit", False) + + def tearDown(self): + """Tear down the test""" + Addon.mod_directory = self.saved_mod_directory + Addon.cache_directory = self.saved_cache_directory + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + pref.SetBool("disableGit", self.saved_git_disabled_status) + + def test_create_addon_list_worker(self): + """Test whether any addons are added: runs the full query, so this potentially is a SLOW + test.""" + worker = CreateAddonListWorker() + worker.addon_repo.connect(self._addon_added) + worker.start() + while worker.isRunning(): + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + + self.assertGreater(self.macro_counter, 0, "No macros returned") + self.assertGreater(self.workbench_counter, 0, "No workbenches returned") + + # Make sure there are no duplicates: + addon_name_set = set() + for addon in self.addon_list: + addon_name_set.add(addon.name) + self.assertEqual( + len(addon_name_set), len(self.addon_list), "Duplicate names are not allowed" + ) + + # Write the cache data + if hasattr(self, "package_cache"): + with open(self.package_cache_filename, "w", encoding="utf-8") as f: + f.write(json.dumps(self.package_cache, indent=" ")) + if hasattr(self, "macro_cache"): + with open(self.macro_cache_filename, "w", encoding="utf-8") as f: + f.write(json.dumps(self.macro_cache, indent=" ")) + + original_macro_counter = self.macro_counter + original_workbench_counter = self.workbench_counter + original_addon_list = self.addon_list.copy() + self.macro_counter = 0 + self.workbench_counter = 0 + self.addon_list.clear() + + # Now try loading the same data from the cache we just created + worker = LoadPackagesFromCacheWorker(self.package_cache_filename) + worker.override_metadata_cache_path( + os.path.join(Addon.cache_directory, "PackageMetadata") + ) + worker.addon_repo.connect(self._addon_added) + + worker.start() + while worker.isRunning(): + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + + worker = LoadMacrosFromCacheWorker(self.macro_cache_filename) + worker.add_macro_signal.connect(self._addon_added) + + worker.start() + while worker.isRunning(): + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + + # Make sure that every addon in the original list is also in the new list + fail_counter = 0 + for original_addon in original_addon_list: + found = False + for addon in self.addon_list: + if addon.name == original_addon.name: + found = True + break + if not found: + print(f"Failed to load {addon.name} from cache") + fail_counter += 1 + self.assertEqual(fail_counter, 0) + + # Make sure there are no duplicates: + addon_name_set.clear() + for addon in self.addon_list: + addon_name_set.add(addon.name) + + self.assertEqual(len(addon_name_set), len(self.addon_list)) + self.assertEqual(len(original_addon_list), len(self.addon_list)) + + self.assertEqual( + original_macro_counter, + self.macro_counter, + "Cache loaded a different number of macros", + ) + # We can't check workbench and preference pack counting at this point, because that relies + # on the package.xml metadata file, which this test does not download. + + def test_create_addon_list_git_disabled(self): + """If the user has git enabled, also test the addon manager with git disabled""" + if self.saved_git_disabled_status: + self.skipTest("Git is disabled, this test is redundant") + + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + pref.SetBool("disableGit", True) + + self.test_create_addon_list_worker() + + def _addon_added(self, addon: Addon): + """Callback for adding an Addon: tracks the list, and counts the various types""" + print(f"Addon added: {addon.name}") + self.addon_list.append(addon) + if addon.contains_workbench(): + self.workbench_counter += 1 + if addon.contains_macro(): + self.macro_counter += 1 + if addon.contains_preference_pack(): + self.prefpack_counter += 1 + + # Also record the information for cache purposes + if addon.macro is None: + self.package_cache[addon.name] = addon.to_cache() + else: + self.macro_cache.append(addon.macro.to_cache()) diff --git a/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_utility.py b/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_utility.py new file mode 100644 index 0000000000..b5b174a42b --- /dev/null +++ b/src/Mod/AddonManager/AddonManagerTest/gui/test_workers_utility.py @@ -0,0 +1,80 @@ +# -*- coding: utf-8 -*- + +# *************************************************************************** +# * Copyright (c) 2022 FreeCAD Project Association * +# * * +# * 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 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +import unittest +import os +import FreeCAD +from addonmanager_workers_utility import ConnectionChecker +from PySide2 import QtCore + +import NetworkManager + + +class TestWorkersUtility(unittest.TestCase): + + MODULE = "test_workers_utility" # file name without extension + + def setUp(self): + self.test_dir = os.path.join( + FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data" + ) + self.last_result = None + + url = "https://api.github.com/zen" + NetworkManager.InitializeNetworkManager() + result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) + if result is None: + self.skipTest("No active internet connection detected") + + def test_connection_checker_basic(self): + """Tests the connection checking worker's basic operation: does not exit until worker thread completes""" + worker = ConnectionChecker() + worker.success.connect(self.connection_succeeded) + worker.failure.connect(self.connection_failed) + self.last_result = None + worker.start() + while worker.isRunning(): + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + self.assertEqual(self.last_result, "SUCCESS") + + def test_connection_checker_thread_interrupt(self): + worker = ConnectionChecker() + worker.success.connect(self.connection_succeeded) + worker.failure.connect(self.connection_failed) + self.last_result = None + worker.start() + worker.requestInterruption() + while worker.isRunning(): + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + self.assertIsNone( + self.last_result, "Requesting interruption of thread failed to interrupt" + ) + + def connection_succeeded(self): + self.last_result = "SUCCESS" + + def connection_failed(self): + self.last_result = "FAILURE" diff --git a/src/Mod/AddonManager/CMakeLists.txt b/src/Mod/AddonManager/CMakeLists.txt index bfc7772c75..6e42aec7fb 100644 --- a/src/Mod/AddonManager/CMakeLists.txt +++ b/src/Mod/AddonManager/CMakeLists.txt @@ -7,9 +7,12 @@ SET(AddonManager_SRCS Addon.py AddonManager.py AddonManager.ui + addonmanager_git.py addonmanager_macro.py addonmanager_utilities.py - addonmanager_workers.py + addonmanager_workers_startup.py + addonmanager_workers_installation.py + addonmanager_workers_utility.py AddonManagerOptions.ui ALLOWED_PYTHON_PACKAGES.txt change_branch.py @@ -22,9 +25,11 @@ SET(AddonManager_SRCS InitGui.py install_to_toolbar.py loading.html + manage_python_dependencies.py NetworkManager.py package_details.py package_list.py + PythonDependencyUpdateDialog.ui select_toolbar_dialog.ui TestAddonManagerApp.py ) @@ -42,6 +47,7 @@ SET(AddonManagerTests_SRCS SET(AddonManagerTestsApp_SRCS AddonManagerTest/app/__init__.py AddonManagerTest/app/test_addon.py + AddonManagerTest/app/test_git.py AddonManagerTest/app/test_macro.py AddonManagerTest/app/test_utilities.py ) @@ -49,6 +55,9 @@ SET(AddonManagerTestsApp_SRCS SET(AddonManagerTestsGui_SRCS AddonManagerTest/gui/__init__.py AddonManagerTest/gui/test_gui.py + AddonManagerTest/gui/test_workers_installation.py + AddonManagerTest/gui/test_workers_startup.py + AddonManagerTest/gui/test_workers_utility.py ) SET(AddonManagerTestsFiles_SRCS @@ -63,6 +72,8 @@ SET(AddonManagerTestsFiles_SRCS AddonManagerTest/data/macro_template.FCStd AddonManagerTest/data/missing_macro_metadata.FCStd AddonManagerTest/data/prefpack_only.xml + AddonManagerTest/data/test_repo.zip + AddonManagerTest/data/TestWorkbench.zip AddonManagerTest/data/test_version_detection.xml AddonManagerTest/data/workbench_only.xml ) diff --git a/src/Mod/AddonManager/NetworkManager.py b/src/Mod/AddonManager/NetworkManager.py index 7a4dd322a2..140bf515cb 100644 --- a/src/Mod/AddonManager/NetworkManager.py +++ b/src/Mod/AddonManager/NetworkManager.py @@ -22,7 +22,7 @@ # * * # *************************************************************************** - +""" ############################################################################# # # ABOUT NETWORK MANAGER @@ -52,7 +52,15 @@ # accesses: the blocking_get() function blocks until the network transmission # is complete, directly returning a QByteArray object with the received data. # Do not run on the main GUI thread! +""" +import threading +import os +import queue +import itertools +import tempfile +import sys +from typing import Dict, List, Optional try: import FreeCAD @@ -62,18 +70,15 @@ try: HAVE_FREECAD = True translate = FreeCAD.Qt.translate -except Exception: +except ImportError: # For standalone testing support working without the FreeCAD import HAVE_FREECAD = False -import threading from PySide2 import QtCore -import os -import queue -import itertools -import tempfile -from typing import Dict, List, Optional +if FreeCAD.GuiUp: + from PySide2 import QtWidgets + # This is the global instance of the NetworkManager that outside code # should access @@ -82,7 +87,7 @@ AM_NETWORK_MANAGER = None HAVE_QTNETWORK = True try: from PySide2 import QtNetwork -except Exception: +except ImportError: if HAVE_FREECAD: FreeCAD.Console.PrintError( translate( @@ -95,12 +100,14 @@ except Exception: print( "Could not import QtNetwork, unable to test this file. Try installing the python3-pyside2.qtnetwork package." ) - exit(1) + sys.exit(1) HAVE_QTNETWORK = False if HAVE_QTNETWORK: class QueueItem: + """A container for information about an item in the network queue.""" + def __init__( self, index: int, request: QtNetwork.QNetworkRequest, track_progress: bool ): @@ -148,7 +155,10 @@ if HAVE_QTNETWORK: self.synchronous_result_data: Dict[int, QtCore.QByteArray] = {} # Make sure we exit nicely on quit - QtCore.QCoreApplication.instance().aboutToQuit.connect(self.__aboutToQuit) + if QtCore.QCoreApplication.instance() is not None: + QtCore.QCoreApplication.instance().aboutToQuit.connect( + self.__aboutToQuit + ) # Create the QNAM on this thread: self.QNAM = QtNetwork.QNetworkAccessManager() @@ -164,68 +174,32 @@ if HAVE_QTNETWORK: self.QNAM.setCache(self.diskCache) self.monitored_connections: List[int] = [] + self._setup_proxy() + + # A helper connection for our blocking interface + self.completed.connect(self.__synchronous_process_completion) + + # Set up our worker connection + self.__request_queued.connect(self.__setup_network_request) + + def _setup_proxy(self): + """Set up the proxy based on user preferences or prompts on command line""" # Set up the proxy, if necesssary: - noProxyCheck = True - systemProxyCheck = False - userProxyCheck = False - proxy_string = "" if HAVE_FREECAD: - pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") - noProxyCheck = pref.GetBool("NoProxyCheck", noProxyCheck) - systemProxyCheck = pref.GetBool("SystemProxyCheck", systemProxyCheck) - userProxyCheck = pref.GetBool("UserProxyCheck", userProxyCheck) - proxy_string = pref.GetString("ProxyUrl", "") - - # Add some error checking to the proxy setup, since for historical reasons they - # are independent booleans, rather than an enumeration: - count = [noProxyCheck, systemProxyCheck, userProxyCheck].count(True) - if count != 1: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Parameter error: mutually exclusive proxy options set. Resetting to default.", - ) - + "\n" - ) - noProxyCheck = True - systemProxyCheck = False - userProxyCheck = False - pref.SetBool("NoProxyCheck", noProxyCheck) - pref.SetBool("SystemProxyCheck", systemProxyCheck) - pref.SetBool("UserProxyCheck", userProxyCheck) - - if userProxyCheck and not proxy_string: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Parameter error: user proxy indicated, but no proxy provided. Resetting to default.", - ) - + "\n" - ) - noProxyCheck = True - userProxyCheck = False - pref.SetBool("NoProxyCheck", noProxyCheck) - pref.SetBool("UserProxyCheck", userProxyCheck) - + ( + noProxyCheck, + systemProxyCheck, + userProxyCheck, + proxy_string, + ) = self._setup_proxy_freecad() else: - print("Please select a proxy type:") - print("1) No proxy") - print("2) Use system proxy settings") - print("3) Custom proxy settings") - result = input("Choice: ") - if result == "1": - pass - elif result == "2": - noProxyCheck = False - systemProxyCheck = True - elif result == "3": - noProxyCheck = False - userProxyCheck = True - proxy_string = input("Enter your proxy server (host:port): ") - else: - print(f"Got {result}, expected 1, 2, or 3.") - app.quit() + ( + noProxyCheck, + systemProxyCheck, + userProxyCheck, + proxy_string, + ) = self._setup_proxy_standalone() if noProxyCheck: pass @@ -247,16 +221,80 @@ if HAVE_QTNETWORK: ) self.QNAM.setProxy(proxy) - # A helper connection for our blocking interface - self.completed.connect(self.__synchronous_process_completion) + def _setup_proxy_freecad(self): + """If we are running within FreeCAD, this uses the config data to set up the proxy""" + noProxyCheck = True + systemProxyCheck = False + userProxyCheck = False + proxy_string = "" + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + noProxyCheck = pref.GetBool("NoProxyCheck", noProxyCheck) + systemProxyCheck = pref.GetBool("SystemProxyCheck", systemProxyCheck) + userProxyCheck = pref.GetBool("UserProxyCheck", userProxyCheck) + proxy_string = pref.GetString("ProxyUrl", "") - # Set up our worker connection - self.__request_queued.connect(self.__setup_network_request) + # Add some error checking to the proxy setup, since for historical reasons they + # are independent booleans, rather than an enumeration: + option_count = [noProxyCheck, systemProxyCheck, userProxyCheck].count(True) + if option_count != 1: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Parameter error: mutually exclusive proxy options set. Resetting to default.", + ) + + "\n" + ) + noProxyCheck = True + systemProxyCheck = False + userProxyCheck = False + pref.SetBool("NoProxyCheck", noProxyCheck) + pref.SetBool("SystemProxyCheck", systemProxyCheck) + pref.SetBool("UserProxyCheck", userProxyCheck) + + if userProxyCheck and not proxy_string: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Parameter error: user proxy indicated, but no proxy provided. Resetting to default.", + ) + + "\n" + ) + noProxyCheck = True + userProxyCheck = False + pref.SetBool("NoProxyCheck", noProxyCheck) + pref.SetBool("UserProxyCheck", userProxyCheck) + return noProxyCheck, systemProxyCheck, userProxyCheck, proxy_string + + def _setup_proxy_standalone(self): + """If we are NOT running inside FreeCAD, prompt the user for proxy information""" + noProxyCheck = True + systemProxyCheck = False + userProxyCheck = False + proxy_string = "" + print("Please select a proxy type:") + print("1) No proxy") + print("2) Use system proxy settings") + print("3) Custom proxy settings") + result = input("Choice: ") + if result == "1": + pass + elif result == "2": + noProxyCheck = False + systemProxyCheck = True + elif result == "3": + noProxyCheck = False + userProxyCheck = True + proxy_string = input("Enter your proxy server (host:port): ") + else: + print(f"Got {result}, expected 1, 2, or 3.") + app.quit() + return noProxyCheck, systemProxyCheck, userProxyCheck, proxy_string def __aboutToQuit(self): - pass + """Called when the application is about to quit. Not currently used.""" def __setup_network_request(self): + """Get the next request off the queue and launch it.""" try: item = self.queue.get_nowait() if item: @@ -272,6 +310,7 @@ if HAVE_QTNETWORK: def __launch_request( self, index: int, request: QtNetwork.QNetworkRequest ) -> None: + """Given a network request, ask the QNetworkAccessManager to begin processing it.""" reply = self.QNAM.get(request) self.replies[index] = reply @@ -342,12 +381,12 @@ if HAVE_QTNETWORK: self.synchronous_complete.pop(current_index) if current_index in self.synchronous_result_data: return self.synchronous_result_data.pop(current_index) - else: - return None + return None def __synchronous_process_completion( self, index: int, code: int, data: QtCore.QByteArray ) -> None: + """Check the return status of a completed process, and handle its returned data (if any).""" with self.synchronous_lock: if index in self.synchronous_complete: if code == 200: @@ -363,6 +402,7 @@ if HAVE_QTNETWORK: self.synchronous_complete[index] = True def __create_get_request(self, url: str) -> QtNetwork.QNetworkRequest: + """Construct a network request to a given URL""" request = QtNetwork.QNetworkRequest(QtCore.QUrl(url)) request.setAttribute( QtNetwork.QNetworkRequest.RedirectPolicyAttribute, @@ -390,6 +430,7 @@ if HAVE_QTNETWORK: break def abort(self, index: int): + """Abort a specific request""" if index in self.replies and self.replies[index].isRunning(): self.replies[index].abort() elif index < self.__last_started_index: @@ -401,6 +442,8 @@ if HAVE_QTNETWORK: reply: QtNetwork.QNetworkProxy, authenticator: QtNetwork.QAuthenticator, ): + """If proxy authentication is required, attempt to authenticate. If the GUI is running this displays + a window asking for credentials. If the GUI is not running, it prompts on the command line.""" if HAVE_FREECAD and FreeCAD.GuiUp: proxy_authentication = FreeCADGui.PySideUic.loadUi( os.path.join(os.path.dirname(__file__), "proxy_authentication.ui") @@ -434,9 +477,10 @@ if HAVE_QTNETWORK: _reply: QtNetwork.QNetworkReply, _authenticator: QtNetwork.QAuthenticator, ): - pass + """Unused.""" def __follow_redirect(self, url): + """Used with the QNetworkAccessManager to follow redirects.""" sender = self.sender() if sender: for index, reply in self.replies.items(): @@ -448,6 +492,7 @@ if HAVE_QTNETWORK: self.__launch_request(current_index, self.__create_get_request(url)) def __on_ssl_error(self, reply: str, errors: List[str]): + """Called when an SSL error occurs: prints the error information.""" if HAVE_FREECAD: FreeCAD.Console.PrintWarning( translate("AddonsInstaller", "Error with encrypted connection") @@ -462,6 +507,7 @@ if HAVE_QTNETWORK: print(error) def __download_progress(self, bytesReceived: int, bytesTotal: int) -> None: + """Monitors download progress and emits a progress_made signal""" sender = self.sender() if not sender: return @@ -471,6 +517,7 @@ if HAVE_QTNETWORK: return def __ready_to_read(self) -> None: + """Called when data is available, this reads that data.""" sender = self.sender() if not sender: return @@ -481,6 +528,7 @@ if HAVE_QTNETWORK: return def __data_incoming(self, index: int, reply: QtNetwork.QNetworkReply) -> None: + """Read incoming data and attach it to a data object""" if not index in self.replies: # We already finished this reply, this is a vestigial signal return @@ -492,7 +540,7 @@ if HAVE_QTNETWORK: f = self.file_buffers[index] try: f.write(buffer.data()) - except Exception as e: + except IOError as e: if HAVE_FREECAD: FreeCAD.Console.PrintError( f"Network Manager internal error: {str(e)}" @@ -501,6 +549,8 @@ if HAVE_QTNETWORK: print(f"Network Manager internal error: {str(e)}") def __reply_finished(self) -> None: + """Called when a reply has been completed: this makes sure the data has been read and + any notifications have been called.""" reply = self.sender() if not reply: print( @@ -567,28 +617,32 @@ else: # HAVE_QTNETWORK is false: self.unmonitored_queue = queue.Queue() def submit_unmonitored_request(self, _) -> int: + """Returns a fake index that can be used for testing -- nothing is actually queued""" current_index = next(itertools.count()) self.unmonitored_queue.put(current_index) return current_index def submit_monitored_request(self, _) -> int: + """Returns a fake index that can be used for testing -- nothing is actually queued""" current_index = next(itertools.count()) self.monitored_queue.put(current_index) return current_index def blocking_get(self, _: str) -> QtCore.QByteArray: + """No operation - returns None immediately""" return None def abort_all( self, ): - pass # Nothing to do + """There is nothing to abort in this case""" def abort(self, _): - pass # Nothing to do + """There is nothing to abort in this case""" def InitializeNetworkManager(): + """Called once at the beginning of program execution to create the appropriate manager object""" global AM_NETWORK_MANAGER if AM_NETWORK_MANAGER is None: AM_NETWORK_MANAGER = NetworkManager() @@ -611,6 +665,7 @@ if __name__ == "__main__": ] def handle_completion(index: int, code: int, data): + """Attached to the completion signal, prints diagnostic information about the network access""" global count if code == 200: print( @@ -624,14 +679,14 @@ if __name__ == "__main__": count += 1 if count >= len(urls): - print(f"Shutting down...", flush=True) + print("Shutting down...", flush=True) AM_NETWORK_MANAGER.requestInterruption() AM_NETWORK_MANAGER.wait(5000) app.quit() AM_NETWORK_MANAGER.completed.connect(handle_completion) - for url in urls: - AM_NETWORK_MANAGER.submit_unmonitored_get(url) + for test_url in urls: + AM_NETWORK_MANAGER.submit_unmonitored_get(test_url) app.exec_() diff --git a/src/Mod/AddonManager/PythonDependencyUpdateDialog.ui b/src/Mod/AddonManager/PythonDependencyUpdateDialog.ui new file mode 100644 index 0000000000..0bb719bf19 --- /dev/null +++ b/src/Mod/AddonManager/PythonDependencyUpdateDialog.ui @@ -0,0 +1,91 @@ + + + PythonDependencyUpdateDialog + + + + 0 + 0 + 528 + 300 + + + + Manage Python Dependencies + + + + + + The following Python packages have been installed locally by the Addon Manager to satisfy Addon dependencies. Installation location: + + + true + + + + + + + placeholder for path + + + Qt::TextSelectableByMouse + + + + + + + true + + + QAbstractItemView::SelectRows + + + true + + + 4 + + + false + + + + Package name + + + + + Installed version + + + + + Available version + + + + + + + + + + + + + + + Update all available + + + + + + + + + + diff --git a/src/Mod/AddonManager/TestAddonManagerApp.py b/src/Mod/AddonManager/TestAddonManagerApp.py index 7602010674..f048466270 100644 --- a/src/Mod/AddonManager/TestAddonManagerApp.py +++ b/src/Mod/AddonManager/TestAddonManagerApp.py @@ -32,8 +32,12 @@ from AddonManagerTest.app.test_addon import ( from AddonManagerTest.app.test_macro import ( TestMacro as AddonManagerTestMacro, ) +from AddonManagerTest.app.test_git import ( + TestGit as AddonManagerTestGit, +) # dummy usage to get flake8 and lgtm quiet False if AddonManagerTestUtilities.__name__ else True False if AddonManagerTestAddon.__name__ else True False if AddonManagerTestMacro.__name__ else True +False if AddonManagerTestGit.__name__ else True diff --git a/src/Mod/AddonManager/TestAddonManagerGui.py b/src/Mod/AddonManager/TestAddonManagerGui.py index 6a7bb6b297..7cb913b305 100644 --- a/src/Mod/AddonManager/TestAddonManagerGui.py +++ b/src/Mod/AddonManager/TestAddonManagerGui.py @@ -25,5 +25,19 @@ # Unit test for the Addon Manager module GUI from AddonManagerTest.gui.test_gui import TestGui as AddonManagerTestGui +from AddonManagerTest.gui.test_workers_utility import ( + TestWorkersUtility as AddonManagerTestWorkersUtility, +) +from AddonManagerTest.gui.test_workers_startup import ( + TestWorkersStartup as AddonManagerTestWorkersStartup, +) +from AddonManagerTest.gui.test_workers_installation import ( + TestWorkersInstallation as AddonManagerTestWorkersInstallation, +) + + # dummy usage to get flake8 and lgtm quiet False if AddonManagerTestGui.__name__ else True +False if AddonManagerTestWorkersUtility.__name__ else True +False if AddonManagerTestWorkersStartup.__name__ else True +False if AddonManagerTestWorkersInstallation.__name__ else True diff --git a/src/Mod/AddonManager/addonmanager_git.py b/src/Mod/AddonManager/addonmanager_git.py new file mode 100644 index 0000000000..5cbc089291 --- /dev/null +++ b/src/Mod/AddonManager/addonmanager_git.py @@ -0,0 +1,311 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 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 * +# * . * +# * * +# *************************************************************************** + +""" Wrapper around git executable to simplify calling git commands from Python. """ + +# pylint: disable=too-few-public-methods + +import os +import platform +import shutil +import subprocess +from typing import List +import time +import FreeCAD + +translate = FreeCAD.Qt.translate + + +def initialize_git() -> object: + """If git is enabled, locate the git executable if necessary and return a new + GitManager object. The executable location is saved in user preferences for reuse, + and git can be disabled by setting the disableGit parameter in the Addons + preference group. Returns None if for any of those reasons we aren't using git.""" + + git_manager = None + pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + disable_git = pref.GetBool("disableGit", False) + if not disable_git: + try: + git_manager = GitManager() + except NoGitFound: + pass + return git_manager + + +class NoGitFound(RuntimeError): + """Could not locate the git executable on this system.""" + + +class GitFailed(RuntimeError): + """The call to git returned an error of some kind""" + + +class GitManager: + """A class to manage access to git: mostly just provides a simple wrapper around the basic + command-line calls. Provides optional asynchronous access to clone and update.""" + + def __init__(self): + self.git_exe = None + self._find_git() + if not self.git_exe: + raise NoGitFound() + + def clone(self, remote, local_path, args: List[str] = None): + """Clones the remote to the local path""" + final_args = ["clone", "--recurse-submodules"] + if args: + final_args.extend(args) + final_args.extend([remote, local_path]) + self._synchronous_call_git(final_args) + + def async_clone(self, remote, local_path, progress_monitor, args: List[str] = None): + """Clones the remote to the local path, sending periodic progress updates + to the passed progress_monitor. Returns a handle that can be used to + cancel the job.""" + + def checkout(self, local_path, spec, args: List[str] = None): + """Checks out a specific git revision, tag, or branch. Any valid argument to + git checkout can be submitted.""" + old_dir = os.getcwd() + os.chdir(local_path) + final_args = ["checkout"] + if args: + final_args.extend(args) + final_args.append(spec) + self._synchronous_call_git(final_args) + os.chdir(old_dir) + + def update(self, local_path): + """Fetches and pulls the local_path from its remote""" + old_dir = os.getcwd() + os.chdir(local_path) + self._synchronous_call_git(["fetch"]) + try: + self._synchronous_call_git(["pull"]) + self._synchronous_call_git(["submodule", "update", "--init", "--recursive"]) + except GitFailed as e: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Basic git update failed with the following message:", + ) + + str(e) + + "\n" + ) + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Backing up the original directory and re-cloning", + ) + + "...\n" + ) + remote = self.get_remote(local_path) + with open(os.path.join(local_path, "ADDON_DISABLED"), "w", encoding="utf-8") as f: + f.write( + "This is a backup of an addon that failed to update cleanly so was re-cloned. " + + "It was disabled by the Addon Manager's git update facility and can be " + + "safely deleted if the addon is working properly." + ) + os.chdir("..") + os.rename(local_path, local_path + ".backup" + str(time.time())) + self.clone(remote, local_path) + os.chdir(old_dir) + + def status(self, local_path) -> str: + """Gets the v1 porcelain status""" + old_dir = os.getcwd() + os.chdir(local_path) + try: + status = self._synchronous_call_git(["status", "-sb", "--porcelain"]) + except GitFailed as e: + os.chdir(old_dir) + raise e + + os.chdir(old_dir) + return status + + def reset(self, local_path, args: List[str] = None): + """Executes the git reset command""" + old_dir = os.getcwd() + os.chdir(local_path) + final_args = ["reset"] + if args: + final_args.extend(args) + try: + self._synchronous_call_git(final_args) + except GitFailed as e: + os.chdir(old_dir) + raise e + os.chdir(old_dir) + + def async_fetch_and_update(self, local_path, progress_monitor, args=None): + """Same as fetch_and_update, but asynchronous""" + + def update_available(self, local_path) -> bool: + """Returns True if an update is available from the remote, or false if not""" + old_dir = os.getcwd() + os.chdir(local_path) + try: + self._synchronous_call_git(["fetch"]) + status = self._synchronous_call_git(["status", "-sb", "--porcelain"]) + except GitFailed as e: + os.chdir(old_dir) + raise e + os.chdir(old_dir) + return "behind" in status + + def current_tag(self, local_path) -> str: + """Get the name of the currently checked-out tag if HEAD is detached""" + old_dir = os.getcwd() + os.chdir(local_path) + try: + tag = self._synchronous_call_git(["describe", "--tags"]).strip() + except GitFailed as e: + os.chdir(old_dir) + raise e + os.chdir(old_dir) + return tag + + def current_branch(self, local_path) -> str: + """Get the name of the current branch""" + old_dir = os.getcwd() + os.chdir(local_path) + try: + # This only works with git 2.22 and later (June 2019) + # branch = self._synchronous_call_git(["branch", "--show-current"]).strip() + + # This is more universal: + branch = self._synchronous_call_git(["rev-parse", "--abbrev-ref", "HEAD"]).strip() + except GitFailed as e: + os.chdir(old_dir) + raise e + os.chdir(old_dir) + return branch + + def repair(self, remote, local_path): + """Assumes that local_path is supposed to be a local clone of the given remote, and + ensures that it is. Note that any local changes in local_path will be destroyed. This + is achieved by archiving the old path, cloning an entirely new copy, and then deleting + the old directory.""" + + original_cwd = os.getcwd() + + # Make sure we are not currently in that directory, otherwise on Windows the rename + # will fail. To guarantee we aren't in it, change to it, then shift up one. + os.chdir(local_path) + os.chdir("..") + backup_path = local_path + ".backup" + str(time.time()) + os.rename(local_path, backup_path) + try: + self.clone(remote, local_path) + except GitFailed as e: + FreeCAD.Console.PrintError( + translate( + "AddonsInstaller", "Failed to clone {} into {} using git" + ).format(remote, local_path) + ) + os.chdir(original_cwd) + raise e + os.chdir(original_cwd) + + def get_remote(self, local_path) -> str: + """Get the repository that this local path is set to fetch from""" + old_dir = os.getcwd() + os.chdir(local_path) + try: + response = self._synchronous_call_git(["remote", "-v", "show"]) + except GitFailed as e: + os.chdir(old_dir) + raise e + lines = response.split("\n") + result = "(unknown remote)" + for line in lines: + if line.endswith("(fetch)"): + + # The line looks like: + # origin https://some/sort/of/path (fetch) + + segments = line.split() + if len(segments) == 3: + result = segments[1] + break + FreeCAD.Console.PrintWarning( + "Error parsing the results from git remote -v show:\n" + ) + FreeCAD.Console.PrintWarning(line + "\n") + os.chdir(old_dir) + return result + + def _find_git(self): + # Find git. In preference order + # A) The value of the GitExecutable user preference + # B) The executable located in the same bin directory as FreeCAD and called "git" + # C) The result of an shutil search for your system's "git" executable + prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + git_exe = prefs.GetString("GitExecutable", "Not set") + if not git_exe or git_exe == "Not set" or not os.path.exists(git_exe): + fc_dir = FreeCAD.getHomePath() + git_exe = os.path.join(fc_dir, "bin", "git") + if "Windows" in platform.system(): + git_exe += ".exe" + + if not git_exe or not os.path.exists(git_exe): + git_exe = shutil.which("git") + + if not git_exe or not os.path.exists(git_exe): + return + + prefs.SetString("GitExecutable", git_exe) + self.git_exe = git_exe + + def _synchronous_call_git(self, args: List[str]) -> str: + """Calls git and returns its output.""" + final_args = [self.git_exe] + final_args.extend(args) + try: + if os.name == "nt": + proc = subprocess.run( + final_args, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=True, + shell=True # On Windows this will prevent all the pop-up consoles + ) + else: + proc = subprocess.run( + final_args, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=True, + ) + except subprocess.CalledProcessError as e: + raise GitFailed(str(e)) from e + + if proc.returncode != 0: + raise GitFailed( + f"Git returned a non-zero exit status: {proc.returncode}\n" + + f"Called with: {' '.join(final_args)}\n\n" + + f"Returned stderr:\n{proc.stderr.decode()}" + ) + + return proc.stdout.decode() diff --git a/src/Mod/AddonManager/addonmanager_macro.py b/src/Mod/AddonManager/addonmanager_macro.py index 6c2a7c7337..bb05f7ff0b 100644 --- a/src/Mod/AddonManager/addonmanager_macro.py +++ b/src/Mod/AddonManager/addonmanager_macro.py @@ -63,6 +63,7 @@ class Macro(object): self.comment = "" self.code = "" self.url = "" + self.raw_code_url = "" self.wiki = "" self.version = "" self.date = "" @@ -252,16 +253,16 @@ class Macro(object): # check if the macro page has its code hosted elsewhere, download if # needed if "rawcodeurl" in p: - rawcodeurl = re.findall('rawcodeurl.*?href="(http.*?)">', p) - if rawcodeurl: - rawcodeurl = rawcodeurl[0] - u2 = NetworkManager.AM_NETWORK_MANAGER.blocking_get(rawcodeurl) + self.raw_code_url = re.findall('rawcodeurl.*?href="(http.*?)">', p) + if self.raw_code_url: + self.raw_code_url = self.raw_code_url[0] + u2 = NetworkManager.AM_NETWORK_MANAGER.blocking_get(self.raw_code_url) if not u2: FreeCAD.Console.PrintWarning( translate( "AddonsInstaller", "Unable to open macro code URL {rawcodeurl}", - ).format(rawcodeurl) + ).format(self.raw_code_url) + "\n" ) return @@ -417,12 +418,29 @@ class Macro(object): src_file = os.path.normpath(os.path.join(base_dir, other_file)) dst_file = os.path.normpath(os.path.join(macro_dir, other_file)) if not os.path.isfile(src_file): - warnings.append( - translate( - "AddonsInstaller", - "Could not locate macro-specified file {} (should have been at {})", - ).format(other_file, src_file) - ) + # If the file does not exist, see if we have a raw code URL to fetch from + if self.raw_code_url: + fetch_url = self.raw_code_url.rsplit("/", 1)[0] + "/" + other_file + FreeCAD.Console.PrintLog(f"Attempting to fetch {fetch_url}...\n") + p = NetworkManager.AM_NETWORK_MANAGER.blocking_get(fetch_url) + if p: + with open(dst_file, "wb") as f: + f.write(p) + else: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Unable to fetch macro-specified file {} from {}", + ).format(other_file, fetch_url) + + "\n" + ) + else: + warnings.append( + translate( + "AddonsInstaller", + "Could not locate macro-specified file {} (should have been at {})", + ).format(other_file, src_file) + ) continue try: shutil.copy(src_file, dst_file) diff --git a/src/Mod/AddonManager/addonmanager_utilities.py b/src/Mod/AddonManager/addonmanager_utilities.py index 52e255c6d6..f02c37f09e 100644 --- a/src/Mod/AddonManager/addonmanager_utilities.py +++ b/src/Mod/AddonManager/addonmanager_utilities.py @@ -21,10 +21,14 @@ # * * # *************************************************************************** +""" Utilities to work across different platforms, providers and python versions """ + import os +import platform +import shutil import re import ctypes -from typing import Union, Optional, Any +from typing import Optional, Any from urllib.parse import urlparse @@ -44,7 +48,8 @@ translate = FreeCAD.Qt.translate def symlink(source, link_name): - """Creates a symlink of a file, if possible. Note that it fails on most modern Windows installations""" + """Creates a symlink of a file, if possible. Note that it fails on most modern Windows + installations""" if os.path.exists(link_name) or os.path.lexists(link_name): pass @@ -53,14 +58,15 @@ def symlink(source, link_name): if callable(os_symlink): os_symlink(source, link_name) else: - # NOTE: This does not work on most normal Windows 10 and later installations, unless developer - # mode is turned on. Make sure to catch any exception thrown and have a fallback plan. + # NOTE: This does not work on most normal Windows 10 and later installations, unless + # developer mode is turned on. Make sure to catch any exception thrown and have a + # fallback plan. csl = ctypes.windll.kernel32.CreateSymbolicLinkW csl.argtypes = (ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint32) csl.restype = ctypes.c_ubyte flags = 1 if os.path.isdir(source) else 0 # set the SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE flag - # (see https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10/#joC5tFKhdXs2gGml.97) + # (see https://blogs.windows.com/buildingapps/2016/12/02/symlinks-windows-10) flags += 2 if csl(link_name, source, flags) == 0: raise ctypes.WinError() @@ -76,9 +82,7 @@ def update_macro_details(old_macro, new_macro): if old_macro.on_git and new_macro.on_git: FreeCAD.Console.PrintLog( - 'The macro "{}" is present twice in github, please report'.format( - old_macro.name - ) + f'The macro "{old_macro.name}" is present twice in github, please report' ) # We don't report macros present twice on the wiki because a link to a # macro is considered as a macro. For example, 'Perpendicular To Wire' @@ -89,16 +93,14 @@ def update_macro_details(old_macro, new_macro): setattr(old_macro, attr, getattr(new_macro, attr)) -def remove_directory_if_empty(dir): - """Remove the directory if it is empty +def remove_directory_if_empty(dir_to_remove): + """Remove the directory if it is empty, with one exception: the directory returned by + FreeCAD.getUserMacroDir(True) will not be removed even if it is empty.""" - Directory FreeCAD.getUserMacroDir(True) will not be removed even if empty. - """ - - if dir == FreeCAD.getUserMacroDir(True): + if dir_to_remove == FreeCAD.getUserMacroDir(True): return - if not os.listdir(dir): - os.rmdir(dir) + if not os.listdir(dir_to_remove): + os.rmdir(dir_to_remove) def restart_freecad(): @@ -114,33 +116,30 @@ def restart_freecad(): def get_zip_url(repo): """Returns the location of a zip file from a repo, if available""" - parsedUrl = urlparse(repo.url) - if parsedUrl.netloc == "github.com": + parsed_url = urlparse(repo.url) + if parsed_url.netloc == "github.com": return f"{repo.url}/archive/{repo.branch}.zip" - elif parsed_url.netloc in ["gitlab.com", "framagit.org", "salsa.debian.org"]: - return f"{repo.url}/-/archive/{repo.branch}/{repo.name}-{repo.branch}.zip" - else: - FreeCAD.Console.PrintLog( - "Debug: addonmanager_utilities.get_zip_url: Unknown git host fetching zip URL:", - parsedUrl.netloc, - "\n", - ) + if parsed_url.netloc in ["gitlab.com", "framagit.org", "salsa.debian.org"]: return f"{repo.url}/-/archive/{repo.branch}/{repo.name}-{repo.branch}.zip" + FreeCAD.Console.PrintLog( + "Debug: addonmanager_utilities.get_zip_url: Unknown git host fetching zip URL:", + parsed_url.netloc, + "\n", + ) + return f"{repo.url}/-/archive/{repo.branch}/{repo.name}-{repo.branch}.zip" def recognized_git_location(repo) -> bool: - """Returns whether this repo is based at a known git repo location: works with github, gitlab, framagit, and salsa.debian.org""" + """Returns whether this repo is based at a known git repo location: works with github, gitlab, + framagit, and salsa.debian.org""" parsed_url = urlparse(repo.url) - if parsed_url.netloc in [ + return parsed_url.netloc in [ "github.com", "gitlab.com", "framagit.org", "salsa.debian.org", - ]: - return True - else: - return False + ] def construct_git_url(repo, filename): @@ -149,16 +148,15 @@ def construct_git_url(repo, filename): parsed_url = urlparse(repo.url) if parsed_url.netloc == "github.com": return f"{repo.url}/raw/{repo.branch}/{filename}" - elif parsed_url.netloc in ["gitlab.com", "framagit.org", "salsa.debian.org"]: - return f"{repo.url}/-/raw/{repo.branch}/{filename}" - else: - FreeCAD.Console.PrintLog( - "Debug: addonmanager_utilities.construct_git_url: Unknown git host:" - + parsed_url.netloc - + f" for file {filename}\n" - ) - # Assume it's some kind of local GitLab instance... + if parsed_url.netloc in ["gitlab.com", "framagit.org", "salsa.debian.org"]: return f"{repo.url}/-/raw/{repo.branch}/{filename}" + FreeCAD.Console.PrintLog( + "Debug: addonmanager_utilities.construct_git_url: Unknown git host:" + + parsed_url.netloc + + f" for file {filename}\n" + ) + # Assume it's some kind of local GitLab instance... + return f"{repo.url}/-/raw/{repo.branch}/{filename}" def get_readme_url(repo): @@ -180,15 +178,14 @@ def get_desc_regex(repo): parsedUrl = urlparse(repo.url) if parsedUrl.netloc == "github.com": return r'' - else: - FreeCAD.Console.PrintLog( - "Debug: addonmanager_utilities.get_desc_regex: Unknown git host:", - repo.url, - "\n", - ) + if parsedUrl.netloc in ["gitlab.com", "salsa.debian.org", "framagit.org"]: return r'' + FreeCAD.Console.PrintLog( + "Debug: addonmanager_utilities.get_desc_regex: Unknown git host:", + repo.url, + "\n", + ) + return r'' def get_readme_html_url(repo): @@ -197,62 +194,12 @@ def get_readme_html_url(repo): parsedUrl = urlparse(repo.url) if parsedUrl.netloc == "github.com": return f"{repo.url}/blob/{repo.branch}/README.md" - elif parsedUrl.netloc in ["gitlab.com", "salsa.debian.org", "framagit.org"]: + if parsedUrl.netloc in ["gitlab.com", "salsa.debian.org", "framagit.org"]: return f"{repo.url}/-/blob/{repo.branch}/README.md" - else: - FreeCAD.Console.PrintLog( - "Unrecognized git repo location '' -- guessing it is a GitLab instance..." - ) - return f"{repo.url}/-/blob/{repo.branch}/README.md" - - -def repair_git_repo(repo_url: str, clone_dir: str) -> None: - # Repair addon installed with raw download by adding the .git - # directory to it - - try: - import git - - # If GitPython is not installed, but the user has a directory named "git" in their Python path, they - # may have the import succeed, but it will not be a real GitPython installation - have_git = hasattr(git, "Repo") - if not have_git: - return - except ImportError: - return - - try: - bare_repo = git.Repo.clone_from( - repo_url, clone_dir + os.sep + ".git", bare=True - ) - with bare_repo.config_writer() as cw: - cw.set("core", "bare", False) - except AttributeError: - FreeCAD.Console.PrintLog( - translate( - "AddonsInstaller", - "Outdated GitPython detected, consider upgrading with pip.", - ) - + "\n" - ) - cw = bare_repo.config_writer() - cw.set("core", "bare", False) - del cw - except Exception as e: - FreeCAD.Console.PrintWarning( - translate("AddonsInstaller", "Failed to repair missing .git directory") - + "\n" - ) - FreeCAD.Console.PrintWarning( - translate("AddonsInstaller", "Repository URL") + f": {repo_url}\n" - ) - FreeCAD.Console.PrintWarning( - translate("AddonsInstaller", "Clone directory") + f": {clone_dir}\n" - ) - FreeCAD.Console.PrintWarning(e) - return - repo = git.Repo(clone_dir) - repo.head.reset("--hard") + FreeCAD.Console.PrintLog( + "Unrecognized git repo location '' -- guessing it is a GitLab instance..." + ) + return f"{repo.url}/-/blob/{repo.branch}/README.md" def is_darkmode() -> bool: @@ -292,11 +239,11 @@ def get_assigned_string_literal(line: str) -> Optional[str]: def get_macro_version_from_file(filename: str) -> str: - """Get the version of the macro from a local macro file. Supports strings, ints, and floats, as - well as a reference to __date__""" + """Get the version of the macro from a local macro file. Supports strings, ints, and floats, + as well as a reference to __date__""" date = "" - with open(filename, "r", errors="ignore") as f: + with open(filename, "r", errors="ignore", encoding="utf-8") as f: line_counter = 0 max_lines_to_scan = 200 while line_counter < max_lines_to_scan: @@ -308,9 +255,20 @@ def get_macro_version_from_file(filename: str) -> str: match = get_assigned_string_literal(line) if match: return match - elif "__date__" in line.lower(): - # Don't do any real syntax checking, just assume the line is something like __version__ = __date__ - return date + if "__date__" in line.lower(): + # Don't do any real syntax checking, just assume the line is something + # like __version__ = __date__ + if date: + return date + # pylint: disable=line-too-long,consider-using-f-string + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Macro {} specified '__version__ = __date__' prior to setting a value for __date__".format( + filename + ), + ) + ) elif line.lower().startswith("__date__"): match = get_assigned_string_literal(line) if match: @@ -319,8 +277,10 @@ def get_macro_version_from_file(filename: str) -> str: def update_macro_installation_details(repo) -> None: + """Determine if a given macro is installed, either in its plain name, + or prefixed with "Macro_" """ if repo is None or not hasattr(repo, "macro") or repo.macro is None: - FreeCAD.Console.PrintLog(f"Requested macro details for non-macro object\n") + FreeCAD.Console.PrintLog("Requested macro details for non-macro object\n") return test_file_one = os.path.join(FreeCAD.getUserMacroDir(True), repo.macro.filename) test_file_two = os.path.join( @@ -336,8 +296,10 @@ def update_macro_installation_details(repo) -> None: return -# Borrowed from Stack Overflow: https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python +# Borrowed from Stack Overflow: +# https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float def is_float(element: Any) -> bool: + """Determine whether a given item can be converted to a floating-point number""" try: float(element) return True @@ -346,3 +308,44 @@ def is_float(element: Any) -> bool: # @} + + +def get_python_exe() -> str: + """Find Python. In preference order + A) The value of the PythonExecutableForPip user preference + B) The executable located in the same bin directory as FreeCAD and called "python3" + C) The executable located in the same bin directory as FreeCAD and called "python" + D) The result of an shutil search for your system's "python3" executable + E) The result of an shutil search for your system's "python" executable""" + prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + python_exe = prefs.GetString("PythonExecutableForPip", "Not set") + if not python_exe or python_exe == "Not set" or not os.path.exists(python_exe): + fc_dir = FreeCAD.getHomePath() + python_exe = os.path.join(fc_dir, "bin", "python3") + if "Windows" in platform.system(): + python_exe += ".exe" + + if not python_exe or not os.path.exists(python_exe): + python_exe = os.path.join(fc_dir, "bin", "python") + if "Windows" in platform.system(): + python_exe += ".exe" + + if not python_exe or not os.path.exists(python_exe): + python_exe = shutil.which("python3") + + if not python_exe or not os.path.exists(python_exe): + python_exe = shutil.which("python") + + if not python_exe or not os.path.exists(python_exe): + return "" + + prefs.SetString("PythonExecutableForPip", python_exe) + return python_exe + + +def get_cache_file_name(file: str) -> str: + """Get the full path to a cache file with a given name.""" + cache_path = FreeCAD.getUserCachePath() + am_path = os.path.join(cache_path, "AddonManager") + os.makedirs(am_path, exist_ok=True) + return os.path.join(am_path, file) diff --git a/src/Mod/AddonManager/addonmanager_workers.py b/src/Mod/AddonManager/addonmanager_workers.py deleted file mode 100644 index 9b8c14bba1..0000000000 --- a/src/Mod/AddonManager/addonmanager_workers.py +++ /dev/null @@ -1,1788 +0,0 @@ -# -*- coding: utf-8 -*- -# *************************************************************************** -# * * -# * Copyright (c) 2019 Yorik van Havre * -# * Copyright (c) 2022 FreeCAD Project Association * -# * * -# * 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 * -# * * -# *************************************************************************** - -import os -import re -import shutil -import stat -import json -import tempfile -import hashlib -import threading -import queue -import io -import time -import subprocess -import sys -import platform -import itertools -from datetime import datetime -from typing import Union, List, Dict -from enum import Enum, auto - - -from PySide2 import QtCore - -import FreeCAD - -if FreeCAD.GuiUp: - import FreeCADGui - -import addonmanager_utilities as utils -from addonmanager_macro import Macro - -from Addon import Addon -import NetworkManager - -translate = FreeCAD.Qt.translate - -have_git = False -try: - import git - - # some versions of git module have no "Repo" class?? Bug #4072 module - # 'git' has no attribute 'Repo' - have_git = hasattr(git, "Repo") - if not have_git: - FreeCAD.Console.PrintMessage( - "'import git' gave strange results (no Repo attribute)... do you have GitPython installed?" - ) -except ImportError: - pass - -have_zip = False -try: - import zipfile - - have_zip = True -except ImportError: - pass - -have_markdown = False -try: - import markdown - - have_markdown = True -except ImportError: - pass - -# @package AddonManager_workers -# \ingroup ADDONMANAGER -# \brief Multithread workers for the addon manager -# @{ - -# reject_listed addons -macros_reject_list = [] -mod_reject_list = [] - -# These addons will print an additional message informing the user -obsolete = [] - -# These addons will print an additional message informing the user Python2 only -py2only = [] - -NOGIT = False # for debugging purposes, set this to True to always use http downloads -NOMARKDOWN = False # for debugging purposes, set this to True to disable Markdown lib -"""Multithread workers for the Addon Manager""" - - -class ConnectionChecker(QtCore.QThread): - - success = QtCore.Signal() - failure = QtCore.Signal(str) - - def __init__(self): - QtCore.QThread.__init__(self) - - def run(self): - FreeCAD.Console.PrintLog("Checking network connection...\n") - url = "https://api.github.com/zen" - result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - if not result: - self.failure.emit( - translate( - "AddonsInstaller", - "Unable to read data from GitHub: check your internet connection and proxy settings and try again.", - ) - ) - return - - result = result.data().decode("utf8") - FreeCAD.Console.PrintLog(f"GitHub's zen message response: {result}\n") - self.success.emit() - - -class UpdateWorker(QtCore.QThread): - """This worker updates the list of available workbenches""" - - status_message = QtCore.Signal(str) - addon_repo = QtCore.Signal(object) - - def __init__(self): - - QtCore.QThread.__init__(self) - - def run(self): - "populates the list of addons" - - self.current_thread = QtCore.QThread.currentThread() - - # update info lists - global obsolete, macros_reject_list, mod_reject_list, py2only - p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( - "https://raw.githubusercontent.com/FreeCAD/FreeCAD-addons/master/addonflags.json" - ) - if p: - p = p.data().decode("utf8") - j = json.loads(p) - if "obsolete" in j and "Mod" in j["obsolete"]: - obsolete = j["obsolete"]["Mod"] - - if "blacklisted" in j and "Macro" in j["blacklisted"]: - macros_reject_list = j["blacklisted"]["Macro"] - - if "blacklisted" in j and "Mod" in j["blacklisted"]: - mod_reject_list = j["blacklisted"]["Mod"] - - if "py2only" in j and "Mod" in j["py2only"]: - py2only = j["py2only"]["Mod"] - - if "deprecated" in j: - fc_major = int(FreeCAD.Version()[0]) - fc_minor = int(FreeCAD.Version()[1]) - for item in j["deprecated"]: - if "as_of" in item and "name" in item: - try: - version_components = item["as_of"].split(".") - major = int(version_components[0]) - if len(version_components) > 1: - minor = int(version_components[1]) - else: - minor = 0 - if major < fc_major or ( - major == fc_major and minor <= fc_minor - ): - if "kind" not in item or item["kind"] == "mod": - obsolete.append(item["name"]) - elif item["kind"] == "macro": - macros_reject_list.append(item["name"]) - else: - FreeCAD.Console.PrintMessage( - f'Unrecognized Addon kind {item["kind"]} in deprecation list.' - ) - except Exception: - FreeCAD.Console.PrintMessage( - f"Exception caught when parsing deprecated Addon {item['name']}, version {item['as_of']}" - ) - - else: - message = translate( - "AddonsInstaller", - "Failed to connect to GitHub. Check your connection and proxy settings.", - ) - FreeCAD.Console.PrintError(message + "\n") - self.status_message.emit(message) - return - - basedir = FreeCAD.getUserAppDataDir() - moddir = basedir + os.sep + "Mod" - package_names = [] - - # querying custom addons first - addon_list = ( - FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") - .GetString("CustomRepositories", "") - .split("\n") - ) - custom_addons = [] - for addon in addon_list: - if " " in addon: - addon_and_branch = addon.split(" ") - custom_addons.append( - {"url": addon_and_branch[0], "branch": addon_and_branch[1]} - ) - else: - custom_addons.append({"url": addon, "branch": "master"}) - for addon in custom_addons: - if self.current_thread.isInterruptionRequested(): - return - if addon and addon["url"]: - if addon["url"][-1] == "/": - addon["url"] = addon["url"][0:-1] # Strip trailing slash - addon["url"] = addon["url"].split(".git")[0] # Remove .git - name = addon["url"].split("/")[-1] - if name in package_names: - # We already have something with this name, skip this one - continue - package_names.append(name) - addondir = moddir + os.sep + name - if os.path.exists(addondir) and os.listdir(addondir): - state = Addon.Status.UNCHECKED - else: - state = Addon.Status.NOT_INSTALLED - repo = Addon(name, addon["url"], state, addon["branch"]) - md_file = os.path.join(addondir, "package.xml") - if os.path.isfile(md_file): - repo.load_metadata_file(md_file) - repo.installed_version = repo.metadata.Version - repo.updated_timestamp = os.path.getmtime(md_file) - repo.verify_url_and_branch(addon["url"], addon["branch"]) - - self.addon_repo.emit(repo) - - # querying official addons - p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( - "https://raw.githubusercontent.com/FreeCAD/FreeCAD-addons/master/.gitmodules" - ) - if not p: - return - p = p.data().decode("utf8") - p = re.findall( - ( - r'(?m)\[submodule\s*"(?P.*)"\]\s*' - r"path\s*=\s*(?P.+)\s*" - r"url\s*=\s*(?Phttps?://.*)\s*" - r"(branch\s*=\s*(?P[^\s]*)\s*)?" - ), - p, - ) - for name, _, url, _, branch in p: - if self.current_thread.isInterruptionRequested(): - return - if name in package_names: - # We already have something with this name, skip this one - continue - package_names.append(name) - if branch is None or len(branch) == 0: - branch = "master" - url = url.split(".git")[0] - addondir = moddir + os.sep + name - if os.path.exists(addondir) and os.listdir(addondir): - # make sure the folder exists and it contains files! - state = Addon.Status.UNCHECKED - else: - state = Addon.Status.NOT_INSTALLED - repo = Addon(name, url, state, branch) - md_file = os.path.join(addondir, "package.xml") - if os.path.isfile(md_file): - repo.load_metadata_file(md_file) - repo.installed_version = repo.metadata.Version - repo.updated_timestamp = os.path.getmtime(md_file) - repo.verify_url_and_branch(url, branch) - - if name in py2only: - repo.python2 = True - if name in mod_reject_list: - repo.rejected = True - if name in obsolete: - repo.obsolete = True - self.addon_repo.emit(repo) - - self.status_message.emit( - translate("AddonsInstaller", "Workbenches list was updated.") - ) - - -class LoadPackagesFromCacheWorker(QtCore.QThread): - addon_repo = QtCore.Signal(object) - - def __init__(self, cache_file: str): - QtCore.QThread.__init__(self) - self.cache_file = cache_file - - def run(self): - metadata_cache_path = os.path.join( - FreeCAD.getUserCachePath(), "AddonManager", "PackageMetadata" - ) - with open(self.cache_file, "r") as f: - data = f.read() - if data: - dict_data = json.loads(data) - for item in dict_data.values(): - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - repo = Addon.from_cache(item) - repo_metadata_cache_path = os.path.join( - metadata_cache_path, repo.name, "package.xml" - ) - if os.path.isfile(repo_metadata_cache_path): - try: - repo.load_metadata_file(repo_metadata_cache_path) - repo.installed_version = repo.metadata.Version - repo.updated_timestamp = os.path.getmtime( - repo_metadata_cache_path - ) - except Exception: - FreeCAD.Console.PrintLog( - f"Failed loading {repo_metadata_cache_path}\n" - ) - self.addon_repo.emit(repo) - - -class LoadMacrosFromCacheWorker(QtCore.QThread): - add_macro_signal = QtCore.Signal(object) - - def __init__(self, cache_file: str): - QtCore.QThread.__init__(self) - self.cache_file = cache_file - - def run(self): - with open(self.cache_file, "r") as f: - data = f.read() - dict_data = json.loads(data) - for item in dict_data: - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - new_macro = Macro.from_cache(item) - repo = Addon.from_macro(new_macro) - utils.update_macro_installation_details(repo) - self.add_macro_signal.emit(repo) - - -class CheckSingleUpdateWorker(QtCore.QObject): - """This worker is a little different from the others: the actual recommended way of - running in a QThread is to make a worker object that gets moved into the thread.""" - - update_status = QtCore.Signal(int) - - def __init__(self, repo: Addon, parent: QtCore.QObject = None): - super().__init__(parent) - self.repo = repo - - def do_work(self): - # Borrow the function from another class: - checker = UpdateChecker() - if self.repo.repo_type == Addon.Kind.WORKBENCH: - checker.check_workbench(self.repo) - elif self.repo.repo_type == Addon.Kind.MACRO: - checker.check_macro(self.repo) - elif self.repo.repo_type == Addon.Kind.PACKAGE: - checker.check_package(self.repo) - - self.update_status.emit(self.repo.update_status) - - -class CheckWorkbenchesForUpdatesWorker(QtCore.QThread): - """This worker checks for available updates for all workbenches""" - - update_status = QtCore.Signal(Addon) - progress_made = QtCore.Signal(int, int) - - def __init__(self, repos: List[Addon]): - - QtCore.QThread.__init__(self) - self.repos = repos - - def run(self): - - self.current_thread = QtCore.QThread.currentThread() - self.basedir = FreeCAD.getUserAppDataDir() - self.moddir = self.basedir + os.sep + "Mod" - checker = UpdateChecker() - count = 1 - for repo in self.repos: - if self.current_thread.isInterruptionRequested(): - return - self.progress_made.emit(count, len(self.repos)) - count += 1 - if repo.status() == Addon.Status.UNCHECKED: - if repo.repo_type == Addon.Kind.WORKBENCH: - checker.check_workbench(repo) - self.update_status.emit(repo) - elif repo.repo_type == Addon.Kind.MACRO: - checker.check_macro(repo) - self.update_status.emit(repo) - elif repo.repo_type == Addon.Kind.PACKAGE: - checker.check_package(repo) - self.update_status.emit(repo) - - -class UpdateChecker: - def __init__(self): - self.basedir = FreeCAD.getUserAppDataDir() - self.moddir = self.basedir + os.sep + "Mod" - - def check_workbench(self, wb): - if not have_git or NOGIT: - wb.set_status(Addon.Status.CANNOT_CHECK) - return - clonedir = self.moddir + os.sep + wb.name - if os.path.exists(clonedir): - # mark as already installed AND already checked for updates - if not os.path.exists(clonedir + os.sep + ".git"): - with wb.git_lock: - utils.repair_git_repo(wb.url, clonedir) - with wb.git_lock: - gitrepo = git.Repo(clonedir) - try: - if gitrepo.head.is_detached: - # By definition, in a detached-head state we cannot - # update, so don't even bother checking. - wb.set_status(Addon.Status.NO_UPDATE_AVAILABLE) - if hasattr(gitrepo.head, "ref"): - wb.branch = gitrepo.head.ref.name - else: - wb.branch = gitrepo.head.name - return - gitrepo.git.fetch() - except Exception as e: - FreeCAD.Console.PrintWarning( - "AddonManager: " - + translate( - "AddonsInstaller", - "Unable to fetch git updates for workbench {}", - ).format(wb.name) - + "\n" - ) - FreeCAD.Console.PrintWarning(str(e) + "\n") - wb.set_status(Addon.Status.CANNOT_CHECK) - else: - try: - if "git pull" in gitrepo.git.status(): - wb.set_status(Addon.Status.UPDATE_AVAILABLE) - else: - wb.set_status(Addon.Status.NO_UPDATE_AVAILABLE) - except Exception: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", "git fetch failed for {}" - ).format(wb.name) - + "\n" - ) - wb.set_status(Addon.Status.CANNOT_CHECK) - - def check_package(self, package: Addon) -> None: - clonedir = self.moddir + os.sep + package.name - if os.path.exists(clonedir): - - # First, try to just do a git-based update, which will give the most accurate results: - if have_git and not NOGIT: - self.check_workbench(package) - if package.status() != Addon.Status.CANNOT_CHECK: - # It worked, just exit now - return - - # If we were unable to do a git-based update, try using the package.xml file instead: - installed_metadata_file = os.path.join(clonedir, "package.xml") - if not os.path.isfile(installed_metadata_file): - # If there is no package.xml file, then it's because the package author added it after the last time - # the local installation was updated. By definition, then, there is an update available, if only to - # download the new XML file. - package.set_status(Addon.Status.UPDATE_AVAILABLE) - package.installed_version = None - return - else: - package.updated_timestamp = os.path.getmtime(installed_metadata_file) - try: - installed_metadata = FreeCAD.Metadata(installed_metadata_file) - package.installed_version = installed_metadata.Version - # Packages are considered up-to-date if the metadata version matches. Authors should update - # their version string when they want the addon manager to alert users of a new version. - if package.metadata.Version != installed_metadata.Version: - package.set_status(Addon.Status.UPDATE_AVAILABLE) - else: - package.set_status(Addon.Status.NO_UPDATE_AVAILABLE) - except Exception: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Failed to read metadata from {name}", - ).format(name=installed_metadata_file) - + "\n" - ) - package.set_status(Addon.Status.CANNOT_CHECK) - - def check_macro(self, macro_wrapper: Addon) -> None: - # Make sure this macro has its code downloaded: - try: - if not macro_wrapper.macro.parsed and macro_wrapper.macro.on_git: - macro_wrapper.macro.fill_details_from_file( - macro_wrapper.macro.src_filename - ) - elif not macro_wrapper.macro.parsed and macro_wrapper.macro.on_wiki: - mac = macro_wrapper.macro.name.replace(" ", "_") - mac = mac.replace("&", "%26") - mac = mac.replace("+", "%2B") - url = "https://wiki.freecad.org/Macro_" + mac - macro_wrapper.macro.fill_details_from_wiki(url) - except Exception: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Failed to fetch code for macro '{name}'", - ).format(name=macro_wrapper.macro.name) - + "\n" - ) - macro_wrapper.set_status(Addon.Status.CANNOT_CHECK) - return - - hasher1 = hashlib.sha1() - hasher2 = hashlib.sha1() - hasher1.update(macro_wrapper.macro.code.encode("utf-8")) - new_sha1 = hasher1.hexdigest() - test_file_one = os.path.join( - FreeCAD.getUserMacroDir(True), macro_wrapper.macro.filename - ) - test_file_two = os.path.join( - FreeCAD.getUserMacroDir(True), "Macro_" + macro_wrapper.macro.filename - ) - if os.path.exists(test_file_one): - with open(test_file_one, "rb") as f: - contents = f.read() - hasher2.update(contents) - old_sha1 = hasher2.hexdigest() - elif os.path.exists(test_file_two): - with open(test_file_two, "rb") as f: - contents = f.read() - hasher2.update(contents) - old_sha1 = hasher2.hexdigest() - else: - return - if new_sha1 == old_sha1: - macro_wrapper.set_status(Addon.Status.NO_UPDATE_AVAILABLE) - else: - macro_wrapper.set_status(Addon.Status.UPDATE_AVAILABLE) - - -class FillMacroListWorker(QtCore.QThread): - """This worker populates the list of macros""" - - add_macro_signal = QtCore.Signal(object) - status_message_signal = QtCore.Signal(str) - progress_made = QtCore.Signal(int, int) - - def __init__(self, repo_dir): - - QtCore.QThread.__init__(self) - self.repo_dir = repo_dir - self.repo_names = [] - - def run(self): - """Populates the list of macros""" - - self.current_thread = QtCore.QThread.currentThread() - - if not self.current_thread.isInterruptionRequested(): - self.status_message_signal.emit( - translate( - "AddonsInstaller", - "Retrieving macros from FreeCAD/FreeCAD-Macros Git repository", - ) - ) - self.retrieve_macros_from_git() - - if not self.current_thread.isInterruptionRequested(): - self.status_message_signal.emit( - translate( - "AddonsInstaller", - "Retrieving macros from FreeCAD wiki", - ) - ) - self.retrieve_macros_from_wiki() - - if self.current_thread.isInterruptionRequested(): - return - - self.status_message_signal.emit( - translate("AddonsInstaller", "Done locating macros.") - ) - - def retrieve_macros_from_git(self): - """Retrieve macros from FreeCAD-macros.git - - Emits a signal for each macro in - https://github.com/FreeCAD/FreeCAD-macros.git - """ - - if not have_git or NOGIT: - message = translate( - "AddonsInstaller", - "Failed to execute Git Python command: check installation of GitPython and/or git", - ) - self.status_message_signal.emit(message) - FreeCAD.Console.PrintWarning(message + "\n") - return - - try: - if os.path.exists(self.repo_dir): - if not os.path.exists(os.path.join(self.repo_dir, ".git")): - FreeCAD.Console.PrintWarning(translate("AddonsInstaller","Attempting to change non-git Macro setup to use git\n")) - utils.repair_git_repo( - "https://github.com/FreeCAD/FreeCAD-macros.git", self.repo_dir - ) - gitrepo = git.Git(self.repo_dir) - gitrepo.pull("--ff-only") - else: - git.Repo.clone_from( - "https://github.com/FreeCAD/FreeCAD-macros.git", self.repo_dir - ) - except Exception as e: - FreeCAD.Console.PrintMessage( - translate( - "AddonsInstaller", "An error occurred updating macros from GitHub, trying clean checkout..." - ) - + f":\n{e}\n" - ) - FreeCAD.Console.PrintMessage(f"{self.repo_dir}\n") - FreeCAD.Console.PrintMessage( - translate( - "AddonsInstaller", "Attempting to do a clean checkout..." - ) + "\n" - ) - try: - shutil.rmtree(self.repo_dir, onerror=self.remove_readonly) - git.Repo.clone_from( - "https://github.com/FreeCAD/FreeCAD-macros.git", self.repo_dir - ) - FreeCAD.Console.PrintMessage( - translate( - "AddonsInstaller", "Clean checkout succeeded" - ) - + "\n" - ) - except Exception as e: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", "Failed to update macros from GitHub -- try clearing the Addon Manager's cache." - ) - + f":\n{str(e)}\n" - ) - return - n_files = 0 - for _, _, filenames in os.walk(self.repo_dir): - n_files += len(filenames) - counter = 0 - for dirpath, _, filenames in os.walk(self.repo_dir): - self.progress_made.emit(counter, n_files) - counter += 1 - if self.current_thread.isInterruptionRequested(): - return - if ".git" in dirpath: - continue - for filename in filenames: - if self.current_thread.isInterruptionRequested(): - return - if filename.lower().endswith(".fcmacro"): - macro = Macro(filename[:-8]) # Remove ".FCMacro". - macro.on_git = True - macro.src_filename = os.path.join(dirpath, filename) - macro.fill_details_from_file(macro.src_filename) - repo = Addon.from_macro(macro) - FreeCAD.Console.PrintLog(f"Found macro {repo.name}\n") - repo.url = "https://github.com/FreeCAD/FreeCAD-macros.git" - utils.update_macro_installation_details(repo) - self.add_macro_signal.emit(repo) - - def retrieve_macros_from_wiki(self): - """Retrieve macros from the wiki - - Read the wiki and emit a signal for each found macro. - Reads only the page https://wiki.freecad.org/Macros_recipes - """ - - p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( - "https://wiki.freecad.org/Macros_recipes" - ) - if not p: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Error connecting to the Wiki, FreeCAD cannot retrieve the Wiki macro list at this time", - ) - + "\n" - ) - return - p = p.data().decode("utf8") - macros = re.findall('title="(Macro.*?)"', p) - macros = [mac for mac in macros if ("translated" not in mac)] - macro_names = [] - for i, mac in enumerate(macros): - self.progress_made.emit(i, len(macros)) - if self.current_thread.isInterruptionRequested(): - return - macname = mac[6:] # Remove "Macro ". - macname = macname.replace("&", "&") - if not macname: - continue - if ( - (macname not in macros_reject_list) - and ("recipes" not in macname.lower()) - and (macname not in macro_names) - ): - macro_names.append(macname) - macro = Macro(macname) - macro.on_wiki = True - macro.parsed = False - repo = Addon.from_macro(macro) - repo.url = "https://wiki.freecad.org/Macros_recipes" - utils.update_macro_installation_details(repo) - self.add_macro_signal.emit(repo) - - def remove_readonly(self, func, path, _) -> None: - """Remove a read-only file.""" - - os.chmod(path, stat.S_IWRITE) - func(path) - - -class CacheMacroCode(QtCore.QThread): - """Download and cache the macro code, and parse its internal metadata""" - - status_message = QtCore.Signal(str) - update_macro = QtCore.Signal(Addon) - progress_made = QtCore.Signal(int, int) - - def __init__(self, repos: List[Addon]) -> None: - QtCore.QThread.__init__(self) - self.repos = repos - self.workers = [] - self.terminators = [] - self.lock = threading.Lock() - self.failed = [] - self.counter = 0 - - def run(self): - self.status_message.emit(translate("AddonsInstaller", "Caching macro code...")) - - self.repo_queue = queue.Queue() - current_thread = QtCore.QThread.currentThread() - num_macros = 0 - for repo in self.repos: - if repo.macro is not None: - self.repo_queue.put(repo) - num_macros += 1 - - # Emulate QNetworkAccessManager and spool up six connections: - for _ in range(6): - self.update_and_advance(None) - - while True: - if current_thread.isInterruptionRequested(): - for worker in self.workers: - worker.blockSignals(True) - worker.requestInterruption() - if not worker.wait(100): - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Addon Manager: a worker process failed to halt ({name})", - ).format(name=worker.macro.name) - + "\n" - ) - return - # Ensure our signals propagate out by running an internal thread-local event loop - QtCore.QCoreApplication.processEvents() - with self.lock: - if self.counter >= num_macros: - break - time.sleep(0.1) - - # Make sure all of our child threads have fully exited: - for worker in self.workers: - worker.wait(50) - if not worker.isFinished(): - FreeCAD.Console.PrintError( - translate( - "AddonsInstaller", - "Addon Manager: a worker process failed to complete while fetching {name}", - ).format(name=worker.macro.name) - + "\n" - ) - - self.repo_queue.join() - for terminator in self.terminators: - if terminator and terminator.isActive(): - terminator.stop() - - if len(self.failed) > 0: - num_failed = len(self.failed) - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Out of {num_macros} macros, {num_failed} timed out while processing", - ).format(num_macros=num_macros, num_failed=num_failed) - ) - - def update_and_advance(self, repo: Addon) -> None: - if repo is not None: - if repo.macro.name not in self.failed: - self.update_macro.emit(repo) - self.repo_queue.task_done() - with self.lock: - self.counter += 1 - - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - - self.progress_made.emit( - len(self.repos) - self.repo_queue.qsize(), len(self.repos) - ) - - try: - next_repo = self.repo_queue.get_nowait() - worker = GetMacroDetailsWorker(next_repo) - worker.finished.connect(lambda: self.update_and_advance(next_repo)) - with self.lock: - self.workers.append(worker) - self.terminators.append( - QtCore.QTimer.singleShot(10000, lambda: self.terminate(worker)) - ) - self.status_message.emit( - translate( - "AddonsInstaller", - "Getting metadata from macro {}", - ).format(next_repo.macro.name) - ) - worker.start() - except queue.Empty: - pass - - def terminate(self, worker) -> None: - if not worker.isFinished(): - macro_name = worker.macro.name - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "Timeout while fetching metadata for macro {}", - ).format(macro_name) - + "\n" - ) - worker.blockSignals(True) - worker.requestInterruption() - worker.wait(100) - if worker.isRunning(): - FreeCAD.Console.PrintError( - translate( - "AddonsInstaller", - "Failed to kill process for macro {}!\n", - ).format(macro_name) - ) - with self.lock: - self.failed.append(macro_name) - - -class GetMacroDetailsWorker(QtCore.QThread): - """Retrieve the macro details for a macro""" - - status_message = QtCore.Signal(str) - readme_updated = QtCore.Signal(str) - - def __init__(self, repo): - - QtCore.QThread.__init__(self) - self.macro = repo.macro - - def run(self): - - self.status_message.emit( - translate("AddonsInstaller", "Retrieving macro description...") - ) - if not self.macro.parsed and self.macro.on_git: - self.status_message.emit( - translate("AddonsInstaller", "Retrieving info from git") - ) - self.macro.fill_details_from_file(self.macro.src_filename) - if not self.macro.parsed and self.macro.on_wiki: - self.status_message.emit( - translate("AddonsInstaller", "Retrieving info from wiki") - ) - mac = self.macro.name.replace(" ", "_") - mac = mac.replace("&", "%26") - mac = mac.replace("+", "%2B") - url = "https://wiki.freecad.org/Macro_" + mac - self.macro.fill_details_from_wiki(url) - message = ( - "

" - + self.macro.name - + "

" - + self.macro.desc - + '

Macro location: ' - + self.macro.url - + "" - ) - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - self.readme_updated.emit(message) - - -class InstallWorkbenchWorker(QtCore.QThread): - "This worker installs a workbench" - - status_message = QtCore.Signal(str) - progress_made = QtCore.Signal(int, int) - success = QtCore.Signal(Addon, str) - failure = QtCore.Signal(Addon, str) - - def __init__(self, repo: Addon): - - QtCore.QThread.__init__(self) - self.repo = repo - self.update_timer = QtCore.QTimer() - self.update_timer.setInterval(100) - self.update_timer.timeout.connect(self.update_status) - self.update_timer.start() - - def run(self): - "installs or updates the selected addon" - - if not self.repo: - return - - if not have_git or NOGIT: - FreeCAD.Console.PrintLog( - translate( - "AddonsInstaller", - "GitPython not found. Using ZIP file download instead.", - ) - + "\n" - ) - if not have_zip: - FreeCAD.Console.PrintError( - translate( - "AddonsInstaller", - "Your version of Python doesn't appear to support ZIP files. Unable to proceed.", - ) - + "\n" - ) - return - - basedir = FreeCAD.getUserAppDataDir() - moddir = basedir + os.sep + "Mod" - if not os.path.exists(moddir): - os.makedirs(moddir) - target_dir = moddir + os.sep + self.repo.name - - if have_git and not NOGIT: - # Do the git process... - self.run_git(target_dir) - else: - - # The zip process uses an event loop, since the download can potentially be quite large - self.launch_zip(target_dir) - self.zip_complete = False - current_thread = QtCore.QThread.currentThread() - while not self.zip_complete: - if current_thread.isInterruptionRequested(): - return - QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) - - def update_status(self) -> None: - if hasattr(self, "git_progress") and self.isRunning(): - self.progress_made.emit(self.git_progress.current, self.git_progress.total) - self.status_message.emit(self.git_progress.message) - - def run_git(self, clonedir: str) -> None: - - if NOGIT or not have_git: - FreeCAD.Console.PrintLog( - translate( - "AddonsInstaller", - "No Git Python installed, skipping git operations", - ) - + "\n" - ) - return - - self.git_progress = GitProgressMonitor() - - if os.path.exists(clonedir): - self.run_git_update(clonedir) - else: - self.run_git_clone(clonedir) - - def run_git_update(self, clonedir: str) -> None: - self.status_message.emit("Updating module...") - if str(self.repo.name) in py2only: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "You are installing a Python 2 workbench on a system running Python 3 - ", - ) - + str(self.repo.name) - + "\n" - ) - with self.repo.git_lock: - if not os.path.exists(clonedir + os.sep + ".git"): - utils.repair_git_repo(self.repo.url, clonedir) - repo = git.Git(clonedir) - try: - repo.pull("--ff-only") # Refuses to take a progress object? - if self.repo.contains_workbench(): - answer = translate( - "AddonsInstaller", - "Workbench successfully updated. Please restart FreeCAD to apply the changes.", - ) - else: - answer = translate( - "AddonsInstaller", - "Workbench successfully updated.", - ) - except Exception as e: - answer = ( - translate("AddonsInstaller", "Error updating module") - + " " - + self.repo.name - + " - " - + translate("AddonsInstaller", "Please fix manually") - + " -- \n" - ) - answer += str(e) - self.failure.emit(self.repo, answer) - else: - # Update the submodules for this repository - repo_sms = git.Repo(clonedir) - self.status_message.emit("Updating submodules...") - for submodule in repo_sms.submodules: - submodule.update(init=True, recursive=True) - self.update_metadata() - self.success.emit(self.repo, answer) - - def run_git_clone(self, clonedir: str) -> None: - self.status_message.emit("Checking module dependencies...") - if str(self.repo.name) in py2only: - FreeCAD.Console.PrintWarning( - translate( - "AddonsInstaller", - "You are installing a Python 2 workbench on a system running Python 3 - ", - ) - + str(self.repo.name) - + "\n" - ) - self.status_message.emit("Cloning module...") - current_thread = QtCore.QThread.currentThread() - - FreeCAD.Console.PrintMessage("Cloning repo...\n") - if self.repo.git_lock.locked(): - FreeCAD.Console.PrintMessage("Waiting for lock to be released to us...\n") - if not self.repo.git_lock.acquire(timeout=2): - FreeCAD.Console.PrintError( - "Timeout waiting for a lock on the git process, failed to clone repo\n" - ) - return - else: - self.repo.git_lock.release() - - with self.repo.git_lock: - FreeCAD.Console.PrintMessage("Lock acquired...\n") - # NOTE: There is no way to interrupt this process in GitPython: someday we should - # support pygit2/libgit2 so we can actually interrupt this properly. - repo = git.Repo.clone_from( - self.repo.url, clonedir, progress=self.git_progress - ) - FreeCAD.Console.PrintMessage("Initial clone complete...\n") - if current_thread.isInterruptionRequested(): - return - - # Make sure to clone all the submodules as well - if repo.submodules: - FreeCAD.Console.PrintMessage("Updating submodules...\n") - repo.submodule_update(recursive=True) - - if current_thread.isInterruptionRequested(): - return - - if self.repo.branch in repo.heads: - FreeCAD.Console.PrintMessage("Checking out HEAD...\n") - repo.heads[self.repo.branch].checkout() - - FreeCAD.Console.PrintMessage("Clone complete\n") - - if self.repo.contains_workbench(): - answer = translate( - "AddonsInstaller", - "Workbench successfully installed. Please restart FreeCAD to apply the changes.", - ) - else: - answer = translate( - "AddonsInstaller", - "Addon successfully installed.", - ) - - if self.repo.repo_type == Addon.Kind.WORKBENCH: - # symlink any macro contained in the module to the macros folder - macro_dir = FreeCAD.getUserMacroDir(True) - if not os.path.exists(macro_dir): - os.makedirs(macro_dir) - if os.path.exists(clonedir): - for f in os.listdir(clonedir): - if f.lower().endswith(".fcmacro"): - try: - utils.symlink( - os.path.join(clonedir, f), os.path.join(macro_dir, f) - ) - except OSError: - # If the symlink failed (e.g. for a non-admin user on Windows), copy the macro instead - shutil.copy( - os.path.join(clonedir, f), os.path.join(macro_dir, f) - ) - FreeCAD.ParamGet( - "User parameter:Plugins/" + self.repo.name - ).SetString("destination", clonedir) - answer += "\n\n" + translate( - "AddonsInstaller", - "A macro has been installed and is available under Macro -> Macros menu", - ) - answer += ":\n" + f + "" - self.update_metadata() - self.success.emit(self.repo, answer) - - def launch_zip(self, zipdir: str) -> None: - "downloads and unzip a zip version from a git repo" - - bakdir = None - if os.path.exists(zipdir): - bakdir = zipdir + ".bak" - if os.path.exists(bakdir): - shutil.rmtree(bakdir) - os.rename(zipdir, bakdir) - os.makedirs(zipdir) - zipurl = utils.get_zip_url(self.repo) - if not zipurl: - self.failure.emit( - self.repo, - translate("AddonsInstaller", "Error: Unable to locate ZIP from") - + " " - + self.repo.name, - ) - return - - self.zipdir = zipdir - self.bakdir = bakdir - - NetworkManager.AM_NETWORK_MANAGER.progress_made.connect(self.update_zip_status) - NetworkManager.AM_NETWORK_MANAGER.progress_complete.connect(self.finish_zip) - self.zip_download_index = ( - NetworkManager.AM_NETWORK_MANAGER.submit_monitored_get(zipurl) - ) - - def update_zip_status(self, index: int, bytes_read: int, data_size: int): - if index == self.zip_download_index: - locale = QtCore.QLocale() - if data_size > 10 * 1024 * 1024: # To avoid overflows, show MB instead - MB_read = bytes_read / 1024 / 1024 - MB_total = data_size / 1024 / 1024 - self.progress_made.emit(MB_read, MB_total) - mbytes_str = locale.toString(MB_read) - mbytes_total_str = locale.toString(MB_total) - percent = int(100 * float(MB_read / MB_total)) - self.status_message.emit( - translate( - "AddonsInstaller", - "Downloading: {mbytes_str}MB of {mbytes_total_str}MB ({percent}%)", - ).format( - mbytes_str=mbytes_str, - mbytes_total_str=mbytes_total_str, - percent=percent, - ) - ) - elif data_size > 0: - self.progress_made.emit(bytes_read, data_size) - bytes_str = locale.toString(bytes_read) - bytes_total_str = locale.toString(data_size) - percent = int(100 * float(bytes_read / data_size)) - self.status_message.emit( - translate( - "AddonsInstaller", - "Downloading: {bytes_str} of {bytes_total_str} bytes ({percent}%)", - ).format( - bytes_str=bytes_str, - bytes_total_str=bytes_total_str, - percent=percent, - ) - ) - else: - MB_read = bytes_read / 1024 / 1024 - bytes_str = locale.toString(MB_read) - self.status_message.emit( - translate( - "AddonsInstaller", - "Downloading: {bytes_str}MB of unknown total", - ).format(bytes_str=bytes_str) - ) - - def finish_zip(self, index: int, response_code: int, filename: os.PathLike): - self.zip_complete = True - if response_code != 200: - self.failure.emit( - self.repo, - translate( - "AddonsInstaller", - "Error: Error while downloading ZIP file for {}", - ).format(self.repo.display_name), - ) - return - - with zipfile.ZipFile(filename, "r") as zfile: - master = zfile.namelist()[0] # github will put everything in a subfolder - self.status_message.emit( - translate("AddonsInstaller", f"Download complete. Unzipping file...") - ) - QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) - zfile.extractall(self.zipdir) - for filename in os.listdir(self.zipdir + os.sep + master): - shutil.move( - self.zipdir + os.sep + master + os.sep + filename, - self.zipdir + os.sep + filename, - ) - os.rmdir(self.zipdir + os.sep + master) - if self.bakdir: - shutil.rmtree(self.bakdir) - self.update_metadata() - self.success.emit( - self.repo, - translate( - "AddonsInstaller", - "Successfully installed {} from ZIP file", - ).format(self.repo.display_name), - ) - - def update_metadata(self): - basedir = FreeCAD.getUserAppDataDir() - package_xml = os.path.join(basedir, "Mod", self.repo.name, "package.xml") - if os.path.isfile(package_xml): - self.repo.load_metadata_file(package_xml) - self.repo.installed_version = self.repo.metadata.Version - self.repo.updated_timestamp = os.path.getmtime(package_xml) - - -class DependencyInstallationWorker(QtCore.QThread): - """Install dependencies using Addonmanager for FreeCAD, and pip for python""" - - no_python_exe = QtCore.Signal() - no_pip = QtCore.Signal(str) # Attempted command - failure = QtCore.Signal(str, str) # Short message, detailed message - success = QtCore.Signal() - - def __init__(self, addons, python_required, python_optional): - QtCore.QThread.__init__(self) - self.addons = addons - self.python_required = python_required - self.python_optional = python_optional - - def run(self): - - for repo in self.addons: - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - worker = InstallWorkbenchWorker(repo) - worker.start() - while worker.isRunning(): - if QtCore.QThread.currentThread().isInterruptionRequested(): - worker.requestInterruption() - worker.wait() - return - time.sleep(0.1) - QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) - - if self.python_required or self.python_optional: - - # Find Python. In preference order - # A) The value of the PythonExecutableForPip user preference - # B) The executable located in the same bin directory as FreeCAD and called "python3" - # C) The executable located in the same bin directory as FreeCAD and called "python" - # D) The result of an shutil search for your system's "python3" executable - # E) The result of an shutil search for your system's "python" executable - prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") - python_exe = prefs.GetString("PythonExecutableForPip", "Not set") - if ( - not python_exe - or python_exe == "Not set" - or not os.path.exists(python_exe) - ): - fc_dir = FreeCAD.getHomePath() - python_exe = os.path.join(fc_dir, "bin", "python3") - if "Windows" in platform.system(): - python_exe += ".exe" - - if not python_exe or not os.path.exists(python_exe): - python_exe = os.path.join(fc_dir, "bin", "python") - if "Windows" in platform.system(): - python_exe += ".exe" - - if not python_exe or not os.path.exists(python_exe): - python_exe = shutil.which("python3") - - if not python_exe or not os.path.exists(python_exe): - python_exe = shutil.which("python") - - if not python_exe or not os.path.exists(python_exe): - self.no_python_exe.emit() - return - - prefs.SetString("PythonExecutableForPip", python_exe) - - pip_failed = False - try: - proc = subprocess.run( - [python_exe, "-m", "pip", "--version"], stdout=subprocess.PIPE - ) - except subprocess.CalledProcessError as e: - pip_failed = True - if proc.returncode != 0: - pip_failed = True - if pip_failed: - self.no_pip.emit(f"{python_exe} -m pip --version") - return - FreeCAD.Console.PrintMessage(proc.stdout) - FreeCAD.Console.PrintWarning(proc.stderr) - result = proc.stdout - FreeCAD.Console.PrintMessage(result.decode()) - vendor_path = os.path.join( - FreeCAD.getUserAppDataDir(), "AdditionalPythonPackages" - ) - if not os.path.exists(vendor_path): - os.makedirs(vendor_path) - - for pymod in self.python_required: - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - proc = subprocess.run( - [ - python_exe, - "-m", - "pip", - "install", - "--disable-pip-version-check", - "--target", - vendor_path, - pymod, - ], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - FreeCAD.Console.PrintMessage(proc.stdout.decode()) - if proc.returncode != 0: - self.failure.emit( - translate( - "AddonsInstaller", - "Installation of Python package {} failed", - ).format(pymod), - proc.stderr, - ) - return - - for pymod in self.python_optional: - if QtCore.QThread.currentThread().isInterruptionRequested(): - return - proc = subprocess.run( - [python_exe, "-m", "pip", "install", "--target", vendor_path, pymod], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - FreeCAD.Console.PrintMessage(proc.stdout.decode()) - if proc.returncode != 0: - self.failure.emit( - translate( - "AddonsInstaller", - "Installation of Python package {} failed", - ).format(pymod), - proc.stderr, - ) - return - - self.success.emit() - - -class UpdateMetadataCacheWorker(QtCore.QThread): - "Scan through all available packages and see if our local copy of package.xml needs to be updated" - - status_message = QtCore.Signal(str) - progress_made = QtCore.Signal(int, int) - package_updated = QtCore.Signal(Addon) - - class RequestType(Enum): - PACKAGE_XML = auto() - METADATA_TXT = auto() - REQUIREMENTS_TXT = auto() - ICON = auto() - - def __init__(self, repos): - - QtCore.QThread.__init__(self) - self.repos = repos - self.requests: Dict[int, (Addon, UpdateMetadataCacheWorker.RequestType)] = {} - NetworkManager.AM_NETWORK_MANAGER.completed.connect(self.download_completed) - self.requests_completed = 0 - self.total_requests = 0 - self.store = os.path.join( - FreeCAD.getUserCachePath(), "AddonManager", "PackageMetadata" - ) - self.updated_repos = set() - - def run(self): - current_thread = QtCore.QThread.currentThread() - - for repo in self.repos: - if repo.url and utils.recognized_git_location(repo): - # package.xml - index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get( - utils.construct_git_url(repo, "package.xml") - ) - self.requests[index] = ( - repo, - UpdateMetadataCacheWorker.RequestType.PACKAGE_XML, - ) - self.total_requests += 1 - - # metadata.txt - index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get( - utils.construct_git_url(repo, "metadata.txt") - ) - self.requests[index] = ( - repo, - UpdateMetadataCacheWorker.RequestType.METADATA_TXT, - ) - self.total_requests += 1 - - # requirements.txt - index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get( - utils.construct_git_url(repo, "requirements.txt") - ) - self.requests[index] = ( - repo, - UpdateMetadataCacheWorker.RequestType.REQUIREMENTS_TXT, - ) - self.total_requests += 1 - - while self.requests: - if current_thread.isInterruptionRequested(): - NetworkManager.AM_NETWORK_MANAGER.completed.disconnect( - self.download_completed - ) - for request in self.requests.keys(): - NetworkManager.AM_NETWORK_MANAGER.abort(request) - return - # 50 ms maximum between checks for interruption - QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) - - # This set contains one copy of each of the repos that got some kind of data in - # this process. For those repos, tell the main Addon Manager code that it needs - # to update its copy of the repo, and redraw its information. - for repo in self.updated_repos: - self.package_updated.emit(repo) - - def download_completed( - self, index: int, code: int, data: QtCore.QByteArray - ) -> None: - if index in self.requests: - self.requests_completed += 1 - self.progress_made.emit(self.requests_completed, self.total_requests) - request = self.requests.pop(index) - if code == 200: # HTTP success - self.updated_repos.add(request[0]) # mark this repo as updated - if request[1] == UpdateMetadataCacheWorker.RequestType.PACKAGE_XML: - self.process_package_xml(request[0], data) - elif request[1] == UpdateMetadataCacheWorker.RequestType.METADATA_TXT: - self.process_metadata_txt(request[0], data) - elif ( - request[1] == UpdateMetadataCacheWorker.RequestType.REQUIREMENTS_TXT - ): - self.process_requirements_txt(request[0], data) - elif request[1] == UpdateMetadataCacheWorker.RequestType.ICON: - self.process_icon(request[0], data) - - def process_package_xml(self, repo: Addon, data: QtCore.QByteArray): - repo.repo_type = Addon.Kind.PACKAGE # By definition - package_cache_directory = os.path.join(self.store, repo.name) - if not os.path.exists(package_cache_directory): - os.makedirs(package_cache_directory) - new_xml_file = os.path.join(package_cache_directory, "package.xml") - with open(new_xml_file, "wb") as f: - f.write(data.data()) - metadata = FreeCAD.Metadata(new_xml_file) - repo.metadata = metadata - self.status_message.emit( - translate("AddonsInstaller", "Downloaded package.xml for {}").format( - repo.name - ) - ) - - # Grab a new copy of the icon as well: we couldn't enqueue this earlier because - # we didn't know the path to it, which is stored in the package.xml file. - icon = metadata.Icon - if not icon: - # If there is no icon set for the entire package, see if there are - # any workbenches, which are required to have icons, and grab the first - # one we find: - content = repo.metadata.Content - if "workbench" in content: - wb = content["workbench"][0] - if wb.Icon: - if wb.Subdirectory: - subdir = wb.Subdirectory - else: - subdir = wb.Name - repo.Icon = subdir + wb.Icon - icon = repo.Icon - - icon_url = utils.construct_git_url(repo, icon) - index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get(icon_url) - self.requests[index] = (repo, UpdateMetadataCacheWorker.RequestType.ICON) - self.total_requests += 1 - - def process_metadata_txt(self, repo: Addon, data: QtCore.QByteArray): - self.status_message.emit( - translate("AddonsInstaller", "Downloaded metadata.txt for {}").format( - repo.display_name - ) - ) - f = io.StringIO(data.data().decode("utf8")) - while True: - line = f.readline() - if not line: - break - if line.startswith("workbenches="): - depswb = line.split("=")[1].split(",") - for wb in depswb: - wb_name = wb.strip() - if wb_name: - repo.requires.add(wb_name) - FreeCAD.Console.PrintLog( - f"{repo.display_name} requires FreeCAD Addon '{wb_name}'\n" - ) - - elif line.startswith("pylibs="): - depspy = line.split("=")[1].split(",") - for pl in depspy: - dep = pl.strip() - if dep: - repo.python_requires.add(dep) - FreeCAD.Console.PrintLog( - f"{repo.display_name} requires python package '{dep}'\n" - ) - - elif line.startswith("optionalpylibs="): - opspy = line.split("=")[1].split(",") - for pl in opspy: - dep = pl.strip() - if dep: - repo.python_optional.add(dep) - FreeCAD.Console.PrintLog( - f"{repo.display_name} optionally imports python package '{pl.strip()}'\n" - ) - # For review and debugging purposes, store the file locally - package_cache_directory = os.path.join(self.store, repo.name) - if not os.path.exists(package_cache_directory): - os.makedirs(package_cache_directory) - new_xml_file = os.path.join(package_cache_directory, "metadata.txt") - with open(new_xml_file, "wb") as f: - f.write(data.data()) - - def process_requirements_txt(self, repo: Addon, data: QtCore.QByteArray): - self.status_message.emit( - translate( - "AddonsInstaller", - "Downloaded requirements.txt for {}", - ).format(repo.display_name) - ) - f = io.StringIO(data.data().decode("utf8")) - lines = f.readlines() - for line in lines: - break_chars = " <>=~!+#" - package = line - for n, c in enumerate(line): - if c in break_chars: - package = line[:n].strip() - break - if package: - repo.python_requires.add(package) - # For review and debugging purposes, store the file locally - package_cache_directory = os.path.join(self.store, repo.name) - if not os.path.exists(package_cache_directory): - os.makedirs(package_cache_directory) - new_xml_file = os.path.join(package_cache_directory, "requirements.txt") - with open(new_xml_file, "wb") as f: - f.write(data.data()) - - def process_icon(self, repo: Addon, data: QtCore.QByteArray): - self.status_message.emit( - translate("AddonsInstaller", "Downloaded icon for {}").format( - repo.display_name - ) - ) - cache_file = repo.get_cached_icon_filename() - with open(cache_file, "wb") as icon_file: - icon_file.write(data.data()) - repo.cached_icon_filename = cache_file - - -if have_git and not NOGIT: - - class GitProgressMonitor(git.RemoteProgress): - """An object that receives git progress updates and stores them for later display""" - - def __init__(self): - super().__init__() - self.current = 0 - self.total = 100 - self.message = "" - - def update( - self, - _: int, - cur_count: Union[str, float], - max_count: Union[str, float, None] = None, - message: str = "", - ) -> None: - if max_count: - self.current = int(cur_count) - self.total = int(max_count) - if message: - self.message = message - - -class UpdateAllWorker(QtCore.QThread): - """Update all listed packages, of any kind""" - - progress_made = QtCore.Signal(int, int) - status_message = QtCore.Signal(str) - success = QtCore.Signal(Addon) - failure = QtCore.Signal(Addon) - - # TODO: This should be re-written to be solidly single-threaded, some of the called code is not re-entrant - - def __init__(self, repos): - super().__init__() - self.repos = repos - - def run(self): - self.progress_made.emit(0, len(self.repos)) - self.repo_queue = queue.Queue() - current_thread = QtCore.QThread.currentThread() - for repo in self.repos: - self.repo_queue.put(repo) - FreeCAD.Console.PrintLog(f" UPDATER: Adding '{repo.name}' to update queue\n") - - # The original design called for multiple update threads at the same time, but the updater - # itself is not thread-safe, so for the time being only spawn one update thread. - workers = [] - for _ in range(1): - FreeCAD.Console.PrintLog(f" UPDATER: Starting worker\n") - worker = UpdateSingleWorker(self.repo_queue) - worker.success.connect(self.on_success) - worker.failure.connect(self.on_failure) - worker.start() - workers.append(worker) - - while not self.repo_queue.empty(): - if current_thread.isInterruptionRequested(): - for worker in workers: - worker.blockSignals(True) - worker.requestInterruption() - worker.wait() - return - # Ensure our signals propagate out by running an internal thread-local event loop - QtCore.QCoreApplication.processEvents() - - self.repo_queue.join() - - # Make sure all of our child threads have fully exited: - for worker in workers: - worker.wait() - - def on_success(self, repo: Addon) -> None: - FreeCAD.Console.PrintLog(f" UPDATER: Main thread received notice that worker successfully updated {repo.name}\n") - self.progress_made.emit( - len(self.repos) - self.repo_queue.qsize(), len(self.repos) - ) - self.success.emit(repo) - - def on_failure(self, repo: Addon) -> None: - FreeCAD.Console.PrintLog(f" UPDATER: Main thread received notice that worker failed to update {repo.name}\n") - self.progress_made.emit( - len(self.repos) - self.repo_queue.qsize(), len(self.repos) - ) - self.failure.emit(repo) - - -class UpdateSingleWorker(QtCore.QThread): - success = QtCore.Signal(Addon) - failure = QtCore.Signal(Addon) - - def __init__(self, repo_queue: queue.Queue): - super().__init__() - self.repo_queue = repo_queue - - def run(self): - current_thread = QtCore.QThread.currentThread() - while True: - if current_thread.isInterruptionRequested(): - FreeCAD.Console.PrintLog(f" UPDATER: Interruption requested, stopping all updates\n") - return - try: - repo = self.repo_queue.get_nowait() - FreeCAD.Console.PrintLog(f" UPDATER: Pulling {repo.name} from the update queue\n") - except queue.Empty: - FreeCAD.Console.PrintLog(f" UPDATER: Worker thread queue is empty, exiting thread\n") - return - if repo.repo_type == Addon.Kind.MACRO: - FreeCAD.Console.PrintLog(f" UPDATER: Updating macro '{repo.name}'\n") - self.update_macro(repo) - else: - FreeCAD.Console.PrintLog(f" UPDATER: Updating addon '{repo.name}'\n") - self.update_package(repo) - self.repo_queue.task_done() - FreeCAD.Console.PrintLog(f" UPDATER: Worker thread completed action for '{repo.name}' and reported result to main thread\n") - - - def update_macro(self, repo: Addon): - """Updating a macro happens in this function, in the current thread""" - - cache_path = os.path.join( - FreeCAD.getUserCachePath(), "AddonManager", "MacroCache" - ) - os.makedirs(cache_path, exist_ok=True) - install_succeeded, _ = repo.macro.install(cache_path) - - if install_succeeded: - install_succeeded, _ = repo.macro.install(FreeCAD.getUserMacroDir(True)) - utils.update_macro_installation_details(repo) - - if install_succeeded: - self.success.emit(repo) - else: - self.failure.emit(repo) - - def update_package(self, repo: Addon): - """Updating a package re-uses the package installation worker, so actually spawns another thread that we block on""" - - worker = InstallWorkbenchWorker(repo) - worker.success.connect(lambda repo, _: self.success.emit(repo)) - worker.failure.connect(lambda repo, _: self.failure.emit(repo)) - worker.start() - while True: - # Ensure our signals propagate out by running an internal thread-local event loop - QtCore.QCoreApplication.processEvents() - if not worker.isRunning(): - break - - time.sleep(0.1) # Give the signal a moment to propagate to the other threads - QtCore.QCoreApplication.processEvents() - - -# @} diff --git a/src/Mod/AddonManager/addonmanager_workers_installation.py b/src/Mod/AddonManager/addonmanager_workers_installation.py new file mode 100644 index 0000000000..5804279334 --- /dev/null +++ b/src/Mod/AddonManager/addonmanager_workers_installation.py @@ -0,0 +1,903 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 FreeCAD Project Association * +# * Copyright (c) 2019 Yorik van Havre * +# * * +# * This library 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +""" Worker thread classes for Addon Manager installation and removal """ + +# pylint: disable=c-extension-no-member,too-few-public-methods + +import io +import os +import queue +import shutil +import subprocess +import time +import zipfile +from typing import Dict, List +from enum import Enum, auto + +from PySide2 import QtCore + +import FreeCAD +import addonmanager_utilities as utils +from Addon import Addon +import NetworkManager +from addonmanager_git import initialize_git + +translate = FreeCAD.Qt.translate + +# @package AddonManager_workers +# \ingroup ADDONMANAGER +# \brief Multithread workers for the addon manager +# @{ + + +class InstallWorkbenchWorker(QtCore.QThread): + "This worker installs a workbench" + + status_message = QtCore.Signal(str) + progress_made = QtCore.Signal(int, int) + success = QtCore.Signal(Addon, str) + failure = QtCore.Signal(Addon, str) + + def __init__(self, repo: Addon, location=None): + + QtCore.QThread.__init__(self) + self.repo = repo + self.update_timer = QtCore.QTimer() + self.update_timer.setInterval(100) + self.update_timer.timeout.connect(self.update_status) + self.update_timer.start() + + if location: + self.clone_directory = location + else: + basedir = FreeCAD.getUserAppDataDir() + self.clone_directory = os.path.join(basedir, "Mod", repo.name) + + if not os.path.exists(self.clone_directory): + os.makedirs(self.clone_directory) + + self.git_manager = initialize_git() + + # Some stored data for the ZIP processing + self.zip_complete = False + self.zipdir = None + self.bakdir = None + self.zip_download_index = None + + def run(self): + """Normally not called directly: instead, create an instance of this worker class and + call start() on it to launch in a new thread. Installs or updates the selected addon""" + + if not self.repo: + return + + if not self.git_manager: + FreeCAD.Console.PrintLog( + translate( + "AddonsInstaller", + "Git disabled - using ZIP file download instead.", + ) + + "\n" + ) + + target_dir = self.clone_directory + + if self.git_manager: + # Do the git process... + self.run_git(target_dir) + else: + + # The zip process uses an event loop, since the download can potentially be quite large + self.launch_zip(target_dir) + self.zip_complete = False + current_thread = QtCore.QThread.currentThread() + while not self.zip_complete: + if current_thread.isInterruptionRequested(): + return + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + + self.repo.set_status(Addon.Status.PENDING_RESTART) + + def update_status(self) -> None: + """Periodically emit the progress of the git download, for asynchronous operations""" + if hasattr(self, "git_progress") and self.isRunning(): + self.progress_made.emit(self.git_progress.current, self.git_progress.total) + self.status_message.emit(self.git_progress.message) + + def run_git(self, clonedir: str) -> None: + """Clone or update the addon using git. Exits if git is disabled.""" + + if not self.git_manager: + FreeCAD.Console.PrintLog( + translate( + "AddonsInstaller", + "Git disabled, skipping git operations", + ) + + "\n" + ) + return + + if os.path.exists(clonedir): + self.run_git_update(clonedir) + else: + self.run_git_clone(clonedir) + + def run_git_update(self, clonedir: str) -> None: + """Runs git update operation: normally a fetch and pull, but if something goew wrong it + will revert to a clean clone.""" + self.status_message.emit("Updating module...") + with self.repo.git_lock: + if not os.path.exists(clonedir + os.sep + ".git"): + self.git_manager.repair(self.repo.url, clonedir) + try: + self.git_manager.update(clonedir) + if self.repo.contains_workbench(): + # pylint: disable=line-too-long + answer = translate( + "AddonsInstaller", + "Workbench successfully updated. Please restart FreeCAD to apply the changes.", + ) + else: + answer = translate( + "AddonsInstaller", + "Workbench successfully updated.", + ) + except GitFailed as e: + answer = ( + translate("AddonsInstaller", "Error updating module") + + " " + + self.repo.name + + " - " + + translate("AddonsInstaller", "Please fix manually") + + " -- \n" + ) + answer += str(e) + self.failure.emit(self.repo, answer) + self.update_metadata() + self.success.emit(self.repo, answer) + + def run_git_clone(self, clonedir: str) -> None: + """Clones a repo using git""" + self.status_message.emit("Cloning module...") + current_thread = QtCore.QThread.currentThread() + + FreeCAD.Console.PrintMessage("Cloning repo...\n") + if self.repo.git_lock.locked(): + FreeCAD.Console.PrintMessage("Waiting for lock to be released to us...\n") + if not self.repo.git_lock.acquire(timeout=2): + FreeCAD.Console.PrintError( + "Timeout waiting for a lock on the git process, failed to clone repo\n" + ) + return + self.repo.git_lock.release() + + with self.repo.git_lock: + FreeCAD.Console.PrintMessage("Lock acquired...\n") + self.git_manager.clone(self.repo.url, clonedir) + FreeCAD.Console.PrintMessage("Initial clone complete...\n") + if current_thread.isInterruptionRequested(): + return + + if current_thread.isInterruptionRequested(): + return + + FreeCAD.Console.PrintMessage("Clone complete\n") + + if self.repo.contains_workbench(): + answer = translate( + "AddonsInstaller", + "Workbench successfully installed. Please restart FreeCAD to apply the changes.", + ) + else: + answer = translate( + "AddonsInstaller", + "Addon successfully installed.", + ) + + if self.repo.repo_type == Addon.Kind.WORKBENCH: + # symlink any macro contained in the module to the macros folder + macro_dir = FreeCAD.getUserMacroDir(True) + if not os.path.exists(macro_dir): + os.makedirs(macro_dir) + if os.path.exists(clonedir): + for f in os.listdir(clonedir): + if f.lower().endswith(".fcmacro"): + try: + utils.symlink( + os.path.join(clonedir, f), os.path.join(macro_dir, f) + ) + except OSError: + # If the symlink failed (e.g. for a non-admin user on Windows), copy + # the macro instead + shutil.copy( + os.path.join(clonedir, f), os.path.join(macro_dir, f) + ) + FreeCAD.ParamGet( + "User parameter:Plugins/" + self.repo.name + ).SetString("destination", clonedir) + # pylint: disable=line-too-long + answer += "\n\n" + translate( + "AddonsInstaller", + "A macro has been installed and is available under Macro -> Macros menu", + ) + answer += ":\n" + f + "" + self.update_metadata() + self.success.emit(self.repo, answer) + + def launch_zip(self, zipdir: str) -> None: + """Downloads and unzip a zip version from a git repo""" + + bakdir = None + if os.path.exists(zipdir): + bakdir = zipdir + ".bak" + if os.path.exists(bakdir): + shutil.rmtree(bakdir) + os.rename(zipdir, bakdir) + os.makedirs(zipdir) + zipurl = utils.get_zip_url(self.repo) + if not zipurl: + self.failure.emit( + self.repo, + translate("AddonsInstaller", "Error: Unable to locate ZIP from") + + " " + + self.repo.name, + ) + return + + self.zipdir = zipdir + self.bakdir = bakdir + + NetworkManager.AM_NETWORK_MANAGER.progress_made.connect(self.update_zip_status) + NetworkManager.AM_NETWORK_MANAGER.progress_complete.connect(self.finish_zip) + self.zip_download_index = ( + NetworkManager.AM_NETWORK_MANAGER.submit_monitored_get(zipurl) + ) + + def update_zip_status(self, index: int, bytes_read: int, data_size: int): + """Called periodically when downloading a zip file, emits a signal to display the + download progress.""" + if index == self.zip_download_index: + locale = QtCore.QLocale() + if data_size > 10 * 1024 * 1024: # To avoid overflows, show MB instead + MB_read = bytes_read / 1024 / 1024 + MB_total = data_size / 1024 / 1024 + self.progress_made.emit(MB_read, MB_total) + mbytes_str = locale.toString(MB_read) + mbytes_total_str = locale.toString(MB_total) + percent = int(100 * float(MB_read / MB_total)) + self.status_message.emit( + translate( + "AddonsInstaller", + "Downloading: {mbytes_str}MB of {mbytes_total_str}MB ({percent}%)", + ).format( + mbytes_str=mbytes_str, + mbytes_total_str=mbytes_total_str, + percent=percent, + ) + ) + elif data_size > 0: + self.progress_made.emit(bytes_read, data_size) + bytes_str = locale.toString(bytes_read) + bytes_total_str = locale.toString(data_size) + percent = int(100 * float(bytes_read / data_size)) + self.status_message.emit( + translate( + "AddonsInstaller", + "Downloading: {bytes_str} of {bytes_total_str} bytes ({percent}%)", + ).format( + bytes_str=bytes_str, + bytes_total_str=bytes_total_str, + percent=percent, + ) + ) + else: + MB_read = bytes_read / 1024 / 1024 + bytes_str = locale.toString(MB_read) + self.status_message.emit( + translate( + "AddonsInstaller", + "Downloading: {bytes_str}MB of unknown total", + ).format(bytes_str=bytes_str) + ) + + def finish_zip(self, _index: int, response_code: int, filename: os.PathLike): + """Once the zip download is finished, unzip it into the correct location.""" + self.zip_complete = True + if response_code != 200: + self.failure.emit( + self.repo, + translate( + "AddonsInstaller", + "Error: Error while downloading ZIP file for {}", + ).format(self.repo.display_name), + ) + return + + with zipfile.ZipFile(filename, "r") as zfile: + master = zfile.namelist()[0] # github will put everything in a subfolder + self.status_message.emit( + translate("AddonsInstaller", "Download complete. Unzipping file...") + ) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents) + zfile.extractall(self.zipdir) + for extracted_filename in os.listdir(self.zipdir + os.sep + master): + shutil.move( + self.zipdir + os.sep + master + os.sep + extracted_filename, + self.zipdir + os.sep + extracted_filename, + ) + os.rmdir(self.zipdir + os.sep + master) + if self.bakdir: + shutil.rmtree(self.bakdir) + self.update_metadata() + self.success.emit( + self.repo, + translate( + "AddonsInstaller", + "Successfully installed {} from ZIP file", + ).format(self.repo.display_name), + ) + + def update_metadata(self): + """Loads the package metadata from the Addon's downloaded package.xml file.""" + basedir = FreeCAD.getUserAppDataDir() + package_xml = os.path.join(basedir, "Mod", self.repo.name, "package.xml") + if os.path.isfile(package_xml): + self.repo.load_metadata_file(package_xml) + self.repo.installed_version = self.repo.metadata.Version + self.repo.updated_timestamp = os.path.getmtime(package_xml) + + +class DependencyInstallationWorker(QtCore.QThread): + """Install dependencies using Addonmanager for FreeCAD, and pip for python""" + + no_python_exe = QtCore.Signal() + no_pip = QtCore.Signal(str) # Attempted command + failure = QtCore.Signal(str, str) # Short message, detailed message + success = QtCore.Signal() + + def __init__( + self, + addons: List[Addon], + python_required: List[str], + python_optional: List[str], + location: os.PathLike = None, + ): + """Install the various types of dependencies that might be specified. If an optional + dependency fails this is non-fatal, but other failures are considered fatal. If location + is specified it overrides the FreeCAD user base directory setting: this is used mostly + for testing purposes and shouldn't be set by normal code in most circumstances.""" + QtCore.QThread.__init__(self) + self.addons = addons + self.python_required = python_required + self.python_optional = python_optional + self.location = location + + def run(self): + """Normally not called directly: create the object and call start() to launch it + in its own thread. Installs dependencies for the Addon.""" + self._install_required_addons() + if self.python_required or self.python_optional: + self._install_python_packages() + self.success.emit() + + def _install_required_addons(self): + """Install whatever FreeCAD Addons were set as required.""" + for repo in self.addons: + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + location = self.location + if location: + location = os.path.join(location, "Mod") + worker = InstallWorkbenchWorker(repo, location=location) + worker.start() + while worker.isRunning(): + if QtCore.QThread.currentThread().isInterruptionRequested(): + worker.requestInterruption() + worker.wait() + return + time.sleep(0.1) + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + + def _install_python_packages(self): + """Install required and optional Python dependencies using pip.""" + if not self._verify_pip(): + return + + if self.location: + vendor_path = os.path.join(self.location, "AdditionalPythonPackages") + else: + vendor_path = os.path.join( + FreeCAD.getUserAppDataDir(), "AdditionalPythonPackages" + ) + if not os.path.exists(vendor_path): + os.makedirs(vendor_path) + + self._install_required(vendor_path) + self._install_optional(vendor_path) + + def _verify_pip(self) -> bool: + """Ensure that pip is working -- returns True if it is, or False if not. Also emits the + no_pip signal if pip cannot execute.""" + python_exe = utils.get_python_exe() + pip_failed = False + if python_exe: + try: + proc = subprocess.run( + [python_exe, "-m", "pip", "--version"], + stdout=subprocess.PIPE, + check=True, + ) + except subprocess.CalledProcessError: + pip_failed = True + if proc.returncode != 0: + pip_failed = True + else: + pip_failed = True + if pip_failed: + self.no_pip.emit(f"{python_exe} -m pip --version") + FreeCAD.Console.PrintMessage(proc.stdout) + FreeCAD.Console.PrintWarning(proc.stderr) + result = proc.stdout + FreeCAD.Console.PrintMessage(result.decode()) + return not pip_failed + + def _install_required(self, vendor_path: os.PathLike): + """Install the required Python package dependencies. If any fail a failure signal is + emitted and the function exits without proceeding with any additional installs.""" + for pymod in self.python_required: + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + proc = subprocess.run( + [ + python_exe, + "-m", + "pip", + "install", + "--disable-pip-version-check", + "--target", + vendor_path, + pymod, + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=True, + ) + FreeCAD.Console.PrintMessage(proc.stdout.decode()) + if proc.returncode != 0: + self.failure.emit( + translate( + "AddonsInstaller", + "Installation of Python package {} failed", + ).format(pymod), + proc.stderr, + ) + return + + def _install_optional(self, vendor_path: os.PathLike): + """Install the optional Python package dependencies. If any fail a message is printed to + the console, but installation of the others continues.""" + for pymod in self.python_optional: + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + try: + proc = subprocess.run( + [ + python_exe, + "-m", + "pip", + "install", + "--target", + vendor_path, + pymod, + ], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + check=True, + ) + except subprocess.CalledProcessError as e: + FreeCAD.Console.PrintError(str(e)) + continue + FreeCAD.Console.PrintMessage(proc.stdout.decode()) + if proc.returncode != 0: + FreeCAD.Console.PrintError(proc.stderr.decode()) + + +class UpdateMetadataCacheWorker(QtCore.QThread): + """Scan through all available packages and see if our local copy of package.xml needs to be + updated""" + + status_message = QtCore.Signal(str) + progress_made = QtCore.Signal(int, int) + package_updated = QtCore.Signal(Addon) + + class RequestType(Enum): + """The type of item being downloaded.""" + + PACKAGE_XML = auto() + METADATA_TXT = auto() + REQUIREMENTS_TXT = auto() + ICON = auto() + + def __init__(self, repos): + + QtCore.QThread.__init__(self) + self.repos = repos + self.requests: Dict[int, (Addon, UpdateMetadataCacheWorker.RequestType)] = {} + NetworkManager.AM_NETWORK_MANAGER.completed.connect(self.download_completed) + self.requests_completed = 0 + self.total_requests = 0 + self.store = os.path.join( + FreeCAD.getUserCachePath(), "AddonManager", "PackageMetadata" + ) + self.updated_repos = set() + + def run(self): + current_thread = QtCore.QThread.currentThread() + + for repo in self.repos: + if repo.url and utils.recognized_git_location(repo): + # package.xml + index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get( + utils.construct_git_url(repo, "package.xml") + ) + self.requests[index] = ( + repo, + UpdateMetadataCacheWorker.RequestType.PACKAGE_XML, + ) + self.total_requests += 1 + + # metadata.txt + index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get( + utils.construct_git_url(repo, "metadata.txt") + ) + self.requests[index] = ( + repo, + UpdateMetadataCacheWorker.RequestType.METADATA_TXT, + ) + self.total_requests += 1 + + # requirements.txt + index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get( + utils.construct_git_url(repo, "requirements.txt") + ) + self.requests[index] = ( + repo, + UpdateMetadataCacheWorker.RequestType.REQUIREMENTS_TXT, + ) + self.total_requests += 1 + + while self.requests: + if current_thread.isInterruptionRequested(): + NetworkManager.AM_NETWORK_MANAGER.completed.disconnect( + self.download_completed + ) + for request in self.requests.keys(): + NetworkManager.AM_NETWORK_MANAGER.abort(request) + return + # 50 ms maximum between checks for interruption + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + + # This set contains one copy of each of the repos that got some kind of data in + # this process. For those repos, tell the main Addon Manager code that it needs + # to update its copy of the repo, and redraw its information. + for repo in self.updated_repos: + self.package_updated.emit(repo) + + def download_completed( + self, index: int, code: int, data: QtCore.QByteArray + ) -> None: + """Callback for handling a completed metadata file download.""" + if index in self.requests: + self.requests_completed += 1 + self.progress_made.emit(self.requests_completed, self.total_requests) + request = self.requests.pop(index) + if code == 200: # HTTP success + self.updated_repos.add(request[0]) # mark this repo as updated + if request[1] == UpdateMetadataCacheWorker.RequestType.PACKAGE_XML: + self.process_package_xml(request[0], data) + elif request[1] == UpdateMetadataCacheWorker.RequestType.METADATA_TXT: + self.process_metadata_txt(request[0], data) + elif ( + request[1] == UpdateMetadataCacheWorker.RequestType.REQUIREMENTS_TXT + ): + self.process_requirements_txt(request[0], data) + elif request[1] == UpdateMetadataCacheWorker.RequestType.ICON: + self.process_icon(request[0], data) + + def process_package_xml(self, repo: Addon, data: QtCore.QByteArray): + """Process the package.xml metadata file""" + repo.repo_type = Addon.Kind.PACKAGE # By definition + package_cache_directory = os.path.join(self.store, repo.name) + if not os.path.exists(package_cache_directory): + os.makedirs(package_cache_directory) + new_xml_file = os.path.join(package_cache_directory, "package.xml") + with open(new_xml_file, "wb") as f: + f.write(data.data()) + metadata = FreeCAD.Metadata(new_xml_file) + repo.metadata = metadata + self.status_message.emit( + translate("AddonsInstaller", "Downloaded package.xml for {}").format( + repo.name + ) + ) + + # Grab a new copy of the icon as well: we couldn't enqueue this earlier because + # we didn't know the path to it, which is stored in the package.xml file. + icon = metadata.Icon + if not icon: + # If there is no icon set for the entire package, see if there are + # any workbenches, which are required to have icons, and grab the first + # one we find: + content = repo.metadata.Content + if "workbench" in content: + wb = content["workbench"][0] + if wb.Icon: + if wb.Subdirectory: + subdir = wb.Subdirectory + else: + subdir = wb.Name + repo.Icon = subdir + wb.Icon + icon = repo.Icon + + icon_url = utils.construct_git_url(repo, icon) + index = NetworkManager.AM_NETWORK_MANAGER.submit_unmonitored_get(icon_url) + self.requests[index] = (repo, UpdateMetadataCacheWorker.RequestType.ICON) + self.total_requests += 1 + + def process_metadata_txt(self, repo: Addon, data: QtCore.QByteArray): + """Process the metadata.txt metadata file""" + self.status_message.emit( + translate("AddonsInstaller", "Downloaded metadata.txt for {}").format( + repo.display_name + ) + ) + f = io.StringIO(data.data().decode("utf8")) + while True: + line = f.readline() + if not line: + break + if line.startswith("workbenches="): + depswb = line.split("=")[1].split(",") + for wb in depswb: + wb_name = wb.strip() + if wb_name: + repo.requires.add(wb_name) + FreeCAD.Console.PrintLog( + f"{repo.display_name} requires FreeCAD Addon '{wb_name}'\n" + ) + + elif line.startswith("pylibs="): + depspy = line.split("=")[1].split(",") + for pl in depspy: + dep = pl.strip() + if dep: + repo.python_requires.add(dep) + FreeCAD.Console.PrintLog( + f"{repo.display_name} requires python package '{dep}'\n" + ) + + elif line.startswith("optionalpylibs="): + opspy = line.split("=")[1].split(",") + for pl in opspy: + dep = pl.strip() + if dep: + repo.python_optional.add(dep) + FreeCAD.Console.PrintLog( + f"{repo.display_name} optionally imports python package" + + f" '{pl.strip()}'\n" + ) + # For review and debugging purposes, store the file locally + package_cache_directory = os.path.join(self.store, repo.name) + if not os.path.exists(package_cache_directory): + os.makedirs(package_cache_directory) + new_xml_file = os.path.join(package_cache_directory, "metadata.txt") + with open(new_xml_file, "wb") as f: + f.write(data.data()) + + def process_requirements_txt(self, repo: Addon, data: QtCore.QByteArray): + """Process the requirements.txt metadata file""" + self.status_message.emit( + translate( + "AddonsInstaller", + "Downloaded requirements.txt for {}", + ).format(repo.display_name) + ) + f = io.StringIO(data.data().decode("utf8")) + lines = f.readlines() + for line in lines: + break_chars = " <>=~!+#" + package = line + for n, c in enumerate(line): + if c in break_chars: + package = line[:n].strip() + break + if package: + repo.python_requires.add(package) + # For review and debugging purposes, store the file locally + package_cache_directory = os.path.join(self.store, repo.name) + if not os.path.exists(package_cache_directory): + os.makedirs(package_cache_directory) + new_xml_file = os.path.join(package_cache_directory, "requirements.txt") + with open(new_xml_file, "wb") as f: + f.write(data.data()) + + def process_icon(self, repo: Addon, data: QtCore.QByteArray): + """Convert icon data into a valid icon file and store it""" + self.status_message.emit( + translate("AddonsInstaller", "Downloaded icon for {}").format( + repo.display_name + ) + ) + cache_file = repo.get_cached_icon_filename() + with open(cache_file, "wb") as icon_file: + icon_file.write(data.data()) + repo.cached_icon_filename = cache_file + + +class UpdateAllWorker(QtCore.QThread): + """Update all listed packages, of any kind""" + + progress_made = QtCore.Signal(int, int) + status_message = QtCore.Signal(str) + success = QtCore.Signal(Addon) + failure = QtCore.Signal(Addon) + + # TODO: This should be re-written to be solidly single-threaded, some of the called code is + # not re-entrant + + def __init__(self, repos): + super().__init__() + self.repos = repos + + def run(self): + self.progress_made.emit(0, len(self.repos)) + self.repo_queue = queue.Queue() + current_thread = QtCore.QThread.currentThread() + for repo in self.repos: + self.repo_queue.put(repo) + FreeCAD.Console.PrintLog( + f" UPDATER: Adding '{repo.name}' to update queue\n" + ) + + # The original design called for multiple update threads at the same time, but the updater + # itself is not thread-safe, so for the time being only spawn one update thread. + workers = [] + for _ in range(1): + FreeCAD.Console.PrintLog(f" UPDATER: Starting worker\n") + worker = UpdateSingleWorker(self.repo_queue) + worker.success.connect(self.on_success) + worker.failure.connect(self.on_failure) + worker.start() + workers.append(worker) + + while not self.repo_queue.empty(): + if current_thread.isInterruptionRequested(): + for worker in workers: + worker.blockSignals(True) + worker.requestInterruption() + worker.wait() + return + # Ensure our signals propagate out by running an internal thread-local event loop + QtCore.QCoreApplication.processEvents() + + self.repo_queue.join() + + # Make sure all of our child threads have fully exited: + for worker in workers: + worker.wait() + + def on_success(self, repo: Addon) -> None: + FreeCAD.Console.PrintLog( + f" UPDATER: Main thread received notice that worker successfully updated {repo.name}\n" + ) + self.progress_made.emit( + len(self.repos) - self.repo_queue.qsize(), len(self.repos) + ) + self.success.emit(repo) + + def on_failure(self, repo: Addon) -> None: + FreeCAD.Console.PrintLog( + f" UPDATER: Main thread received notice that worker failed to update {repo.name}\n" + ) + self.progress_made.emit( + len(self.repos) - self.repo_queue.qsize(), len(self.repos) + ) + self.failure.emit(repo) + + +class UpdateSingleWorker(QtCore.QThread): + success = QtCore.Signal(Addon) + failure = QtCore.Signal(Addon) + + def __init__(self, repo_queue: queue.Queue, location=None): + super().__init__() + self.repo_queue = repo_queue + self.location = location + + def run(self): + current_thread = QtCore.QThread.currentThread() + while True: + if current_thread.isInterruptionRequested(): + FreeCAD.Console.PrintLog( + f" UPDATER: Interruption requested, stopping all updates\n" + ) + return + try: + repo = self.repo_queue.get_nowait() + FreeCAD.Console.PrintLog( + f" UPDATER: Pulling {repo.name} from the update queue\n" + ) + except queue.Empty: + FreeCAD.Console.PrintLog( + f" UPDATER: Worker thread queue is empty, exiting thread\n" + ) + return + if repo.repo_type == Addon.Kind.MACRO: + FreeCAD.Console.PrintLog(f" UPDATER: Updating macro '{repo.name}'\n") + self.update_macro(repo) + else: + FreeCAD.Console.PrintLog(f" UPDATER: Updating addon '{repo.name}'\n") + self.update_package(repo) + self.repo_queue.task_done() + FreeCAD.Console.PrintLog( + f" UPDATER: Worker thread completed action for '{repo.name}' and reported result " + + "to main thread\n" + ) + + def update_macro(self, repo: Addon): + """Updating a macro happens in this function, in the current thread""" + + cache_path = os.path.join( + FreeCAD.getUserCachePath(), "AddonManager", "MacroCache" + ) + os.makedirs(cache_path, exist_ok=True) + install_succeeded, _ = repo.macro.install(cache_path) + + if install_succeeded: + install_succeeded, _ = repo.macro.install(FreeCAD.getUserMacroDir(True)) + utils.update_macro_installation_details(repo) + + if install_succeeded: + self.success.emit(repo) + else: + self.failure.emit(repo) + + def update_package(self, repo: Addon): + """Updating a package re-uses the package installation worker, so actually spawns another + thread that we block on""" + + worker = InstallWorkbenchWorker(repo, location=self.location) + worker.success.connect(lambda repo, _: self.success.emit(repo)) + worker.failure.connect(lambda repo, _: self.failure.emit(repo)) + worker.start() + while True: + # Ensure our signals propagate out by running an internal thread-local event loop + QtCore.QCoreApplication.processEvents() + if not worker.isRunning(): + break + + time.sleep(0.1) # Give the signal a moment to propagate to the other threads + QtCore.QCoreApplication.processEvents() + + +# @} diff --git a/src/Mod/AddonManager/addonmanager_workers_startup.py b/src/Mod/AddonManager/addonmanager_workers_startup.py new file mode 100644 index 0000000000..192131bdf6 --- /dev/null +++ b/src/Mod/AddonManager/addonmanager_workers_startup.py @@ -0,0 +1,904 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 FreeCAD Project Association * +# * Copyright (c) 2019 Yorik van Havre * +# * * +# * This library 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +""" Worker thread classes for Addon Manager startup """ + +import hashlib +import json +import os +import queue +import re +import shutil +import stat +import threading +import time +from typing import List + +from PySide2 import QtCore + +import FreeCAD +import addonmanager_utilities as utils +from addonmanager_macro import Macro +from Addon import Addon +import NetworkManager +from addonmanager_git import initialize_git + +translate = FreeCAD.Qt.translate + +# Workers only have one public method by design +# pylint: disable=too-few-public-methods + + +class CreateAddonListWorker(QtCore.QThread): + """This worker updates the list of available workbenches, emitting an "addon_repo" + signal for each Addon as they are processed.""" + + status_message = QtCore.Signal(str) + addon_repo = QtCore.Signal(object) + + def __init__(self): + QtCore.QThread.__init__(self) + + # reject_listed addons + self.macros_reject_list = [] + self.mod_reject_list = [] + + # These addons will print an additional message informing the user + self.obsolete = [] + + # These addons will print an additional message informing the user Python2 only + self.py2only = [] + + self.package_names = [] + self.moddir = os.path.join(FreeCAD.getUserAppDataDir(), "Mod") + self.current_thread = None + + self.git_manager = initialize_git() + + def run(self): + "populates the list of addons" + + self.current_thread = QtCore.QThread.currentThread() + try: + self._get_freecad_addon_repo_data() + except ConnectionError: + return + self._get_custom_addons() + self._get_official_addons() + self._retrieve_macros_from_git() + self._retrieve_macros_from_wiki() + + def _get_freecad_addon_repo_data(self): + # update info lists + p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( + "https://raw.githubusercontent.com/FreeCAD/FreeCAD-addons/master/addonflags.json" + ) + if p: + p = p.data().decode("utf8") + j = json.loads(p) + if "obsolete" in j and "Mod" in j["obsolete"]: + self.obsolete = j["obsolete"]["Mod"] + + if "blacklisted" in j and "Macro" in j["blacklisted"]: + self.macros_reject_list = j["blacklisted"]["Macro"] + + if "blacklisted" in j and "Mod" in j["blacklisted"]: + self.mod_reject_list = j["blacklisted"]["Mod"] + + if "py2only" in j and "Mod" in j["py2only"]: + self.py2only = j["py2only"]["Mod"] + + if "deprecated" in j: + self._process_deprecated(j["deprecated"]) + + else: + message = translate( + "AddonsInstaller", + "Failed to connect to GitHub. Check your connection and proxy settings.", + ) + FreeCAD.Console.PrintError(message + "\n") + self.status_message.emit(message) + raise ConnectionError + + def _process_deprecated(self, deprecated_addons): + """Parse the section on deprecated addons""" + + fc_major = int(FreeCAD.Version()[0]) + fc_minor = int(FreeCAD.Version()[1]) + for item in deprecated_addons: + if "as_of" in item and "name" in item: + try: + version_components = item["as_of"].split(".") + major = int(version_components[0]) + if len(version_components) > 1: + minor = int(version_components[1]) + else: + minor = 0 + if major < fc_major or (major == fc_major and minor <= fc_minor): + if "kind" not in item or item["kind"] == "mod": + self.obsolete.append(item["name"]) + elif item["kind"] == "macro": + self.macros_reject_list.append(item["name"]) + else: + FreeCAD.Console.PrintMessage( + f'Unrecognized Addon kind {item["kind"]} in deprecation list.' + ) + except ValueError: + FreeCAD.Console.PrintMessage( + f"Failed to parse version from {item['name']}, version {item['as_of']}" + ) + + def _get_custom_addons(self): + + # querying custom addons first + addon_list = ( + FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") + .GetString("CustomRepositories", "") + .split("\n") + ) + custom_addons = [] + for addon in addon_list: + if " " in addon: + addon_and_branch = addon.split(" ") + custom_addons.append( + {"url": addon_and_branch[0], "branch": addon_and_branch[1]} + ) + else: + custom_addons.append({"url": addon, "branch": "master"}) + for addon in custom_addons: + if self.current_thread.isInterruptionRequested(): + return + if addon and addon["url"]: + if addon["url"][-1] == "/": + addon["url"] = addon["url"][0:-1] # Strip trailing slash + addon["url"] = addon["url"].split(".git")[0] # Remove .git + name = addon["url"].split("/")[-1] + if name in self.package_names: + # We already have something with this name, skip this one + continue + self.package_names.append(name) + addondir = os.path.join(self.moddir, name) + if os.path.exists(addondir) and os.listdir(addondir): + state = Addon.Status.UNCHECKED + else: + state = Addon.Status.NOT_INSTALLED + repo = Addon(name, addon["url"], state, addon["branch"]) + md_file = os.path.join(addondir, "package.xml") + if os.path.isfile(md_file): + repo.load_metadata_file(md_file) + repo.installed_version = repo.metadata.Version + repo.updated_timestamp = os.path.getmtime(md_file) + repo.verify_url_and_branch(addon["url"], addon["branch"]) + + self.addon_repo.emit(repo) + + def _get_official_addons(self): + # querying official addons + p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( + "https://raw.githubusercontent.com/FreeCAD/FreeCAD-addons/master/.gitmodules" + ) + if not p: + return + p = p.data().decode("utf8") + p = re.findall( + ( + r'(?m)\[submodule\s*"(?P.*)"\]\s*' + r"path\s*=\s*(?P.+)\s*" + r"url\s*=\s*(?Phttps?://.*)\s*" + r"(branch\s*=\s*(?P[^\s]*)\s*)?" + ), + p, + ) + for name, _, url, _, branch in p: + if self.current_thread.isInterruptionRequested(): + return + if name in self.package_names: + # We already have something with this name, skip this one + continue + self.package_names.append(name) + if branch is None or len(branch) == 0: + branch = "master" + url = url.split(".git")[0] + addondir = os.path.join(self.moddir, name) + if os.path.exists(addondir) and os.listdir(addondir): + # make sure the folder exists and it contains files! + state = Addon.Status.UNCHECKED + else: + state = Addon.Status.NOT_INSTALLED + repo = Addon(name, url, state, branch) + md_file = os.path.join(addondir, "package.xml") + if os.path.isfile(md_file): + repo.load_metadata_file(md_file) + repo.installed_version = repo.metadata.Version + repo.updated_timestamp = os.path.getmtime(md_file) + repo.verify_url_and_branch(url, branch) + + if name in self.py2only: + repo.python2 = True + if name in self.mod_reject_list: + repo.rejected = True + if name in self.obsolete: + repo.obsolete = True + self.addon_repo.emit(repo) + + self.status_message.emit( + translate("AddonsInstaller", "Workbenches list was updated.") + ) + + def _retrieve_macros_from_git(self): + """Retrieve macros from FreeCAD-macros.git + + Emits a signal for each macro in + https://github.com/FreeCAD/FreeCAD-macros.git + """ + + macro_cache_location = utils.get_cache_file_name("Macros") + + if not self.git_manager: + message = translate( + "AddonsInstaller", + "Git is disabled, skipping git macros", + ) + self.status_message.emit(message) + FreeCAD.Console.PrintWarning(message + "\n") + return + + update_succeeded = self._update_local_git_repo() + if not update_succeeded: + return + + n_files = 0 + for _, _, filenames in os.walk(macro_cache_location): + n_files += len(filenames) + counter = 0 + for dirpath, _, filenames in os.walk(macro_cache_location): + counter += 1 + if self.current_thread.isInterruptionRequested(): + return + if ".git" in dirpath: + continue + for filename in filenames: + if self.current_thread.isInterruptionRequested(): + return + if filename.lower().endswith(".fcmacro"): + macro = Macro(filename[:-8]) # Remove ".FCMacro". + if macro.name in self.package_names: + FreeCAD.Console.PrintLog( + f"Ignoring second macro named {macro.name} (found on git)\n" + ) + continue # We already have a macro with this name + self.package_names.append(macro.name) + macro.on_git = True + macro.src_filename = os.path.join(dirpath, filename) + macro.fill_details_from_file(macro.src_filename) + repo = Addon.from_macro(macro) + FreeCAD.Console.PrintLog(f"Found macro {repo.name}\n") + repo.url = "https://github.com/FreeCAD/FreeCAD-macros.git" + utils.update_macro_installation_details(repo) + self.addon_repo.emit(repo) + + def _update_local_git_repo(self) -> bool: + macro_cache_location = utils.get_cache_file_name("Macros") + try: + if os.path.exists(macro_cache_location): + if not os.path.exists(os.path.join(macro_cache_location, ".git")): + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Attempting to change non-git Macro setup to use git\n", + ) + ) + self.git_manager.repair( + "https://github.com/FreeCAD/FreeCAD-macros.git", + macro_cache_location, + ) + self.git_manager.update(macro_cache_location) + else: + self.git_manager.clone( + "https://github.com/FreeCAD/FreeCAD-macros.git", + macro_cache_location, + ) + except GitFailed as e: + FreeCAD.Console.PrintMessage( + translate( + "AddonsInstaller", + "An error occurred updating macros from GitHub, trying clean checkout...", + ) + + f":\n{e}\n" + ) + FreeCAD.Console.PrintMessage(f"{macro_cache_location}\n") + FreeCAD.Console.PrintMessage( + translate("AddonsInstaller", "Attempting to do a clean checkout...") + + "\n" + ) + try: + shutil.rmtree(macro_cache_location, onerror=self._remove_readonly) + self.git_manager.clone( + "https://github.com/FreeCAD/FreeCAD-macros.git", + macro_cache_location, + ) + FreeCAD.Console.PrintMessage( + translate("AddonsInstaller", "Clean checkout succeeded") + "\n" + ) + except GitFailed as e2: + # The Qt Python translation extractor doesn't support splitting this string (yet) + # pylint: disable=line-too-long + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Failed to update macros from GitHub -- try clearing the Addon Manager's cache.", + ) + + f":\n{str(e2)}\n" + ) + return False + return True + + def _retrieve_macros_from_wiki(self): + """Retrieve macros from the wiki + + Read the wiki and emit a signal for each found macro. + Reads only the page https://wiki.freecad.org/Macros_recipes + """ + + p = NetworkManager.AM_NETWORK_MANAGER.blocking_get( + "https://wiki.freecad.org/Macros_recipes" + ) + if not p: + # The Qt Python translation extractor doesn't support splitting this string (yet) + # pylint: disable=line-too-long + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Error connecting to the Wiki, FreeCAD cannot retrieve the Wiki macro list at this time", + ) + + "\n" + ) + return + p = p.data().decode("utf8") + macros = re.findall('title="(Macro.*?)"', p) + macros = [mac for mac in macros if "translated" not in mac] + macro_names = [] + for _, mac in enumerate(macros): + if self.current_thread.isInterruptionRequested(): + return + macname = mac[6:] # Remove "Macro ". + macname = macname.replace("&", "&") + if not macname: + continue + if ( + (macname not in self.macros_reject_list) + and ("recipes" not in macname.lower()) + and (macname not in macro_names) + ): + macro_names.append(macname) + macro = Macro(macname) + if macro.name in self.package_names: + FreeCAD.Console.PrintLog( + f"Ignoring second macro named {macro.name} (found on wiki)\n" + ) + continue # We already have a macro with this name + self.package_names.append(macro.name) + macro.on_wiki = True + macro.parsed = False + repo = Addon.from_macro(macro) + repo.url = "https://wiki.freecad.org/Macros_recipes" + utils.update_macro_installation_details(repo) + self.addon_repo.emit(repo) + + def _remove_readonly(self, func, path, _) -> None: + """Remove a read-only file.""" + + os.chmod(path, stat.S_IWRITE) + func(path) + + +class LoadPackagesFromCacheWorker(QtCore.QThread): + """A subthread worker that loads package information from its cache file.""" + + addon_repo = QtCore.Signal(object) + + def __init__(self, cache_file: str): + QtCore.QThread.__init__(self) + self.cache_file = cache_file + self.metadata_cache_path = os.path.join( + FreeCAD.getUserCachePath(), "AddonManager", "PackageMetadata" + ) + + def override_metadata_cache_path(self, path): + """For testing purposes, override the location to fetch the package metadata from.""" + self.metadata_cache_path = path + + def run(self): + """Rarely called directly: create an instance and call start() on it instead to + launch in a new thread""" + with open(self.cache_file, "r", encoding="utf-8") as f: + data = f.read() + if data: + dict_data = json.loads(data) + for item in dict_data.values(): + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + repo = Addon.from_cache(item) + repo_metadata_cache_path = os.path.join( + self.metadata_cache_path, repo.name, "package.xml" + ) + if os.path.isfile(repo_metadata_cache_path): + try: + repo.load_metadata_file(repo_metadata_cache_path) + repo.installed_version = repo.metadata.Version + repo.updated_timestamp = os.path.getmtime( + repo_metadata_cache_path + ) + except Exception: + FreeCAD.Console.PrintLog( + f"Failed loading {repo_metadata_cache_path}\n" + ) + self.addon_repo.emit(repo) + + +class LoadMacrosFromCacheWorker(QtCore.QThread): + """A worker object to load macros from a cache file""" + + add_macro_signal = QtCore.Signal(object) + + def __init__(self, cache_file: str): + QtCore.QThread.__init__(self) + self.cache_file = cache_file + + def run(self): + """Rarely called directly: create an instance and call start() on it instead to + launch in a new thread""" + + with open(self.cache_file, "r", encoding="utf-8") as f: + data = f.read() + dict_data = json.loads(data) + for item in dict_data: + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + new_macro = Macro.from_cache(item) + repo = Addon.from_macro(new_macro) + utils.update_macro_installation_details(repo) + self.add_macro_signal.emit(repo) + + +class CheckSingleUpdateWorker(QtCore.QObject): + """This worker is a little different from the others: the actual recommended way of + running in a QThread is to make a worker object that gets moved into the thread.""" + + update_status = QtCore.Signal(int) + + def __init__(self, repo: Addon, parent: QtCore.QObject = None): + super().__init__(parent) + self.repo = repo + + def do_work(self): + """Use the UpdateChecker class to do the work of this function, depending on the + type of Addon""" + + checker = UpdateChecker() + if self.repo.repo_type == Addon.Kind.WORKBENCH: + checker.check_workbench(self.repo) + elif self.repo.repo_type == Addon.Kind.MACRO: + checker.check_macro(self.repo) + elif self.repo.repo_type == Addon.Kind.PACKAGE: + checker.check_package(self.repo) + + self.update_status.emit(self.repo.update_status) + + +class CheckWorkbenchesForUpdatesWorker(QtCore.QThread): + """This worker checks for available updates for all workbenches""" + + update_status = QtCore.Signal(Addon) + progress_made = QtCore.Signal(int, int) + + def __init__(self, repos: List[Addon]): + + QtCore.QThread.__init__(self) + self.repos = repos + self.current_thread = None + self.basedir = FreeCAD.getUserAppDataDir() + self.moddir = os.path.join(self.basedir, "Mod") + + def run(self): + """Rarely called directly: create an instance and call start() on it instead to + launch in a new thread""" + + self.current_thread = QtCore.QThread.currentThread() + checker = UpdateChecker() + count = 1 + for repo in self.repos: + if self.current_thread.isInterruptionRequested(): + return + self.progress_made.emit(count, len(self.repos)) + count += 1 + if repo.status() == Addon.Status.UNCHECKED: + if repo.repo_type == Addon.Kind.WORKBENCH: + checker.check_workbench(repo) + self.update_status.emit(repo) + elif repo.repo_type == Addon.Kind.MACRO: + checker.check_macro(repo) + self.update_status.emit(repo) + elif repo.repo_type == Addon.Kind.PACKAGE: + checker.check_package(repo) + self.update_status.emit(repo) + + +class UpdateChecker: + """A utility class used by the CheckWorkbenchesForUpdatesWorker class. Each function is + designed for a specific Addon type, and modifies the passed-in Addon with the determined + update status.""" + + def __init__(self): + self.basedir = FreeCAD.getUserAppDataDir() + self.moddir = os.path.join(self.basedir, "Mod") + self.git_manager = initialize_git() + + def override_mod_directory(self, moddir): + """Primarily for use when testing, sets an alternate directory to use for mods""" + self.moddir = moddir + + def check_workbench(self, wb): + """Given a workbench Addon wb, check it for updates using git. If git is not + available, does nothing.""" + if not self.git_manager: + wb.set_status(Addon.Status.CANNOT_CHECK) + return + clonedir = os.path.join(self.moddir, wb.name) + if os.path.exists(clonedir): + # mark as already installed AND already checked for updates + if not os.path.exists(os.path.join(clonedir, ".git")): + with wb.git_lock: + self.git_manager.repair(wb.url, clonedir) + with wb.git_lock: + try: + status = self.git_manager.status(clonedir) + if "(no branch)" in self.git_manager.status(clonedir): + # By definition, in a detached-head state we cannot + # update, so don't even bother checking. + wb.set_status(Addon.Status.NO_UPDATE_AVAILABLE) + wb.branch = self.git_manager.current_branch(clonedir) + return + except GitFailed as e: + FreeCAD.Console.PrintWarning( + "AddonManager: " + + translate( + "AddonsInstaller", + "Unable to fetch git updates for workbench {}", + ).format(wb.name) + + "\n" + ) + FreeCAD.Console.PrintWarning(str(e) + "\n") + wb.set_status(Addon.Status.CANNOT_CHECK) + else: + try: + if self.git_manager.update_available(clonedir): + wb.set_status(Addon.Status.UPDATE_AVAILABLE) + else: + wb.set_status(Addon.Status.NO_UPDATE_AVAILABLE) + except GitFailed: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", "git status failed for {}" + ).format(wb.name) + + "\n" + ) + wb.set_status(Addon.Status.CANNOT_CHECK) + + def check_package(self, package: Addon) -> None: + """Given a packaged Addon package, check it for updates. If git is available that is + used. If not, the package's metadata is examined, and if the metadata file has changed + compared to the installed copy, an update is flagged.""" + + clonedir = self.moddir + os.sep + package.name + if os.path.exists(clonedir): + + # First, try to just do a git-based update, which will give the most accurate results: + if self.git_manager: + self.check_workbench(package) + if package.status() != Addon.Status.CANNOT_CHECK: + # It worked, just exit now + return + + # If we were unable to do a git-based update, try using the package.xml file instead: + installed_metadata_file = os.path.join(clonedir, "package.xml") + if not os.path.isfile(installed_metadata_file): + # If there is no package.xml file, then it's because the package author added it + # after the last time the local installation was updated. By definition, then, + # there is an update available, if only to download the new XML file. + package.set_status(Addon.Status.UPDATE_AVAILABLE) + package.installed_version = None + return + package.updated_timestamp = os.path.getmtime(installed_metadata_file) + try: + installed_metadata = FreeCAD.Metadata(installed_metadata_file) + package.installed_version = installed_metadata.Version + # Packages are considered up-to-date if the metadata version matches. Authors + # should update their version string when they want the addon manager to alert + # users of a new version. + if package.metadata.Version != installed_metadata.Version: + package.set_status(Addon.Status.UPDATE_AVAILABLE) + else: + package.set_status(Addon.Status.NO_UPDATE_AVAILABLE) + except Exception: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Failed to read metadata from {name}", + ).format(name=installed_metadata_file) + + "\n" + ) + package.set_status(Addon.Status.CANNOT_CHECK) + + def check_macro(self, macro_wrapper: Addon) -> None: + """Check to see if the online copy of the macro's code differs from the local copy.""" + + # Make sure this macro has its code downloaded: + try: + if not macro_wrapper.macro.parsed and macro_wrapper.macro.on_git: + macro_wrapper.macro.fill_details_from_file( + macro_wrapper.macro.src_filename + ) + elif not macro_wrapper.macro.parsed and macro_wrapper.macro.on_wiki: + mac = macro_wrapper.macro.name.replace(" ", "_") + mac = mac.replace("&", "%26") + mac = mac.replace("+", "%2B") + url = "https://wiki.freecad.org/Macro_" + mac + macro_wrapper.macro.fill_details_from_wiki(url) + except Exception: + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Failed to fetch code for macro '{name}'", + ).format(name=macro_wrapper.macro.name) + + "\n" + ) + macro_wrapper.set_status(Addon.Status.CANNOT_CHECK) + return + + hasher1 = hashlib.sha1() + hasher2 = hashlib.sha1() + hasher1.update(macro_wrapper.macro.code.encode("utf-8")) + new_sha1 = hasher1.hexdigest() + test_file_one = os.path.join( + FreeCAD.getUserMacroDir(True), macro_wrapper.macro.filename + ) + test_file_two = os.path.join( + FreeCAD.getUserMacroDir(True), "Macro_" + macro_wrapper.macro.filename + ) + if os.path.exists(test_file_one): + with open(test_file_one, "rb") as f: + contents = f.read() + hasher2.update(contents) + old_sha1 = hasher2.hexdigest() + elif os.path.exists(test_file_two): + with open(test_file_two, "rb") as f: + contents = f.read() + hasher2.update(contents) + old_sha1 = hasher2.hexdigest() + else: + return + if new_sha1 == old_sha1: + macro_wrapper.set_status(Addon.Status.NO_UPDATE_AVAILABLE) + else: + macro_wrapper.set_status(Addon.Status.UPDATE_AVAILABLE) + + +class CacheMacroCodeWorker(QtCore.QThread): + """Download and cache the macro code, and parse its internal metadata""" + + status_message = QtCore.Signal(str) + update_macro = QtCore.Signal(Addon) + progress_made = QtCore.Signal(int, int) + + def __init__(self, repos: List[Addon]) -> None: + QtCore.QThread.__init__(self) + self.repos = repos + self.workers = [] + self.terminators = [] + self.lock = threading.Lock() + self.failed = [] + self.counter = 0 + self.repo_queue = None + + def run(self): + """Rarely called directly: create an instance and call start() on it instead to + launch in a new thread""" + + self.status_message.emit(translate("AddonsInstaller", "Caching macro code...")) + + self.repo_queue = queue.Queue() + num_macros = 0 + for repo in self.repos: + if repo.macro is not None: + self.repo_queue.put(repo) + num_macros += 1 + + interrupted = self._process_queue(num_macros) + if interrupted: + return + + # Make sure all of our child threads have fully exited: + for worker in self.workers: + worker.wait(50) + if not worker.isFinished(): + # The Qt Python translation extractor doesn't support splitting this string (yet) + # pylint: disable=line-too-long + FreeCAD.Console.PrintError( + translate( + "AddonsInstaller", + "Addon Manager: a worker process failed to complete while fetching {name}", + ).format(name=worker.macro.name) + + "\n" + ) + + self.repo_queue.join() + for terminator in self.terminators: + if terminator and terminator.isActive(): + terminator.stop() + + if len(self.failed) > 0: + num_failed = len(self.failed) + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Out of {num_macros} macros, {num_failed} timed out while processing", + ).format(num_macros=num_macros, num_failed=num_failed) + ) + + def _process_queue(self, num_macros) -> bool: + """Spools up six network connections and downloads the macro code. Returns True if + it was interrupted by user request, or False if it ran to completion.""" + + # Emulate QNetworkAccessManager and spool up six connections: + for _ in range(6): + self.update_and_advance(None) + + current_thread = QtCore.QThread.currentThread() + while True: + if current_thread.isInterruptionRequested(): + for worker in self.workers: + worker.blockSignals(True) + worker.requestInterruption() + if not worker.wait(100): + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Addon Manager: a worker process failed to halt ({name})", + ).format(name=worker.macro.name) + + "\n" + ) + return True + # Ensure our signals propagate out by running an internal thread-local event loop + QtCore.QCoreApplication.processEvents() + with self.lock: + if self.counter >= num_macros: + break + time.sleep(0.1) + return False + + def update_and_advance(self, repo: Addon) -> None: + """Emit the updated signal and launch the next item from the queue.""" + if repo is not None: + if repo.macro.name not in self.failed: + self.update_macro.emit(repo) + self.repo_queue.task_done() + with self.lock: + self.counter += 1 + + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + + self.progress_made.emit( + len(self.repos) - self.repo_queue.qsize(), len(self.repos) + ) + + try: + next_repo = self.repo_queue.get_nowait() + worker = GetMacroDetailsWorker(next_repo) + worker.finished.connect(lambda: self.update_and_advance(next_repo)) + with self.lock: + self.workers.append(worker) + self.terminators.append( + QtCore.QTimer.singleShot(10000, lambda: self.terminate(worker)) + ) + self.status_message.emit( + translate( + "AddonsInstaller", + "Getting metadata from macro {}", + ).format(next_repo.macro.name) + ) + worker.start() + except queue.Empty: + pass + + def terminate(self, worker) -> None: + """Shut down all running workers and exit the thread""" + if not worker.isFinished(): + macro_name = worker.macro.name + FreeCAD.Console.PrintWarning( + translate( + "AddonsInstaller", + "Timeout while fetching metadata for macro {}", + ).format(macro_name) + + "\n" + ) + worker.blockSignals(True) + worker.requestInterruption() + worker.wait(100) + if worker.isRunning(): + FreeCAD.Console.PrintError( + translate( + "AddonsInstaller", + "Failed to kill process for macro {}!\n", + ).format(macro_name) + ) + with self.lock: + self.failed.append(macro_name) + + +class GetMacroDetailsWorker(QtCore.QThread): + """Retrieve the macro details for a macro""" + + status_message = QtCore.Signal(str) + readme_updated = QtCore.Signal(str) + + def __init__(self, repo): + + QtCore.QThread.__init__(self) + self.macro = repo.macro + + def run(self): + """Rarely called directly: create an instance and call start() on it instead to + launch in a new thread""" + + self.status_message.emit( + translate("AddonsInstaller", "Retrieving macro description...") + ) + if not self.macro.parsed and self.macro.on_git: + self.status_message.emit( + translate("AddonsInstaller", "Retrieving info from git") + ) + self.macro.fill_details_from_file(self.macro.src_filename) + if not self.macro.parsed and self.macro.on_wiki: + self.status_message.emit( + translate("AddonsInstaller", "Retrieving info from wiki") + ) + mac = self.macro.name.replace(" ", "_") + mac = mac.replace("&", "%26") + mac = mac.replace("+", "%2B") + url = "https://wiki.freecad.org/Macro_" + mac + self.macro.fill_details_from_wiki(url) + message = ( + "

" + + self.macro.name + + "

" + + self.macro.desc + + '

Macro location: ' + + self.macro.url + + "" + ) + if QtCore.QThread.currentThread().isInterruptionRequested(): + return + self.readme_updated.emit(message) diff --git a/src/Mod/AddonManager/addonmanager_workers_utility.py b/src/Mod/AddonManager/addonmanager_workers_utility.py new file mode 100644 index 0000000000..1f612ab842 --- /dev/null +++ b/src/Mod/AddonManager/addonmanager_workers_utility.py @@ -0,0 +1,69 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 FreeCAD Project Association * +# * * +# * This library 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +""" Misc. worker thread classes for the FreeCAD Addon Manager. """ + +from typing import Optional + +import FreeCAD +from PySide2 import QtCore +import NetworkManager + + +class ConnectionChecker(QtCore.QThread): + """A worker thread for checking the connection to GitHub as a proxy for overall + network connectivity. It has two signals: success() and failure(str). The failure + signal contains a translated error message suitable for display to an end user.""" + + success = QtCore.Signal() + failure = QtCore.Signal(str) + + def __init__(self): + QtCore.QThread.__init__(self) + + def run(self): + """Not generally called directly: create a new ConnectionChecker object and + call start() on it to spawn a child thread.""" + + FreeCAD.Console.PrintLog("Checking network connection...\n") + result = self.check_network_connection() + if QtCore.QThread.currentThread().isInterruptionRequested(): + FreeCAD.Console.PrintLog("Connection check cancelled\n") + return + if not result: + self.failure.emit( + translate( + "AddonsInstaller", + "Unable to read data from GitHub: check your internet connection and proxy settings and try again.", + ) + ) + return + FreeCAD.Console.PrintLog(f"GitHub's zen message response: {result}\n") + self.success.emit() + + def check_network_connection(self) -> Optional[str]: + """The main work of this object: returns the decoded result of the connection request, or + None if the request failed""" + url = "https://api.github.com/zen" + result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) + if result: + return result.data().decode("utf8") + return None diff --git a/src/Mod/AddonManager/install_to_toolbar.py b/src/Mod/AddonManager/install_to_toolbar.py index c2457d836f..32f39d649f 100644 --- a/src/Mod/AddonManager/install_to_toolbar.py +++ b/src/Mod/AddonManager/install_to_toolbar.py @@ -19,17 +19,21 @@ # * * # *************************************************************************** +""" A collection of functions to handle installing a macro icon to the toolbar. """ + +import os + import FreeCAD import FreeCADGui from PySide2 import QtCore, QtWidgets import Addon -import os - translate = FreeCAD.Qt.translate def ask_to_install_toolbar_button(repo: Addon) -> None: + """Presents a dialog to the user asking if they want to install a toolbar button for + a particular macro, and walks through that process if they agree to do so.""" pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") do_not_show_dialog = pref.GetBool("dontShowAddMacroButtonDialog", False) button_exists = check_for_button(repo) @@ -48,6 +52,7 @@ def ask_to_install_toolbar_button(repo: Addon) -> None: def check_for_button(repo: Addon) -> bool: + """Returns True if a button already exists for this macro, or False if not.""" command = FreeCADGui.Command.findCustomCommand(repo.macro.filename) if not command: return False @@ -62,9 +67,10 @@ def check_for_button(repo: Addon) -> bool: return False -def ask_for_toolbar( - repo: Addon, custom_toolbars -) -> object: # Returns the pref group for the new toolbar +def ask_for_toolbar(repo: Addon, custom_toolbars) -> object: + """Determine what toolbar to add the icon to. The first time it is called it prompts the + user to select or create a toolbar. After that, the prompt is optional and can be configured + via a preference. Returns the pref group for the new toolbar.""" pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") # In this one spot, default True: if this is the first time we got to @@ -102,24 +108,24 @@ def ask_for_toolbar( pref.SetBool("alwaysAskForToolbar", True) if selection == new_menubar_option_text: return create_new_custom_toolbar() - else: - return get_toolbar_with_name(selection) - else: - return None - else: - custom_toolbar_name = pref.GetString( - "CustomToolbarName", "Auto-Created Macro Toolbar" - ) - toolbar = get_toolbar_with_name(custom_toolbar_name) - if not toolbar: - # They told us not to ask, but then the toolbar got deleted... ask anyway! - ask = pref.RemBool("alwaysAskForToolbar") - return ask_for_toolbar(repo, custom_toolbars) - else: - return toolbar + return get_toolbar_with_name(selection) + return None + + # If none of the above code returned... + custom_toolbar_name = pref.GetString( + "CustomToolbarName", "Auto-Created Macro Toolbar" + ) + toolbar = get_toolbar_with_name(custom_toolbar_name) + if not toolbar: + # They told us not to ask, but then the toolbar got deleted... ask anyway! + ask = pref.RemBool("alwaysAskForToolbar") + return ask_for_toolbar(repo, custom_toolbars) + return toolbar def get_toolbar_with_name(name: str) -> object: + """Try to find a toolbar with a given name. Returns the preference group for the toolbar + if found, or None if it does not exist.""" top_group = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar") custom_toolbars = top_group.GetGroups() for toolbar in custom_toolbars: @@ -133,6 +139,7 @@ def get_toolbar_with_name(name: str) -> object: def create_new_custom_toolbar() -> object: + """Create a new custom toolbar and returns its preference group.""" # We need two names: the name of the auto-created toolbar, as it will be displayed to the # user in various menus, and the underlying name of the toolbar group. Both must be @@ -140,15 +147,14 @@ def create_new_custom_toolbar() -> object: # First, the displayed name custom_toolbar_name = "Auto-Created Macro Toolbar" - pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") top_group = FreeCAD.ParamGet("User parameter:BaseApp/Workbench/Global/Toolbar") custom_toolbars = top_group.GetGroups() - name_taken = check_for_toolbar(custom_toolbars, custom_toolbar_name) + name_taken = check_for_toolbar(custom_toolbar_name) if name_taken: i = 2 # Don't use (1), start at (2) while True: test_name = custom_toolbar_name + f" ({i})" - if not check_for_toolbar(custom_toolbars, test_name): + if not check_for_toolbar(test_name): custom_toolbar_name = test_name i = i + 1 @@ -168,15 +174,14 @@ def create_new_custom_toolbar() -> object: return custom_toolbar -def check_for_toolbar(custom_toolbars, toolbar_name: str) -> bool: - tb = get_toolbar_with_name(toolbar_name) - if tb: - return True - else: - return False +def check_for_toolbar(toolbar_name: str) -> bool: + """Returns True if the toolbar exists, otherwise False""" + return get_toolbar_with_name(toolbar_name) is not None def install_toolbar_button(repo: Addon) -> None: + """If the user has requested a toolbar button be installed, this function is called + to continue the process and request any additional required information.""" pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") custom_toolbar_name = pref.GetString( "CustomToolbarName", "Auto-Created Macro Toolbar" @@ -220,11 +225,12 @@ def install_toolbar_button(repo: Addon) -> None: install_macro_to_toolbar(repo, custom_toolbar) else: FreeCAD.Console.PrintMessage( - f"In the end, no custom toolbar was set, bailing out\n" + "In the end, no custom toolbar was set, bailing out\n" ) def install_macro_to_toolbar(repo: Addon, toolbar: object) -> None: + """Adds an icon for the given macro to the given toolbar.""" menuText = repo.display_name tooltipText = f"{repo.display_name}" if repo.macro.comment: @@ -250,7 +256,7 @@ def install_macro_to_toolbar(repo: Addon, toolbar: object) -> None: icon_file = os.path.normpath( os.path.join(macro_repo_dir, repo.macro.name + "_icon.xpm") ) - with open(icon_file, "w") as f: + with open(icon_file, "w", encoding="utf-8") as f: f.write(repo.macro.xpm) pixmapText = icon_file else: diff --git a/src/Mod/AddonManager/manage_python_dependencies.py b/src/Mod/AddonManager/manage_python_dependencies.py new file mode 100644 index 0000000000..625c9b7e7f --- /dev/null +++ b/src/Mod/AddonManager/manage_python_dependencies.py @@ -0,0 +1,274 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 FreeCAD Project Association * +# * * +# * This program 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. * +# * * +# * 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 * +# * Lesser General Public License for more details. * +# * * +# * You should have received a copy of the GNU Lesser General Public * +# * License along with this library; if not, write to the Free Software * +# * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * +# * 02110-1301 USA * +# * * +# *************************************************************************** + +""" Provides classes and support functions for managing the automatically-installed +Python library dependencies. No support is provided for uninstalling those dependencies +because pip's uninstall function does not support the target directory argument. """ + +from typing import List, Dict + +import os +import subprocess +from functools import partial + +import FreeCAD +import FreeCADGui +from PySide2 import QtCore, QtGui, QtWidgets + +import addonmanager_utilities as utils + +translate = FreeCAD.Qt.translate + + +class CheckForPythonPackageUpdatesWorker(QtCore.QThread): + """Perform non-blocking Python library update availability checking""" + + python_package_updates_available = QtCore.Signal() + + def __init__(self): + QtCore.QThread.__init__(self) + + def run(self): + """Usually not called directly: instead, instantiate this class and call its start() function + in a parent thread. emits a python_package_updates_available signal if updates are available + for any of the installed Python packages.""" + + if check_for_python_package_updates(): + self.python_package_updates_available.emit() + + +def check_for_python_package_updates() -> bool: + """Returns True if any of the Python packages installed into the AdditionalPythonPackages directory + have updates available, or False if the are all up-to-date.""" + + vendor_path = os.path.join(FreeCAD.getUserAppDataDir(), "AdditionalPythonPackages") + package_counter = 0 + outdated_packages_stdout = call_pip(["list", "-o", "--path", vendor_path]) + FreeCAD.Console.PrintLog("Output from pip -o:\n") + for line in outdated_packages_stdout: + if len(line) > 0: + package_counter += 1 + FreeCAD.Console.PrintLog(f" {line}\n") + return package_counter > 0 + + +def call_pip(args) -> List[str]: + """Tries to locate the appropriate Python executable and run pip with version checking disabled. Fails + if Python can't be found or if pip is not installed.""" + + python_exe = utils.get_python_exe() + pip_failed = False + if python_exe: + try: + call_args = [python_exe, "-m", "pip", "--disable-pip-version-check"] + call_args.extend(args) + proc = subprocess.run( + call_args, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + shell=True, + check=True, + ) + except subprocess.CalledProcessError: + pip_failed = True + if proc.returncode != 0: + pip_failed = True + else: + pip_failed = True + + result = [] + if not pip_failed: + data = proc.stdout.decode() + result = data.split("\n") + else: + raise Exception(proc.stderr.decode()) + return result + + +class PythonPackageManager: + + """A GUI-based pip interface allowing packages to be updated, either individually or all at once.""" + + def __init__(self): + self.dlg = FreeCADGui.PySideUic.loadUi( + os.path.join(os.path.dirname(__file__), "PythonDependencyUpdateDialog.ui") + ) + self.vendor_path = os.path.join( + FreeCAD.getUserAppDataDir(), "AdditionalPythonPackages" + ) + + def show(self): + """Run the modal dialog""" + + self._create_list_from_pip() + self.dlg.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint, True) + self.dlg.tableWidget.setSortingEnabled(False) + self.dlg.labelInstallationPath.setText(self.vendor_path) + self.dlg.exec() + + def _create_list_from_pip(self): + """Uses pip and pip -o to generate a list of installed packages, and creates the user + interface elements for those packages.""" + + all_packages_stdout = call_pip(["list", "--path", self.vendor_path]) + outdated_packages_stdout = call_pip(["list", "-o", "--path", self.vendor_path]) + package_list = self._parse_pip_list_output( + all_packages_stdout, outdated_packages_stdout + ) + self.dlg.buttonUpdateAll.clicked.connect( + partial(self._update_all_packages, package_list) + ) + + self.dlg.tableWidget.setRowCount(len(package_list)) + updateButtons = [] + counter = 0 + update_counter = 0 + self.dlg.tableWidget.setSortingEnabled(False) + for package_name, package_details in package_list.items(): + self.dlg.tableWidget.setItem( + counter, 0, QtWidgets.QTableWidgetItem(package_name) + ) + self.dlg.tableWidget.setItem( + counter, + 1, + QtWidgets.QTableWidgetItem(package_details["installed_version"]), + ) + self.dlg.tableWidget.setItem( + counter, + 2, + QtWidgets.QTableWidgetItem(package_details["available_version"]), + ) + if len(package_details["available_version"]) > 0: + updateButtons.append( + QtWidgets.QPushButton(translate("AddonsInstaller", "Update")) + ) + updateButtons[-1].setIcon(QtGui.QIcon(":/icons/button_up.svg")) + updateButtons[-1].clicked.connect( + partial(self._update_package, package_name) + ) + self.dlg.tableWidget.setCellWidget(counter, 3, updateButtons[-1]) + update_counter += 1 + else: + self.dlg.tableWidget.removeCellWidget(counter, 3) + counter += 1 + self.dlg.tableWidget.setSortingEnabled(True) + + self.dlg.tableWidget.horizontalHeader().setStretchLastSection(False) + self.dlg.tableWidget.horizontalHeader().setSectionResizeMode( + 0, QtWidgets.QHeaderView.Stretch + ) + self.dlg.tableWidget.horizontalHeader().setSectionResizeMode( + 1, QtWidgets.QHeaderView.ResizeToContents + ) + self.dlg.tableWidget.horizontalHeader().setSectionResizeMode( + 2, QtWidgets.QHeaderView.ResizeToContents + ) + self.dlg.tableWidget.horizontalHeader().setSectionResizeMode( + 3, QtWidgets.QHeaderView.ResizeToContents + ) + + if update_counter > 0: + self.dlg.buttonUpdateAll.setEnabled(True) + else: + self.dlg.buttonUpdateAll.setEnabled(False) + + def _parse_pip_list_output( + self, all_packages, outdated_packages + ) -> Dict[str, Dict[str, str]]: + """Parses the output from pip into a dictionary with update information in it. The pip output should + be an array of lines of text.""" + + # All Packages output looks like this: + # Package Version + # ---------- ------- + # gitdb 4.0.9 + # GitPython 3.1.27 + # setuptools 41.2.0 + + # Outdated Packages output looks like this: + # Package Version Latest Type + # ---------- ------- ------ ----- + # pip 21.0.1 22.1.2 wheel + # setuptools 41.2.0 63.2.0 wheel + + packages = {} + skip_counter = 0 + for line in all_packages: + if skip_counter < 2: + skip_counter += 1 + continue + entries = line.split() + if len(entries) > 1: + package_name = entries[0] + installed_version = entries[1] + packages[package_name] = { + "installed_version": installed_version, + "available_version": "", + } + + skip_counter = 0 + for line in outdated_packages: + if skip_counter < 2: + skip_counter += 1 + continue + entries = line.split() + if len(entries) > 1: + package_name = entries[0] + installed_version = entries[1] + available_version = entries[2] + packages[package_name] = { + "installed_version": installed_version, + "available_version": available_version, + } + + return packages + + def _update_package(self, package_name) -> None: + """Run pip --upgrade on the given package. Updates all dependent packages as well.""" + for line in range(self.dlg.tableWidget.rowCount()): + if self.dlg.tableWidget.item(line, 0).text() == package_name: + self.dlg.tableWidget.setItem( + line, + 2, + QtWidgets.QTableWidgetItem( + translate("AddonsInstaller", "Updating...") + ), + ) + break + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + + call_pip(["install", "--upgrade", package_name, "--target", self.vendor_path]) + self._create_list_from_pip() + QtCore.QCoreApplication.processEvents(QtCore.QEventLoop.AllEvents, 50) + + def _update_all_packages(self, package_list) -> None: + """Updates all packages with available updates.""" + updates = [] + for package_name, package_details in package_list.items(): + if ( + len(package_details["available_version"]) > 0 + and package_details["available_version"] + != package_details["installed_version"] + ): + updates.append(package_name) + + for package_name in updates: + self._update_package(package_name) diff --git a/src/Mod/AddonManager/package_details.py b/src/Mod/AddonManager/package_details.py index c29a910029..b916a445c8 100644 --- a/src/Mod/AddonManager/package_details.py +++ b/src/Mod/AddonManager/package_details.py @@ -21,19 +21,21 @@ # * USA * # * * # *************************************************************************** -from posixpath import normpath + +""" Provides the PackageDetails widget. """ + +import os +from typing import Optional + from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * - -import os - import FreeCAD import FreeCADGui import addonmanager_utilities as utils -from addonmanager_workers import GetMacroDetailsWorker, CheckSingleUpdateWorker +from addonmanager_workers_startup import GetMacroDetailsWorker, CheckSingleUpdateWorker from Addon import Addon import NetworkManager from change_branch import ChangeBranchDialog @@ -47,7 +49,6 @@ try: except ImportError: pass -from typing import Optional translate = FreeCAD.Qt.translate @@ -57,7 +58,7 @@ try: from PySide2.QtWebEngineWidgets import * HAS_QTWEBENGINE = True -except Exception: +except ImportError: FreeCAD.Console.PrintWarning( translate( "AddonsInstaller", @@ -69,6 +70,8 @@ except Exception: class PackageDetails(QWidget): + """The PackageDetails QWidget shows package README information and provides + install, uninstall, and update buttons.""" back = Signal() install = Signal(Addon) @@ -104,13 +107,16 @@ class PackageDetails(QWidget): self.ui.webView.loadFinished.connect(self.load_finished) loading_html_file = os.path.join(os.path.dirname(__file__), "loading.html") - with open(loading_html_file, "r", errors="ignore") as f: + with open(loading_html_file, "r", errors="ignore", encoding="utf-8") as f: html = f.read() self.ui.loadingLabel.setHtml(html) self.ui.loadingLabel.show() self.ui.webView.hide() def show_repo(self, repo: Addon, reload: bool = False) -> None: + """The main entry point for this class, shows the package details and related buttons + for the provided repo. If reload is true, then even if this is already the current repo + the data is reloaded.""" # If this is the same repo we were already showing, we do not have to do the # expensive refetch unless reload is true @@ -149,19 +155,22 @@ class PackageDetails(QWidget): if repo.status() == Addon.Status.UNCHECKED: if not self.status_update_thread: self.status_update_thread = QThread() - self.status_update_worker = CheckSingleUpdateWorker(repo) - self.status_update_worker.moveToThread(self.status_update_thread) + self.status_create_addon_list_worker = CheckSingleUpdateWorker(repo) + self.status_create_addon_list_worker.moveToThread(self.status_update_thread) self.status_update_thread.finished.connect( - self.status_update_worker.deleteLater + self.status_create_addon_list_worker.deleteLater + ) + self.check_for_update.connect(self.status_create_addon_list_worker.do_work) + self.status_create_addon_list_worker.update_status.connect( + self.display_repo_status ) - self.check_for_update.connect(self.status_update_worker.do_work) - self.status_update_worker.update_status.connect(self.display_repo_status) self.status_update_thread.start() self.check_for_update.emit(self.repo) self.display_repo_status(self.repo.update_status) def display_repo_status(self, status): + """Updates the contents of the widget to display the current install status of the widget.""" repo = self.repo self.set_change_branch_button_state() self.set_disable_button_state() @@ -383,6 +392,10 @@ class PackageDetails(QWidget): self.ui.labelWarningInfo.hide() def requires_newer_freecad(self) -> Optional[str]: + """If the current package is not installed, returns the first supported version of + FreeCAD, if one is set, or None if no information is available (or if the package is + already installed).""" + # If it's not installed, check to see if it's for a newer version of FreeCAD if self.repo.status() == Addon.Status.NOT_INSTALLED and self.repo.metadata: # Only hide if ALL content items require a newer version, otherwise @@ -399,7 +412,7 @@ class PackageDetails(QWidget): if int(required_version[0]) > fc_major: return first_supported_version - elif int(required_version[0]) == fc_major and len(required_version) > 1: + if int(required_version[0]) == fc_major and len(required_version) > 1: if int(required_version[1]) > fc_minor: return first_supported_version return None @@ -438,6 +451,7 @@ class PackageDetails(QWidget): self.ui.buttonChangeBranch.show() def set_disable_button_state(self): + """Set up the enable/disable button based on the enabled/disabled state of the addon""" self.ui.buttonEnable.hide() self.ui.buttonDisable.hide() status = self.repo.status() @@ -491,6 +505,7 @@ class PackageDetails(QWidget): self.macro_readme_updated() def macro_readme_updated(self): + """Update the display of a Macro's README data.""" url = self.repo.macro.wiki if not url: url = self.repo.macro.url @@ -575,13 +590,16 @@ class PackageDetails(QWidget): self.ui.webView.page().runJavaScript(s) def load_started(self): + """Called when loading is started: sets up the progress bar""" self.ui.progressBar.show() self.ui.progressBar.setValue(0) def load_progress(self, progress: int): + """Called during load to update the progress bar""" self.ui.progressBar.setValue(progress) def load_finished(self, load_succeeded: bool): + """Once loading is complete, update the display of the progress bar and loading widget.""" self.ui.loadingLabel.hide() self.ui.slowLoadLabel.hide() self.ui.webView.show() @@ -608,12 +626,14 @@ class PackageDetails(QWidget): self.show_error_for(url) def long_load_running(self): + """Displays a message about loading taking a long time.""" if hasattr(self.ui, "webView") and self.ui.webView.isHidden(): self.ui.slowLoadLabel.show() self.ui.loadingLabel.hide() self.ui.webView.show() def show_error_for(self, url: QUrl) -> None: + """Displays error information.""" m = translate( "AddonsInstaller", "Could not load README data from URL {}" ).format(url.toString()) @@ -621,6 +641,7 @@ class PackageDetails(QWidget): self.ui.webView.setHtml(html) def change_branch_clicked(self) -> None: + """Loads the branch-switching dialog""" basedir = FreeCAD.getUserAppDataDir() path_to_repo = os.path.join(basedir, "Mod", self.repo.name) change_branch_dialog = ChangeBranchDialog(path_to_repo, self) @@ -628,6 +649,7 @@ class PackageDetails(QWidget): change_branch_dialog.exec() def enable_clicked(self) -> None: + """Called by the Enable button, enables this Addon and updates GUI to reflect that status.""" self.repo.enable() self.repo.set_status(Addon.Status.PENDING_RESTART) self.set_disable_button_state() @@ -644,6 +666,7 @@ class PackageDetails(QWidget): self.ui.labelWarningInfo.setStyleSheet("color:" + utils.bright_color_string()) def disable_clicked(self) -> None: + """Called by the Disable button, disables this Addon and updates the GUI to reflect that status.""" self.repo.disable() self.repo.set_status(Addon.Status.PENDING_RESTART) self.set_disable_button_state() @@ -662,6 +685,7 @@ class PackageDetails(QWidget): ) def branch_changed(self, name: str) -> None: + """Displays a dialog confirming the branch changed, and tries to access the metadata file from that branch.""" QMessageBox.information( self, translate("AddonsInstaller", "Success"), @@ -706,6 +730,8 @@ if HAS_QTWEBENGINE: self.settings().setAttribute(QWebEngineSettings.ErrorPageEnabled, False) def acceptNavigationRequest(self, url, _type, isMainFrame): + """A callback for navigation requests: this widget will only display navigation requests to the + FreeCAD Wiki (for translation purposes) -- anything else will open in a new window.""" if _type == QWebEnginePage.NavigationTypeLinkClicked: # See if the link is to a FreeCAD Wiki page -- if so, follow it, otherwise ask the OS to open it @@ -714,12 +740,14 @@ if HAS_QTWEBENGINE: or url.host() == "wiki.freecadweb.org" ): return super().acceptNavigationRequest(url, _type, isMainFrame) - else: - QDesktopServices.openUrl(url) - return False + QDesktopServices.openUrl(url) + return False return super().acceptNavigationRequest(url, _type, isMainFrame) - def javaScriptConsoleMessage(self, level, message, lineNumber, sourceID): + def javaScriptConsoleMessage(self, level, message, lineNumber, _): + """Handle JavaScript console messages by optionally outputting them to the FreeCAD Console. This + must be manually enabled in this Python file by setting the global show_javascript_console_output + to true.""" global show_javascript_console_output if show_javascript_console_output: tag = translate("AddonsInstaller", "Page JavaScript reported") @@ -732,6 +760,8 @@ if HAS_QTWEBENGINE: class Ui_PackageDetails(object): + """The generated UI from the Qt Designer UI file""" + def setupUi(self, PackageDetails): if not PackageDetails.objectName(): PackageDetails.setObjectName("PackageDetails") diff --git a/src/Mod/AddonManager/package_list.py b/src/Mod/AddonManager/package_list.py index 9ffd66ce76..0bf5255044 100644 --- a/src/Mod/AddonManager/package_list.py +++ b/src/Mod/AddonManager/package_list.py @@ -22,15 +22,17 @@ # * * # *************************************************************************** +""" Defines the PackageList QWidget for displaying a list of Addons. """ + +from enum import IntEnum +import threading + import FreeCAD from PySide2.QtCore import * from PySide2.QtGui import * from PySide2.QtWidgets import * -from enum import IntEnum -import threading - from Addon import Addon from compact_view import Ui_CompactView @@ -42,11 +44,15 @@ translate = FreeCAD.Qt.translate class ListDisplayStyle(IntEnum): + """The display mode of the list""" + COMPACT = 0 EXPANDED = 1 class StatusFilter(IntEnum): + """Predefined filers""" + ANY = 0 INSTALLED = 1 NOT_INSTALLED = 2 @@ -89,7 +95,11 @@ class PackageList(QWidget): status = pref.GetInt("StatusSelection", 0) self.ui.comboStatus.setCurrentIndex(status) + # Pre-init of other members: + self.item_model = None + def setModel(self, model): + """This is a model-view-controller widget: set its model.""" self.item_model = model self.item_filter.setSourceModel(self.item_model) self.item_filter.sort(0) @@ -109,6 +119,8 @@ class PackageList(QWidget): ) def on_listPackages_clicked(self, index: QModelIndex): + """Determine what addon was selected and emit the itemSelected signal with it as + an argument.""" source_selection = self.item_filter.mapToSource(index) selected_repo = self.item_model.repos[source_selection.row()] self.itemSelected.emit(selected_repo) @@ -166,6 +178,7 @@ class PackageList(QWidget): self.item_filter.setFilterRegExp(text_filter) def set_view_style(self, style: ListDisplayStyle) -> None: + """Set the style (compact or expanded) of the list""" self.item_model.layoutAboutToBeChanged.emit() self.item_delegate.set_view(style) if style == ListDisplayStyle.COMPACT: @@ -179,6 +192,7 @@ class PackageList(QWidget): class PackageListItemModel(QAbstractListModel): + """The model for use with the PackageList class.""" repos = [] write_lock = threading.Lock() @@ -187,20 +201,20 @@ class PackageListItemModel(QAbstractListModel): StatusUpdateRole = Qt.UserRole + 1 IconUpdateRole = Qt.UserRole + 2 - def __init__(self, parent=None) -> None: - super().__init__(parent) - def rowCount(self, parent: QModelIndex = QModelIndex()) -> int: + """The number of rows""" if parent.isValid(): return 0 return len(self.repos) def columnCount(self, parent: QModelIndex = QModelIndex()) -> int: + """Only one column, always returns 1.""" if parent.isValid(): return 0 return 1 def data(self, index: QModelIndex, role: int = Qt.DisplayRole): + """Get the data for a given index and role.""" if not index.isValid(): return None row = index.row() @@ -219,52 +233,53 @@ class PackageListItemModel(QAbstractListModel): "AddonsInstaller", "Click for details about macro {}" ).format(self.repos[row].display_name) return tooltip - elif role == PackageListItemModel.DataAccessRole: + if role == PackageListItemModel.DataAccessRole: return self.repos[row] - def headerData(self, section, orientation, role=Qt.DisplayRole): + def headerData(self, _unused1, _unused2, _role=Qt.DisplayRole): + """No header in this implementation: always returns None.""" return None def setData(self, index: QModelIndex, value, role=Qt.EditRole) -> None: """Set the data for this row. The column of the index is ignored.""" row = index.row() - self.write_lock.acquire() - if role == PackageListItemModel.StatusUpdateRole: - self.repos[row].set_status(value) - self.dataChanged.emit( - self.index(row, 2), - self.index(row, 2), - [PackageListItemModel.StatusUpdateRole], - ) - elif role == PackageListItemModel.IconUpdateRole: - self.repos[row].icon = value - self.dataChanged.emit( - self.index(row, 0), - self.index(row, 0), - [PackageListItemModel.IconUpdateRole], - ) - self.write_lock.release() + with self.write_lock: + if role == PackageListItemModel.StatusUpdateRole: + self.repos[row].set_status(value) + self.dataChanged.emit( + self.index(row, 2), + self.index(row, 2), + [PackageListItemModel.StatusUpdateRole], + ) + elif role == PackageListItemModel.IconUpdateRole: + self.repos[row].icon = value + self.dataChanged.emit( + self.index(row, 0), + self.index(row, 0), + [PackageListItemModel.IconUpdateRole], + ) def append_item(self, repo: Addon) -> None: + """Adds this addon to the end of the model. Thread safe.""" if repo in self.repos: # Cowardly refuse to insert the same repo a second time return - self.write_lock.acquire() - self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) - self.repos.append(repo) - self.endInsertRows() - self.write_lock.release() + with self.write_lock: + self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount()) + self.repos.append(repo) + self.endInsertRows() def clear(self) -> None: + """Clear the model, removing all rows. Thread safe.""" if self.rowCount() > 0: - self.write_lock.acquire() - self.beginRemoveRows(QModelIndex(), 0, self.rowCount() - 1) - self.repos = [] - self.endRemoveRows() - self.write_lock.release() + with self.write_lock: + self.beginRemoveRows(QModelIndex(), 0, self.rowCount() - 1) + self.repos = [] + self.endRemoveRows() def update_item_status(self, name: str, status: Addon.Status) -> None: + """Set the status of addon with name to status.""" for row, item in enumerate(self.repos): if item.name == name: self.setData( @@ -273,6 +288,7 @@ class PackageListItemModel(QAbstractListModel): return def update_item_icon(self, name: str, icon: QIcon) -> None: + """Set the icon for Addon with name to icon""" for row, item in enumerate(self.repos): if item.name == name: self.setData( @@ -281,11 +297,11 @@ class PackageListItemModel(QAbstractListModel): return def reload_item(self, repo: Addon) -> None: + """Sets the addon data for the given addon (based on its name)""" for index, item in enumerate(self.repos): if item.name == repo.name: - self.write_lock.acquire() - self.repos[index] = repo - self.write_lock.release() + with self.write_lock: + self.repos[index] = repo return @@ -322,14 +338,17 @@ class PackageListItemDelegate(QStyledItemDelegate): self.widget = self.expanded def set_view(self, style: ListDisplayStyle) -> None: + """Set the view of to style""" if not self.displayStyle == style: self.displayStyle = style - def sizeHint(self, option, index): + def sizeHint(self, _option, index): + """Attempt to figure out the correct height for the widget based on its current contents.""" self.update_content(index) return self.widget.sizeHint() def update_content(self, index): + """Creates the display of the content for a given index.""" repo = index.data(PackageListItemModel.DataAccessRole) if self.displayStyle == ListDisplayStyle.EXPANDED: self.widget = self.expanded @@ -347,57 +366,9 @@ class PackageListItemDelegate(QStyledItemDelegate): self.widget.ui.labelDescription.setText(repo.metadata.Description) self.widget.ui.labelVersion.setText(f"v{repo.metadata.Version}") if self.displayStyle == ListDisplayStyle.EXPANDED: - maintainers = repo.metadata.Maintainer - maintainers_string = "" - if len(maintainers) == 1: - maintainers_string = ( - translate("AddonsInstaller", "Maintainer") - + f": {maintainers[0]['name']} <{maintainers[0]['email']}>" - ) - elif len(maintainers) > 1: - n = len(maintainers) - maintainers_string = translate( - "AddonsInstaller", "Maintainers:", "", n - ) - for maintainer in maintainers: - maintainers_string += ( - f"\n{maintainer['name']} <{maintainer['email']}>" - ) - self.widget.ui.labelMaintainer.setText(maintainers_string) - if repo.tags: - self.widget.ui.labelTags.setText( - translate("AddonsInstaller", "Tags") - + ": " - + ", ".join(repo.tags) - ) + self._setup_expanded_package(repo) elif repo.macro and repo.macro.parsed: - self.widget.ui.labelDescription.setText(repo.macro.comment) - version_string = "" - if repo.macro.version: - version_string = repo.macro.version + " " - if repo.macro.on_wiki: - version_string += "(wiki)" - elif repo.macro.on_git: - version_string += "(git)" - else: - version_string += "(unknown source)" - if repo.macro.date: - version_string = ( - version_string - + ", " - + translate("AddonsInstaller", "updated") - + " " - + repo.macro.date - ) - self.widget.ui.labelVersion.setText("" + version_string + "") - if self.displayStyle == ListDisplayStyle.EXPANDED: - if repo.macro.author: - caption = translate("AddonsInstaller", "Author") - self.widget.ui.labelMaintainer.setText( - caption + ": " + repo.macro.author - ) - else: - self.widget.ui.labelMaintainer.setText("") + self._setup_macro(repo) else: self.widget.ui.labelDescription.setText("") self.widget.ui.labelVersion.setText("") @@ -412,6 +383,56 @@ class PackageListItemDelegate(QStyledItemDelegate): self.widget.adjustSize() + def _setup_expanded_package(self, repo: Addon): + """Set up the display for a package in expanded view""" + maintainers = repo.metadata.Maintainer + maintainers_string = "" + if len(maintainers) == 1: + maintainers_string = ( + translate("AddonsInstaller", "Maintainer") + + f": {maintainers[0]['name']} <{maintainers[0]['email']}>" + ) + elif len(maintainers) > 1: + n = len(maintainers) + maintainers_string = translate("AddonsInstaller", "Maintainers:", "", n) + for maintainer in maintainers: + maintainers_string += f"\n{maintainer['name']} <{maintainer['email']}>" + self.widget.ui.labelMaintainer.setText(maintainers_string) + if repo.tags: + self.widget.ui.labelTags.setText( + translate("AddonsInstaller", "Tags") + ": " + ", ".join(repo.tags) + ) + + def _setup_macro(self, repo: Addon): + """Set up the display for a macro""" + self.widget.ui.labelDescription.setText(repo.macro.comment) + version_string = "" + if repo.macro.version: + version_string = repo.macro.version + " " + if repo.macro.on_wiki: + version_string += "(wiki)" + elif repo.macro.on_git: + version_string += "(git)" + else: + version_string += "(unknown source)" + if repo.macro.date: + version_string = ( + version_string + + ", " + + translate("AddonsInstaller", "updated") + + " " + + repo.macro.date + ) + self.widget.ui.labelVersion.setText("" + version_string + "") + if self.displayStyle == ListDisplayStyle.EXPANDED: + if repo.macro.author: + caption = translate("AddonsInstaller", "Author") + self.widget.ui.labelMaintainer.setText( + caption + ": " + repo.macro.author + ) + else: + self.widget.ui.labelMaintainer.setText("") + def get_compact_update_string(self, repo: Addon) -> str: """Get a single-line string listing details about the installed version and date""" @@ -501,6 +522,8 @@ class PackageListItemDelegate(QStyledItemDelegate): return result def paint(self, painter: QPainter, option: QStyleOptionViewItem, _: QModelIndex): + """Main paint function: renders this widget into a given rectangle, successively drawing + all of its children.""" painter.save() self.widget.resize(option.rect.size()) painter.translate(option.rect.topLeft()) @@ -521,36 +544,44 @@ class PackageListFilter(QSortFilterProxyModel): self.hide_newer_freecad_required = False def setPackageFilter( - self, type: int + self, package_type: int ) -> None: # 0=All, 1=Workbenches, 2=Macros, 3=Preference Packs - self.package_type = type + """Set the package filter to package_type and refreshes.""" + self.package_type = package_type self.invalidateFilter() def setStatusFilter( self, status: int ) -> None: # 0=Any, 1=Installed, 2=Not installed, 3=Update available + """Sets the status filter to status and refreshes.""" self.status = status self.invalidateFilter() def setHidePy2(self, hide_py2: bool) -> None: + """Sets whether or not to hide Python 2-only Addons""" self.hide_py2 = hide_py2 self.invalidateFilter() def setHideObsolete(self, hide_obsolete: bool) -> None: + """Sets whether or not to hide Addons marked obsolete""" self.hide_obsolete = hide_obsolete self.invalidateFilter() def setHideNewerFreeCADRequired(self, hide_nfr: bool) -> None: + """Sets whether or not to hide packages that have indicated they need a newer version + of FreeCAD than the one currently running.""" self.hide_newer_freecad_required = hide_nfr self.invalidateFilter() def lessThan(self, left, right) -> bool: + """Enable sorting of display name (not case sensitive).""" l = self.sourceModel().data(left, PackageListItemModel.DataAccessRole) r = self.sourceModel().data(right, PackageListItemModel.DataAccessRole) return l.display_name.lower() < r.display_name.lower() def filterAcceptsRow(self, row, parent=QModelIndex()): + """Do the actual filtering (called automatically by Qt when drawing the list)""" index = self.sourceModel().createIndex(row, 0) data = self.sourceModel().data(index, PackageListItemModel.DataAccessRole) if self.package_type == 1: @@ -607,7 +638,7 @@ class PackageListFilter(QSortFilterProxyModel): if int(required_version[0]) > fc_major: return False - elif int(required_version[0]) == fc_major and len(required_version) > 1: + if int(required_version[0]) == fc_major and len(required_version) > 1: if int(required_version[1]) > fc_minor: return False @@ -630,29 +661,25 @@ class PackageListFilter(QSortFilterProxyModel): for tag in data.tags: if re.match(tag).hasMatch(): return True - return False - else: - return False - else: - re = self.filterRegExp() - if re.isValid(): - re.setCaseSensitivity(Qt.CaseInsensitive) - if re.indexIn(name) != -1: + return False + # Only get here for Qt < 5.12 + re = self.filterRegExp() + if re.isValid(): + re.setCaseSensitivity(Qt.CaseInsensitive) + if re.indexIn(name) != -1: + return True + if re.indexIn(desc) != -1: + return True + if ( + data.macro + and data.macro.comment + and re.indexIn(data.macro.comment) != -1 + ): + return True + for tag in data.tags: + if re.indexIn(tag) != -1: return True - if re.indexIn(desc) != -1: - return True - if ( - data.macro - and data.macro.comment - and re.indexIn(data.macro.comment) != -1 - ): - return True - for tag in data.tags: - if re.indexIn(tag) != -1: - return True - return False - else: - return False + return False class Ui_PackageList(object): diff --git a/src/Mod/Arch/ArchAxis.py b/src/Mod/Arch/ArchAxis.py index c35013a17f..693b731407 100644 --- a/src/Mod/Arch/ArchAxis.py +++ b/src/Mod/Arch/ArchAxis.py @@ -26,7 +26,7 @@ from FreeCAD import Vector if FreeCAD.GuiUp: import FreeCADGui, re from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from pivy import coin from PySide.QtCore import QT_TRANSLATE_NOOP @@ -398,7 +398,7 @@ class _ViewProviderAxis: center = p2.add(Vector(dv).multiply(rad)) normal = vobj.Object.Placement.Rotation.multVec(Vector(0,0,1)) chord = dv.cross(normal) - if arrow == True: + if arrow: p3 = p2.add(Vector(chord).multiply(rad/2).negative()) if vobj.BubblePosition.startswith("Arrow"): p4 = p3.add(Vector(dv).multiply(rad*2).negative()) diff --git a/src/Mod/Arch/ArchAxisSystem.py b/src/Mod/Arch/ArchAxisSystem.py index e8bd28ee84..b507c87850 100644 --- a/src/Mod/Arch/ArchAxisSystem.py +++ b/src/Mod/Arch/ArchAxisSystem.py @@ -23,7 +23,7 @@ import FreeCAD, DraftGeomUtils if FreeCAD.GuiUp: import FreeCADGui, Draft from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from pivy import coin from PySide.QtCore import QT_TRANSLATE_NOOP else: diff --git a/src/Mod/Arch/ArchBuilding.py b/src/Mod/Arch/ArchBuilding.py index 2d37f63af6..a574b15017 100644 --- a/src/Mod/Arch/ArchBuilding.py +++ b/src/Mod/Arch/ArchBuilding.py @@ -24,7 +24,7 @@ import FreeCAD,Draft,ArchCommands,ArchFloor if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -231,7 +231,7 @@ class _CommandBuilding: if not Draft.getType(obj) in ["Site", "Building"] : buildingobj.append(obj) else : - if link == True : + if link : buildingobj.append(obj) else: warning = True diff --git a/src/Mod/Arch/ArchBuildingPart.py b/src/Mod/Arch/ArchBuildingPart.py index 4de74ba342..b8549d9e52 100644 --- a/src/Mod/Arch/ArchBuildingPart.py +++ b/src/Mod/Arch/ArchBuildingPart.py @@ -24,13 +24,12 @@ import FreeCAD import Draft import ArchCommands import DraftVecUtils -import sys import ArchIFC import tempfile import os if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP import draftutils.units as units else: @@ -40,8 +39,7 @@ else: def QT_TRANSLATE_NOOP(ctxt,txt): return txt # \endcond -if sys.version_info.major >= 3: - unicode = str +unicode = str ## @package ArchBuildingPart # \ingroup ARCH @@ -758,10 +756,7 @@ class ViewProviderBuildingPart: elif prop == "FontName": if hasattr(vobj,"FontName") and hasattr(self,"fon"): if vobj.FontName: - if sys.version_info.major < 3: - self.fon.name = vobj.FontName.encode("utf8") - else: - self.fon.name = vobj.FontName + self.fon.name = vobj.FontName elif prop in ["FontSize","DisplayOffset","OriginOffset"]: if hasattr(vobj,"FontSize") and hasattr(vobj,"DisplayOffset") and hasattr(vobj,"OriginOffset") and hasattr(self,"fon"): fs = vobj.FontSize.Value diff --git a/src/Mod/Arch/ArchCommands.py b/src/Mod/Arch/ArchCommands.py index 18c9cf5471..8f729bb9e5 100644 --- a/src/Mod/Arch/ArchCommands.py +++ b/src/Mod/Arch/ArchCommands.py @@ -20,7 +20,6 @@ #* * #*************************************************************************** -import sys import FreeCAD,Draft,ArchComponent,DraftVecUtils from FreeCAD import Vector if FreeCAD.GuiUp: @@ -60,8 +59,6 @@ def string_replace(text, pattern, replacement): u'abc mm \xc2\xb3' ``` """ - if sys.version_info.major < 3: - text = text.encode("utf8") return text.replace(pattern, replacement) @@ -427,7 +424,8 @@ def getCutVolume(cutplane,shapes,clip=False,depth=None): return None,None,None ce = p.CenterOfMass ax = p.normalAt(0,0) - u = p.Vertexes[1].Point.sub(p.Vertexes[0].Point).normalize() + prm_range = p.ParameterRange # (uMin, uMax, vMin, vMax) + u = p.valueAt(prm_range[0], 0).sub(p.valueAt(prm_range[1], 0)).normalize() v = u.cross(ax) if not bb.isCutPlane(ce,ax): #FreeCAD.Console.PrintMessage(translate("Arch","No objects are cut by the plane)+"\n") @@ -936,8 +934,6 @@ def survey(callback=False): if FreeCAD.SurveyObserver.totalLength: u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalLength,FreeCAD.Units.Length) t = u.getUserPreferred()[0] - if sys.version_info.major < 3: - t = t.encode("utf8") msg += " Length: " + t if FreeCAD.SurveyObserver.totalArea: u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalArea,FreeCAD.Units.Area) @@ -1044,8 +1040,6 @@ class SurveyTaskPanel: if hasattr(FreeCAD,"SurveyObserver"): u = FreeCAD.Units.Quantity(FreeCAD.SurveyObserver.totalLength,FreeCAD.Units.Length) t = u.getUserPreferred()[0] - if sys.version_info.major < 3: - t = t.encode("utf8") if FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch").GetBool("surveyUnits",True): QtGui.QApplication.clipboard().setText(t) else: @@ -1109,11 +1103,7 @@ class SurveyTaskPanel: if rows: filename = QtGui.QFileDialog.getSaveFileName(QtGui.QApplication.activeWindow(), translate("Arch","Export CSV File"), None, "CSV file (*.csv)"); if filename: - if sys.version_info.major < 3: - mode = 'wb' - else: - mode = 'w' - with open(filename[0].encode("utf8"), mode) as csvfile: + with open(filename[0].encode("utf8"), "w") as csvfile: csvfile = csv.writer(csvfile,delimiter="\t") suml = 0 for i in range(rows): @@ -1329,15 +1319,11 @@ def getExtrusionData(shape,sortmethod="area"): def printMessage( message ): FreeCAD.Console.PrintMessage( message ) if FreeCAD.GuiUp : - if sys.version_info.major < 3: - message = message.decode("utf8") QtGui.QMessageBox.information( None , "" , message ) def printWarning( message ): FreeCAD.Console.PrintMessage( message ) if FreeCAD.GuiUp : - if sys.version_info.major < 3: - message = message.decode("utf8") QtGui.QMessageBox.warning( None , "" , message ) @@ -1703,7 +1689,7 @@ class _ToggleSubs: if mode is None: # take the first sub as base mode = sub.ViewObject.isVisible() - if mode == True: + if mode: sub.ViewObject.hide() else: sub.ViewObject.show() diff --git a/src/Mod/Arch/ArchComponent.py b/src/Mod/Arch/ArchComponent.py index ae269bb6bd..5daa637d75 100644 --- a/src/Mod/Arch/ArchComponent.py +++ b/src/Mod/Arch/ArchComponent.py @@ -31,7 +31,7 @@ __title__ = "FreeCAD Arch Component" __author__ = "Yorik van Havre" __url__ = "https://www.freecadweb.org" -import FreeCAD,Draft,ArchCommands,sys,ArchIFC +import FreeCAD,Draft,ArchCommands,ArchIFC if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui,QtCore @@ -2085,11 +2085,7 @@ class ComponentTaskPanel: if not ptype.startswith("Ifc"): ptype = self.ptypes[self.plabels.index(ptype)] pvalue = self.ifcModel.item(row,0).child(childrow,2).text() - if sys.version_info.major >= 3: - ifcdict[prop] = pset+";;"+ptype+";;"+pvalue - else: - # keys cannot be unicode - ifcdict[prop.encode("utf8")] = pset+";;"+ptype+";;"+pvalue + ifcdict[prop] = pset+";;"+ptype+";;"+pvalue ifcData = self.obj.IfcData ifcData["IfcUID"] = self.ifcEditor.labelUUID.text() ifcData["FlagForceBrep"] = str(self.ifcEditor.checkBrep.isChecked()) @@ -2132,7 +2128,7 @@ class ComponentTaskPanel: "New Property". ptype: str, optional The name of the property type the new property will be set as. If - not specified, the the property's type will be determined using the + not specified, the property's type will be determined using the idx parameter. """ diff --git a/src/Mod/Arch/ArchCurtainWall.py b/src/Mod/Arch/ArchCurtainWall.py index 6f85f31113..a5187486a0 100644 --- a/src/Mod/Arch/ArchCurtainWall.py +++ b/src/Mod/Arch/ArchCurtainWall.py @@ -32,7 +32,7 @@ import DraftVecUtils if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchCutPlane.py b/src/Mod/Arch/ArchCutPlane.py index 4f8c677b5a..11b8ae0116 100644 --- a/src/Mod/Arch/ArchCutPlane.py +++ b/src/Mod/Arch/ArchCutPlane.py @@ -24,7 +24,7 @@ import FreeCAD,ArchCommands if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate else: # \cond def translate(ctxt,txt): diff --git a/src/Mod/Arch/ArchEquipment.py b/src/Mod/Arch/ArchEquipment.py index ae16f0e631..f93811cbe2 100644 --- a/src/Mod/Arch/ArchEquipment.py +++ b/src/Mod/Arch/ArchEquipment.py @@ -28,7 +28,7 @@ import FreeCAD,ArchComponent,DraftVecUtils if FreeCAD.GuiUp: import FreeCADGui from PySide import QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchFloor.py b/src/Mod/Arch/ArchFloor.py index 94d85bc962..90c9281f25 100644 --- a/src/Mod/Arch/ArchFloor.py +++ b/src/Mod/Arch/ArchFloor.py @@ -31,7 +31,7 @@ IfcType. import FreeCAD,Draft,ArchCommands, DraftVecUtils, ArchIFC if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -139,7 +139,7 @@ class _CommandFloor: if not Draft.getType(obj) in ["Site", "Building"] : floorobj.append(obj) else : - if link == True : + if link: floorobj.append(obj) else: warning = True diff --git a/src/Mod/Arch/ArchFrame.py b/src/Mod/Arch/ArchFrame.py index 7686efbd13..ef71bd69ed 100644 --- a/src/Mod/Arch/ArchFrame.py +++ b/src/Mod/Arch/ArchFrame.py @@ -22,7 +22,7 @@ import FreeCAD,Draft,ArchComponent,DraftVecUtils if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchGrid.py b/src/Mod/Arch/ArchGrid.py index 28cc17dd28..7352deba29 100644 --- a/src/Mod/Arch/ArchGrid.py +++ b/src/Mod/Arch/ArchGrid.py @@ -23,7 +23,7 @@ import FreeCAD, Part, math if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -521,7 +521,7 @@ class ArchGridTaskPanel: if (s[0] == r.topRow()) and (s[1] == r.leftColumn()): f = i break - if f != None: + if f is not None: self.spans.pop(f) def editHorizontalHeader(self, index): diff --git a/src/Mod/Arch/ArchMaterial.py b/src/Mod/Arch/ArchMaterial.py index 6dbcce39f2..356c674fb5 100644 --- a/src/Mod/Arch/ArchMaterial.py +++ b/src/Mod/Arch/ArchMaterial.py @@ -24,7 +24,7 @@ if FreeCAD.GuiUp: import FreeCADGui, os import Arch_rc # Needed for access to icons # lgtm [py/unused_import] from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchPanel.py b/src/Mod/Arch/ArchPanel.py index 33d2e48552..8bceb0f910 100644 --- a/src/Mod/Arch/ArchPanel.py +++ b/src/Mod/Arch/ArchPanel.py @@ -24,7 +24,7 @@ from FreeCAD import Vector if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP import draftguitools.gui_trackers as DraftTrackers else: diff --git a/src/Mod/Arch/ArchPipe.py b/src/Mod/Arch/ArchPipe.py index e0b059ae7b..ab6e2b6843 100644 --- a/src/Mod/Arch/ArchPipe.py +++ b/src/Mod/Arch/ArchPipe.py @@ -23,7 +23,7 @@ import FreeCAD, ArchComponent if FreeCAD.GuiUp: import FreeCADGui, Arch_rc - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchPrecast.py b/src/Mod/Arch/ArchPrecast.py index 78a6b16f88..6ac350e893 100644 --- a/src/Mod/Arch/ArchPrecast.py +++ b/src/Mod/Arch/ArchPrecast.py @@ -29,7 +29,7 @@ Beams, pillars, slabs and panels""" import ArchCommands,ArchComponent,FreeCAD from FreeCAD import Vector if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchProfile.py b/src/Mod/Arch/ArchProfile.py index 3a5b8fdc73..3b89fc3612 100644 --- a/src/Mod/Arch/ArchProfile.py +++ b/src/Mod/Arch/ArchProfile.py @@ -38,7 +38,7 @@ import csv if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -101,6 +101,10 @@ def makeProfile(profile=[0,'REC','REC100x100','R',100,100]): _ProfileRH(obj, profile) elif profile[3]=="U": _ProfileU(obj, profile) + elif profile[3]=="L": + _ProfileL(obj, profile) + elif profile[3]=="T": + _ProfileT(obj, profile) else : print("Profile not supported") if FreeCAD.GuiUp: @@ -239,13 +243,25 @@ class _Profile(Draft._DraftObject): def __setstate__(self,state): if isinstance(state,list): self.Profile = state + + def cleanProperties(self, obj): + + '''Remove all Profile properties''' + + obj.removeProperty("Width") + obj.removeProperty("Height") + obj.removeProperty("WebThickness") + obj.removeProperty("FlangeThickness") + obj.removeProperty("OutDiameter") + obj.removeProperty("Thickness") class _ProfileC(_Profile): - '''A parametric circular tubeprofile. Profile data: [Outside diameter, Inside diameter]''' + '''A parametric circular tubeprofile. Profile data: [Outside diameter, Wall thickness]''' def __init__(self,obj, profile): + self.cleanProperties(obj) obj.addProperty("App::PropertyLength","OutDiameter","Draft",QT_TRANSLATE_NOOP("App::Property","Outside Diameter")).OutDiameter = profile[4] obj.addProperty("App::PropertyLength","Thickness","Draft",QT_TRANSLATE_NOOP("App::Property","Wall thickness")).Thickness = profile[5] _Profile.__init__(self,obj,profile) @@ -270,6 +286,7 @@ class _ProfileH(_Profile): '''A parametric H or I beam profile. Profile data: [width, height, web thickness, flange thickness] (see http://en.wikipedia.org/wiki/I-beam for reference)''' def __init__(self,obj, profile): + self.cleanProperties(obj) obj.addProperty("App::PropertyLength","Width","Draft",QT_TRANSLATE_NOOP("App::Property","Width of the beam")).Width = profile[4] obj.addProperty("App::PropertyLength","Height","Draft",QT_TRANSLATE_NOOP("App::Property","Height of the beam")).Height = profile[5] obj.addProperty("App::PropertyLength","WebThickness","Draft",QT_TRANSLATE_NOOP("App::Property","Thickness of the web")).WebThickness = profile[6] @@ -303,6 +320,7 @@ class _ProfileR(_Profile): '''A parametric rectangular beam profile based on [Width, Height]''' def __init__(self,obj, profile): + self.cleanProperties(obj) obj.addProperty("App::PropertyLength","Width","Draft",QT_TRANSLATE_NOOP("App::Property","Width of the beam")).Width = profile[4] obj.addProperty("App::PropertyLength","Height","Draft",QT_TRANSLATE_NOOP("App::Property","Height of the beam")).Height = profile[5] _Profile.__init__(self,obj,profile) @@ -326,6 +344,7 @@ class _ProfileRH(_Profile): '''A parametric Rectangular hollow beam profile. Profile data: [width, height, thickness]''' def __init__(self,obj, profile): + self.cleanProperties(obj) obj.addProperty("App::PropertyLength","Width","Draft",QT_TRANSLATE_NOOP("App::Property","Width of the beam")).Width = profile[4] obj.addProperty("App::PropertyLength","Height","Draft",QT_TRANSLATE_NOOP("App::Property","Height of the beam")).Height = profile[5] obj.addProperty("App::PropertyLength","Thickness","Draft",QT_TRANSLATE_NOOP("App::Property","Thickness of the sides")).Thickness = profile[6] @@ -355,9 +374,10 @@ class _ProfileRH(_Profile): class _ProfileU(_Profile): - '''A parametric H or I beam profile. Profile data: [width, height, web thickness, flange thickness] (see http://en.wikipedia.org/wiki/I-beam forreference)''' + '''A parametric U profile. Profile data: [width, height, web thickness, flange thickness] (see https://en.wikipedia.org/wiki/Structural_channel for reference)''' def __init__(self,obj, profile): + self.cleanProperties(obj) obj.addProperty("App::PropertyLength","Width","Draft",QT_TRANSLATE_NOOP("App::Property","Width of the beam")).Width = profile[4] obj.addProperty("App::PropertyLength","Height","Draft",QT_TRANSLATE_NOOP("App::Property","Height of the beam")).Height = profile[5] obj.addProperty("App::PropertyLength","WebThickness","Draft",QT_TRANSLATE_NOOP("App::Property","Thickness of the webs")).WebThickness = profile[6] @@ -380,6 +400,64 @@ class _ProfileU(_Profile): #p.reverse() obj.Shape = p obj.Placement = pl + + +class _ProfileL(_Profile): + + '''A parametric L profile. Profile data: [width, height, thickness]''' + + def __init__(self, obj, profile): + self.cleanProperties(obj) + obj.addProperty("App::PropertyLength","Width","Draft",QT_TRANSLATE_NOOP("App::Property","Width of the beam")).Width = profile[4] + obj.addProperty("App::PropertyLength","Height","Draft",QT_TRANSLATE_NOOP("App::Property","Height of the beam")).Height = profile[5] + obj.addProperty("App::PropertyLength","Thickness","Draft",QT_TRANSLATE_NOOP("App::Property","Thickness of the legs")).Thickness = profile[6] + _Profile.__init__(self,obj,profile) + + def execute(self,obj): + import Part + pl = obj.Placement + p1 = Vector(-obj.Width.Value/2, obj.Height.Value/2, 0) + p2 = Vector(-obj.Width.Value/2, -obj.Height.Value/2, 0) + p3 = Vector(obj.Width.Value/2, -obj.Height.Value/2, 0) + p4 = Vector(obj.Width.Value/2, -obj.Height.Value/2+obj.Thickness.Value, 0) + p5 = Vector(-obj.Width.Value/2+obj.Thickness.Value, -obj.Height.Value/2+obj.Thickness.Value, 0) + p6 = Vector(-obj.Width.Value/2+obj.Thickness.Value, obj.Height.Value/2, 0) + p = Part.makePolygon([p1,p2,p3,p4,p5,p6,p1]) + p = Part.Face(p) + #p.reverse() + obj.Shape = p + obj.Placement = pl + + +class _ProfileT(_Profile): + + '''A parametric T profile. Profile data: [width, height, web thickness, flange thickness]''' + + def __init__(self, obj, profile): + self.cleanProperties(obj) + obj.addProperty("App::PropertyLength","Width","Draft",QT_TRANSLATE_NOOP("App::Property","Width of the beam")).Width = profile[4] + obj.addProperty("App::PropertyLength","Height","Draft",QT_TRANSLATE_NOOP("App::Property","Height of the beam")).Height = profile[5] + obj.addProperty("App::PropertyLength","WebThickness","Draft",QT_TRANSLATE_NOOP("App::Property","Thickness of the web")).WebThickness = profile[6] + obj.addProperty("App::PropertyLength","FlangeThickness","Draft",QT_TRANSLATE_NOOP("App::Property","Thickness of the flanges")).FlangeThickness = profile[7] + _Profile.__init__(self,obj,profile) + + def execute(self,obj): + import Part + pl = obj.Placement + p1 = Vector(obj.WebThickness.Value/2, -obj.Height.Value/2, 0) + p2 = Vector(obj.WebThickness.Value/2, obj.Height.Value/2-obj.FlangeThickness.Value, 0) + p3 = Vector(obj.Width.Value/2, obj.Height.Value/2-obj.FlangeThickness.Value, 0) + p4 = Vector(obj.Width.Value/2, obj.Height.Value/2, 0) + p5 = Vector(-obj.Width.Value/2, obj.Height.Value/2, 0) + p6 = Vector(-obj.Width.Value/2, obj.Height.Value/2-obj.FlangeThickness.Value, 0) + p7 = Vector(-obj.WebThickness.Value/2, obj.Height.Value/2-obj.FlangeThickness.Value, 0) + p8 = Vector(-obj.WebThickness.Value/2, -obj.Height.Value/2, 0) + p = Part.makePolygon([p1,p2,p3,p4,p5,p6,p7,p8,p1]) + p = Part.Face(p) + #p.reverse() + obj.Shape = p + obj.Placement = pl + class ViewProviderProfile(Draft._ViewProviderDraft): @@ -427,6 +505,10 @@ class ProfileTaskPanel: self.type = "RH" elif isinstance(self.obj.Proxy,_ProfileU): self.type = "U" + elif isinstance(self.obj.Proxy,_ProfileL): + self.type = "L" + elif isinstance(self.obj.Proxy,_ProfileT): + self.type = "T" else: self.type = "Undefined" self.form = QtGui.QWidget() @@ -441,9 +523,8 @@ class ProfileTaskPanel: self.categories = [] self.presets = readPresets() for pre in self.presets: - if pre[3] == self.type: - if pre[1] not in self.categories: - self.categories.append(pre[1]) + if pre[1] not in self.categories: + self.categories.append(pre[1]) self.comboCategory.addItem(" ") if self.categories: self.comboCategory.addItems(self.categories) @@ -489,21 +570,26 @@ class ProfileTaskPanel: self.Profile = self.currentpresets[idx] def accept(self): - + + self.obj.Label = self.Profile[2] if self.Profile: - self.obj.Label = self.Profile[2] - if self.type in ["H","R","RH","U"]: - self.obj.Width = self.Profile[4] - self.obj.Height = self.Profile[5] - if self.type in ["H","U"]: - self.obj.WebThickness = self.Profile[6] - self.obj.FlangeThickness = self.Profile[7] - elif self.type == "RH": - self.obj.Thickness = self.Profile[6] - elif self.type == "C": - self.obj.OutDiameter = self.Profile[4] - self.obj.Thickness = self.Profile[5] - self.obj.Proxy.Profile = self.Profile + if self.Profile[3]=="C": + _ProfileC(self.obj, self.Profile) + elif self.Profile[3]=="H": + _ProfileH(self.obj, self.Profile) + elif self.Profile[3]=="R": + _ProfileR(self.obj, self.Profile) + elif self.Profile[3]=="RH": + _ProfileRH(self.obj, self.Profile) + elif self.Profile[3]=="U": + _ProfileU(self.obj, self.Profile) + elif self.Profile[3]=="L": + _ProfileL(self.obj, self.Profile) + elif self.Profile[3]=="T": + _ProfileT(self.obj, self.Profile) + else: + print("Profile not supported") + FreeCAD.ActiveDocument.recompute() FreeCADGui.ActiveDocument.resetEdit() return True diff --git a/src/Mod/Arch/ArchProject.py b/src/Mod/Arch/ArchProject.py index 503631235c..73f206969b 100644 --- a/src/Mod/Arch/ArchProject.py +++ b/src/Mod/Arch/ArchProject.py @@ -28,7 +28,7 @@ certain IFC relevant values. import FreeCAD,ArchIFC,ArchIFCView if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: def translate(ctxt,txt): diff --git a/src/Mod/Arch/ArchRebar.py b/src/Mod/Arch/ArchRebar.py index bf0bbf45a1..fb21af61c3 100644 --- a/src/Mod/Arch/ArchRebar.py +++ b/src/Mod/Arch/ArchRebar.py @@ -23,7 +23,7 @@ import FreeCAD,Draft,ArchComponent,DraftVecUtils,ArchCommands if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -86,7 +86,7 @@ def makeRebar(baseobj=None,sketch=None,diameter=None,amount=1,offset=None,name=" obj.Diameter = p.GetFloat("RebarDiameter",6) obj.Amount = amount obj.Document.recompute() - if offset != None: + if offset is not None: obj.OffsetStart = offset obj.OffsetEnd = offset else: diff --git a/src/Mod/Arch/ArchReference.py b/src/Mod/Arch/ArchReference.py index c62321b8c4..b5038c4b86 100644 --- a/src/Mod/Arch/ArchReference.py +++ b/src/Mod/Arch/ArchReference.py @@ -28,11 +28,10 @@ import FreeCAD import os import zipfile import re -import sys if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -160,8 +159,7 @@ class ArchReference: f = zdoc.open(self.parts[obj.Part][1]) shapedata = f.read() f.close() - if sys.version_info.major >= 3: - shapedata = shapedata.decode("utf8") + shapedata = shapedata.decode("utf8") shape = self.cleanShape(shapedata,obj,self.parts[obj.Part][2]) obj.Shape = shape if not pl.isIdentity(): @@ -263,8 +261,7 @@ class ArchReference: materials = {} writemode = False for line in docf: - if sys.version_info.major >= 3: - line = line.decode("utf8") + line = line.decode("utf8") if "= 3: - line = line.decode("utf8") + line = line.decode("utf8") if ("= 3: - colors.append((buf[i*4+3]/255.0,buf[i*4+2]/255.0,buf[i*4+1]/255.0,buf[i*4]/255.0)) - else: - colors.append((ord(buf[i*4+3])/255.0,ord(buf[i*4+2])/255.0,ord(buf[i*4+1])/255.0,ord(buf[i*4])/255.0)) + colors.append((buf[i*4+3]/255.0,buf[i*4+2]/255.0,buf[i*4+1]/255.0,buf[i*4]/255.0)) if colors: return colors return None @@ -473,7 +466,7 @@ class ViewProviderArchReference: if vobj.DiffuseColor and vobj.UpdateColors: vobj.DiffuseColor = vobj.DiffuseColor elif prop == "Visibility": - if vobj.Visibility == True: + if vobj.Visibility: if (not vobj.Object.Shape) or vobj.Object.Shape.isNull(): vobj.Object.Proxy.reload = True vobj.Object.Proxy.execute(vobj.Object) @@ -610,8 +603,7 @@ class ViewProviderArchReference: writemode1 = False writemode2 = False for line in docf: - if sys.version_info.major >= 3: - line = line.decode("utf8") + line = line.decode("utf8") if ("= 3: - buf = buf.decode("utf8") + buf = buf.decode("utf8") f.close() buf = buf.replace("lineWidth 2","lineWidth "+str(int(obj.ViewObject.LineWidth))) return buf diff --git a/src/Mod/Arch/ArchRoof.py b/src/Mod/Arch/ArchRoof.py index 00aa34ac58..f3bcb65a15 100644 --- a/src/Mod/Arch/ArchRoof.py +++ b/src/Mod/Arch/ArchRoof.py @@ -32,7 +32,7 @@ from FreeCAD import Vector if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchSchedule.py b/src/Mod/Arch/ArchSchedule.py index 13454bf423..0a667f8c3b 100644 --- a/src/Mod/Arch/ArchSchedule.py +++ b/src/Mod/Arch/ArchSchedule.py @@ -21,12 +21,11 @@ #*************************************************************************** from __future__ import print_function -import sys import FreeCAD if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -172,11 +171,7 @@ class _ArchSchedule: # blank line continue # write description - if sys.version_info.major >= 3: - # use unicode for python3 - self.data["A"+str(li)] = obj.Description[i] - else: - self.data["A"+str(li)] = obj.Description[i].encode("utf8") + self.data["A"+str(li)] = obj.Description[i] if verbose: l= "OPERATION: "+obj.Description[i] print("") @@ -192,7 +187,7 @@ class _ArchSchedule: if objs: objs = objs.split(";") objs = [FreeCAD.ActiveDocument.getObject(o) for o in objs] - objs = [o for o in objs if o != None] + objs = [o for o in objs if o is not None] else: objs = FreeCAD.ActiveDocument.Objects if len(objs) == 1: @@ -261,8 +256,6 @@ class _ArchSchedule: q = None if obj.Unit[i]: unit = obj.Unit[i] - if sys.version_info.major < 3: - unit = unit.encode("utf8") unit = unit.replace("2","^2") unit = unit.replace("3","^3") unit = unit.replace("²","^2") @@ -504,8 +497,6 @@ class ArchScheduleTaskPanel: filename = QtGui.QFileDialog.getOpenFileName(QtGui.QApplication.activeWindow(), translate("Arch","Import CSV File"), None, "CSV file (*.csv)"); if filename: filename = filename[0] - if sys.version_info.major < 3: - filename = filename.encode("utf8") self.form.list.clearContents() import csv with open(filename,'r') as csvfile: @@ -542,8 +533,6 @@ class ArchScheduleTaskPanel: if filename: filt = filename[1] filename = filename[0] - if sys.version_info.major < 3: - filename = filename.encode("utf8") # add missing extension if (not filename.lower().endswith(".csv")) and (not filename.lower().endswith(".tsv")) and (not filename.lower().endswith(".md")): if "csv" in filt: diff --git a/src/Mod/Arch/ArchSectionPlane.py b/src/Mod/Arch/ArchSectionPlane.py index 9e9e1576e3..2ac30b83d5 100644 --- a/src/Mod/Arch/ArchSectionPlane.py +++ b/src/Mod/Arch/ArchSectionPlane.py @@ -34,7 +34,7 @@ from FreeCAD import Vector if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from pivy import coin from PySide.QtCore import QT_TRANSLATE_NOOP else: diff --git a/src/Mod/Arch/ArchSite.py b/src/Mod/Arch/ArchSite.py index b89d90a0bd..7b7de59f33 100644 --- a/src/Mod/Arch/ArchSite.py +++ b/src/Mod/Arch/ArchSite.py @@ -27,7 +27,7 @@ containers for Arch objects, and also define a terrain surface. import FreeCAD,Draft,ArchCommands,math,re,datetime,ArchIFC if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -516,15 +516,15 @@ class _CommandSite: link = p.GetBool("FreeLinking",False) siteobj = [] warning = False - for obj in sel : + for obj in sel: if (Draft.getType(obj) == "Building") or (hasattr(obj,"IfcType") and obj.IfcType == "Building"): siteobj.append(obj) - else : - if link == True : + else: + if link: siteobj.append(obj) else: warning = True - if warning : + if warning: message = translate( "Arch" , "Please either select only Building objects or nothing at all!\n\ Site is not allowed to accept any other object besides Building.\n\ Other objects will be removed from the selection.\n\ @@ -534,7 +534,7 @@ Note: You can change that in the preferences.") message = translate( "Arch" , "There is no valid object in the selection.\n\ Site creation aborted.") + "\n" ArchCommands.printMessage( message ) - else : + else: ss = "[ " for o in siteobj: ss += "FreeCAD.ActiveDocument." + o.Name + ", " diff --git a/src/Mod/Arch/ArchSpace.py b/src/Mod/Arch/ArchSpace.py index 418eee053d..220d09fa95 100644 --- a/src/Mod/Arch/ArchSpace.py +++ b/src/Mod/Arch/ArchSpace.py @@ -145,11 +145,11 @@ ConditioningTypes = [ "NaturallyVentedOnly" ] -import FreeCAD,ArchComponent,ArchCommands,Draft,sys +import FreeCAD,ArchComponent,ArchCommands,Draft if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond @@ -650,8 +650,6 @@ class _ViewProviderSpace(ArchComponent.ViewProviderComponent): t = t.replace("$walls",vobj.Object.FinishWalls) if hasattr(vobj.Object,"FinishCeiling"): t = t.replace("$ceiling",vobj.Object.FinishCeiling) - if sys.version_info.major < 3: - t = t.encode("utf8") if first: text1.append(t) else: diff --git a/src/Mod/Arch/ArchStairs.py b/src/Mod/Arch/ArchStairs.py index d247fe9d98..33c2d2063a 100644 --- a/src/Mod/Arch/ArchStairs.py +++ b/src/Mod/Arch/ArchStairs.py @@ -31,7 +31,7 @@ import Part, DraftGeomUtils from FreeCAD import Vector if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchStructure.py b/src/Mod/Arch/ArchStructure.py index d27f7b1fcb..e33c3c53f6 100644 --- a/src/Mod/Arch/ArchStructure.py +++ b/src/Mod/Arch/ArchStructure.py @@ -27,7 +27,7 @@ import ArchProfile if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP import ArchPrecast import draftguitools.gui_trackers as DraftTrackers @@ -1379,7 +1379,7 @@ class _StructuralSystem(ArchComponent.Component): # OBSOLETE - All Arch objects if hasattr(obj,"Align"): if obj.Align == False : apl = self.getAxisPlacement(obj) - if obj.Align == True : + if obj.Align: apl = None else : apl = self.getAxisPlacement(obj) @@ -1419,7 +1419,7 @@ class _StructuralSystem(ArchComponent.Component): # OBSOLETE - All Arch objects pts = [] if len(obj.Axes) == 1: if hasattr(obj,"Align"): - if obj.Align == True : + if obj.Align: p0 = obj.Axes[0].Shape.Edges[0].Vertexes[1].Point for e in obj.Axes[0].Shape.Edges: p = e.Vertexes[1].Point diff --git a/src/Mod/Arch/ArchTruss.py b/src/Mod/Arch/ArchTruss.py index 40fb76076e..088635b888 100644 --- a/src/Mod/Arch/ArchTruss.py +++ b/src/Mod/Arch/ArchTruss.py @@ -30,7 +30,7 @@ import ArchComponent if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP else: # \cond diff --git a/src/Mod/Arch/ArchVRM.py b/src/Mod/Arch/ArchVRM.py index 6fc243c9c1..cc3896fc1f 100644 --- a/src/Mod/Arch/ArchVRM.py +++ b/src/Mod/Arch/ArchVRM.py @@ -464,9 +464,9 @@ class Renderer: else: if faces.index(f2) < h: h = faces.index(f2) - if l != None: + if l is not None: return l + 1 - elif h != None: + elif h is not None: return h else: return None diff --git a/src/Mod/Arch/ArchWall.py b/src/Mod/Arch/ArchWall.py index 4d6a7b1ea9..d9d54bca2d 100644 --- a/src/Mod/Arch/ArchWall.py +++ b/src/Mod/Arch/ArchWall.py @@ -34,7 +34,7 @@ from FreeCAD import Vector if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP import draftguitools.gui_trackers as DraftTrackers else: diff --git a/src/Mod/Arch/ArchWindow.py b/src/Mod/Arch/ArchWindow.py index d7048a2f70..46d3559565 100644 --- a/src/Mod/Arch/ArchWindow.py +++ b/src/Mod/Arch/ArchWindow.py @@ -30,7 +30,7 @@ from draftutils.messages import _wrn if FreeCAD.GuiUp: import FreeCADGui from PySide import QtCore, QtGui, QtSvg - from DraftTools import translate + from draftutils.translate import translate from PySide.QtCore import QT_TRANSLATE_NOOP import draftguitools.gui_trackers as DraftTrackers else: diff --git a/src/Mod/Arch/Dice3DS/dom3ds.py b/src/Mod/Arch/Dice3DS/dom3ds.py index 8cf31cec75..1234edc465 100644 --- a/src/Mod/Arch/Dice3DS/dom3ds.py +++ b/src/Mod/Arch/Dice3DS/dom3ds.py @@ -20,9 +20,6 @@ import sys, struct import numpy -# xrange is not available in python3 -if sys.version_info.major >= 3: - xrange = range # Exceptions @@ -394,11 +391,11 @@ class ChunkBase(object): for attr in self.single_order: self.out_chunk(attr,flo,indent,flags) for attr in self.multiple_order: - for i in xrange(len(getattr(self,attr))): + for i in range(len(getattr(self,attr))): self.out_chunk_index(attr,i,flo,indent,flags) if self.freechunks: attr = "subchunks" - for i in xrange(len(self.subchunks)): + for i in range(len(self.subchunks)): self.out_chunk_index(attr,i,flo,indent,flags) # Dump self to stream flo at a certain indentation @@ -636,7 +633,7 @@ class MatrixChunk(ArrayChunk): super(MatrixChunk,self).dump_array(flo,indent,flags) if flags['arraylines'] == 0: return - for i in xrange(4): + for i in range(4): flo.write("%s %12.4g%12.4g%12.4g%12.4g\n" % (indent,self.array[i,0],self.array[i,1], self.array[i,2],self.array[i,3])) @@ -650,7 +647,7 @@ class TrackChunk(ChunkBase): struct = "short flags, long unused1, long unused2, long nkeys" def read_array(self,fbuf,flags): self.keys = [] - for i in xrange(self.nkeys): + for i in range(self.nkeys): kf = self.Key() kf.frameno = self.get_long(fbuf,flags) kf.flags = self.get_short(fbuf,flags) @@ -693,7 +690,7 @@ class TrackChunk(ChunkBase): n = self.nkeys else: n = min(flags['arraylines'],self.nkeys) - for i in xrange(n): + for i in range(n): kf = self.keys[i] flo.write("%skeys[0] = %s.Key\n" % (indent,self.label)) flo.write("%s frameno = %r\n" % (indent,kf.frameno)) @@ -1007,7 +1004,7 @@ class POINT_ARRAY(ArrayChunk): n = self.npoints else: n = min(flags['arraylines'],self.npoints) - for i in xrange(n): + for i in range(n): flo.write("%s %12.4g%12.4g%12.4g\n" % (indent,self.array[i,0],self.array[i,1], self.array[i,2])) @@ -1047,7 +1044,7 @@ class FACE_ARRAY(ArrayChunk): n = self.nfaces else: n = min(flags['arraylines'],self.nfaces) - for i in xrange(n): + for i in range(n): flo.write("%s %10d%10d%10d%10d\n" % (indent,self.array[i,0],self.array[i,1], self.array[i,2],self.array[i,3])) @@ -1071,7 +1068,7 @@ class MSH_MAT_GROUP(ArrayChunk): n = self.mfaces else: n = min(flags['arraylines'],self.mfaces) - for i in xrange(n): + for i in range(n): flo.write("%s %10d\n" % (indent,self.array[i])) if n < self.mfaces: flo.write("%s ...\n" % indent) @@ -1096,7 +1093,7 @@ class TEX_VERTS(ArrayChunk): n = self.npoints else: n = min(flags['arraylines'],self.npoints) - for i in xrange(n): + for i in range(n): flo.write("%s %12.4g%12.4g\n" % (indent,self.array[i,0],self.array[i,1])) if n < self.npoints: @@ -1118,7 +1115,7 @@ class SMOOTH_GROUP(ArrayChunk): n = len(self.array) else: n = min(flags['arraylines'],len(self.array)) - for i in xrange(n): + for i in range(n): flo.write("%s %10d\n" % (indent,self.array[i])) if n < len(self.array): flo.write("%s ...\n" % indent) diff --git a/src/Mod/Arch/Dice3DS/util.py b/src/Mod/Arch/Dice3DS/util.py index 413ea423c4..b623c73c67 100644 --- a/src/Mod/Arch/Dice3DS/util.py +++ b/src/Mod/Arch/Dice3DS/util.py @@ -7,11 +7,7 @@ Defines some routines for calculating normals and transforming points. """ import numpy -import sys -# xrange is not available in python3 -if sys.version_info.major >= 3: - xrange = range # Can push numpy.float64 (or even numpy.float80) into this if you # would like to use higher precision when calculating; results will be @@ -153,7 +149,7 @@ def calculate_normals_by_cross_product(pointarray,facearray,smarray): rslice = numpy.empty((len(brs)+1,),numpy.int) rslice[:-1] = brs rslice[-1] = 3*m - for i in xrange(len(brs)+1): + for i in range(len(brs)+1): rgroup = lex[lslice[i]:rslice[i]] xgroup = exarray[rgroup] normpat = numpy.logical_or( @@ -258,7 +254,7 @@ def calculate_normals_by_angle_subtended(pointarray,facearray,smarray): rslice = numpy.empty((len(brs)+1,),numpy.int) rslice[:-1] = brs rslice[-1] = 3*m - for i in xrange(len(brs)+1): + for i in range(len(brs)+1): rgroup = lex[lslice[i]:rslice[i]] xgroup = exarray[rgroup] normpat = numpy.logical_or( diff --git a/src/Mod/Arch/OfflineRenderingUtils.py b/src/Mod/Arch/OfflineRenderingUtils.py index 408986e126..278a8aa8cf 100755 --- a/src/Mod/Arch/OfflineRenderingUtils.py +++ b/src/Mod/Arch/OfflineRenderingUtils.py @@ -122,7 +122,7 @@ class FreeCADGuiHandler(xml.sax.ContentHandler): # plus a GuiCameraSettings key that contains an iv repr of a coin camera def __init__(self): - + super().__init__() self.guidata = {} self.current = None @@ -188,7 +188,7 @@ class FreeCADGuiHandler(xml.sax.ContentHandler): self.current = None self.properties = {} elif tag == "Property": - if self.currentprop and (self.currentval != None): + if self.currentprop and (self.currentval is not None): self.properties[self.currentprop] = {"type":self.currenttype,"value":self.currentval} self.currentprop = None self.currentval = None @@ -225,10 +225,7 @@ def getGuiData(filename): df.close() cols = [] for i in range(1,int(len(buf)/4)): - if sys.version_info.major < 3: - cols.append(ord(buf[i*4+3])/255.0,ord(buf[i*4+2])/255.0,ord(buf[i*4+1])/255.0,ord(buf[i*4])/255.0) - else: - cols.append((buf[i*4+3]/255.0,buf[i*4+2]/255.0,buf[i*4+1]/255.0,buf[i*4]/255.0)) + cols.append((buf[i*4+3]/255.0,buf[i*4+2]/255.0,buf[i*4+1]/255.0,buf[i*4]/255.0)) guidata[key][propname]["value"] = cols zdoc.close() #print ("guidata:",guidata) @@ -243,11 +240,7 @@ def saveDiffuseColor(colorlist): property. Returns the path to the created temp file""" def tochr(i): - #print("tochr:",i) - if sys.version_info.major < 3: - return chr(i) - else: - return bytes((i,)) + return bytes((i,)) # if too many colors, bail out and use only the first one for now... if len(colorlist) > 254: colorlist = colorlist[:1] diff --git a/src/Mod/Arch/Presets/profiles.csv b/src/Mod/Arch/Presets/profiles.csv index 3a582b9954..fb2293f57d 100644 --- a/src/Mod/Arch/Presets/profiles.csv +++ b/src/Mod/Arch/Presets/profiles.csv @@ -16,11 +16,6 @@ ########################################### -# Circular tube - -# Category,Name,C,Outside diameter,Thickness - -CTH,CTH423,C,42.4,3.2 # Circular Hollow Sections @@ -654,6 +649,76 @@ American Wide Flange,W27x146,H,355.6,695.96,15.367,24.765 American Wide Flange,W27x161,H,356.108,701.04,16.764,27.432 American Wide Flange,W27x178,H,357.886,706.12,18.415,30.226 + +# Indian Standard I section (H profiles) + +IS Beam,ISHB150(1),H,150,150,5.4,9 +IS Beam,ISHB150(2),H,150,150,8.4,9 +IS Beam,ISHB150(3),H,150,150,11.8,9 +IS Beam,ISHB200(1),H,200,200,6.1,9 +IS Beam,ISHB200(2),H,200,200,7.8,9 +IS Beam,ISHB225(1),H,225,225,6.5,9.1 +IS Beam,ISHB225(2),H,225,225,8.6,9.1 +IS Beam,ISHB250(1),H,250,250,6.9,9.7 +IS Beam,ISHB250(2),H,250,250,8.8,9.7 +IS Beam,ISHB300(1),H,250,300,7.6,10.6 +IS Beam,ISHB300(2),H,250,300,9.4,10.6 +IS Beam,ISHB350(1),H,250,350,8.3,11.6 +IS Beam,ISHB350(2),H,250,350,10.1,11.6 +IS Beam,ISHB400(1),H,250,400,9.1,12.7 +IS Beam,ISHB400(2),H,250,400,10.6,12.7 +IS Beam,ISHB450(1),H,250,450,9.8,13.7 +IS Beam,ISHB450(2),H,250,450,11.3,13.7 +IS Beam,ISJB150,H,50,150,3,4.6 +IS Beam,ISJB175,H,50,175,3.2,4.8 +IS Beam,ISJB200,H,60,200,3.4,5 +IS Beam,ISJB225,H,80,225,3.7,5 +IS Beam,ISLB75,H,50,75,3.7,5 +IS Beam,ISLB100,H,50,100,4,6.4 +IS Beam,ISLB125,H,75,125,4.4,6.5 +IS Beam,ISLB150,H,80,150,4.8,6.8 +IS Beam,ISLB175,H,90,175,5.1,6.9 +IS Beam,ISLB200,H,100,200,5.4,7.3 +IS Beam,ISLB225,H,100,225,5.8,8.6 +IS Beam,ISLB250,H,125,250,6.1,8.2 +IS Beam,ISLB275,H,140,275,6.4,8.8 +IS Beam,ISLB300,H,150,300,6.7,9.4 +IS Beam,ISLB325,H,165,325,7,9.8 +IS Beam,ISLB350,H,165,350,7.4,11.4 +IS Beam,ISLB400,H,165,400,8,12.5 +IS Beam,ISLB450,H,170,450,8.6,13.4 +IS Beam,ISLB500,H,180,500,9.2,14.1 +IS Beam,ISLB550,H,190,550,9.9,15 +IS Beam,ISLB600,H,210,600,10.5,15.5 +IS Beam,ISMB100,H,75,100,4,7.2 +IS Beam,ISMB125,H,75,125,4.4,7.6 +IS Beam,ISMB150,H,80,150,4.8,7.6 +IS Beam,ISMB175,H,90,175,5.5,8.6 +IS Beam,ISMB200,H,100,200,5.7,10.8 +IS Beam,ISMB225,H,110,225,6.5,11.8 +IS Beam,ISMB250,H,125,250,6.9,12.5 +IS Beam,ISMB300,H,140,300,7.5,12.4 +IS Beam,ISMB350,H,140,350,8.1,14.2 +IS Beam,ISMB400,H,140,400,8.9,16 +IS Beam,ISMB450,H,150,450,9.4,17.4 +IS Beam,ISMB500,H,180,500,10.2,17.2 +IS Beam,ISMB550,H,190,550,11.2,19.3 +IS Beam,ISMB600,H,210,600,12,20.8 +IS Beam,ISWB150,H,100,150,5.4,7 +IS Beam,ISWB175,H,125,175,5.8,7.4 +IS Beam,ISWB200,H,140,200,6.1,9 +IS Beam,ISWB225,H,150,225,6.4,9.9 +IS Beam,ISWB250,H,200,250,6.7,9 +IS Beam,ISWB300,H,200,300,7.4,10 +IS Beam,ISWB350,H,200,350,8,11.4 +IS Beam,ISWB400,H,200,400,8.6,13 +IS Beam,ISWB450,H,200,450,9.2,15.4 +IS Beam,ISWB500,H,250,500,9.9,14.7 +IS Beam,ISWB550,H,250,550,10.5,17.6 +IS Beam,ISWB600(1),H,250,600,11.2,21.3 +IS Beam,ISWB600(2),H,250,600,11.8,23.6 + + # Rectangular # Category,Name,R,width,height @@ -719,318 +784,409 @@ Eurocode timber,300x300,R,300,300 # Category,Name,RH,width,height,thickness -RHS,RHS50x30,RH,50,30,2.9 -RHS,RHS50x30,RH,50,30,3.0 -RHS,RHS50x30,RH,50,30,3.2 -RHS,RHS50x30,RH,50,30,3.6 -RHS,RHS50x30,RH,50,30,4.0 -RHS,RHS50x30,RH,50,30,5.0 -RHS,RHS50x30,RH,50,30,5.6 -RHS,RHS50x30,RH,50,30,6.3 -RHS,RHS60x40,RH,60,40,2.9 -RHS,RHS60x40,RH,60,40,3.0 -RHS,RHS60x40,RH,60,40,3.2 -RHS,RHS60x40,RH,60,40,3.6 -RHS,RHS60x40,RH,60,40,4.0 -RHS,RHS60x40,RH,60,40,5.0 -RHS,RHS60x40,RH,60,40,5.6 -RHS,RHS60x40,RH,60,40,6.3 -RHS,RHS60x40,RH,60,40,7.1 -RHS,RHS60x40,RH,60,40,8.0 -RHS,RHS80x40,RH,80,40,2.9 -RHS,RHS80x40,RH,80,40,3.0 -RHS,RHS80x40,RH,80,40,3.2 -RHS,RHS80x40,RH,80,40,3.6 -RHS,RHS80x40,RH,80,40,4.0 -RHS,RHS80x40,RH,80,40,5.0 -RHS,RHS80x40,RH,80,40,5.6 -RHS,RHS80x40,RH,80,40,6.3 -RHS,RHS80x40,RH,80,40,7.1 -RHS,RHS80x40,RH,80,40,8.0 -RHS,RHS90x50,RH,90,50,3.0 -RHS,RHS90x50,RH,90,50,3.2 -RHS,RHS90x50,RH,90,50,3.6 -RHS,RHS90x50,RH,90,50,4.0 -RHS,RHS90x50,RH,90,50,5.0 -RHS,RHS90x50,RH,90,50,5.6 -RHS,RHS90x50,RH,90,50,6.3 -RHS,RHS90x50,RH,90,50,7.1 -RHS,RHS90x50,RH,90,50,8.0 -RHS,RHS90x50,RH,90,50,8.8 -RHS,RHS100x50,RH,100,50,3.2 -RHS,RHS100x50,RH,100,50,3.6 -RHS,RHS100x50,RH,100,50,4.0 -RHS,RHS100x50,RH,100,50,5.0 -RHS,RHS100x50,RH,100,50,5.6 -RHS,RHS100x50,RH,100,50,6.3 -RHS,RHS100x50,RH,100,50,7.1 -RHS,RHS100x50,RH,100,50,8.0 -RHS,RHS100x50,RH,100,50,8.8 -RHS,RHS100x50,RH,100,50,10.0 -RHS,RHS100x60,RH,100,60,3.2 -RHS,RHS100x60,RH,100,60,3.6 -RHS,RHS100x60,RH,100,60,4.0 -RHS,RHS100x60,RH,100,60,5.0 -RHS,RHS100x60,RH,100,60,5.6 -RHS,RHS100x60,RH,100,60,6.3 -RHS,RHS100x60,RH,100,60,7.1 -RHS,RHS100x60,RH,100,60,8.0 -RHS,RHS100x60,RH,100,60,8.8 -RHS,RHS100x60,RH,100,60,10.0 -RHS,RHS120x60,RH,120,60,3.6 -RHS,RHS120x60,RH,120,60,4.0 -RHS,RHS120x60,RH,120,60,5.0 -RHS,RHS120x60,RH,120,60,5.6 -RHS,RHS120x60,RH,120,60,6.3 -RHS,RHS120x60,RH,120,60,7.1 -RHS,RHS120x60,RH,120,60,8.0 -RHS,RHS120x60,RH,120,60,8.8 -RHS,RHS120x60,RH,120,60,10.0 -RHS,RHS120x80,RH,120,80,3.6 -RHS,RHS120x80,RH,120,80,4.0 -RHS,RHS120x80,RH,120,80,5.0 -RHS,RHS120x80,RH,120,80,5.6 -RHS,RHS120x80,RH,120,80,6.3 -RHS,RHS120x80,RH,120,80,7.1 -RHS,RHS120x80,RH,120,80,8.0 -RHS,RHS120x80,RH,120,80,8.8 -RHS,RHS120x80,RH,120,80,10.0 -RHS,RHS150x100,RH,150,100,4.0 -RHS,RHS150x100,RH,150,100,5.0 -RHS,RHS150x100,RH,150,100,5.6 -RHS,RHS150x100,RH,150,100,6.3 -RHS,RHS150x100,RH,150,100,7.1 -RHS,RHS150x100,RH,150,100,8.0 -RHS,RHS150x100,RH,150,100,8.8 -RHS,RHS150x100,RH,150,100,10.0 -RHS,RHS150x100,RH,150,100,11.0 -RHS,RHS150x100,RH,150,100,12.5 -RHS,RHS160x80,RH,160,80,4.0 -RHS,RHS160x80,RH,160,80,5.0 -RHS,RHS160x80,RH,160,80,5.6 -RHS,RHS160x80,RH,160,80,6.3 -RHS,RHS160x80,RH,160,80,7.1 -RHS,RHS160x80,RH,160,80,8.0 -RHS,RHS160x80,RH,160,80,8.8 -RHS,RHS160x80,RH,160,80,10.0 -RHS,RHS160x80,RH,160,80,11.0 -RHS,RHS160x80,RH,160,80,12.5 -RHS,RHS180x60,RH,180,60,4.0 -RHS,RHS180x60,RH,180,60,5.0 -RHS,RHS180x60,RH,180,60,5.6 -RHS,RHS180x60,RH,180,60,6.3 -RHS,RHS180x60,RH,180,60,7.1 -RHS,RHS180x60,RH,180,60,8.0 -RHS,RHS180x60,RH,180,60,8.8 -RHS,RHS180x60,RH,180,60,10.0 -RHS,RHS180x60,RH,180,60,11.0 -RHS,RHS180x60,RH,180,60,12.5 -RHS,RHS180x100,RH,180,100,4.0 -RHS,RHS180x100,RH,180,100,5.0 -RHS,RHS180x100,RH,180,100,5.6 -RHS,RHS180x100,RH,180,100,6.3 -RHS,RHS180x100,RH,180,100,7.1 -RHS,RHS180x100,RH,180,100,8.0 -RHS,RHS180x100,RH,180,100,8.8 -RHS,RHS180x100,RH,180,100,10.0 -RHS,RHS180x100,RH,180,100,11.0 -RHS,RHS180x100,RH,180,100,12.5 -RHS,RHS180x100,RH,180,100,14.2 -RHS,RHS200x100,RH,200,100,4.0 -RHS,RHS200x100,RH,200,100,5.0 -RHS,RHS200x100,RH,200,100,5.6 -RHS,RHS200x100,RH,200,100,6.3 -RHS,RHS200x100,RH,200,100,7.1 -RHS,RHS200x100,RH,200,100,8.0 -RHS,RHS200x100,RH,200,100,8.8 -RHS,RHS200x100,RH,200,100,10.0 -RHS,RHS200x100,RH,200,100,11.0 -RHS,RHS200x100,RH,200,100,12.5 -RHS,RHS200x100,RH,200,100,14.2 -RHS,RHS200x100,RH,200,100,16.0 -RHS,RHS200x120,RH,200,120,5.0 -RHS,RHS200x120,RH,200,120,5.6 -RHS,RHS200x120,RH,200,120,6.3 -RHS,RHS200x120,RH,200,120,7.1 -RHS,RHS200x120,RH,200,120,8.0 -RHS,RHS200x120,RH,200,120,8.8 -RHS,RHS200x120,RH,200,120,10.0 -RHS,RHS200x120,RH,200,120,11.0 -RHS,RHS200x120,RH,200,120,12.5 -RHS,RHS200x120,RH,200,120,14.2 -RHS,RHS200x120,RH,200,120,16.0 -RHS,RHS200x150,RH,200,150,5.0 -RHS,RHS200x150,RH,200,150,5.6 -RHS,RHS200x150,RH,200,150,6.3 -RHS,RHS200x150,RH,200,150,7.1 -RHS,RHS200x150,RH,200,150,8.0 -RHS,RHS200x150,RH,200,150,8.8 -RHS,RHS200x150,RH,200,150,10.0 -RHS,RHS200x150,RH,200,150,11.0 -RHS,RHS200x150,RH,200,150,12.5 -RHS,RHS200x150,RH,200,150,14.2 -RHS,RHS200x150,RH,200,150,16.0 -RHS,RHS220x120,RH,220,120,7.1 -RHS,RHS220x120,RH,220,120,8.0 -RHS,RHS220x120,RH,220,120,8.8 -RHS,RHS220x120,RH,220,120,10.0 -RHS,RHS220x120,RH,220,120,11.0 -RHS,RHS220x120,RH,220,120,12.5 -RHS,RHS220x120,RH,220,120,14.2 -RHS,RHS220x120,RH,220,120,16.0 -RHS,RHS250x100,RH,250,100,5.0 -RHS,RHS250x100,RH,250,100,5.6 -RHS,RHS250x100,RH,250,100,6.3 -RHS,RHS250x100,RH,250,100,7.1 -RHS,RHS250x100,RH,250,100,8.0 -RHS,RHS250x100,RH,250,100,8.8 -RHS,RHS250x100,RH,250,100,10.0 -RHS,RHS250x100,RH,250,100,11.0 -RHS,RHS250x100,RH,250,100,12.5 -RHS,RHS250x100,RH,250,100,14.2 -RHS,RHS250x100,RH,250,100,16.0 -RHS,RHS250x150,RH,250,150,5.0 -RHS,RHS250x150,RH,250,150,5.6 -RHS,RHS250x150,RH,250,150,6.3 -RHS,RHS250x150,RH,250,150,7.1 -RHS,RHS250x150,RH,250,150,8.0 -RHS,RHS250x150,RH,250,150,8.8 -RHS,RHS250x150,RH,250,150,10.0 -RHS,RHS250x150,RH,250,150,11.0 -RHS,RHS250x150,RH,250,150,12.5 -RHS,RHS250x150,RH,250,150,14.2 -RHS,RHS250x150,RH,250,150,16.0 -RHS,RHS260x140,RH,260,140,5.0 -RHS,RHS260x140,RH,260,140,5.6 -RHS,RHS260x140,RH,260,140,6.3 -RHS,RHS260x140,RH,260,140,7.1 -RHS,RHS260x140,RH,260,140,8.0 -RHS,RHS260x140,RH,260,140,8.8 -RHS,RHS260x140,RH,260,140,10.0 -RHS,RHS260x140,RH,260,140,11.0 -RHS,RHS260x140,RH,260,140,12.5 -RHS,RHS260x140,RH,260,140,14.2 -RHS,RHS260x140,RH,260,140,16.0 -RHS,RHS260x180,RH,260,180,8.0 -RHS,RHS260x180,RH,260,180,8.8 -RHS,RHS260x180,RH,260,180,10.0 -RHS,RHS260x180,RH,260,180,11.0 -RHS,RHS260x180,RH,260,180,12.5 -RHS,RHS260x180,RH,260,180,14.2 -RHS,RHS260x180,RH,260,180,16.0 -RHS,RHS300x100,RH,300,100,5.0 -RHS,RHS300x100,RH,300,100,5.6 -RHS,RHS300x100,RH,300,100,6.3 -RHS,RHS300x100,RH,300,100,7.1 -RHS,RHS300x100,RH,300,100,8.0 -RHS,RHS300x100,RH,300,100,8.8 -RHS,RHS300x100,RH,300,100,10.0 -RHS,RHS300x100,RH,300,100,11.0 -RHS,RHS300x100,RH,300,100,12.5 -RHS,RHS300x100,RH,300,100,14.2 -RHS,RHS300x100,RH,300,100,16.0 -RHS,RHS300x200,RH,300,200,5.0 -RHS,RHS300x200,RH,300,200,5.6 -RHS,RHS300x200,RH,300,200,6.3 -RHS,RHS300x200,RH,300,200,7.1 -RHS,RHS300x200,RH,300,200,8.0 -RHS,RHS300x200,RH,300,200,8.8 -RHS,RHS300x200,RH,300,200,10.0 -RHS,RHS300x200,RH,300,200,11.0 -RHS,RHS300x200,RH,300,200,12.5 -RHS,RHS300x200,RH,300,200,14.2 -RHS,RHS300x200,RH,300,200,16.0 -RHS,RHS300x250,RH,300,250,6.3 -RHS,RHS300x250,RH,300,250,7.1 -RHS,RHS300x250,RH,300,250,8.0 -RHS,RHS300x250,RH,300,250,8.8 -RHS,RHS300x250,RH,300,250,10.0 -RHS,RHS300x250,RH,300,250,11.0 -RHS,RHS300x250,RH,300,250,12.5 -RHS,RHS300x250,RH,300,250,14.2 -RHS,RHS300x250,RH,300,250,16.0 -RHS,RHS350x150,RH,350,150,5.0 -RHS,RHS350x150,RH,350,150,5.6 -RHS,RHS350x150,RH,350,150,6.3 -RHS,RHS350x150,RH,350,150,7.1 -RHS,RHS350x150,RH,350,150,8.0 -RHS,RHS350x150,RH,350,150,8.8 -RHS,RHS350x150,RH,350,150,10.0 -RHS,RHS350x150,RH,350,150,11.0 -RHS,RHS350x150,RH,350,150,12.5 -RHS,RHS350x150,RH,350,150,14.2 -RHS,RHS350x150,RH,350,150,16.0 -RHS,RHS350x200,RH,350,200,6.3 -RHS,RHS350x200,RH,350,200,7.1 -RHS,RHS350x200,RH,350,200,8.0 -RHS,RHS350x200,RH,350,200,8.8 -RHS,RHS350x200,RH,350,200,10.0 -RHS,RHS350x200,RH,350,200,11.0 -RHS,RHS350x200,RH,350,200,12.5 -RHS,RHS350x200,RH,350,200,14.2 -RHS,RHS350x200,RH,350,200,16.0 -RHS,RHS350x250,RH,350,250,6.3 -RHS,RHS350x250,RH,350,250,7.1 -RHS,RHS350x250,RH,350,250,8.0 -RHS,RHS350x250,RH,350,250,8.8 -RHS,RHS350x250,RH,350,250,10.0 -RHS,RHS350x250,RH,350,250,11.0 -RHS,RHS350x250,RH,350,250,12.5 -RHS,RHS350x250,RH,350,250,14.2 -RHS,RHS350x250,RH,350,250,16.0 -RHS,RHS400x150,RH,400,150,6.3 -RHS,RHS400x150,RH,400,150,7.1 -RHS,RHS400x150,RH,400,150,8.0 -RHS,RHS400x150,RH,400,150,8.8 -RHS,RHS400x150,RH,400,150,10.0 -RHS,RHS400x150,RH,400,150,11.0 -RHS,RHS400x150,RH,400,150,12.5 -RHS,RHS400x150,RH,400,150,14.2 -RHS,RHS400x150,RH,400,150,16.0 -RHS,RHS400x200,RH,400,200,6.3 -RHS,RHS400x200,RH,400,200,7.1 -RHS,RHS400x200,RH,400,200,8.0 -RHS,RHS400x200,RH,400,200,8.8 -RHS,RHS400x200,RH,400,200,10.0 -RHS,RHS400x200,RH,400,200,11.0 -RHS,RHS400x200,RH,400,200,12.5 -RHS,RHS400x200,RH,400,200,14.2 -RHS,RHS400x200,RH,400,200,16.0 -RHS,RHS400x300,RH,400,300,8.0 -RHS,RHS400x300,RH,400,300,8.8 -RHS,RHS400x300,RH,400,300,10.0 -RHS,RHS400x300,RH,400,300,11.0 -RHS,RHS400x300,RH,400,300,12.5 -RHS,RHS400x300,RH,400,300,14.2 -RHS,RHS400x300,RH,400,300,16.0 -RHS,RHS450x150,RH,450,150,8.0 -RHS,RHS450x150,RH,450,150,8.8 -RHS,RHS450x150,RH,450,150,10.0 -RHS,RHS450x150,RH,450,150,11.0 -RHS,RHS450x150,RH,450,150,12.5 -RHS,RHS450x150,RH,450,150,14.2 -RHS,RHS450x150,RH,450,150,16.0 -RHS,RHS450x250,RH,450,250,8.0 -RHS,RHS450x250,RH,450,250,8.8 -RHS,RHS450x250,RH,450,250,10.0 -RHS,RHS450x250,RH,450,250,11.0 -RHS,RHS450x250,RH,450,250,12.5 -RHS,RHS450x250,RH,450,250,14.2 -RHS,RHS450x250,RH,450,250,16.0 -RHS,RHS500x200,RH,500,200,8.0 -RHS,RHS500x200,RH,500,200,8.8 -RHS,RHS500x200,RH,500,200,10.0 -RHS,RHS500x200,RH,500,200,11.0 -RHS,RHS500x200,RH,500,200,12.5 -RHS,RHS500x200,RH,500,200,14.2 -RHS,RHS500x200,RH,500,200,16.0 -RHS,RHS500x300,RH,500,300,8.0 -RHS,RHS500x300,RH,500,300,8.8 -RHS,RHS500x300,RH,500,300,10.0 -RHS,RHS500x300,RH,500,300,11.0 -RHS,RHS500x300,RH,500,300,12.5 -RHS,RHS500x300,RH,500,300,14.2 -RHS,RHS500x300,RH,500,300,16.0 +RHS,RHS50x30x2.9,RH,50,30,2.9 +RHS,RHS50x30x3,RH,50,30,3 +RHS,RHS50x30x3.2,RH,50,30,3.2 +RHS,RHS50x30x3.6,RH,50,30,3.6 +RHS,RHS50x30x4,RH,50,30,4 +RHS,RHS50x30x5,RH,50,30,5 +RHS,RHS50x30x5.6,RH,50,30,5.6 +RHS,RHS50x30x6.3,RH,50,30,6.3 +RHS,RHS60x40x2.9,RH,60,40,2.9 +RHS,RHS60x40x3,RH,60,40,3 +RHS,RHS60x40x3.2,RH,60,40,3.2 +RHS,RHS60x40x3.6,RH,60,40,3.6 +RHS,RHS60x40x4,RH,60,40,4 +RHS,RHS60x40x5,RH,60,40,5 +RHS,RHS60x40x5.6,RH,60,40,5.6 +RHS,RHS60x40x6.3,RH,60,40,6.3 +RHS,RHS60x40x7.1,RH,60,40,7.1 +RHS,RHS60x40x8,RH,60,40,8 +RHS,RHS80x40x2.9,RH,80,40,2.9 +RHS,RHS80x40x3,RH,80,40,3 +RHS,RHS80x40x3.2,RH,80,40,3.2 +RHS,RHS80x40x3.6,RH,80,40,3.6 +RHS,RHS80x40x4,RH,80,40,4 +RHS,RHS80x40x5,RH,80,40,5 +RHS,RHS80x40x5.6,RH,80,40,5.6 +RHS,RHS80x40x6.3,RH,80,40,6.3 +RHS,RHS80x40x7.1,RH,80,40,7.1 +RHS,RHS80x40x8,RH,80,40,8 +RHS,RHS90x50x3,RH,90,50,3 +RHS,RHS90x50x3.2,RH,90,50,3.2 +RHS,RHS90x50x3.6,RH,90,50,3.6 +RHS,RHS90x50x4,RH,90,50,4 +RHS,RHS90x50x5,RH,90,50,5 +RHS,RHS90x50x5.6,RH,90,50,5.6 +RHS,RHS90x50x6.3,RH,90,50,6.3 +RHS,RHS90x50x7.1,RH,90,50,7.1 +RHS,RHS90x50x8,RH,90,50,8 +RHS,RHS90x50x8.8,RH,90,50,8.8 +RHS,RHS100x50x3.2,RH,100,50,3.2 +RHS,RHS100x50x3.6,RH,100,50,3.6 +RHS,RHS100x50x4,RH,100,50,4 +RHS,RHS100x50x5,RH,100,50,5 +RHS,RHS100x50x5.6,RH,100,50,5.6 +RHS,RHS100x50x6.3,RH,100,50,6.3 +RHS,RHS100x50x7.1,RH,100,50,7.1 +RHS,RHS100x50x8,RH,100,50,8 +RHS,RHS100x50x8.8,RH,100,50,8.8 +RHS,RHS100x50x10,RH,100,50,10 +RHS,RHS100x60x3.2,RH,100,60,3.2 +RHS,RHS100x60x3.6,RH,100,60,3.6 +RHS,RHS100x60x4,RH,100,60,4 +RHS,RHS100x60x5,RH,100,60,5 +RHS,RHS100x60x5.6,RH,100,60,5.6 +RHS,RHS100x60x6.3,RH,100,60,6.3 +RHS,RHS100x60x7.1,RH,100,60,7.1 +RHS,RHS100x60x8,RH,100,60,8 +RHS,RHS100x60x8.8,RH,100,60,8.8 +RHS,RHS100x60x10,RH,100,60,10 +RHS,RHS120x60x3.6,RH,120,60,3.6 +RHS,RHS120x60x4,RH,120,60,4 +RHS,RHS120x60x5,RH,120,60,5 +RHS,RHS120x60x5.6,RH,120,60,5.6 +RHS,RHS120x60x6.3,RH,120,60,6.3 +RHS,RHS120x60x7.1,RH,120,60,7.1 +RHS,RHS120x60x8,RH,120,60,8 +RHS,RHS120x60x8.8,RH,120,60,8.8 +RHS,RHS120x60x10,RH,120,60,10 +RHS,RHS120x80x3.6,RH,120,80,3.6 +RHS,RHS120x80x4,RH,120,80,4 +RHS,RHS120x80x5,RH,120,80,5 +RHS,RHS120x80x5.6,RH,120,80,5.6 +RHS,RHS120x80x6.3,RH,120,80,6.3 +RHS,RHS120x80x7.1,RH,120,80,7.1 +RHS,RHS120x80x8,RH,120,80,8 +RHS,RHS120x80x8.8,RH,120,80,8.8 +RHS,RHS120x80x10,RH,120,80,10 +RHS,RHS150x100x4,RH,150,100,4 +RHS,RHS150x100x5,RH,150,100,5 +RHS,RHS150x100x5.6,RH,150,100,5.6 +RHS,RHS150x100x6.3,RH,150,100,6.3 +RHS,RHS150x100x7.1,RH,150,100,7.1 +RHS,RHS150x100x8,RH,150,100,8 +RHS,RHS150x100x8.8,RH,150,100,8.8 +RHS,RHS150x100x10,RH,150,100,10 +RHS,RHS150x100x11,RH,150,100,11 +RHS,RHS150x100x12.5,RH,150,100,12.5 +RHS,RHS160x80x4,RH,160,80,4 +RHS,RHS160x80x5,RH,160,80,5 +RHS,RHS160x80x5.6,RH,160,80,5.6 +RHS,RHS160x80x6.3,RH,160,80,6.3 +RHS,RHS160x80x7.1,RH,160,80,7.1 +RHS,RHS160x80x8,RH,160,80,8 +RHS,RHS160x80x8.8,RH,160,80,8.8 +RHS,RHS160x80x10,RH,160,80,10 +RHS,RHS160x80x11,RH,160,80,11 +RHS,RHS160x80x12.5,RH,160,80,12.5 +RHS,RHS180x60x4,RH,180,60,4 +RHS,RHS180x60x5,RH,180,60,5 +RHS,RHS180x60x5.6,RH,180,60,5.6 +RHS,RHS180x60x6.3,RH,180,60,6.3 +RHS,RHS180x60x7.1,RH,180,60,7.1 +RHS,RHS180x60x8,RH,180,60,8 +RHS,RHS180x60x8.8,RH,180,60,8.8 +RHS,RHS180x60x10,RH,180,60,10 +RHS,RHS180x60x11,RH,180,60,11 +RHS,RHS180x60x12.5,RH,180,60,12.5 +RHS,RHS180x100x4,RH,180,100,4 +RHS,RHS180x100x5,RH,180,100,5 +RHS,RHS180x100x5.6,RH,180,100,5.6 +RHS,RHS180x100x6.3,RH,180,100,6.3 +RHS,RHS180x100x7.1,RH,180,100,7.1 +RHS,RHS180x100x8,RH,180,100,8 +RHS,RHS180x100x8.8,RH,180,100,8.8 +RHS,RHS180x100x10,RH,180,100,10 +RHS,RHS180x100x11,RH,180,100,11 +RHS,RHS180x100x12.5,RH,180,100,12.5 +RHS,RHS180x100x14.2,RH,180,100,14.2 +RHS,RHS200x100x4,RH,200,100,4 +RHS,RHS200x100x5,RH,200,100,5 +RHS,RHS200x100x5.6,RH,200,100,5.6 +RHS,RHS200x100x6.3,RH,200,100,6.3 +RHS,RHS200x100x7.1,RH,200,100,7.1 +RHS,RHS200x100x8,RH,200,100,8 +RHS,RHS200x100x8.8,RH,200,100,8.8 +RHS,RHS200x100x10,RH,200,100,10 +RHS,RHS200x100x11,RH,200,100,11 +RHS,RHS200x100x12.5,RH,200,100,12.5 +RHS,RHS200x100x14.2,RH,200,100,14.2 +RHS,RHS200x100x16,RH,200,100,16 +RHS,RHS200x120x5,RH,200,120,5 +RHS,RHS200x120x5.6,RH,200,120,5.6 +RHS,RHS200x120x6.3,RH,200,120,6.3 +RHS,RHS200x120x7.1,RH,200,120,7.1 +RHS,RHS200x120x8,RH,200,120,8 +RHS,RHS200x120x8.8,RH,200,120,8.8 +RHS,RHS200x120x10,RH,200,120,10 +RHS,RHS200x120x11,RH,200,120,11 +RHS,RHS200x120x12.5,RH,200,120,12.5 +RHS,RHS200x120x14.2,RH,200,120,14.2 +RHS,RHS200x120x16,RH,200,120,16 +RHS,RHS200x150x5,RH,200,150,5 +RHS,RHS200x150x5.6,RH,200,150,5.6 +RHS,RHS200x150x6.3,RH,200,150,6.3 +RHS,RHS200x150x7.1,RH,200,150,7.1 +RHS,RHS200x150x8,RH,200,150,8 +RHS,RHS200x150x8.8,RH,200,150,8.8 +RHS,RHS200x150x10,RH,200,150,10 +RHS,RHS200x150x11,RH,200,150,11 +RHS,RHS200x150x12.5,RH,200,150,12.5 +RHS,RHS200x150x14.2,RH,200,150,14.2 +RHS,RHS200x150x16,RH,200,150,16 +RHS,RHS220x120x7.1,RH,220,120,7.1 +RHS,RHS220x120x8,RH,220,120,8 +RHS,RHS220x120x8.8,RH,220,120,8.8 +RHS,RHS220x120x10,RH,220,120,10 +RHS,RHS220x120x11,RH,220,120,11 +RHS,RHS220x120x12.5,RH,220,120,12.5 +RHS,RHS220x120x14.2,RH,220,120,14.2 +RHS,RHS220x120x16,RH,220,120,16 +RHS,RHS250x100x5,RH,250,100,5 +RHS,RHS250x100x5.6,RH,250,100,5.6 +RHS,RHS250x100x6.3,RH,250,100,6.3 +RHS,RHS250x100x7.1,RH,250,100,7.1 +RHS,RHS250x100x8,RH,250,100,8 +RHS,RHS250x100x8.8,RH,250,100,8.8 +RHS,RHS250x100x10,RH,250,100,10 +RHS,RHS250x100x11,RH,250,100,11 +RHS,RHS250x100x12.5,RH,250,100,12.5 +RHS,RHS250x100x14.2,RH,250,100,14.2 +RHS,RHS250x100x16,RH,250,100,16 +RHS,RHS250x150x5,RH,250,150,5 +RHS,RHS250x150x5.6,RH,250,150,5.6 +RHS,RHS250x150x6.3,RH,250,150,6.3 +RHS,RHS250x150x7.1,RH,250,150,7.1 +RHS,RHS250x150x8,RH,250,150,8 +RHS,RHS250x150x8.8,RH,250,150,8.8 +RHS,RHS250x150x10,RH,250,150,10 +RHS,RHS250x150x11,RH,250,150,11 +RHS,RHS250x150x12.5,RH,250,150,12.5 +RHS,RHS250x150x14.2,RH,250,150,14.2 +RHS,RHS250x150x16,RH,250,150,16 +RHS,RHS260x140x5,RH,260,140,5 +RHS,RHS260x140x5.6,RH,260,140,5.6 +RHS,RHS260x140x6.3,RH,260,140,6.3 +RHS,RHS260x140x7.1,RH,260,140,7.1 +RHS,RHS260x140x8,RH,260,140,8 +RHS,RHS260x140x8.8,RH,260,140,8.8 +RHS,RHS260x140x10,RH,260,140,10 +RHS,RHS260x140x11,RH,260,140,11 +RHS,RHS260x140x12.5,RH,260,140,12.5 +RHS,RHS260x140x14.2,RH,260,140,14.2 +RHS,RHS260x140x16,RH,260,140,16 +RHS,RHS260x180x8,RH,260,180,8 +RHS,RHS260x180x8.8,RH,260,180,8.8 +RHS,RHS260x180x10,RH,260,180,10 +RHS,RHS260x180x11,RH,260,180,11 +RHS,RHS260x180x12.5,RH,260,180,12.5 +RHS,RHS260x180x14.2,RH,260,180,14.2 +RHS,RHS260x180x16,RH,260,180,16 +RHS,RHS300x100x5,RH,300,100,5 +RHS,RHS300x100x5.6,RH,300,100,5.6 +RHS,RHS300x100x6.3,RH,300,100,6.3 +RHS,RHS300x100x7.1,RH,300,100,7.1 +RHS,RHS300x100x8,RH,300,100,8 +RHS,RHS300x100x8.8,RH,300,100,8.8 +RHS,RHS300x100x10,RH,300,100,10 +RHS,RHS300x100x11,RH,300,100,11 +RHS,RHS300x100x12.5,RH,300,100,12.5 +RHS,RHS300x100x14.2,RH,300,100,14.2 +RHS,RHS300x100x16,RH,300,100,16 +RHS,RHS300x200x5,RH,300,200,5 +RHS,RHS300x200x5.6,RH,300,200,5.6 +RHS,RHS300x200x6.3,RH,300,200,6.3 +RHS,RHS300x200x7.1,RH,300,200,7.1 +RHS,RHS300x200x8,RH,300,200,8 +RHS,RHS300x200x8.8,RH,300,200,8.8 +RHS,RHS300x200x10,RH,300,200,10 +RHS,RHS300x200x11,RH,300,200,11 +RHS,RHS300x200x12.5,RH,300,200,12.5 +RHS,RHS300x200x14.2,RH,300,200,14.2 +RHS,RHS300x200x16,RH,300,200,16 +RHS,RHS300x250x6.3,RH,300,250,6.3 +RHS,RHS300x250x7.1,RH,300,250,7.1 +RHS,RHS300x250x8,RH,300,250,8 +RHS,RHS300x250x8.8,RH,300,250,8.8 +RHS,RHS300x250x10,RH,300,250,10 +RHS,RHS300x250x11,RH,300,250,11 +RHS,RHS300x250x12.5,RH,300,250,12.5 +RHS,RHS300x250x14.2,RH,300,250,14.2 +RHS,RHS300x250x16,RH,300,250,16 +RHS,RHS350x150x5,RH,350,150,5 +RHS,RHS350x150x5.6,RH,350,150,5.6 +RHS,RHS350x150x6.3,RH,350,150,6.3 +RHS,RHS350x150x7.1,RH,350,150,7.1 +RHS,RHS350x150x8,RH,350,150,8 +RHS,RHS350x150x8.8,RH,350,150,8.8 +RHS,RHS350x150x10,RH,350,150,10 +RHS,RHS350x150x11,RH,350,150,11 +RHS,RHS350x150x12.5,RH,350,150,12.5 +RHS,RHS350x150x14.2,RH,350,150,14.2 +RHS,RHS350x150x16,RH,350,150,16 +RHS,RHS350x200x6.3,RH,350,200,6.3 +RHS,RHS350x200x7.1,RH,350,200,7.1 +RHS,RHS350x200x8,RH,350,200,8 +RHS,RHS350x200x8.8,RH,350,200,8.8 +RHS,RHS350x200x10,RH,350,200,10 +RHS,RHS350x200x11,RH,350,200,11 +RHS,RHS350x200x12.5,RH,350,200,12.5 +RHS,RHS350x200x14.2,RH,350,200,14.2 +RHS,RHS350x200x16,RH,350,200,16 +RHS,RHS350x250x6.3,RH,350,250,6.3 +RHS,RHS350x250x7.1,RH,350,250,7.1 +RHS,RHS350x250x8,RH,350,250,8 +RHS,RHS350x250x8.8,RH,350,250,8.8 +RHS,RHS350x250x10,RH,350,250,10 +RHS,RHS350x250x11,RH,350,250,11 +RHS,RHS350x250x12.5,RH,350,250,12.5 +RHS,RHS350x250x14.2,RH,350,250,14.2 +RHS,RHS350x250x16,RH,350,250,16 +RHS,RHS400x150x6.3,RH,400,150,6.3 +RHS,RHS400x150x7.1,RH,400,150,7.1 +RHS,RHS400x150x8,RH,400,150,8 +RHS,RHS400x150x8.8,RH,400,150,8.8 +RHS,RHS400x150x10,RH,400,150,10 +RHS,RHS400x150x11,RH,400,150,11 +RHS,RHS400x150x12.5,RH,400,150,12.5 +RHS,RHS400x150x14.2,RH,400,150,14.2 +RHS,RHS400x150x16,RH,400,150,16 +RHS,RHS400x200x6.3,RH,400,200,6.3 +RHS,RHS400x200x7.1,RH,400,200,7.1 +RHS,RHS400x200x8,RH,400,200,8 +RHS,RHS400x200x8.8,RH,400,200,8.8 +RHS,RHS400x200x10,RH,400,200,10 +RHS,RHS400x200x11,RH,400,200,11 +RHS,RHS400x200x12.5,RH,400,200,12.5 +RHS,RHS400x200x14.2,RH,400,200,14.2 +RHS,RHS400x200x16,RH,400,200,16 +RHS,RHS400x300x8,RH,400,300,8 +RHS,RHS400x300x8.8,RH,400,300,8.8 +RHS,RHS400x300x10,RH,400,300,10 +RHS,RHS400x300x11,RH,400,300,11 +RHS,RHS400x300x12.5,RH,400,300,12.5 +RHS,RHS400x300x14.2,RH,400,300,14.2 +RHS,RHS400x300x16,RH,400,300,16 +RHS,RHS450x150x8,RH,450,150,8 +RHS,RHS450x150x8.8,RH,450,150,8.8 +RHS,RHS450x150x10,RH,450,150,10 +RHS,RHS450x150x11,RH,450,150,11 +RHS,RHS450x150x12.5,RH,450,150,12.5 +RHS,RHS450x150x14.2,RH,450,150,14.2 +RHS,RHS450x150x16,RH,450,150,16 +RHS,RHS450x250x8,RH,450,250,8 +RHS,RHS450x250x8.8,RH,450,250,8.8 +RHS,RHS450x250x10,RH,450,250,10 +RHS,RHS450x250x11,RH,450,250,11 +RHS,RHS450x250x12.5,RH,450,250,12.5 +RHS,RHS450x250x14.2,RH,450,250,14.2 +RHS,RHS450x250x16,RH,450,250,16 +RHS,RHS500x200x8,RH,500,200,8 +RHS,RHS500x200x8.8,RH,500,200,8.8 +RHS,RHS500x200x10,RH,500,200,10 +RHS,RHS500x200x11,RH,500,200,11 +RHS,RHS500x200x12.5,RH,500,200,12.5 +RHS,RHS500x200x14.2,RH,500,200,14.2 +RHS,RHS500x200x16,RH,500,200,16 +RHS,RHS500x300x8,RH,500,300,8 +RHS,RHS500x300x8.8,RH,500,300,8.8 +RHS,RHS500x300x10,RH,500,300,10 +RHS,RHS500x300x11,RH,500,300,11 +RHS,RHS500x300x12.5,RH,500,300,12.5 +RHS,RHS500x300x14.2,RH,500,300,14.2 +RHS,RHS500x300x16,RH,500,300,16 + + +# Indian Rectangular Hollow Sections + +IS RHS,RHS50x25x2.9,RH,50,25,2.9 +IS RHS,RHS50x25x3.2,RH,50,25,3.2 +IS RHS,RHS60x40x2.9,RH,60,40,2.9 +IS RHS,RHS66x33x2.9,RH,66,33,2.9 +IS RHS,RHS66x33x3.6,RH,66,33,3.6 +IS RHS,RHS66x33x4.5,RH,66,33,4.5 +IS RHS,RHS70x30x2.9,RH,70,30,2.9 +IS RHS,RHS70x30x3.2,RH,70,30,3.2 +IS RHS,RHS70x30x4,RH,70,30,4 +IS RHS,RHS80x40x2.9,RH,80,40,2.9 +IS RHS,RHS80x40x3.2,RH,80,40,3.2 +IS RHS,RHS80x40x4,RH,80,40,4 +IS RHS,RHS96x48x3.2,RH,96,48,3.2 +IS RHS,RHS96x48x4,RH,96,48,4 +IS RHS,RHS96x48x4.8,RH,96,48,4.8 +IS RHS,RHS100x50x3.2,RH,100,50,3.2 +IS RHS,RHS100x50x4,RH,100,50,4 +IS RHS,RHS122x61x3.6,RH,122,61,3.6 +IS RHS,RHS122x61x4.5,RH,122,61,4.5 +IS RHS,RHS122x61x5.4,RH,122,61,5.4 +IS RHS,RHS127x50x3.6,RH,127,50,3.6 +IS RHS,RHS127x50x4.6,RH,127,50,4.6 +IS RHS,RHS145x82x4.8,RH,145,82,4.8 +IS RHS,RHS145x82x5.4,RH,145,82,5.4 +IS RHS,RHS172x92x4.8,RH,172,92,4.8 +IS RHS,RHS172x92x5.4,RH,172,92,5.4 + +# Indian Square Hollow Sections + +IS SHS,SHS25x25x2.6,RH,25,25,2.6 +IS SHS,SHS25x25x3.2,RH,25,25,3.2 +IS SHS,SHS30x30x2.6,RH,30,30,2.6 +IS SHS,SHS30x30x3.2,RH,30,30,3.2 +IS SHS,SHS30x30x4,RH,30,30,4 +IS SHS,SHS32x32x2.6,RH,32,32,2.6 +IS SHS,SHS32x32x3.2,RH,32,32,3.2 +IS SHS,SHS32x32x4,RH,32,32,4 +IS SHS,SHS35x35x2.6,RH,35,35,2.6 +IS SHS,SHS35x35x3.2,RH,35,35,3.2 +IS SHS,SHS35x35x4,RH,35,35,4 +IS SHS,SHS38x38x2.6,RH,38,38,2.6 +IS SHS,SHS38x38x2.9,RH,38,38,2.9 +IS SHS,SHS38x38x3.2,RH,38,38,3.2 +IS SHS,SHS38x38x3.6,RH,38,38,3.6 +IS SHS,SHS38x38x4,RH,38,38,4 +IS SHS,SHS40x40x2.6,RH,40,40,2.6 +IS SHS,SHS40x40x3.2,RH,40,40,3.2 +IS SHS,SHS40x40x3.6,RH,40,40,3.6 +IS SHS,SHS40x40x4,RH,40,40,4 +IS SHS,SHS45x45x2.6,RH,45,45,2.6 +IS SHS,SHS45x45x2.9,RH,45,45,2.9 +IS SHS,SHS45x45x3.2,RH,45,45,3.2 +IS SHS,SHS45x45x3.6,RH,45,45,3.6 +IS SHS,SHS45x45x4.5,RH,45,45,4.5 +IS SHS,SHS49.5x49.5x2.9,RH,49.5,49.5,2.9 +IS SHS,SHS49.5x49.5x3.6,RH,49.5,49.5,3.6 +IS SHS,SHS49.5x49.5x4.5,RH,49.5,49.5,4.5 +IS SHS,SHS63.5x63.5x3.2,RH,63.5,63.5,3.2 +IS SHS,SHS63.5x63.5x3.6,RH,63.5,63.5,3.6 +IS SHS,SHS63.5x63.5x4.5,RH,63.5,63.5,4.5 +IS SHS,SHS72x72x3.2,RH,72,72,3.2 +IS SHS,SHS72x72x4,RH,72,72,4 +IS SHS,SHS72x72x4.8,RH,72,72,4.8 +IS SHS,SHS75x75x3.2,RH,75,75,3.2 +IS SHS,SHS75x75x4,RH,75,75,4 +IS SHS,SHS75x75x4.9,RH,75,75,4.9 +IS SHS,SHS88.9x88.9x3.6,RH,88.9,88.9,3.6 +IS SHS,SHS88.9x88.9x4.5,RH,88.9,88.9,4.5 +IS SHS,SHS88.9x88.9x4.9,RH,88.9,88.9,4.9 +IS SHS,SHS91.5x91.5x3.6,RH,91.5,91.5,3.6 +IS SHS,SHS91.5x91.5x4.5,RH,91.5,91.5,4.5 +IS SHS,SHS91.5x91.5x5.4,RH,91.5,91.5,5.4 +IS SHS,SHS100x100x4,RH,100,100,4 +IS SHS,SHS100x100x5,RH,100,100,5 +IS SHS,SHS100x100x6,RH,100,100,6 +IS SHS,SHS113.5x113.5x4.5,RH,113.5,113.5,4.5 +IS SHS,SHS113.5x113.5x4.8,RH,113.5,113.5,4.8 +IS SHS,SHS113.5x113.5x5.4,RH,113.5,113.5,5.4 +IS SHS,SHS113.5x113.5x6,RH,113.5,113.5,6 +IS SHS,SHS125x125x4.5,RH,125,125,4.5 +IS SHS,SHS125x125x5,RH,125,125,5 +IS SHS,SHS125.5x125.5x6,RH,125.5,125.5,6 +IS SHS,SHS132x132x4.8,RH,132,132,4.8 +IS SHS,SHS132x132x5.4,RH,132,132,5.4 +IS SHS,SHS132x132x6,RH,132,132,6 +IS SHS,SHS150x150x5,RH,150,150,5 +IS SHS,SHS150x150x6,RH,150,150,6 # U-profile @@ -1075,102 +1231,144 @@ Aluminium C Channel,10x4.25 Channel,U,254,107.95,12.7,7.874 Aluminium C Channel,12x4 Channel,U,304.8,101.6,11.938,7.366 Aluminium C Channel,12x5 Channel,U,304.8,127,15.748,8.89 -# Indian Standard I section (H profiles) - -# Category,Name,H,width,height,web thickness,flange thickness -IS,ISHB150(1),H,150,150,5.4,9 -IS,ISHB150(2),H,150,150,8.4,9 -IS,ISHB150(3),H,150,150,11.8,9 -IS,ISHB200(1),H,200,200,6.1,9 -IS,ISHB200(2),H,200,200,7.8,9 -IS,ISHB225(1),H,225,225,6.5,9.1 -IS,ISHB225(2),H,225,225,8.6,9.1 -IS,ISHB250(1),H,250,250,6.9,9.7 -IS,ISHB250(2),H,250,250,8.8,9.7 -IS,ISHB300(1),H,250,300,7.6,10.6 -IS,ISHB300(2),H,250,300,9.4,10.6 -IS,ISHB350(1),H,250,350,8.3,11.6 -IS,ISHB350(2),H,250,350,10.1,11.6 -IS,ISHB400(1),H,250,400,9.1,12.7 -IS,ISHB400(2),H,250,400,10.6,12.7 -IS,ISHB450(1),H,250,450,9.8,13.7 -IS,ISHB450(2),H,250,450,11.3,13.7 -IS,ISJB150,H,50,150,3,4.6 -IS,ISJB175,H,50,175,3.2,4.8 -IS,ISJB200,H,60,200,3.4,5 -IS,ISJB225,H,80,225,3.7,5 -IS,ISLB75,H,50,75,3.7,5 -IS,ISLB100,H,50,100,4,6.4 -IS,ISLB125,H,75,125,4.4,6.5 -IS,ISLB150,H,80,150,4.8,6.8 -IS,ISLB175,H,90,175,5.1,6.9 -IS,ISLB200,H,100,200,5.4,7.3 -IS,ISLB225,H,100,225,5.8,8.6 -IS,ISLB250,H,125,250,6.1,8.2 -IS,ISLB275,H,140,275,6.4,8.8 -IS,ISLB300,H,150,300,6.7,9.4 -IS,ISLB325,H,165,325,7,9.8 -IS,ISLB350,H,165,350,7.4,11.4 -IS,ISLB400,H,165,400,8,12.5 -IS,ISLB450,H,170,450,8.6,13.4 -IS,ISLB500,H,180,500,9.2,14.1 -IS,ISLB550,H,190,550,9.9,15 -IS,ISLB600,H,210,600,10.5,15.5 -IS,ISMB100,H,75,100,4,7.2 -IS,ISMB125,H,75,125,4.4,7.6 -IS,ISMB150,H,80,150,4.8,7.6 -IS,ISMB175,H,90,175,5.5,8.6 -IS,ISMB200,H,100,200,5.7,10.8 -IS,ISMB225,H,110,225,6.5,11.8 -IS,ISMB250,H,125,250,6.9,12.5 -IS,ISMB300,H,140,300,7.5,12.4 -IS,ISMB350,H,140,350,8.1,14.2 -IS,ISMB400,H,140,400,8.9,16 -IS,ISMB450,H,150,450,9.4,17.4 -IS,ISMB500,H,180,500,10.2,17.2 -IS,ISMB550,H,190,550,11.2,19.3 -IS,ISMB600,H,210,600,12,20.8 -IS,ISWB150,H,100,150,5.4,7 -IS,ISWB175,H,125,175,5.8,7.4 -IS,ISWB200,H,140,200,6.1,9 -IS,ISWB225,H,150,225,6.4,9.9 -IS,ISWB250,H,200,250,6.7,9 -IS,ISWB300,H,200,300,7.4,10 -IS,ISWB350,H,200,350,8,11.4 -IS,ISWB400,H,200,400,8.6,13 -IS,ISWB450,H,200,450,9.2,15.4 -IS,ISWB500,H,250,500,9.9,14.7 -IS,ISWB550,H,250,550,10.5,17.6 -IS,ISWB600(1),H,250,600,11.2,21.3 -IS,ISWB600(2),H,250,600,11.8,23.6 # Indian Standard Channel Sections (U profiles) -# + +IS Channel,ISJC100,U,100,45,3,5.1 +IS Channel,ISJC125,U,125,50,3,6.6 +IS Channel,ISJC150,U,150,55,3.6,6.9 +IS Channel,ISJC175,U,175,60,3.6,6.9 +IS Channel,ISJC200,U,200,70,4.1,7.1 +IS Channel,ISLC75,U,75,40,3.7,6 +IS Channel,ISLC100,U,100,50,4,6.4 +IS Channel,ISLC125,U,125,65,4.4,6.6 +IS Channel,ISLC150,U,150,75,4.8,7.8 +IS Channel,ISLC175,U,175,75,5.1,9.5 +IS Channel,ISLC200,U,200,75,5.5,10.8 +IS Channel,ISLC225,U,225,90,5.8,10.2 +IS Channel,ISLC250,U,250,100,6.1,10.7 +IS Channel,ISLC300,U,300,100,6.7,11.6 +IS Channel,ISLC350,U,350,100,7.4,12.5 +IS Channel,ISLC400,U,400,100,8,14 +IS Channel,ISMC75,U,75,40,4.4,7.3 +IS Channel,ISMC100,U,100,50,4.7,7.5 +IS Channel,ISMC125,U,125,65,5,8.1 +IS Channel,ISMC150,U,150,75,5.4,9 +IS Channel,ISMC175,U,175,75,5.7,10.2 +IS Channel,ISMC200,U,200,75,6.1,11.4 +IS Channel,ISMC225,U,225,80,6.4,12.4 +IS Channel,ISMC250,U,250,80,7.1,14.1 +IS Channel,ISMC300,U,300,90,7.6,13.6 +IS Channel,ISMC350,U,350,100,8.1,13.5 +IS Channel,ISMC400,U,400,100,8.6,15.3 + + +# L-profiles + +# Category,Name,U,width,height,thickness + + +# Indian Standard Angle Sections (L profiles) + +IS Angle,ISA20x20x3,L,20,20,3 +IS Angle,ISA20x20x4,L,20,20,4 +IS Angle,ISA25x25x3,L,25,25,3 +IS Angle,ISA25x25x4,L,25,25,4 +IS Angle,ISA25x25x5,L,25,25,5 +IS Angle,ISA30x30x3,L,30,30,3 +IS Angle,ISA30x30x4,L,30,30,4 +IS Angle,ISA30x30x5,L,30,30,5 +IS Angle,ISA35x35x3,L,35,35,3 +IS Angle,ISA35x35x4,L,35,35,4 +IS Angle,ISA35x35x5,L,35,35,5 +IS Angle,ISA35x35x6,L,35,35,6 +IS Angle,ISA40x40x3,L,40,40,3 +IS Angle,ISA40x40x4,L,40,40,4 +IS Angle,ISA40x40x5,L,40,40,5 +IS Angle,ISA40x40x6,L,40,40,6 +IS Angle,ISA45x45x3,L,45,45,3 +IS Angle,ISA45x45x4,L,45,45,4 +IS Angle,ISA45x45x5,L,45,45,5 +IS Angle,ISA45x45x6,L,45,45,6 +IS Angle,ISA50x50x3,L,50,50,3 +IS Angle,ISA50x50x4,L,50,50,4 +IS Angle,ISA50x50x5,L,50,50,5 +IS Angle,ISA50x50x6,L,50,50,6 +IS Angle,ISA55x55x4,L,55,55,4 +IS Angle,ISA55x55x5,L,55,55,5 +IS Angle,ISA55x55x6,L,55,55,6 +IS Angle,ISA55x55x8,L,55,55,8 +IS Angle,ISA60x60x4,L,60,60,4 +IS Angle,ISA60x60x5,L,60,60,5 +IS Angle,ISA60x60x6,L,60,60,6 +IS Angle,ISA60x60x8,L,60,60,8 +IS Angle,ISA65x65x4,L,65,65,4 +IS Angle,ISA65x65x5,L,65,65,5 +IS Angle,ISA65x65x6,L,65,65,6 +IS Angle,ISA65x65x8,L,65,65,8 +IS Angle,ISA70x70x5,L,70,70,5 +IS Angle,ISA70x70x6,L,70,70,6 +IS Angle,ISA70x70x8,L,70,70,8 +IS Angle,ISA70x70x10,L,70,70,10 +IS Angle,ISA75x75x5,L,75,75,5 +IS Angle,ISA75x75x6,L,75,75,6 +IS Angle,ISA75x75x8,L,75,75,8 +IS Angle,ISA75x75x10,L,75,75,10 +IS Angle,ISA80x80x6,L,80,80,6 +IS Angle,ISA80x80x8,L,80,80,8 +IS Angle,ISA80x80x10,L,80,80,10 +IS Angle,ISA80x80x12,L,80,80,12 +IS Angle,ISA90x90x6,L,90,90,6 +IS Angle,ISA90x90x8,L,90,90,8 +IS Angle,ISA90x90x10,L,90,90,10 +IS Angle,ISA90x90x12,L,90,90,12 +IS Angle,ISA100x100x6,L,100,100,6 +IS Angle,ISA100x100x8,L,100,100,8 +IS Angle,ISA100x100x10,L,100,100,10 +IS Angle,ISA100x100x12,L,100,100,12 +IS Angle,ISA110x110x8,L,110,110,8 +IS Angle,ISA110x110x10,L,110,110,10 +IS Angle,ISA110x110x12,L,110,110,12 +IS Angle,ISA110x110x16,L,110,110,16 +IS Angle,ISA130x130x8,L,130,130,8 +IS Angle,ISA130x130x10,L,130,130,10 +IS Angle,ISA130x130x12,L,130,130,12 +IS Angle,ISA130x130x16,L,130,130,16 +IS Angle,ISA150x150x10,L,150,150,10 +IS Angle,ISA150x150x12,L,150,150,12 +IS Angle,ISA150x150x16,L,150,150,16 +IS Angle,ISA150x150x20,L,150,150,20 +IS Angle,ISA200x200x10,L,200,200,10 +IS Angle,ISA200x200x12,L,200,200,12 +IS Angle,ISA200x200x16,L,200,200,16 +IS Angle,ISA200x200x20,L,200,200,20 + + +# T-profiles + # Category,Name,H,width,height,web thickness,flange thickness -IS,ISJC100,U,100,45,3,5.1 -IS,ISJC125,U,125,50,3,6.6 -IS,ISJC150,U,150,55,3.6,6.9 -IS,ISJC175,U,175,60,3.6,6.9 -IS,ISJC200,U,200,70,4.1,7.1 -IS,ISLC75,U,75,40,3.7,6 -IS,ISLC100,U,100,50,4,6.4 -IS,ISLC125,U,125,65,4.4,6.6 -IS,ISLC150,U,150,75,4.8,7.8 -IS,ISLC175,U,175,75,5.1,9.5 -IS,ISLC200,U,200,75,5.5,10.8 -IS,ISLC225,U,225,90,5.8,10.2 -IS,ISLC250,U,250,100,6.1,10.7 -IS,ISLC300,U,300,100,6.7,11.6 -IS,ISLC350,U,350,100,7.4,12.5 -IS,ISLC400,U,400,100,8,14 -IS,ISMC75,U,75,40,4.4,7.3 -IS,ISMC100,U,100,50,4.7,7.5 -IS,ISMC125,U,125,65,5,8.1 -IS,ISMC150,U,150,75,5.4,9 -IS,ISMC175,U,175,75,5.7,10.2 -IS,ISMC200,U,200,75,6.1,11.4 -IS,ISMC225,U,225,80,6.4,12.4 -IS,ISMC250,U,250,80,7.1,14.1 -IS,ISMC300,U,300,90,7.6,13.6 -IS,ISMC350,U,350,100,8.1,13.5 -IS,ISMC400,U,400,100,8.6,15.3 + + +# Indian Standard Tee Bar Sections (T profiles) + +IS Tee,ISNT 20,T,20,20,4,4 +IS Tee,ISNT 30,T,30,30,4,4 +IS Tee,ISNT 40,T,40,40,6,6 +IS Tee,ISNT 50,T,50,50,6,6 +IS Tee,ISNT 60,T,60,60,6,6 +IS Tee,ISNT 75,T,75,75,9,9 +IS Tee,ISNT 100,T,100,100,10,10 +IS Tee,ISNT 150,T,150,150,10,10 +IS Tee,ISDT 100,T,50,100,5.8,10 +IS Tee,ISDT 150,T,75,100,8,11.6 +IS Tee,ISLT 200,T,165,200,8,12.5 +IS Tee,ISLT 250,T,180,250,9.2,14.1 +IS Tee,ISMT 50,T,70,50,4.5,7.5 +IS Tee,ISMT 62.5,T,70,62.5,5,8 +IS Tee,ISMT 75,T,75,75,5,8 +IS Tee,ISMT 87.5,T,85,87.5,5.8,9 +IS Tee,ISMT 100,T,100,100,5.7,10.8 +IS Tee,ISHT 75,T,150,75,8.4,9 +IS Tee,ISHT 100,T,200,100,7.8,9 +IS Tee,ISHT 125,T,250,125,8.8,9.7 +IS Tee,ISHT 150,T,250,150,7.6,10.6 diff --git a/src/Mod/Arch/importDAE.py b/src/Mod/Arch/importDAE.py index 35a49e8083..06e16bbf17 100644 --- a/src/Mod/Arch/importDAE.py +++ b/src/Mod/Arch/importDAE.py @@ -21,7 +21,7 @@ import FreeCAD, Mesh, os, numpy, MeshPart, Arch, Draft if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate else: # \cond def translate(context,text): @@ -146,13 +146,13 @@ def read(filename): if "}" in node.xmlnode.tag: bt = node.xmlnode.tag.split("}")[0]+"}" gnode = node.xmlnode.find(bt+"instance_geometry") - if gnode != None: + if gnode is not None: bnode = gnode.find(bt+"bind_material") - if bnode != None: + if bnode is not None: tnode = bnode.find(bt+"technique_common") - if tnode != None: + if tnode is not None: mnode = tnode.find(bt+"instance_material") - if mnode != None: + if mnode is not None: if "target" in mnode.keys(): mname = mnode.get("target").strip("#") for m in col.materials: diff --git a/src/Mod/Arch/importGBXML.py b/src/Mod/Arch/importGBXML.py index 21416fe404..cefa77f93b 100644 --- a/src/Mod/Arch/importGBXML.py +++ b/src/Mod/Arch/importGBXML.py @@ -26,7 +26,7 @@ __url__ = "https://www.freecadweb.org" import FreeCAD,Draft if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate else: # \cond def translate(ctx,txt): diff --git a/src/Mod/Arch/importIFClegacy.py b/src/Mod/Arch/importIFClegacy.py index 1d4cd4a183..6d7a869561 100644 --- a/src/Mod/Arch/importIFClegacy.py +++ b/src/Mod/Arch/importIFClegacy.py @@ -27,7 +27,7 @@ import FreeCAD, Arch, Draft, os, sys, time, Part, DraftVecUtils, uuid, math, re -from DraftTools import translate +from draftutils.translate import translate __title__="FreeCAD IFC importer" __author__ = "Yorik van Havre" @@ -77,7 +77,7 @@ def insert(filename,docname,skip=None): getConfig() read(filename,skip) return doc - + def getConfig(): "Gets Arch IFC import preferences" global SKIP, CREATE_IFC_GROUPS, ASMESH, PREFIX_NUMBERS, FORCE_PYTHON_PARSER, SEPARATE_OPENINGS, SEPARATE_PLACEMENTS, JOINSOLIDS, AGGREGATE_WINDOWS @@ -85,7 +85,7 @@ def getConfig(): ASMESH = ["IfcFurnishingElement"] p = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Arch") CREATE_IFC_GROUPS = p.GetBool("createIfcGroups",False) - FORCE_PYTHON_PARSER = p.GetBool("forceIfcPythonParser",False) + FORCE_PYTHON_PARSER = p.GetBool("forceIfcPythonParser",False) DEBUG = p.GetBool("ifcDebug",False) SEPARATE_OPENINGS = p.GetBool("ifcSeparateOpenings",False) SEPARATE_PLACEMENTS = p.GetBool("ifcSeparatePlacements",False) @@ -125,22 +125,22 @@ def read(filename,skip=None): # parsing the IFC file t1 = time.time() - + processedIds = [] skipIds = skip if not skipIds: skipIds = [] elif isinstance(skipIds,int): skipIds = [skipIds] - + if getIfcOpenShell() and not FORCE_PYTHON_PARSER: # use the IfcOpenShell parser - + # preparing IfcOpenShell if DEBUG: global ifcObjects,ifcParents ifcObjects = {} # a table to relate ifc id with freecad object ifcParents = {} # a table to relate ifc id with parent id - if SEPARATE_OPENINGS: + if SEPARATE_OPENINGS: if not IFCOPENSHELL5: if hasattr(IfcImport,"DISABLE_OPENING_SUBTRACTIONS"): IfcImport.Settings(IfcImport.DISABLE_OPENING_SUBTRACTIONS,True) @@ -166,13 +166,13 @@ def read(filename,skip=None): relations = ifc.by_type("IfcRelAggregates") + ifc.by_type("IfcRelContainedInSpatialStructure") + ifc.by_type("IfcRelVoidsElement") if not objects: print("Error opening IFC file") - return + return else: num_lines = sum(1 for line in pyopen(filename)) if not IfcImport.Init(filename): print("Error opening IFC file") return - + # processing geometry idx = 0 while True: @@ -195,11 +195,11 @@ def read(filename,skip=None): elif r.is_a("IfcRelVoidsElement"): if str(obj) == str(getAttr(r,"RelatedOpeningElement")): objparentid.append(int(str(getAttr(r,"RelatingBuildingElement")).split("=")[0].strip("#"))) - + else: if hasattr(IfcImport, 'GetBrepData'): - obj = IfcImport.GetBrepData() - else: + obj = IfcImport.GetBrepData() + else: obj = IfcImport.Get() objid = obj.id idx = objid @@ -220,7 +220,7 @@ def read(filename,skip=None): elif objtype in SKIP: if DEBUG: print(" skipping because type is in skip list") nobj = None - + # check if object was already processed, to workaround an ifcopenshell bug elif objid in processedIds: if DEBUG: print(" skipping because this object was already processed") @@ -242,41 +242,41 @@ def read(filename,skip=None): # structs elif objtype in ["IfcBeam","IfcColumn","IfcSlab","IfcFooting"]: nobj = makeStructure(objid,shape,objtype,n) - + # roofs elif objtype in ["IfcRoof"]: nobj = makeRoof(objid,shape,n) - + # furniture elif objtype in ["IfcFurnishingElement"]: nobj = FreeCAD.ActiveDocument.addObject("Part::Feature",n) nobj.Shape = shape - + # sites elif objtype in ["IfcSite"]: nobj = makeSite(objid,shape,n) - + # floors elif objtype in ["IfcBuildingStorey"]: nobj = Arch.makeFloor(name=n) nobj.Label = n - + # floors elif objtype in ["IfcBuilding"]: nobj = Arch.makeBuilding(name=n) nobj.Label = n - + # spaces elif objtype in ["IfcSpace"]: nobj = makeSpace(objid,shape,n) - + elif shape: # treat as dumb parts if DEBUG: print("Fixme: Shape-containing object not handled: ",objid, " ", objtype) nobj = FreeCAD.ActiveDocument.addObject("Part::Feature",n) nobj.Label = n nobj.Shape = shape - + else: # treat as meshes if DEBUG: print("Warning: Object without shape: ",objid, " ", objtype) @@ -290,7 +290,7 @@ def read(filename,skip=None): nobj.Placement = pl else: if DEBUG: print("Error: Skipping object without mesh: ",objid, " ", objtype) - + # registering object number and parent if objparentid: ifcParents[objid] = [] @@ -298,7 +298,7 @@ def read(filename,skip=None): ifcParents[objid].append([p,not (objtype in subtractiveTypes)]) ifcObjects[objid] = nobj processedIds.append(objid) - + if IFCOPENSHELL5: if idx >= len(objects): break @@ -317,7 +317,7 @@ def read(filename,skip=None): for c in comps: parent_id = c[0] additive = c[1] - + if (id <= 0) or (parent_id <= 0): # root dummy object parent = None @@ -371,7 +371,7 @@ def read(filename,skip=None): parents_temp[parentid] = [parent_ifcobj.parent_id,True] if parent and (not parentid in ifcObjects): ifcObjects[parentid] = parent - + # attributing parent if parent and (id in ifcObjects): if ifcObjects[id] and (ifcObjects[id].Name != parent.Name): @@ -383,10 +383,10 @@ def read(filename,skip=None): ArchCommands.removeComponents(ifcObjects[id],parent) if not IFCOPENSHELL5: IfcImport.CleanUp() - + else: # use only the internal python parser - + FreeCAD.Console.PrintWarning(translate("Arch","IfcOpenShell not found or disabled, falling back on internal parser.")+"\n") schema=getSchema() if schema: @@ -397,28 +397,28 @@ def read(filename,skip=None): return None t2 = time.time() if DEBUG: print("Successfully loaded",ifc,"in %s s" % ((t2-t1))) - + # getting walls for w in ifc.getEnt("IfcWallStandardCase"): nobj = makeWall(w) - + # getting windows and doors for w in (ifc.getEnt("IfcWindow") + ifc.getEnt("IfcDoor")): nobj = makeWindow(w) - + # getting structs for w in (ifc.getEnt("IfcSlab") + ifc.getEnt("IfcBeam") + ifc.getEnt("IfcColumn") \ + ifc.getEnt("IfcFooting")): nobj = makeStructure(w) - + # getting floors for f in ifc.getEnt("IfcBuildingStorey"): group(f,ifc,"Floor") - + # getting buildings for b in ifc.getEnt("IfcBuilding"): group(b,ifc,"Building") - + # getting sites for s in ifc.getEnt("IfcSite"): group(s,ifc,"Site") @@ -427,7 +427,7 @@ def read(filename,skip=None): FreeCAD.ActiveDocument.recompute() t3 = time.time() if DEBUG: print("done processing IFC file in %s s" % ((t3-t1))) - + return None @@ -459,7 +459,7 @@ def makeWall(entity,shape=None,name="Wall"): wall.Label = name if DEBUG: print(" made wall object ",entity,":",wall) return wall - + # use internal parser if DEBUG: print("=====> making wall",entity.id) placement = wall = wire = body = width = height = None @@ -505,7 +505,7 @@ def makeWindow(entity,shape=None,name="Window"): window.Label = name if DEBUG: print(" made window object ",entity,":",window) return window - + # use internal parser if DEBUG: print("=====> making window",entity.id) placement = window = wire = body = width = height = None @@ -552,7 +552,7 @@ def makeStructure(entity,shape=None,ifctype=None,name="Structure"): structure.Role = "Foundation" if DEBUG: print(" made structure object ",entity,":",structure," (type: ",ifctype,")") return structure - + # use internal parser if DEBUG: print("=====> making struct",entity.id) placement = structure = wire = body = width = height = None @@ -596,7 +596,7 @@ def makeSite(entity,shape=None,name="Site"): return site except Exception: return None - + def makeSpace(entity,shape=None,name="Space"): "makes a space in the freecad document" try: @@ -734,10 +734,10 @@ def getShape(obj,objid): if not sh.isNull(): return sh return None - + def getPlacement(entity): "returns a placement from the given entity" - if not entity: + if not entity: return None if DEBUG: print(" getting placement ",entity) if IFCOPENSHELL5: @@ -772,7 +772,7 @@ def getPlacement(entity): pl.move(loc) if DEBUG: print(" made placement for ",entityid,":",pl) return pl - + def getAttr(entity,attr): "returns the given attribute from the given entity" if IFCOPENSHELL5: @@ -782,7 +782,7 @@ def getAttr(entity,attr): return entity.get_argument(i) else: return getattr(entity,attr) - + def getVector(entity): "returns a vector from the given entity" if not entity: @@ -807,9 +807,9 @@ def getVector(entity): else: return FreeCAD.Vector(tuple(Coordinates+[0])) return None - + # below is only used by the internal parser ######################################### - + def decode(name): "decodes encoded strings" try: @@ -837,12 +837,12 @@ def getSchema(): p = ArchCommands.download(SCHEMA) if p: return p - return None - + return None + def group(entity,ifc,mode=None): "gathers the children of the given entity" # only used by the internal parser - + try: if DEBUG: print("=====> making group",entity.id) placement = None @@ -865,14 +865,14 @@ def group(entity,ifc,mode=None): if not isinstance(s,list): s = [s] elts.extend(s) print("found dependent elements: ",elts) - + groups = [['Wall',['IfcWallStandardCase'],[]], ['Window',['IfcWindow','IfcDoor'],[]], ['Structure',['IfcSlab','IfcFooting','IfcBeam','IfcColumn'],[]], ['Floor',['IfcBuildingStorey'],[]], ['Building',['IfcBuilding'],[]], ['Furniture',['IfcFurnishingElement'],[]]] - + for e in elts: for g in groups: for t in g[1]: @@ -910,7 +910,7 @@ def group(entity,ifc,mode=None): cell.Label = label except Exception: if DEBUG: print("error: skipping group ",entity.id) - + def getWire(entity,placement=None): "returns a wire (created in the freecad document) from the given entity" # only used by the internal parser @@ -927,7 +927,7 @@ def getWire(entity,placement=None): pts.append(getVector(p)) return Draft.getWire(pts,closed=True,placement=placement) - + # EXPORT ########################################################## def export(exportList,filename): @@ -949,7 +949,7 @@ def export(exportList,filename): if (not hasattr(ifcw,"IfcFile")) and (not hasattr(ifcw,"file")): FreeCAD.Console.PrintError(translate("Arch","Error: your IfcOpenShell version is too old")+"\n") print("""importIFC: The version of ifcOpenShell installed on this system doesn't - have IFC export capabilities. IFC export currently requires an experimental + have IFC export capabilities. IFC export currently requires an experimental version of IfcOpenShell available from https://github.com/aothms/IfcOpenShell""") return import Arch,Draft @@ -994,7 +994,7 @@ def export(exportList,filename): others.append(obj) objectslist = buildings + floors + others if DEBUG: print("adding ", len(objectslist), " objects") - + global unprocessed unprocessed = [] @@ -1011,7 +1011,7 @@ def export(exportList,filename): representation = None descr = None extra = None - + # setting the IFC type if hasattr(obj,"Role"): ifctype = obj.Role.replace(" ","") @@ -1034,10 +1034,10 @@ def export(exportList,filename): brepflag = True if DEBUG: print("Adding " + obj.Label + " as Ifc" + ifctype) - - # writing IFC data + + # writing IFC data if obj.isDerivedFrom("App::DocumentObjectGroup"): - + # getting parent building if parent: parent = ifc.findByName("IfcBuilding",str(parent.Label)) @@ -1114,7 +1114,7 @@ def export(exportList,filename): if DEBUG: print(" Type ",ifctype," is not supported yet. Exporting as IfcBuildingElementProxy instead") ifctype = "IfcBuildingElementProxy" extra = ["ELEMENT"] - + product = ifc.addProduct( ifctype, representation, storey=parent, placement=placement, name=name, description=descr, extra=extra ) if product: @@ -1131,7 +1131,7 @@ def export(exportList,filename): for i in range(36-len(obj.Label)): spacer += " " txt.append(obj.Label + spacer + ifctype) - + # adding object to group, if any for g in groups.keys(): group = FreeCAD.ActiveDocument.getObject(g) @@ -1139,7 +1139,7 @@ def export(exportList,filename): for o in group.Group: if o.Name == obj.Name: groups[g].append(product) - + else: unprocessed.append(obj) else: @@ -1152,7 +1152,7 @@ def export(exportList,filename): if o: if DEBUG: print("Adding group ", o.Label, " with ",len(entities)," elements") grp = ifc.addGroup( entities, o.Label ) - + ifc.write() if exporttxt: @@ -1177,7 +1177,7 @@ def export(exportList,filename): f.close() FreeCAD.ActiveDocument.recompute() - + if unprocessed: print("\nWARNING: " + str(len(unprocessed)) + " objects were not exported (stored in importIFC.unprocessed):") for o in unprocessed: @@ -1227,11 +1227,11 @@ def getTuples(data,scale=1,placement=None,normal=None,close=True): def getIfcExtrusionData(obj,scale=1,nosubs=False): """getIfcExtrusionData(obj,[scale,nosubs]): returns a closed path (a list of tuples), a tuple expressing an extrusion - vector, and a list of 3 tuples for base position, x axis and z axis. Or returns None, if a base loop and + vector, and a list of 3 tuples for base position, x axis and z axis. Or returns None, if a base loop and an extrusion direction cannot be extracted. Scale can indicate a scale factor.""" - + CURVEMODE = "PARAMETER" # For trimmed curves. CARTESIAN or PARAMETER - + if hasattr(obj,"Additions"): if obj.Additions: # TODO provisorily treat objs with additions as breps @@ -1291,7 +1291,7 @@ def getIfcExtrusionData(obj,scale=1,nosubs=False): p1 = math.degrees(-DraftVecUtils.angle(e.Vertexes[0].Point.sub(e.Curve.Center))) p2 = math.degrees(-DraftVecUtils.angle(e.Vertexes[-1].Point.sub(e.Curve.Center))) da = DraftVecUtils.angle(e.valueAt(e.FirstParameter+0.1).sub(e.Curve.Center),e.Vertexes[0].Point.sub(e.Curve.Center)) - if p1 < 0: + if p1 < 0: p1 = 360 + p1 if p2 < 0: p2 = 360 + p2 @@ -1317,11 +1317,11 @@ def getIfcExtrusionData(obj,scale=1,nosubs=False): else: # Polyline profile return "polyline", getTuples(p,scale), getTuples(v,scale), d - return None - + return None + def getIfcBrepFacesData(obj,scale=1,sub=False,tessellation=1): - """getIfcBrepFacesData(obj,[scale,tessellation]): returns a list(0) of lists(1) of lists(2) of lists(3), - list(3) being a list of vertices defining a loop, list(2) describing a face from one or + """getIfcBrepFacesData(obj,[scale,tessellation]): returns a list(0) of lists(1) of lists(2) of lists(3), + list(3) being a list of vertices defining a loop, list(2) describing a face from one or more loops, list(1) being the whole solid made of several faces, list(0) being the list of solids inside the object. Scale can indicate a scaling factor. Tessellation is the tessellation factor to apply on curved faces.""" @@ -1376,7 +1376,7 @@ def getIfcBrepFacesData(obj,scale=1,sub=False,tessellation=1): sols.append(s) return sols return None - + def getIfcElevation(obj): """getIfcElevation(obj): Returns the lowest height (Z coordinate) of this object""" if obj.isDerivedFrom("Part::Feature"): @@ -1398,7 +1398,7 @@ def explore(filename=None): d = explorer(filename,schema) d.show() return d - + # IfcReader ############################################# class IfcSchema: @@ -1422,30 +1422,30 @@ class IfcSchema: def readTypes(self): """ - Parse all the possible types from the schema, + Parse all the possible types from the schema, returns a dictionary Name -> Type """ types = {} for m in re.finditer("TYPE (.*) = (.*);", self.data): - typename, typetype = m.groups() + typename, typetype = m.groups() if typetype in self.SIMPLETYPES: types[typename] = typetype else: types[typename] = "#" + typetype - + return types - + def readEntities(self): """ Parse all the possible entities from the schema, returns a dictionary of the form: - { name: { - "supertype": supertype, + { name: { + "supertype": supertype, "attributes": [{ key: value }, ..] - }} + }} """ entities = {} - + # Regexes must be greedy to prevent matching outer entity and end_entity strings # Regexes have re.DOTALL to match newlines for m in re.finditer("ENTITY (.*?)END_ENTITY;", self.data, re.DOTALL): @@ -1459,17 +1459,17 @@ class IfcSchema: # find the shortest string matched from the end of the entity type header to the # first occurrence of a NO_ATTR string (when it occurs on a new line) - inner_str = re.search(";(.*?)$", raw_entity_str, re.DOTALL).groups()[0] + inner_str = re.search(";(.*?)$", raw_entity_str, re.DOTALL).groups()[0] attrs_str = min([inner_str.partition("\r\n "+a)[0] for a in self.NO_ATTR]) attrs = [] for am in re.finditer("(.*?) : (.*?);", attrs_str, re.DOTALL): name, attr_type = [s.replace("\r\n\t","") for s in am.groups()] attrs.append((name, attr_type)) - + entity["attributes"] = attrs entities[entity["name"]] = entity - + return entities @@ -1480,7 +1480,7 @@ class IfcSchema: ent = self.entities[name] attrs = [] - while ent != None: + while ent is not None: this_ent_attrs = copy.copy(ent["attributes"]) this_ent_attrs.reverse() attrs.extend(this_ent_attrs) @@ -1502,7 +1502,7 @@ class IfcFile: Parses an ifc file given by filename, entities can be retrieved by name and id The whole file is stored in a dictionary (in memory) """ - + entsById = {} entsByName = {} @@ -1513,10 +1513,10 @@ class IfcFile: self.entById, self.entsByName, self.header = self.read() self.file.close() if DEBUG: print("Parsed from file %s: %s entities" % (self.filename, len(self.entById))) - + def getEntityById(self, id): return self.entById.get(id, None) - + def getEntitiesByName(self, name): return self.entsByName.get(name, None) @@ -1542,13 +1542,13 @@ class IfcFile: readheader = False else: header += line - + return [entById, entsByName, header] def parseLine(self, line): """ - Parse a line - """ + Parse a line + """ m = IFCLINE_RE.search(line) # id,name,attrs if m: id, name, attrs = m.groups() @@ -1557,7 +1557,7 @@ class IfcFile: attrs = attrs.strip() else: return False - + return {"id": id, "name": name, "attributes": self.parseAttributes(name, attrs)} def parseAttributes(self, ent_name, attrs_str): @@ -1566,20 +1566,20 @@ class IfcFile: """ parts = [] lastpos = 0 - + while lastpos < len(attrs_str): newpos = self.nextString(attrs_str, lastpos) parts.extend(self.parseAttribute(attrs_str[lastpos:newpos-1])) lastpos = newpos - + schema_attributes = self.schema.getAttributes(ent_name) assert len(schema_attributes) == len(parts), \ "Expected %s attributes, got %s (entity: %s" % \ (len(schema_attributes), len(parts), ent_name) - + attribute_names = [a[0] for a in schema_attributes] - + return dict(zip(attribute_names, parts)) def parseAttribute(self, attr_str): @@ -1605,7 +1605,7 @@ class IfcFile: parts.append(s) # ref, enum or other lastpos = newpos - + return parts @@ -1628,8 +1628,8 @@ class IfcFile: quotes = 1 elif c =="\'" and quotes == 1: quotes = 0 - - return len(s)+1 + + return len(s)+1 class IfcEntity: "a container for an IFC entity" @@ -1674,7 +1674,7 @@ class IfcEntity: if hasattr(self,attr): return self.__dict__[attr] return None - + class IfcDocument: "an object representing an IFC document" def __init__(self,filename,schema="IFC2X3_TC1.exp"): @@ -1743,7 +1743,7 @@ class IfcDocument: if DEBUG: print("error parsing attribute",value) val = value return val - + def __repr__(self): return "IFC Document: " + self.filename + ', ' + str(len(self.Entities)) + " entities " @@ -1860,7 +1860,7 @@ def explorer(filename,schema="IFC2X3_TC1.exp"): if isinstance(v,list): for vi in v: if isinstance(vi,IfcEntity): - t = "Entity #" + str(vi.id) + ": " + str(vi.type) + t = "Entity #" + str(vi.id) + ": " + str(vi.type) else: t = vi t = " " + str(t) @@ -1874,7 +1874,7 @@ def explorer(filename,schema="IFC2X3_TC1.exp"): layout = QtGui.QVBoxLayout(d) layout.addWidget(tree) return d - + # IfcWriter ######################################## class _tempEntityHolder: @@ -1882,7 +1882,7 @@ class _tempEntityHolder: to be made into something nicer later...""" def __init__(self): self.refs = [] - + holder = _tempEntityHolder() def uid(): @@ -1890,7 +1890,7 @@ def uid(): u = str(uuid.uuid4())[:22] u = u.replace("-","_") return u - + def now(string=False): "returns a suitable Ifc Time" if string: @@ -1899,7 +1899,7 @@ def now(string=False): return int(time.time()) def getPropertyNames(entity): - """getPropertyNames(entity): Returns a dictionary with + """getPropertyNames(entity): Returns a dictionary with the numbers and names of the pythonproperties available for this entity""" ents = {} @@ -1910,7 +1910,7 @@ def getPropertyNames(entity): for i in range(l): ents[i] = entity.get_argument_name(i) return ents - + def getTuple(vec): """getTuple(vec): returns a tuple from other coordinate structures: tuple, list, 3d vector, or occ vertex""" @@ -1926,7 +1926,7 @@ def getTuple(vec): return (fmt(vec.x),fmt(vec.y),fmt(vec.z)) elif hasattr(vec,"X") and hasattr(vec,"Y") and hasattr(vec,"Z"): return (fmt(vec.X),fmt(vec.Y),fmt(vec.Z)) - + def getValueAndDirection(vec): """getValueAndDirection(vec): returns a length and a tuple representing a normalized vector from a tuple""" @@ -1940,8 +1940,8 @@ def getValueAndDirection(vec): return length,normal def create(ifcdoc=None,ifcname=None,arguments=[]): - """create(ifcdoc,ifcname,[arguments]):creates an entity - of the given name in the given document and optionally + """create(ifcdoc,ifcname,[arguments]):creates an entity + of the given name in the given document and optionally gives it an ordered list of arguments""" if hasattr(ifcw,"Entity"): entity = ifcw.Entity(ifcname) @@ -1968,7 +1968,7 @@ def create(ifcdoc=None,ifcname=None,arguments=[]): class IfcWriter(object): """IfcWriter([filepath,name,owner,organization,application,version]) Creates an empty IFC document.""" - + def __init__(self,filepath="",name="",owner="",organization="",application="Python IFC exporter",version="0.0"): if hasattr(ifcw,"IfcFile"): self._fileobject = ifcw.IfcFile() @@ -2004,7 +2004,7 @@ class IfcWriter(object): def __repr__(self): return "IFC document " + self.Name #+ " containing " + str(len(holder)) + " entities" - + def __setattr__(self,key,value): if value: if key == "Owner": @@ -2014,7 +2014,7 @@ class IfcWriter(object): elif key == "Name": self.Project.set_argument(2,str(value)) self.__dict__.__setitem__(key,value) - + def findByName(self,ifctype,name): "finds an entity of a given ifctype by name" objs = self._fileobject.by_type(ifctype) @@ -2098,7 +2098,7 @@ class IfcWriter(object): return lpl else: return gpl - + def addSite(self,placement=None,name="Site",description=None,latitude=None,longitude=None,elevation=None,landtitlenumber=None,address=None): """makeSite(ifcdoc,project,owner,[placement,name,description]): creates a site in the given ifc document""" @@ -2108,7 +2108,7 @@ class IfcWriter(object): placement = self.addPlacement() self.Site = create(self._fileobject,"IfcSite",[uid(),self._owner,str(name),description,None,placement,None,None,"ELEMENT",latitude,longitude,elevation,landtitlenumber,address]) self._relate(self.Project,self.Site) - + def addBuilding(self,placement=None,name="Default building",description=None): """addBuilding([placement,name,description]): adds a building""" if not placement: @@ -2119,7 +2119,7 @@ class IfcWriter(object): self._relate(self.Site,bdg) self.Buildings.append(bdg) return bdg - + def addStorey(self,building=None,placement=None,name="Default storey",description=None): """addStorey([building,placement,name,description]): adds a storey""" if not placement: @@ -2133,7 +2133,7 @@ class IfcWriter(object): self._relate(building,sto) self.Storeys.append(sto) return sto - + def addGroup(self,entities,name="Default group",description=None): """addGroup(entities,[name,description]): adds a group with the given entities""" if not isinstance(entities,list): @@ -2141,7 +2141,7 @@ class IfcWriter(object): gro = create(self._fileobject,"IfcGroup",[uid(),self._owner,str(name),description,None]) rel = create(self._fileobject,"IfcRelAssignsToGroup",[uid(),self._owner,str(name)+"-relation",None,entities,"PRODUCT",gro]) return gro - + def _relate(self,container,entities): """relate(container,entities): relates the given entities to the given container""" @@ -2215,11 +2215,11 @@ class IfcWriter(object): psa = create(self._fileobject,"IfcPresentationStyleAssignment",[[iss]]) isi = create(self._fileobject,"IfcStyledItem",[rep,[psa],None]) return isi - + def addProfile(self,ifctype,data,curvetype="AREA"): """addProfile(ifctype,data): creates a 2D profile of the given type, with the given data as arguments, which must be formatted correctly according to the type.""" - + # Expected ifctype and corresponding data formatting: # IfcPolyLine: [ (0,0,0), (2,1,0), (3,3,0) ] # list of points # IfcCompositeCurve: [ ["line",[ (0,0,0), (2,1,0) ] ], # list of points @@ -2227,7 +2227,7 @@ class IfcWriter(object): # ... ] # IfcCircleProfileDef: [ (0,0,0), 15 ] # center, radius # IfcEllipseProfileDef: [ (0,0,0), 15, 7 ] # center, radiusX, radiusY - + if ifctype == "IfcPolyline": pts = [create(self._fileobject,"IfcCartesianPoint",getTuple(p)[:2]) for p in data] pol = create(self._fileobject,"IfcPolyline",[pts]) @@ -2271,7 +2271,7 @@ class IfcWriter(object): edir = create(self._fileobject,"IfcDirection",[norm]) solid = create(self._fileobject,"IfcExtrudedAreaSolid",[profile,placement,edir,value]) return solid - + def addExtrudedPolyline(self,points,extrusion,placement=None,color=None): """addExtrudedPolyline(points,extrusion,[placement,color]): makes an extruded polyline from the given points and the given extrusion vector""" @@ -2293,7 +2293,7 @@ class IfcWriter(object): if color: self.addColor(color,exp) return exp - + def addExtrudedEllipse(self,data,extrusion,placement=None,color=None): """addExtrudedEllipse(data,extrusion,[placement,color]): makes an extruded ellipse from the given data (center,radiusx,radiusy) and the given extrusion vector""" @@ -2304,7 +2304,7 @@ class IfcWriter(object): if color: self.addColor(color,exp) return exp - + def addExtrudedCompositeCurve(self,curves,extrusion,placement=None,color=None): """addExtrudedCompositeCurve(curves,extrusion,[placement,color]): makes an extruded polyline from the given curves and the given extrusion vector""" @@ -2315,7 +2315,7 @@ class IfcWriter(object): if color: self.addColor(color,exp) return exp - + def addFace(self,face): """addFace(face): creates a face from the given face data (a list of lists of points). The first is the outer wire, the next are optional inner wires. They must be reversed in order""" diff --git a/src/Mod/Arch/importJSON.py b/src/Mod/Arch/importJSON.py index 840d1dbb15..5ad1e800ea 100644 --- a/src/Mod/Arch/importJSON.py +++ b/src/Mod/Arch/importJSON.py @@ -27,7 +27,7 @@ import six if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate else: FreeCADGui = None diff --git a/src/Mod/Arch/importOBJ.py b/src/Mod/Arch/importOBJ.py index 0dd361d186..2283312bcb 100644 --- a/src/Mod/Arch/importOBJ.py +++ b/src/Mod/Arch/importOBJ.py @@ -19,10 +19,10 @@ #* * #*************************************************************************** -import FreeCAD, DraftGeomUtils, Part, Draft, Arch, Mesh, MeshPart, os, sys, codecs, ntpath +import FreeCAD, DraftGeomUtils, Part, Draft, Arch, Mesh, MeshPart, os, codecs, ntpath # import numpy as np if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate else: # \cond def translate(context,text): @@ -44,10 +44,6 @@ if open.__module__ in ['__builtin__','io']: pythonopen = open def decode(txt): - - if sys.version_info.major < 3: - if isinstance(txt,unicode): - return txt.encode("utf8") return txt def findVert(aVertex,aList): @@ -390,5 +386,5 @@ def makeMesh(doc,activeobject,verts,facets,material,colortable): if material and FreeCAD.GuiUp: if material in colortable: mobj.ViewObject.ShapeColor = colortable[material][0] - if colortable[material][1] != None: + if colortable[material][1] is not None: mobj.ViewObject.Transparency = colortable[material][1] diff --git a/src/Mod/Arch/importWebGL.py b/src/Mod/Arch/importWebGL.py index e2e2302200..54336f7ea7 100644 --- a/src/Mod/Arch/importWebGL.py +++ b/src/Mod/Arch/importWebGL.py @@ -42,7 +42,7 @@ import textwrap if FreeCAD.GuiUp: import FreeCADGui - from DraftTools import translate + from draftutils.translate import translate else: FreeCADGui = None def translate(ctxt, txt): return txt diff --git a/src/Mod/Draft/App/AppDraftUtilsPy.cpp b/src/Mod/Draft/App/AppDraftUtilsPy.cpp index e22b58aa21..aa81190e31 100644 --- a/src/Mod/Draft/App/AppDraftUtilsPy.cpp +++ b/src/Mod/Draft/App/AppDraftUtilsPy.cpp @@ -46,7 +46,7 @@ public: initialize("The DraftUtils module contains utility functions for the Draft module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object readDXF(const Py::Tuple& /*args*/) diff --git a/src/Mod/Draft/DraftGui.py b/src/Mod/Draft/DraftGui.py index 4fc91be56c..dc6fbd283e 100644 --- a/src/Mod/Draft/DraftGui.py +++ b/src/Mod/Draft/DraftGui.py @@ -156,6 +156,11 @@ inCommandShortcuts = { translate("draft","Toggle near snap on/off"), None ], + "Undo": [ + Draft.getParam("inCommandShortcutNearSnap", "/"), + translate("draft","Undo last segment"), + None + ], } from draftutils.todo import todo @@ -785,7 +790,7 @@ class DraftToolBar: # self.symmetricButton.setToolTip(translate("draft", "Make Bezier node symmetric")) # self.arc3PtButton.setToolTip(translate("draft", "Toggle radius and angles arc editing")) - self.undoButton.setText(translate("draft", "&Undo (CTRL+Z)")) + self.undoButton.setText(translate("draft", "&Undo")+" ("+inCommandShortcuts["Undo"][0]+")") self.undoButton.setToolTip(translate("draft", "Undo the last segment")) self.closeButton.setText(translate("draft", "Close")+" ("+inCommandShortcuts["Close"][0]+")") self.closeButton.setToolTip(translate("draft", "Finishes and closes the current line")) @@ -819,7 +824,7 @@ class DraftToolBar: pb = [] for i in range(self.layout.count()): w = self.layout.itemAt(i).widget() - if w != None and w.inherits('QPushButton'): + if w is not None and w.inherits('QPushButton'): pb.append(w) for i in pb: @@ -1631,6 +1636,7 @@ class DraftToolBar: #Length #Wipe #SetWP + #Undo spec = False if txt.upper().startswith(inCommandShortcuts["Relative"][0]): @@ -1705,6 +1711,9 @@ class DraftToolBar: if self.isCopy.isVisible(): self.isCopy.setChecked(not self.isCopy.isChecked()) spec = True + elif txt.upper().startswith(inCommandShortcuts["Undo"][0]): + self.undoSegment() + spec = True elif txt.upper().startswith(inCommandShortcuts["SubelementMode"][0]): if self.isSubelementMode.isVisible(): self.isSubelementMode.setChecked(not self.isSubelementMode.isChecked()) @@ -1770,7 +1779,7 @@ class DraftToolBar: dp = None if point: dp = point - if self.relativeMode: # and (last != None): + if self.relativeMode: # and (last is not None): if self.globalMode: dp = point - last else: @@ -2206,7 +2215,7 @@ class DraftToolBar: "Draft_ShapeString","Draft_BezCurve"] self.title = "Create objects" def shouldShow(self): - return (FreeCAD.ActiveDocument != None) and (not FreeCADGui.Selection.getSelection()) + return (FreeCAD.ActiveDocument is not None) and (not FreeCADGui.Selection.getSelection()) class DraftModifyWatcher: def __init__(self): @@ -2217,7 +2226,7 @@ class DraftToolBar: "Draft_Drawing"] self.title = "Modify objects" def shouldShow(self): - return (FreeCAD.ActiveDocument != None) and (FreeCADGui.Selection.getSelection() != []) + return (FreeCAD.ActiveDocument is not None) and (FreeCADGui.Selection.getSelection() != []) # OBSOLETE #class DraftTrayWatcher: @@ -2254,7 +2263,7 @@ class DraftToolBar: self.draftWidget.toggleViewAction().setVisible(True) def Deactivated(self): - if (FreeCAD.activeDraftCommand != None): + if (FreeCAD.activeDraftCommand is not None): self.continueMode = False FreeCAD.activeDraftCommand.finish() if self.taskmode: diff --git a/src/Mod/Draft/Resources/ui/preferences-draftinterface.ui b/src/Mod/Draft/Resources/ui/preferences-draftinterface.ui index f10eea7957..d8f735206c 100644 --- a/src/Mod/Draft/Resources/ui/preferences-draftinterface.ui +++ b/src/Mod/Draft/Resources/ui/preferences-draftinterface.ui @@ -924,21 +924,9 @@ 0 - - Enable draft statusbar customization - Draft Statusbar - - true - - - DisplayStatusbar - - - Mod/Draft - diff --git a/src/Mod/Draft/WorkingPlane.py b/src/Mod/Draft/WorkingPlane.py index 60a559fb49..3fdd900b83 100644 --- a/src/Mod/Draft/WorkingPlane.py +++ b/src/Mod/Draft/WorkingPlane.py @@ -571,7 +571,7 @@ class Plane: See Also -------- - alignToPointAndAxis, DraftGeomUtils.getQuad + alignToPointAndAxis """ # Set face to the unique selected face, if found if shape.ShapeType == 'Face': @@ -579,22 +579,28 @@ class Plane: place = parent.getGlobalPlacement() else: place = FreeCAD.Placement() - cen = place.multVec(shape.Faces[0].CenterOfMass) - place.Base = FreeCAD.Vector(0, 0, 0) # Reset the Base for the conversion of the normal. - nor = place.multVec(shape.Faces[0].normalAt(0, 0)) + rot = place.Rotation + + cen = place.multVec(shape.CenterOfMass) + nor = rot.multVec(shape.normalAt(0, 0)) self.alignToPointAndAxis(cen, nor, offset) - import DraftGeomUtils - q = DraftGeomUtils.getQuad(shape) - if q: - self.u = place.multVec(q[1]) - self.v = place.multVec(q[2]) - if not DraftVecUtils.equals(self.u.cross(self.v), self.axis): - self.u, self.v = self.v, self.u - if DraftVecUtils.equals(self.u, Vector(0, 0, 1)): - # the X axis is vertical: rotate 90 degrees - self.u, self.v = self.v.negative(), self.u - elif DraftVecUtils.equals(self.u, Vector(0, 0, -1)): - self.u, self.v = self.v, self.u.negative() + + pmr = shape.ParameterRange # (uMin, uMax, vMin, vMax) + u = shape.valueAt(pmr[1], 0).sub(shape.valueAt(pmr[0], 0)) + v = shape.valueAt(0, pmr[3]).sub(shape.valueAt(0, pmr[2])) + self.u = rot.multVec(u).normalize() + self.v = rot.multVec(v).normalize() + + if shape.Orientation == "Reversed": + self.u, self.v = self.v, self.u + + # If self.u or self.v matches a wrong global axis, rotate them: + if DraftVecUtils.equals(self.v, Vector(0, 0, -1)): + self.u, self.v = self.u.negative(), self.v.negative() + elif DraftVecUtils.equals(self.u, Vector(0, 0, 1)): + self.u, self.v = self.v.negative(), self.u + elif DraftVecUtils.equals(self.u, Vector(0, 0, -1)): + self.u, self.v = self.v, self.u.negative() self.weak = False return True diff --git a/src/Mod/Draft/draftfunctions/move.py b/src/Mod/Draft/draftfunctions/move.py index a826a9e02d..4f606fc482 100644 --- a/src/Mod/Draft/draftfunctions/move.py +++ b/src/Mod/Draft/draftfunctions/move.py @@ -38,21 +38,21 @@ import draftmake.make_line as make_line def move(objectslist, vector, copy=False): """move(objects,vector,[copy]) - + Move the objects contained in objects (that can be an object or a list of objects) in the direction and distance indicated by the given - vector. + vector. Parameters ---------- objectslist : list vector : Base.Vector - Delta Vector to move the clone from the original position. + Delta Vector to move the clone from the original position. copy : bool If copy is True, the actual objects are not moved, but copies - are created instead. + are created instead. Return ---------- @@ -67,8 +67,17 @@ def move(objectslist, vector, copy=False): newgroups = {} objectslist = utils.filter_objects_for_modifiers(objectslist, copy) + if copy: + doc = App.ActiveDocument + for obj in objectslist: + if obj.isDerivedFrom("App::DocumentObjectGroup") \ + and obj.Name not in newgroups.keys(): + newgroups[obj.Name] = doc.addObject(obj.TypeId, + utils.get_real_name(obj.Name)) + for obj in objectslist: newobj = None + # real_vector have been introduced to take into account # the possibility that object is inside an App::Part # TODO: Make Move work also with App::Link @@ -88,9 +97,12 @@ def move(objectslist, vector, copy=False): newobj.Z = obj.Z.Value + real_vector.z elif obj.isDerivedFrom("App::DocumentObjectGroup"): - pass + if copy: + newobj = newgroups[obj.Name] + else: + newobj = obj - elif hasattr(obj,'Shape'): + elif hasattr(obj, "Shape"): if copy: newobj = make_copy.make_copy(obj) else: @@ -98,14 +110,14 @@ def move(objectslist, vector, copy=False): pla = newobj.Placement pla.move(real_vector) - elif utils.get_type(obj) == "Annotation": + elif obj.isDerivedFrom("App::Annotation"): if copy: newobj = make_copy.make_copy(obj) else: newobj = obj newobj.Position = obj.Position.add(real_vector) - elif utils.get_type(obj) in ("Text", "DraftText"): + elif utils.get_type(obj) in ["Text", "DraftText"]: if copy: newobj = make_copy.make_copy(obj) else: @@ -121,37 +133,36 @@ def move(objectslist, vector, copy=False): newobj.End = obj.End.add(real_vector) newobj.Dimline = obj.Dimline.add(real_vector) - elif utils.get_type(obj) in ["AngularDimension"]: + elif utils.get_type(obj) == "AngularDimension": if copy: newobj = make_copy.make_copy(obj) else: newobj = obj newobj.Center = obj.Start.add(real_vector) - elif "Placement" in obj.PropertiesList: + elif hasattr(obj, "Placement"): if copy: newobj = make_copy.make_copy(obj) else: newobj = obj - pla = obj.Placement + pla = newobj.Placement pla.move(real_vector) if newobj is not None: newobjlist.append(newobj) + if copy: + for parent in obj.InList: + if parent.isDerivedFrom("App::DocumentObjectGroup") \ + and (parent in objectslist): + newgroups[parent.Name].addObject(newobj) + if utils.get_type(parent) == "Layer": + parent.Proxy.addObject(parent ,newobj) - if copy: - for p in obj.InList: - if p.isDerivedFrom("App::DocumentObjectGroup") and (p in objectslist): - g = newgroups.setdefault(p.Name,App.ActiveDocument.addObject(p.TypeId,p.Name)) - g.addObject(newobj) - break - if utils.get_type(p) == "Layer": - p.Proxy.addObject(p,newobj) - - if copy and utils.get_param("selectBaseObjects",False): + if copy and utils.get_param("selectBaseObjects", False): gui_utils.select(objectslist) else: gui_utils.select(newobjlist) + if len(newobjlist) == 1: return newobjlist[0] return newobjlist diff --git a/src/Mod/Draft/draftfunctions/rotate.py b/src/Mod/Draft/draftfunctions/rotate.py index b1b6b2ed19..48d8c93aa6 100644 --- a/src/Mod/Draft/draftfunctions/rotate.py +++ b/src/Mod/Draft/draftfunctions/rotate.py @@ -39,8 +39,8 @@ import draftmake.make_line as make_line import draftmake.make_copy as make_copy -def rotate(objectslist, angle, center=App.Vector(0,0,0), - axis=App.Vector(0,0,1), copy=False): +def rotate(objectslist, angle, center=App.Vector(0, 0, 0), + axis=App.Vector(0, 0, 1), copy=False): """rotate(objects,angle,[center,axis,copy]) Rotates the objects contained in objects (that can be a list of objects @@ -49,9 +49,9 @@ def rotate(objectslist, angle, center=App.Vector(0,0,0), Parameters ---------- - objectlist : list + objectslist : list - angle : list + angle : rotation angle (in degrees) center : Base.Vector @@ -76,8 +76,17 @@ def rotate(objectslist, angle, center=App.Vector(0,0,0), newgroups = {} objectslist = utils.filter_objects_for_modifiers(objectslist, copy) + if copy: + doc = App.ActiveDocument + for obj in objectslist: + if obj.isDerivedFrom("App::DocumentObjectGroup") \ + and obj.Name not in newgroups.keys(): + newgroups[obj.Name] = doc.addObject(obj.TypeId, + utils.get_real_name(obj.Name)) + for obj in objectslist: newobj = None + # real_center and real_axis are introduced to take into account # the possibility that object is inside an App::Part if hasattr(obj, "getGlobalPlacement"): @@ -89,61 +98,83 @@ def rotate(objectslist, angle, center=App.Vector(0,0,0), real_center = center real_axis = axis - if copy: - newobj = make_copy.make_copy(obj) - else: - newobj = obj if obj.isDerivedFrom("App::Annotation"): # TODO: this is very different from how move handle annotations # maybe we can uniform the two methods - if axis.normalize() == App.Vector(1,0,0): + if copy: + newobj = make_copy.make_copy(obj) + else: + newobj = obj + if axis.normalize() == App.Vector(1, 0, 0): newobj.ViewObject.RotationAxis = "X" newobj.ViewObject.Rotation = angle - elif axis.normalize() == App.Vector(0,1,0): + elif axis.normalize() == App.Vector(0, 1, 0): newobj.ViewObject.RotationAxis = "Y" newobj.ViewObject.Rotation = angle - elif axis.normalize() == App.Vector(0,-1,0): + elif axis.normalize() == App.Vector(0, -1, 0): newobj.ViewObject.RotationAxis = "Y" newobj.ViewObject.Rotation = -angle - elif axis.normalize() == App.Vector(0,0,1): + elif axis.normalize() == App.Vector(0, 0, 1): newobj.ViewObject.RotationAxis = "Z" newobj.ViewObject.Rotation = angle - elif axis.normalize() == App.Vector(0,0,-1): + elif axis.normalize() == App.Vector(0, 0, -1): newobj.ViewObject.RotationAxis = "Z" newobj.ViewObject.Rotation = -angle + elif utils.get_type(obj) == "Point": - v = App.Vector(obj.X,obj.Y,obj.Z) + if copy: + newobj = make_copy.make_copy(obj) + else: + newobj = obj + v = App.Vector(newobj.X, newobj.Y, newobj.Z) rv = v.sub(real_center) rv = DraftVecUtils.rotate(rv, math.radians(angle), real_axis) v = real_center.add(rv) newobj.X = v.x newobj.Y = v.y newobj.Z = v.z + elif obj.isDerivedFrom("App::DocumentObjectGroup"): - pass - elif hasattr(obj,"Placement"): - #FreeCAD.Console.PrintMessage("placement rotation\n") - shape = Part.Shape() - shape.Placement = obj.Placement - shape.rotate(DraftVecUtils.tup(real_center), DraftVecUtils.tup(real_axis), angle) - newobj.Placement = shape.Placement - elif hasattr(obj,'Shape') and (utils.get_type(obj) not in ["WorkingPlaneProxy","BuildingPart"]): - #think it make more sense to try first to rotate placement and later to try with shape. no? - shape = obj.Shape.copy() - shape.rotate(DraftVecUtils.tup(real_center), DraftVecUtils.tup(real_axis), angle) + if copy: + newobj = newgroups[obj.Name] + else: + newobj = obj + + elif hasattr(obj, "Placement"): + # App.Console.PrintMessage("placement rotation\n") + if copy: + newobj = make_copy.make_copy(obj) + else: + newobj = obj + # Workaround for `faulty` implementation of Base.Placement.rotate(center, axis, angle). + # See: https://forum.freecadweb.org/viewtopic.php?p=613196#p613196 + offset_rotation = App.Placement(App.Vector(0, 0, 0), App.Rotation(real_axis, angle), real_center) + newobj.Placement = offset_rotation * newobj.Placement + + elif hasattr(obj, "Shape"): + if copy: + newobj = make_copy.make_copy(obj) + else: + newobj = obj + shape = newobj.Shape.copy() + shape.rotate(real_center, real_axis, angle) newobj.Shape = shape - if copy: - gui_utils.formatObject(newobj,obj) + if newobj is not None: newobjlist.append(newobj) - if copy: - for p in obj.InList: - if p.isDerivedFrom("App::DocumentObjectGroup") and (p in objectslist): - g = newgroups.setdefault(p.Name, App.ActiveDocument.addObject(p.TypeId, p.Name)) - g.addObject(newobj) - break + if copy: + for parent in obj.InList: + if parent.isDerivedFrom("App::DocumentObjectGroup") \ + and (parent in objectslist): + newgroups[parent.Name].addObject(newobj) + if utils.get_type(parent) == "Layer": + parent.Proxy.addObject(parent ,newobj) + + if copy and utils.get_param("selectBaseObjects", False): + gui_utils.select(objectslist) + else: + gui_utils.select(newobjlist) - gui_utils.select(newobjlist) if len(newobjlist) == 1: return newobjlist[0] return newobjlist diff --git a/src/Mod/Draft/draftfunctions/upgrade.py b/src/Mod/Draft/draftfunctions/upgrade.py index 8543653c01..a26916af1d 100644 --- a/src/Mod/Draft/draftfunctions/upgrade.py +++ b/src/Mod/Draft/draftfunctions/upgrade.py @@ -161,7 +161,7 @@ def upgrade(objects, delete=False, force=None): return None if len(obj.Shape.Edges) == 1: return None - if is_straight_line(obj.Shape) == True: + if is_straight_line(obj.Shape): return None if utils.get_type(obj) == "Wire": obj.Closed = True @@ -507,10 +507,9 @@ def upgrade(objects, delete=False, force=None): elif len(objects) > 1 and len(edges) > 1: result = makeWires(objects) if result: - if result == True: - _msg(translate("draft","Found several wires or edges: wiring them")) - else: - _msg(translate("draft","Found several non-treatable objects: creating compound")) + _msg(translate("draft","Found several wires or edges: wiring them")) + else: + _msg(translate("draft","Found several non-treatable objects: creating compound")) # special case, we have only one open wire. We close it, # unless it has only 1 edge! elif len(objects) == 1 and len(openwires) == 1: diff --git a/src/Mod/Draft/draftguitools/gui_dimensions.py b/src/Mod/Draft/draftguitools/gui_dimensions.py index d091568ea8..7f9949e365 100644 --- a/src/Mod/Draft/draftguitools/gui_dimensions.py +++ b/src/Mod/Draft/draftguitools/gui_dimensions.py @@ -153,7 +153,7 @@ class Dimension(gui_base_original.Creator): if v.Point == edge.Vertexes[1].Point: v2 = i - if v1 != None and v2 != None: # note that v1 or v2 can be zero + if v1 is not None and v2 is not None: # note that v1 or v2 can be zero self.link = [sel_object.Object, v1, v2] elif DraftGeomUtils.geomType(edge) == "Circle": self.node.extend([edge.Curve.Center, diff --git a/src/Mod/Draft/draftguitools/gui_edit_draft_objects.py b/src/Mod/Draft/draftguitools/gui_edit_draft_objects.py index 228872dc47..1298265078 100644 --- a/src/Mod/Draft/draftguitools/gui_edit_draft_objects.py +++ b/src/Mod/Draft/draftguitools/gui_edit_draft_objects.py @@ -189,26 +189,27 @@ class DraftBSplineGuiTools(DraftWireGuiTools): def add_point(self, edit_command, obj, pos): """Add point to obj. """ - info, pt = edit_command.get_specific_object_info(obj,pos) + info, global_pt = edit_command.get_specific_object_info(obj,pos) + pt = edit_command.localize_vector(obj, global_pt) + if not info or (pt is None): return pts = obj.Points - if (obj.Closed == True): + if obj.Closed: curve = obj.Shape.Edges[0].Curve else: curve = obj.Shape.Curve - uNewPoint = curve.parameter(pt) - uPoints = [] - for p in obj.Points: - uPoints.append(curve.parameter(p)) + uNewPoint = curve.parameter(obj.Placement.multVec(pt)) + uPoints = curve.getKnots() + for i in range(len(uPoints) - 1): if ( uNewPoint > uPoints[i] ) and ( uNewPoint < uPoints[i+1] ): - pts.insert(i + 1, edit_command.localize_vector(obj, pt)) + pts.insert(i + 1, pt) break # DNC: fix: add points to last segment if curve is closed if obj.Closed and (uNewPoint > uPoints[-1]): - pts.append(edit_command.localize_vector(obj, pt)) + pts.append(pt) obj.Points = pts obj.recompute() @@ -455,7 +456,7 @@ class DraftCircleGuiTools(GuiTools): px = obj.Radius * math.cos(math.radians(angle)) py = obj.Radius * math.sin(math.radians(angle)) p = App.Vector(px, py, 0.0) - if global_placement == True: + if global_placement: p = obj.getGlobalPlacement().multVec(p) return p return None diff --git a/src/Mod/Draft/draftguitools/gui_hatch.py b/src/Mod/Draft/draftguitools/gui_hatch.py index 2f7f2a27a5..aa17eb07e6 100644 --- a/src/Mod/Draft/draftguitools/gui_hatch.py +++ b/src/Mod/Draft/draftguitools/gui_hatch.py @@ -106,6 +106,7 @@ class Draft_Hatch_TaskPanel: import FreeCADGui FreeCADGui.Control.closeDialog() + FreeCADGui.ActiveDocument.resetEdit() FreeCAD.ActiveDocument.recompute() def onFileChanged(self,filename): diff --git a/src/Mod/Draft/draftguitools/gui_snapper.py b/src/Mod/Draft/draftguitools/gui_snapper.py index 3bf543ffae..335ea344f3 100644 --- a/src/Mod/Draft/draftguitools/gui_snapper.py +++ b/src/Mod/Draft/draftguitools/gui_snapper.py @@ -1157,13 +1157,18 @@ class Snapper: # This should be in device-independent pixels return 32 + def get_quarter_widget(self, mw): + views = [] + for w in mw.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): + if w.inherits("SIM::Coin3D::Quarter::QuarterWidget"): + views.append(w) + return views + def device_pixel_ratio(self): device_pixel_ratio = 1 - mw = Gui.getMainWindow() - for w in mw.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): - if w.metaObject().className() == "SIM::Coin3D::Quarter::QuarterWidget": - if int(QtCore.qVersion().split('.')[0]) > 4: - device_pixel_ratio = w.devicePixelRatio() + for w in self.get_quarter_widget(Gui.getMainWindow()): + if int(QtCore.qVersion().split('.')[0]) > 4: + device_pixel_ratio = w.devicePixelRatio() return device_pixel_ratio def get_cursor_with_tail(self, base_icon_name, tail_icon_name=None): @@ -1195,16 +1200,12 @@ class Snapper: def setCursor(self, mode=None): """Set or reset the cursor to the given mode or resets.""" if self.selectMode: - mw = Gui.getMainWindow() - for w in mw.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): - if w.metaObject().className() == "SIM::Coin3D::Quarter::QuarterWidget": - w.unsetCursor() + for w in self.get_quarter_widget(Gui.getMainWindow()): + w.unsetCursor() self.cursorMode = None elif not mode: - mw = Gui.getMainWindow() - for w in mw.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): - if w.metaObject().className() == "SIM::Coin3D::Quarter::QuarterWidget": - w.unsetCursor() + for w in self.get_quarter_widget(Gui.getMainWindow()): + w.unsetCursor() self.cursorMode = None else: if mode != self.cursorMode: @@ -1213,10 +1214,8 @@ class Snapper: if not (mode == 'passive'): tail_icon_name = self.cursors[mode] cur = self.get_cursor_with_tail(base_icon_name, tail_icon_name) - mw = Gui.getMainWindow() - for w in mw.findChild(QtGui.QMdiArea).findChildren(QtGui.QWidget): - if w.metaObject().className() == "SIM::Coin3D::Quarter::QuarterWidget": - w.setCursor(cur) + for w in self.get_quarter_widget(Gui.getMainWindow()): + w.setCursor(cur) self.cursorMode = mode def restack(self): diff --git a/src/Mod/Draft/draftmake/make_bezcurve.py b/src/Mod/Draft/draftmake/make_bezcurve.py index 95eeb5e99f..ec617339ec 100644 --- a/src/Mod/Draft/draftmake/make_bezcurve.py +++ b/src/Mod/Draft/draftmake/make_bezcurve.py @@ -42,9 +42,9 @@ def make_bezcurve(pointslist, closed=False, placement=None, face=None, support=None, degree=None): """make_bezcurve(pointslist, [closed], [placement]) - + Creates a Bezier Curve object from the given list of vectors. - + Parameters ---------- pointlist : [Base.Vector] @@ -53,19 +53,19 @@ def make_bezcurve(pointslist, TODO: Change the name so! closed : bool - If closed is True or first and last points are identical, + If closed is True or first and last points are identical, the created BSpline will be closed. placement : Base.Placement If a placement is given, it is used. - - face : Bool - If face is False, the rectangle is shown as a wireframe, - otherwise as a face. - support : + face : Bool + If face is False, the rectangle is shown as a wireframe, + otherwise as a face. + + support : TODO: Describe - + degree : int Degree of the BezCurve """ @@ -92,7 +92,7 @@ def make_bezcurve(pointslist, Part.BezierCurve().MaxDegree) obj.Closed = closed obj.Support = support - if face != None: + if face is not None: obj.MakeFace = face obj.Proxy.resetcontinuity(obj) if placement: obj.Placement = placement diff --git a/src/Mod/Draft/draftmake/make_bspline.py b/src/Mod/Draft/draftmake/make_bspline.py index 4b7fe3edaa..1795978020 100644 --- a/src/Mod/Draft/draftmake/make_bspline.py +++ b/src/Mod/Draft/draftmake/make_bspline.py @@ -40,9 +40,9 @@ if App.GuiUp: def make_bspline(pointslist, closed=False, placement=None, face=None, support=None): """make_bspline(pointslist, [closed], [placement]) - + Creates a B-Spline object from the given list of vectors. - + Parameters ---------- pointlist : [Base.Vector] @@ -51,17 +51,17 @@ def make_bspline(pointslist, closed=False, placement=None, face=None, support=No TODO: Change the name so! closed : bool - If closed is True or first and last points are identical, + If closed is True or first and last points are identical, the created BSpline will be closed. placement : Base.Placement If a placement is given, it is used. - - face : Bool - If face is False, the rectangle is shown as a wireframe, - otherwise as a face. - support : + face : Bool + If face is False, the rectangle is shown as a wireframe, + otherwise as a face. + + support : TODO: Describe """ if not App.ActiveDocument: @@ -97,7 +97,7 @@ def make_bspline(pointslist, closed=False, placement=None, face=None, support=No obj.Closed = closed obj.Points = pointslist obj.Support = support - if face != None: + if face is not None: obj.MakeFace = face if placement: obj.Placement = placement if App.GuiUp: diff --git a/src/Mod/Draft/draftmake/make_circle.py b/src/Mod/Draft/draftmake/make_circle.py index 890a72c0ca..3e0a148046 100644 --- a/src/Mod/Draft/draftmake/make_circle.py +++ b/src/Mod/Draft/draftmake/make_circle.py @@ -45,29 +45,29 @@ def make_circle(radius, placement=None, face=None, startangle=None, endangle=Non """make_circle(radius, [placement, face, startangle, endangle]) or make_circle(edge,[face]): - Creates a circle object with given parameters. + Creates a circle object with given parameters. Parameters ---------- radius : the radius of the circle. - placement : - If placement is given, it is used. - + placement : + If placement is given, it is used. + face : Bool - If face is False, the circle is shown as a wireframe, - otherwise as a face. - + If face is False, the circle is shown as a wireframe, + otherwise as a face. + startangle : start angle of the arc (in degrees) endangle : end angle of the arc (in degrees) - if startangle and endangle are equal, a circle is created, + if startangle and endangle are equal, a circle is created, if they are different an arc is created edge : edge.Curve must be a 'Part.Circle' the circle is created from the given edge - support : + support : TODO: Describe """ @@ -87,7 +87,7 @@ def make_circle(radius, placement=None, face=None, startangle=None, endangle=Non Circle(obj) - if face != None: + if face is not None: obj.MakeFace = face if isinstance(radius,Part.Edge): @@ -112,14 +112,14 @@ def make_circle(radius, placement=None, face=None, startangle=None, endangle=Non obj.LastAngle = a1 else: obj.Radius = radius - if (startangle != None) and (endangle != None): + if (startangle is not None) and (endangle is not None): if startangle == -0: startangle = 0 obj.FirstAngle = startangle obj.LastAngle = endangle obj.Support = support - if placement: + if placement: obj.Placement = placement if App.GuiUp: diff --git a/src/Mod/Draft/draftmake/make_ellipse.py b/src/Mod/Draft/draftmake/make_ellipse.py index 3a277dcd38..de7206d631 100644 --- a/src/Mod/Draft/draftmake/make_ellipse.py +++ b/src/Mod/Draft/draftmake/make_ellipse.py @@ -38,26 +38,26 @@ if App.GuiUp: def make_ellipse(majradius, minradius, placement=None, face=None, support=None): """make_ellipse(majradius, minradius, [placement], [face], [support]) - + Makes an ellipse with the given major and minor radius, and optionally a placement. Parameters ---------- - majradius : + majradius : Major radius of the ellipse. - minradius : + minradius : Minor radius of the ellipse. placement : Base.Placement If a placement is given, it is used. - - face : Bool - If face is False, the rectangle is shown as a wireframe, - otherwise as a face. - support : + face : Bool + If face is False, the rectangle is shown as a wireframe, + otherwise as a face. + + support : TODO: Describe. """ @@ -74,7 +74,7 @@ def make_ellipse(majradius, minradius, placement=None, face=None, support=None): obj.MinorRadius = minradius obj.Support = support - if face != None: + if face is not None: obj.MakeFace = face if placement: diff --git a/src/Mod/Draft/draftmake/make_hatch.py b/src/Mod/Draft/draftmake/make_hatch.py index 004082dd4a..594ef25a64 100644 --- a/src/Mod/Draft/draftmake/make_hatch.py +++ b/src/Mod/Draft/draftmake/make_hatch.py @@ -44,3 +44,4 @@ def make_hatch(baseobject, filename, pattern, scale, rotation): obj.Rotation = rotation if FreeCAD.GuiUp: ViewProviderDraftHatch(obj.ViewObject) + return obj diff --git a/src/Mod/Draft/draftmake/make_point.py b/src/Mod/Draft/draftmake/make_point.py index a0a91d6cd4..843ec2297b 100644 --- a/src/Mod/Draft/draftmake/make_point.py +++ b/src/Mod/Draft/draftmake/make_point.py @@ -45,7 +45,7 @@ def make_point(X=0, Y=0, Z=0, color=None, name="Point", point_size=5): Parameters ---------- - X : + X : float -> X coordinate of the point Base.Vector -> Ignore Y and Z coordinates and create the point from the vector. @@ -59,9 +59,9 @@ def make_point(X=0, Y=0, Z=0, color=None, name="Point", point_size=5): color : (R, G, B) Point color as RGB example to create a colored point: - make_point(0,0,0,(1,0,0)) # color = red + make_point(0, 0, 0, (1, 0, 0)) # color = red example to change the color, make sure values are floats: - p1.ViewObject.PointColor =(0.0,0.0,1.0) + p1.ViewObject.PointColor = (0.0, 0.0, 1.0) """ if not App.ActiveDocument: App.Console.PrintError("No active document. Aborting\n") @@ -76,18 +76,13 @@ def make_point(X=0, Y=0, Z=0, color=None, name="Point", point_size=5): Point(obj, X, Y, Z) - # TODO: Check if this is a repetition: - obj.X = X - obj.Y = Y - obj.Z = Z - if App.GuiUp: ViewProviderPoint(obj.ViewObject) - if hasattr(Gui,"draftToolBar") and (not color): - color = Gui.draftToolBar.getDefaultColor('line') - obj.ViewObject.PointColor = (float(color[0]), float(color[1]), float(color[2])) + if hasattr(Gui,"draftToolBar") and color is None: + color = Gui.draftToolBar.getDefaultColor("line") + if color is not None: + obj.ViewObject.PointColor = (float(color[0]), float(color[1]), float(color[2])) obj.ViewObject.PointSize = point_size - obj.ViewObject.Visibility = True gui_utils.select(obj) return obj diff --git a/src/Mod/Draft/draftmake/make_polygon.py b/src/Mod/Draft/draftmake/make_polygon.py index 9e733e584c..ce75de6783 100644 --- a/src/Mod/Draft/draftmake/make_polygon.py +++ b/src/Mod/Draft/draftmake/make_polygon.py @@ -44,20 +44,20 @@ def make_polygon(nfaces, radius=1, inscribed=True, placement=None, face=None, su edges : int Number of edges of the polygon. - radius : + radius : Radius of the control circle. inscribed : bool Defines is the polygon is inscribed or not into the control circle. placement : Base.Placement - If placement is given, it is used. - + If placement is given, it is used. + face : bool - If face is True, the resulting shape is displayed as a face, + If face is True, the resulting shape is displayed as a face, otherwise as a wireframe. - - support : + + support : TODO: Describe """ if not App.ActiveDocument: @@ -68,7 +68,7 @@ def make_polygon(nfaces, radius=1, inscribed=True, placement=None, face=None, su Polygon(obj) obj.FacesNumber = nfaces obj.Radius = radius - if face != None: + if face is not None: obj.MakeFace = face if inscribed: obj.DrawMode = "inscribed" diff --git a/src/Mod/Draft/draftmake/make_rectangle.py b/src/Mod/Draft/draftmake/make_rectangle.py index b76100c9e0..38de5a843c 100644 --- a/src/Mod/Draft/draftmake/make_rectangle.py +++ b/src/Mod/Draft/draftmake/make_rectangle.py @@ -84,7 +84,7 @@ def make_rectangle(length, height=0, placement=None, face=None, support=None): obj.Height = height obj.Support = support - if face != None: + if face is not None: obj.MakeFace = face if placement: obj.Placement = placement diff --git a/src/Mod/Draft/draftmake/make_wire.py b/src/Mod/Draft/draftmake/make_wire.py index d3790f0668..de77855ab4 100644 --- a/src/Mod/Draft/draftmake/make_wire.py +++ b/src/Mod/Draft/draftmake/make_wire.py @@ -39,7 +39,7 @@ if App.GuiUp: def make_wire(pointslist, closed=False, placement=None, face=None, support=None, bs2wire=False): """make_wire(pointslist, [closed], [placement]) - + Creates a Wire object from the given list of vectors. If face is true (and wire is closed), the wire will appear filled. Instead of a pointslist, you can also pass a Part Wire. @@ -50,19 +50,19 @@ def make_wire(pointslist, closed=False, placement=None, face=None, support=None, List of points to create the polyline closed : bool - If closed is True or first and last points are identical, + If closed is True or first and last points are identical, the created polyline will be closed. placement : Base.Placement If a placement is given, it is used. - - face : Bool - If face is False, the rectangle is shown as a wireframe, - otherwise as a face. - support : + face : Bool + If face is False, the rectangle is shown as a wireframe, + otherwise as a face. + + support : TODO: Describe - + bs2wire : bool TODO: Describe """ @@ -96,16 +96,16 @@ def make_wire(pointslist, closed=False, placement=None, face=None, support=None, if len(pointslist) == 0: App.Console.PrintWarning("Draft Wire created with empty point list\n") - + if placement: utils.type_check([(placement, App.Placement)], "make_wire") ipl = placement.inverse() if not bs2wire: pointslist = [ipl.multVec(p) for p in pointslist] - if len(pointslist) == 2: + if len(pointslist) == 2: fname = "Line" - else: + else: fname = "Wire" obj = App.ActiveDocument.addObject("Part::Part2DObjectPython", fname) @@ -113,11 +113,11 @@ def make_wire(pointslist, closed=False, placement=None, face=None, support=None, obj.Points = pointslist obj.Closed = closed obj.Support = support - - if face != None: + + if face is not None: obj.MakeFace = face - if placement: + if placement: obj.Placement = placement if App.GuiUp: diff --git a/src/Mod/Draft/draftobjects/shape2dview.py b/src/Mod/Draft/draftobjects/shape2dview.py index df08c6ab34..b02f8c3370 100644 --- a/src/Mod/Draft/draftobjects/shape2dview.py +++ b/src/Mod/Draft/draftobjects/shape2dview.py @@ -116,6 +116,11 @@ class Shape2DView(DraftObject): "A list of exclusion points. Any edge touching any of those points will not be drawn.") obj.addProperty("App::PropertyVectorList", "ExclusionPoints", "Draft", _tip) + if not "ExclusionNames" in pl: + _tip = QT_TRANSLATE_NOOP("App::Property", + "A list of exclusion object names. Any object viewed that matches a name from the list will not be drawn.") + obj.addProperty("App::PropertyStringList", "ExclusionNames", + "Draft", _tip) if not "OnlySolids" in pl: _tip = QT_TRANSLATE_NOOP("App::Property", "If this is True, only solid geometry is handled. This overrides the base object's Only Solids property") @@ -183,7 +188,13 @@ class Shape2DView(DraftObject): nedges.append(e) return nedges + def excludeNames(self,obj,objs): + if hasattr(obj,"ExclusionNames"): + objs = [o for o in objs if not(o.Name in obj.ExclusionNames)] + return objs + def execute(self,obj): + if not getattr(obj,"AutoUpdate", True): return True import Part, DraftGeomUtils @@ -193,10 +204,10 @@ class Shape2DView(DraftObject): if utils.get_type(obj.Base) in ["BuildingPart","SectionPlane"]: objs = [] if utils.get_type(obj.Base) == "SectionPlane": - objs = obj.Base.Objects + objs = self.excludeNames(obj,obj.Base.Objects) cutplane = obj.Base.Shape else: - objs = obj.Base.Group + objs = self.excludeNames(obj,obj.Base.Group) cutplane = Part.makePlane(1000, 1000, App.Vector(-500, -500, 0)) m = 1 if obj.Base.ViewObject and hasattr(obj.Base.ViewObject,"CutMargin"): @@ -312,7 +323,7 @@ class Shape2DView(DraftObject): elif obj.Base.isDerivedFrom("App::DocumentObjectGroup"): shapes = [] - objs = groups.get_group_contents(obj.Base) + objs = self.excludeNames(obj,groups.get_group_contents(obj.Base)) for o in objs: if hasattr(o,'Shape'): if o.Shape: diff --git a/src/Mod/Draft/draftutils/init_draft_statusbar.py b/src/Mod/Draft/draftutils/init_draft_statusbar.py index c2cc538918..c79be417b2 100644 --- a/src/Mod/Draft/draftutils/init_draft_statusbar.py +++ b/src/Mod/Draft/draftutils/init_draft_statusbar.py @@ -179,12 +179,7 @@ def init_draft_statusbar_scale(): param = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft") mw = Gui.getMainWindow() - if mw: - sb = mw.statusBar() - if sb is None: - return - else: - return + sb = mw.statusBar() scale_widget = QtGui.QToolBar() scale_widget.setObjectName("draft_status_scale_widget") @@ -227,12 +222,7 @@ def init_draft_statusbar_snap(): param = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft") mw = Gui.getMainWindow() - if mw: - sb = mw.statusBar() - if sb is None: - return - else: - return + sb = mw.statusBar() # SNAP WIDGET - init ---------------------------------------------------- @@ -351,15 +341,11 @@ def show_draft_statusbar(): shows draft statusbar if present or initializes it """ params = App.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft") - display_statusbar = params.GetBool("DisplayStatusbar", True) - - if not display_statusbar: - return mw = Gui.getMainWindow() - if mw: - sb = mw.statusBar() + sb = mw.statusBar() + if params.GetBool("DisplayStatusbarScaleWidget", True): scale_widget = sb.findChild(QtGui.QToolBar, "draft_status_scale_widget") if scale_widget: @@ -370,10 +356,11 @@ def show_draft_statusbar(): if scale_widget: sb.insertPermanentWidget(3, scale_widget) scale_widget.show() - elif params.GetBool("DisplayStatusbarScaleWidget", True): + else: t = QtCore.QTimer() t.singleShot(500, init_draft_statusbar_scale) + if params.GetBool("DisplayStatusbarSnapWidget", True): snap_widget = sb.findChild(QtGui.QToolBar,"draft_snap_widget") if snap_widget: snap_widget.setOrientation(QtCore.Qt.Orientation.Horizontal) @@ -384,7 +371,7 @@ def show_draft_statusbar(): sb.insertPermanentWidget(2, snap_widget) snap_widget.setOrientation(QtCore.Qt.Orientation.Horizontal) snap_widget.show() - elif params.GetBool("DisplayStatusbarSnapWidget", True): + else: t = QtCore.QTimer() t.singleShot(500, init_draft_statusbar_snap) @@ -394,8 +381,6 @@ def hide_draft_statusbar(): hides draft statusbar if present """ mw = Gui.getMainWindow() - if not mw: - return sb = mw.statusBar() # hide scale widget diff --git a/src/Mod/Draft/draftutils/utils.py b/src/Mod/Draft/draftutils/utils.py index 8e8aa5890a..64a8a32921 100644 --- a/src/Mod/Draft/draftutils/utils.py +++ b/src/Mod/Draft/draftutils/utils.py @@ -391,9 +391,9 @@ def get_real_name(name): The returned string cannot be empty; it will have at least one letter. """ - for i in range(1, len(name)): + for i in range(1, len(name) + 1): if name[-i] not in '1234567890': - return name[:len(name) - (i-1)] + return name[:len(name) - (i - 1)] return name diff --git a/src/Mod/Draft/draftviewproviders/view_text.py b/src/Mod/Draft/draftviewproviders/view_text.py index 1dda2fdab9..e0fc077f53 100644 --- a/src/Mod/Draft/draftviewproviders/view_text.py +++ b/src/Mod/Draft/draftviewproviders/view_text.py @@ -221,7 +221,9 @@ class ViewProviderText(ViewProviderDraftAnnotation): def setEdit(self,vobj,mode): import FreeCADGui - self.text = '' + if not hasattr(FreeCADGui, "draftToolBar"): + import DraftGui + self.text = "" FreeCADGui.draftToolBar.sourceCmd = self FreeCADGui.draftToolBar.taskUi() FreeCADGui.draftToolBar.textUi() diff --git a/src/Mod/Draft/importAirfoilDAT.py b/src/Mod/Draft/importAirfoilDAT.py index 56603ee416..2b4738cc12 100644 --- a/src/Mod/Draft/importAirfoilDAT.py +++ b/src/Mod/Draft/importAirfoilDAT.py @@ -44,7 +44,7 @@ from FreeCAD import Console as FCC if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate else: def translate(context, txt): return txt diff --git a/src/Mod/Draft/importDWG.py b/src/Mod/Draft/importDWG.py index 23372bfee9..45bbd45d0a 100644 --- a/src/Mod/Draft/importDWG.py +++ b/src/Mod/Draft/importDWG.py @@ -49,7 +49,7 @@ import FreeCAD from FreeCAD import Console as FCC if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate else: def translate(context, txt): return txt diff --git a/src/Mod/Draft/importDXF.py b/src/Mod/Draft/importDXF.py index c6131e54f8..6d0b0887cb 100644 --- a/src/Mod/Draft/importDXF.py +++ b/src/Mod/Draft/importDXF.py @@ -72,7 +72,7 @@ if gui: draftui = FreeCADGui.draftToolBar except (AttributeError, NameError): draftui = None - from DraftTools import translate + from draftutils.translate import translate from PySide import QtGui else: def translate(context, txt): diff --git a/src/Mod/Draft/importOCA.py b/src/Mod/Draft/importOCA.py index c95b8ae117..8935aa4d16 100644 --- a/src/Mod/Draft/importOCA.py +++ b/src/Mod/Draft/importOCA.py @@ -46,7 +46,7 @@ from FreeCAD import Vector from FreeCAD import Console as FCC if FreeCAD.GuiUp: - from DraftTools import translate + from draftutils.translate import translate else: def translate(context, txt): return txt diff --git a/src/Mod/Draft/importSVG.py b/src/Mod/Draft/importSVG.py index e01dc52944..216e927663 100644 --- a/src/Mod/Draft/importSVG.py +++ b/src/Mod/Draft/importSVG.py @@ -718,7 +718,7 @@ class svgHandler(xml.sax.ContentHandler): inks_doc_name = attrs.getValue('sodipodi:docname') inks_full_ver = attrs.getValue('inkscape:version') inks_ver_pars = re.search("\d+\.\d+", inks_full_ver) - if inks_ver_pars != None: + if inks_ver_pars is not None: inks_ver_f = float(inks_ver_pars.group(0)) else: inks_ver_f = 99.99 diff --git a/src/Mod/Drawing/App/AppDrawingPy.cpp b/src/Mod/Drawing/App/AppDrawingPy.cpp index ecefd3d5a8..259ade9aea 100644 --- a/src/Mod/Drawing/App/AppDrawingPy.cpp +++ b/src/Mod/Drawing/App/AppDrawingPy.cpp @@ -59,7 +59,7 @@ namespace Drawing { string key; string value; - for (auto keyPy : sourceRange.keys()) { + for (const auto& keyPy : sourceRange.keys()) { key = Py::String(keyPy); value = Py::String(sourceRange[keyPy]); *targetIt = {key, value}; diff --git a/src/Mod/Drawing/App/CMakeLists.txt b/src/Mod/Drawing/App/CMakeLists.txt index a6e0ff1c4b..86127d38a1 100644 --- a/src/Mod/Drawing/App/CMakeLists.txt +++ b/src/Mod/Drawing/App/CMakeLists.txt @@ -10,6 +10,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Drawing/Gui/CMakeLists.txt b/src/Mod/Drawing/Gui/CMakeLists.txt index d5f90073b2..5579504cb4 100644 --- a/src/Mod/Drawing/Gui/CMakeLists.txt +++ b/src/Mod/Drawing/Gui/CMakeLists.txt @@ -13,6 +13,7 @@ include_directories( ${PYTHON_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Drawing/Gui/Command.cpp b/src/Mod/Drawing/Gui/Command.cpp index 0c1b4b2e68..9126056635 100644 --- a/src/Mod/Drawing/Gui/Command.cpp +++ b/src/Mod/Drawing/Gui/Command.cpp @@ -101,7 +101,7 @@ CmdDrawingNewPage::CmdDrawingNewPage() void CmdDrawingNewPage::activated(int iMsg) { Gui::ActionGroup* pcAction = qobject_cast(_pcAction); - QAction* a = pcAction->actions()[iMsg]; + QAction* a = qAsConst(pcAction)->actions()[iMsg]; std::string FeatName = getUniqueObjectName("Page"); @@ -164,7 +164,7 @@ Gui::Action * CmdDrawingNewPage::createAction(void) lastPaper = paper; lastId = id; - QFile file(QString::fromLatin1(":/icons/actions/drawing-%1-%2%3.svg").arg(orientation.toLower()).arg(paper).arg(id)); + QFile file(QString::fromLatin1(":/icons/actions/drawing-%1-%2%3.svg").arg(orientation.toLower(), paper).arg(id)); QAction* a = pcAction->addAction(QString()); if (file.open(QFile::ReadOnly)) { QByteArray data = file.readAll(); @@ -195,7 +195,7 @@ Gui::Action * CmdDrawingNewPage::createAction(void) pcAction->setProperty("defaultAction", QVariant(defaultId)); } else if (!pcAction->actions().isEmpty()) { - pcAction->setIcon(pcAction->actions()[0]->icon()); + pcAction->setIcon(qAsConst(pcAction)->actions()[0]->icon()); pcAction->setProperty("defaultAction", QVariant(0)); } @@ -225,28 +225,28 @@ void CmdDrawingNewPage::languageChange() if (info.isEmpty()) { (*it)->setText(QCoreApplication::translate( "Drawing_NewPage", "%1%2 %3") - .arg(paper) - .arg(id) - .arg(orientation)); + .arg(paper, + QString::number(id), + orientation)); (*it)->setToolTip(QCoreApplication::translate( "Drawing_NewPage", "Insert new %1%2 %3 drawing") - .arg(paper) - .arg(id) - .arg(orientation)); + .arg(paper, + QString::number(id), + orientation)); } else { (*it)->setText(QCoreApplication::translate( "Drawing_NewPage", "%1%2 %3 (%4)") - .arg(paper) - .arg(id) - .arg(orientation) - .arg(info)); + .arg(paper, + QString::number(id), + orientation, + info)); (*it)->setToolTip(QCoreApplication::translate( "Drawing_NewPage", "Insert new %1%2 %3 (%4) drawing") - .arg(paper) - .arg(id) - .arg(orientation) - .arg(info)); + .arg(paper, + QString::number(id), + orientation, + info)); } } } diff --git a/src/Mod/Drawing/Gui/DrawingView.cpp b/src/Mod/Drawing/Gui/DrawingView.cpp index 0799fdc002..df8b25e12f 100644 --- a/src/Mod/Drawing/Gui/DrawingView.cpp +++ b/src/Mod/Drawing/Gui/DrawingView.cpp @@ -509,7 +509,7 @@ void DrawingView::printPdf() if (dlg.exec() == QDialog::Accepted) { Gui::WaitCursor wc; - QString filename = dlg.selectedFiles().front(); + QString filename = dlg.selectedFiles().constFirst(); QPrinter printer(QPrinter::HighResolution); printer.setFullPage(true); printer.setOutputFormat(QPrinter::PdfFormat); diff --git a/src/Mod/Fem/App/AppFemPy.cpp b/src/Mod/Fem/App/AppFemPy.cpp index 241a63d2f9..937d99fb30 100644 --- a/src/Mod/Fem/App/AppFemPy.cpp +++ b/src/Mod/Fem/App/AppFemPy.cpp @@ -75,10 +75,10 @@ public: initialize("This module is the Fem module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) + Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); diff --git a/src/Mod/Fem/App/FemAnalysis.cpp b/src/Mod/Fem/App/FemAnalysis.cpp index bc2f075d6e..c795df19a7 100644 --- a/src/Mod/Fem/App/FemAnalysis.cpp +++ b/src/Mod/Fem/App/FemAnalysis.cpp @@ -67,7 +67,7 @@ PROPERTY_SOURCE_ABSTRACT(Fem::DocumentObject, App::DocumentObject) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Fem::FemAnalysisPython, Fem::FemAnalysis) -template<> const char* Fem::FemAnalysisPython::getViewProviderName(void) const { +template<> const char* Fem::FemAnalysisPython::getViewProviderName() const { return "FemGui::ViewProviderFemAnalysisPython"; } @@ -92,10 +92,10 @@ template class FemExport FeaturePythonT; namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Fem::FeaturePython, Fem::DocumentObject) -template<> const char* Fem::FeaturePython::getViewProviderName(void) const { +template<> const char* Fem::FeaturePython::getViewProviderName() const { return "Gui::ViewProviderPythonFeature"; } -template<> PyObject* Fem::FeaturePython::getPyObject(void) { +template<> PyObject* Fem::FeaturePython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new App::FeaturePythonPyT(this), true); diff --git a/src/Mod/Fem/App/FemAnalysis.h b/src/Mod/Fem/App/FemAnalysis.h index 38b012fe64..36418bede7 100644 --- a/src/Mod/Fem/App/FemAnalysis.h +++ b/src/Mod/Fem/App/FemAnalysis.h @@ -33,7 +33,7 @@ namespace Fem { /** * @brief Container of objects relevant to one simulation. - * + * * @details * A Analysis contains all objects necessary for a complete specification * of a simulation. After computing it also contains the result of the @@ -50,7 +50,7 @@ namespace Fem { * Analysis. */ class FemExport FemAnalysis : public App::DocumentObjectGroup { - PROPERTY_HEADER(Fem::FemAnalysis); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemAnalysis); public: /** @@ -58,7 +58,7 @@ public: * unique id because PropertyUUID doesn't initialize itself. */ FemAnalysis(); - virtual ~FemAnalysis(); + ~FemAnalysis() override; /** * A unique identifier for each Analysis object. Useful when doing @@ -68,7 +68,7 @@ public: */ App::PropertyUUID Uid; - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemAnalysis"; } @@ -82,13 +82,13 @@ protected: * property of DocumentObjectGroup. This methods translates old files * still using the "Member" property. */ - virtual void handleChangedPropertyName( - Base::XMLReader &reader, const char * TypeName, const char *PropName); + void handleChangedPropertyName( + Base::XMLReader &reader, const char * TypeName, const char *PropName) override; }; class FemExport DocumentObject : public App::DocumentObject { - PROPERTY_HEADER(Fem::DocumentObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::DocumentObject); }; typedef App::FeaturePythonT FemAnalysisPython; diff --git a/src/Mod/Fem/App/FemConstraint.cpp b/src/Mod/Fem/App/FemConstraint.cpp index 7b796696e3..d6f10a2dc5 100644 --- a/src/Mod/Fem/App/FemConstraint.cpp +++ b/src/Mod/Fem/App/FemConstraint.cpp @@ -81,9 +81,9 @@ PROPERTY_SOURCE(Fem::Constraint, App::DocumentObject) Constraint::Constraint() { - ADD_PROPERTY_TYPE(References,(nullptr,nullptr),"Constraint",(App::PropertyType)(App::Prop_None),"Elements where the constraint is applied"); - ADD_PROPERTY_TYPE(NormalDirection,(Base::Vector3d(0,0,1)),"Constraint",App::PropertyType(App::Prop_ReadOnly|App::Prop_Output),"Normal direction pointing outside of solid"); - ADD_PROPERTY_TYPE(Scale,(1),"Base",App::PropertyType(App::Prop_Output),"Scale used for drawing constraints"); //OvG: Add scale parameter inherited by all derived constraints + ADD_PROPERTY_TYPE(References, (nullptr, nullptr), "Constraint", (App::PropertyType)(App::Prop_None), "Elements where the constraint is applied"); + ADD_PROPERTY_TYPE(NormalDirection, (Base::Vector3d(0, 0, 1)), "Constraint", App::PropertyType(App::Prop_ReadOnly | App::Prop_Output), "Normal direction pointing outside of solid"); + ADD_PROPERTY_TYPE(Scale, (1), "Base", App::PropertyType(App::Prop_Output), "Scale used for drawing constraints"); //OvG: Add scale parameter inherited by all derived constraints References.setScope(App::LinkScope::Global); } @@ -92,7 +92,7 @@ Constraint::~Constraint() { } -App::DocumentObjectExecReturn *Constraint::execute(void) +App::DocumentObjectExecReturn *Constraint::execute() { try { References.touch(); @@ -146,9 +146,9 @@ void Constraint::onChanged(const App::Property* prop) BRepGProp_Face props(face); gp_Vec normal; gp_Pnt center; - double u1,u2,v1,v2; - props.Bounds(u1,u2,v1,v2); - props.Normal((u1+u2)/2.0,(v1+v2)/2.0,center,normal); + double u1, u2, v1, v2; + props.Bounds(u1, u2, v1, v2); + props.Normal((u1+u2)/2.0, (v1+v2)/2.0, center, normal); normal.Normalize(); NormalDirection.setValue(normal.X(), normal.Y(), normal.Z()); // One face is enough... @@ -298,8 +298,8 @@ bool Constraint::getPoints(std::vector &points, std::vector= 30) //OvG: Increase 10 units distance proportionately to lv for larger objects. { - *scale = this->calcDrawScaleFactor(lv,lu); //OvG: setup draw scale for constraint - stepsv = (int)round(lv / (10*( *scale))); + *scale = this->calcDrawScaleFactor(lv, lu); //OvG: setup draw scale for constraint + stepsv = (int)round(lv / (10 * (*scale))); stepsv = stepsv<3?3:stepsv; } else if (lv >= 20.0) @@ -391,7 +391,7 @@ Base::Vector3d Constraint::getBasePoint(const Base::Vector3d& base, const Base:: // Get the point specified by Location and Distance App::DocumentObject* objLoc = location.getValue(); std::vector names = location.getSubValues(); - if (names.size() == 0) + if (names.empty()) return Base::Vector3d(0,0,0); std::string subName = names.front(); Part::Feature* featLoc = static_cast(objLoc); @@ -458,7 +458,7 @@ const Base::Vector3d Constraint::getDirection(const App::PropertyLinkSub &direct } std::vector names = direction.getSubValues(); - if (names.size() == 0) + if (names.empty()) return Base::Vector3d(0,0,0); std::string subName = names.front(); Part::Feature* feat = static_cast(obj); @@ -483,11 +483,11 @@ const Base::Vector3d Constraint::getDirection(const App::PropertyLinkSub &direct namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Fem::ConstraintPython, Fem::Constraint) -template<> const char* Fem::ConstraintPython::getViewProviderName(void) const { +template<> const char* Fem::ConstraintPython::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintPython"; } -template<> PyObject* Fem::ConstraintPython::getPyObject(void) { +template<> PyObject* Fem::ConstraintPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new App::FeaturePythonPyT(this),true); diff --git a/src/Mod/Fem/App/FemConstraint.h b/src/Mod/Fem/App/FemConstraint.h index bcbc58444b..c0903a65f2 100644 --- a/src/Mod/Fem/App/FemConstraint.h +++ b/src/Mod/Fem/App/FemConstraint.h @@ -57,11 +57,11 @@ namespace Fem { * scale&). */ class FemExport Constraint : public App::DocumentObject { - PROPERTY_HEADER(Fem::Constraint); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::Constraint); public: Constraint(); - virtual ~Constraint(); + ~Constraint() override; /** * @brief List of objects the constraints applies to. @@ -113,7 +113,7 @@ public: * cleared right after the @ref execute call by the recompute mechanism. * See Document::recompute() and DocumentObject::purgeTouched(). */ - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /** * @brief Calculates scale factor based on length of edge. @@ -154,7 +154,7 @@ public: */ int calcDrawScaleFactor() const; - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraint"; } @@ -163,7 +163,7 @@ protected: /** * @brief Updates NormalDirection if References change. */ - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; /** * @brief Triggers @ref onChanged to update View Provider. @@ -172,7 +172,7 @@ protected: * This should not be necessary and is properly a bug in the View Provider * of FemConstraint. */ - virtual void onDocumentRestored(); + void onDocumentRestored() override; /** * @brief Returns data based on References relevant for rendering widgets. diff --git a/src/Mod/Fem/App/FemConstraintBearing.cpp b/src/Mod/Fem/App/FemConstraintBearing.cpp index 2ca239ff1b..9cf7cf63ed 100644 --- a/src/Mod/Fem/App/FemConstraintBearing.cpp +++ b/src/Mod/Fem/App/FemConstraintBearing.cpp @@ -57,7 +57,7 @@ ConstraintBearing::ConstraintBearing() "Axis of bearing seat"); } -App::DocumentObjectExecReturn *ConstraintBearing::execute(void) +App::DocumentObjectExecReturn *ConstraintBearing::execute() { return Constraint::execute(); } @@ -80,7 +80,7 @@ void ConstraintBearing::onChanged(const App::Property* prop) Height.setValue(height); // Update base point base = base + axis * height/2; - if (Location.getValue() != nullptr) { + if (Location.getValue()) { base = getBasePoint(base, axis, Location, Dist.getValue()); } BasePoint.setValue(base); @@ -88,7 +88,7 @@ void ConstraintBearing::onChanged(const App::Property* prop) } else if ((prop == &Location) || (prop == &Dist)) { App::DocumentObject* obj = Location.getValue(); std::vector names = Location.getSubValues(); - if (names.size() == 0) { + if (names.empty()) { return; } std::string subName = names.front(); diff --git a/src/Mod/Fem/App/FemConstraintBearing.h b/src/Mod/Fem/App/FemConstraintBearing.h index ab027b9dfa..62a3ef8d3d 100644 --- a/src/Mod/Fem/App/FemConstraintBearing.h +++ b/src/Mod/Fem/App/FemConstraintBearing.h @@ -36,11 +36,11 @@ namespace Fem class FemExport ConstraintBearing : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintBearing); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintBearing); public: /// Constructor - ConstraintBearing(void); + ConstraintBearing(); /// Location reference App::PropertyLinkSub Location; @@ -55,15 +55,15 @@ public: App::PropertyVector Axis; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraintBearing"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } //namespace Fem diff --git a/src/Mod/Fem/App/FemConstraintContact.cpp b/src/Mod/Fem/App/FemConstraintContact.cpp index 390f09efc4..d368ef24d9 100644 --- a/src/Mod/Fem/App/FemConstraintContact.cpp +++ b/src/Mod/Fem/App/FemConstraintContact.cpp @@ -55,12 +55,12 @@ ConstraintContact::ConstraintContact() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintContact::execute(void) +App::DocumentObjectExecReturn *ConstraintContact::execute() { return Constraint::execute(); } -const char* ConstraintContact::getViewProviderName(void) const +const char* ConstraintContact::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintContact"; } diff --git a/src/Mod/Fem/App/FemConstraintContact.h b/src/Mod/Fem/App/FemConstraintContact.h index a4ba7f92bd..1c48949f64 100644 --- a/src/Mod/Fem/App/FemConstraintContact.h +++ b/src/Mod/Fem/App/FemConstraintContact.h @@ -32,11 +32,11 @@ namespace Fem class FemExport ConstraintContact : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintContact); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintContact); public: /// Constructor - ConstraintContact(void); + ConstraintContact(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyVectorList Points; @@ -57,13 +57,13 @@ public: /* */ /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintDisplacement.cpp b/src/Mod/Fem/App/FemConstraintDisplacement.cpp index 6a50add28c..e7da523dfe 100644 --- a/src/Mod/Fem/App/FemConstraintDisplacement.cpp +++ b/src/Mod/Fem/App/FemConstraintDisplacement.cpp @@ -88,12 +88,12 @@ ConstraintDisplacement::ConstraintDisplacement() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintDisplacement::execute(void) +App::DocumentObjectExecReturn *ConstraintDisplacement::execute() { return Constraint::execute(); } -const char* ConstraintDisplacement::getViewProviderName(void) const +const char* ConstraintDisplacement::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintDisplacement"; } diff --git a/src/Mod/Fem/App/FemConstraintDisplacement.h b/src/Mod/Fem/App/FemConstraintDisplacement.h index 2ebae5030f..9e6958ebd8 100644 --- a/src/Mod/Fem/App/FemConstraintDisplacement.h +++ b/src/Mod/Fem/App/FemConstraintDisplacement.h @@ -34,11 +34,11 @@ namespace Fem class FemExport ConstraintDisplacement : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintDisplacement); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintDisplacement); public: /// Constructor - ConstraintDisplacement(void); + ConstraintDisplacement(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyVectorList Points; @@ -66,13 +66,13 @@ public: //App::PropertyBool element; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintFixed.cpp b/src/Mod/Fem/App/FemConstraintFixed.cpp index 5b8874ec90..30bf786c05 100644 --- a/src/Mod/Fem/App/FemConstraintFixed.cpp +++ b/src/Mod/Fem/App/FemConstraintFixed.cpp @@ -60,7 +60,7 @@ ConstraintFixed::ConstraintFixed() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintFixed::execute(void) +App::DocumentObjectExecReturn *ConstraintFixed::execute() { return Constraint::execute(); } diff --git a/src/Mod/Fem/App/FemConstraintFixed.h b/src/Mod/Fem/App/FemConstraintFixed.h index 7731f1a9aa..40fdb31c46 100644 --- a/src/Mod/Fem/App/FemConstraintFixed.h +++ b/src/Mod/Fem/App/FemConstraintFixed.h @@ -35,26 +35,26 @@ namespace Fem class FemExport ConstraintFixed : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintFixed); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintFixed); public: /// Constructor - ConstraintFixed(void); + ConstraintFixed(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyVectorList Points; App::PropertyVectorList Normals; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraintFixed"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } //namespace Fem diff --git a/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp b/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp index dd323516bb..3b3644b280 100644 --- a/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/App/FemConstraintFluidBoundary.cpp @@ -113,7 +113,7 @@ ConstraintFluidBoundary::ConstraintFluidBoundary() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintFluidBoundary::execute(void) +App::DocumentObjectExecReturn *ConstraintFluidBoundary::execute() { return Constraint::execute(); } @@ -182,7 +182,7 @@ void ConstraintFluidBoundary::onChanged(const App::Property* prop) } } else if (prop == &NormalDirection) { // Set a default direction if no direction reference has been given - if (Direction.getValue() == nullptr) { + if (!Direction.getValue()) { Base::Vector3d direction = NormalDirection.getValue(); if (Reversed.getValue()) direction = -direction; diff --git a/src/Mod/Fem/App/FemConstraintFluidBoundary.h b/src/Mod/Fem/App/FemConstraintFluidBoundary.h index 531c6384d5..4ffcb85ff1 100644 --- a/src/Mod/Fem/App/FemConstraintFluidBoundary.h +++ b/src/Mod/Fem/App/FemConstraintFluidBoundary.h @@ -37,11 +37,11 @@ namespace Fem class FemExport ConstraintFluidBoundary: public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintFluidBoundary); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintFluidBoundary); public: /// Constructor - ConstraintFluidBoundary(void); + ConstraintFluidBoundary(); // App::PropertyEnumeration BoundaryType; App::PropertyEnumeration Subtype; @@ -64,15 +64,15 @@ public: App::PropertyVector DirectionVector; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraintFluidBoundary"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: Base::Vector3d naturalDirectionVector; diff --git a/src/Mod/Fem/App/FemConstraintForce.cpp b/src/Mod/Fem/App/FemConstraintForce.cpp index 77ef50d9de..2a14d6d1ae 100644 --- a/src/Mod/Fem/App/FemConstraintForce.cpp +++ b/src/Mod/Fem/App/FemConstraintForce.cpp @@ -57,7 +57,7 @@ ConstraintForce::ConstraintForce() Points.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintForce::execute(void) +App::DocumentObjectExecReturn *ConstraintForce::execute() { return Constraint::execute(); } @@ -99,7 +99,7 @@ void ConstraintForce::onChanged(const App::Property* prop) } } else if (prop == &NormalDirection) { // Set a default direction if no direction reference has been given - if (Direction.getValue() == nullptr) { + if (!Direction.getValue()) { Base::Vector3d direction = NormalDirection.getValue(); if (Reversed.getValue()) direction = -direction; diff --git a/src/Mod/Fem/App/FemConstraintForce.h b/src/Mod/Fem/App/FemConstraintForce.h index b263676c11..cc3ee43818 100644 --- a/src/Mod/Fem/App/FemConstraintForce.h +++ b/src/Mod/Fem/App/FemConstraintForce.h @@ -36,11 +36,11 @@ namespace Fem class FemExport ConstraintForce : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintForce); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintForce); public: /// Constructor - ConstraintForce(void); + ConstraintForce(); App::PropertyFloat Force; App::PropertyLinkSub Direction; @@ -50,15 +50,15 @@ public: App::PropertyVector DirectionVector; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraintForce"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: Base::Vector3d naturalDirectionVector; diff --git a/src/Mod/Fem/App/FemConstraintGear.cpp b/src/Mod/Fem/App/FemConstraintGear.cpp index 10c1559323..df15ad06a5 100644 --- a/src/Mod/Fem/App/FemConstraintGear.cpp +++ b/src/Mod/Fem/App/FemConstraintGear.cpp @@ -56,7 +56,7 @@ ConstraintGear::ConstraintGear() naturalDirectionVector = Base::Vector3d(1,1,1).Normalize(); } -App::DocumentObjectExecReturn *ConstraintGear::execute(void) +App::DocumentObjectExecReturn *ConstraintGear::execute() { return ConstraintBearing::execute(); } diff --git a/src/Mod/Fem/App/FemConstraintGear.h b/src/Mod/Fem/App/FemConstraintGear.h index 27f186bf1a..59b03497c6 100644 --- a/src/Mod/Fem/App/FemConstraintGear.h +++ b/src/Mod/Fem/App/FemConstraintGear.h @@ -36,11 +36,11 @@ namespace Fem class FemExport ConstraintGear : public Fem::ConstraintBearing { - PROPERTY_HEADER(Fem::ConstraintGear); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintGear); public: /// Constructor - ConstraintGear(void); + ConstraintGear(); App::PropertyFloat Diameter; App::PropertyFloat Force; @@ -51,15 +51,15 @@ public: App::PropertyVector DirectionVector; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraintGear"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: Base::Vector3d naturalDirectionVector; diff --git a/src/Mod/Fem/App/FemConstraintHeatflux.cpp b/src/Mod/Fem/App/FemConstraintHeatflux.cpp index c9e7847664..3a652c979f 100644 --- a/src/Mod/Fem/App/FemConstraintHeatflux.cpp +++ b/src/Mod/Fem/App/FemConstraintHeatflux.cpp @@ -61,12 +61,12 @@ ConstraintHeatflux::ConstraintHeatflux() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintHeatflux::execute(void) +App::DocumentObjectExecReturn *ConstraintHeatflux::execute() { return Constraint::execute(); } -const char* ConstraintHeatflux::getViewProviderName(void) const +const char* ConstraintHeatflux::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintHeatflux"; } diff --git a/src/Mod/Fem/App/FemConstraintHeatflux.h b/src/Mod/Fem/App/FemConstraintHeatflux.h index 33f1a4485c..1031bd94c0 100644 --- a/src/Mod/Fem/App/FemConstraintHeatflux.h +++ b/src/Mod/Fem/App/FemConstraintHeatflux.h @@ -33,10 +33,10 @@ namespace Fem { class FemExport ConstraintHeatflux : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintHeatflux); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintHeatflux); public: - ConstraintHeatflux(void); + ConstraintHeatflux(); App::PropertyFloat AmbientTemp; /*App::PropertyFloat FaceTemp;*/ @@ -48,13 +48,13 @@ public: App::PropertyVectorList Normals; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } diff --git a/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp b/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp index ace92e2061..81e024839b 100644 --- a/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp +++ b/src/Mod/Fem/App/FemConstraintInitialTemperature.cpp @@ -57,12 +57,12 @@ ConstraintInitialTemperature::ConstraintInitialTemperature() References.setStatus(App::Property::Hidden, true); } -App::DocumentObjectExecReturn *ConstraintInitialTemperature::execute(void) +App::DocumentObjectExecReturn *ConstraintInitialTemperature::execute() { return Constraint::execute(); } -const char* ConstraintInitialTemperature::getViewProviderName(void) const +const char* ConstraintInitialTemperature::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintInitialTemperature"; } diff --git a/src/Mod/Fem/App/FemConstraintInitialTemperature.h b/src/Mod/Fem/App/FemConstraintInitialTemperature.h index c594490c24..6cd0414b67 100644 --- a/src/Mod/Fem/App/FemConstraintInitialTemperature.h +++ b/src/Mod/Fem/App/FemConstraintInitialTemperature.h @@ -34,11 +34,11 @@ namespace Fem class FemExport ConstraintInitialTemperature : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintInitialTemperature); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintInitialTemperature); public: /// Constructor - ConstraintInitialTemperature(void); + ConstraintInitialTemperature(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyVectorList Points; @@ -49,13 +49,13 @@ public: /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintPlaneRotation.cpp b/src/Mod/Fem/App/FemConstraintPlaneRotation.cpp index 2831840141..58b03ebdb5 100644 --- a/src/Mod/Fem/App/FemConstraintPlaneRotation.cpp +++ b/src/Mod/Fem/App/FemConstraintPlaneRotation.cpp @@ -51,12 +51,12 @@ ConstraintPlaneRotation::ConstraintPlaneRotation() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintPlaneRotation::execute(void) +App::DocumentObjectExecReturn *ConstraintPlaneRotation::execute() { return Constraint::execute(); } -const char* ConstraintPlaneRotation::getViewProviderName(void) const +const char* ConstraintPlaneRotation::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintPlaneRotation"; } diff --git a/src/Mod/Fem/App/FemConstraintPlaneRotation.h b/src/Mod/Fem/App/FemConstraintPlaneRotation.h index 15c8e851a1..04be57401f 100644 --- a/src/Mod/Fem/App/FemConstraintPlaneRotation.h +++ b/src/Mod/Fem/App/FemConstraintPlaneRotation.h @@ -32,11 +32,11 @@ namespace Fem class FemExport ConstraintPlaneRotation : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintPlaneRotation); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintPlaneRotation); public: /// Constructor - ConstraintPlaneRotation(void); + ConstraintPlaneRotation(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyVectorList Points; @@ -44,13 +44,13 @@ public: /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintPressure.cpp b/src/Mod/Fem/App/FemConstraintPressure.cpp index 75365ba960..85e095ce02 100644 --- a/src/Mod/Fem/App/FemConstraintPressure.cpp +++ b/src/Mod/Fem/App/FemConstraintPressure.cpp @@ -53,12 +53,12 @@ ConstraintPressure::ConstraintPressure() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintPressure::execute(void) +App::DocumentObjectExecReturn *ConstraintPressure::execute() { return Constraint::execute(); } -const char* ConstraintPressure::getViewProviderName(void) const +const char* ConstraintPressure::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintPressure"; } diff --git a/src/Mod/Fem/App/FemConstraintPressure.h b/src/Mod/Fem/App/FemConstraintPressure.h index e25b36cf54..e0773f072b 100644 --- a/src/Mod/Fem/App/FemConstraintPressure.h +++ b/src/Mod/Fem/App/FemConstraintPressure.h @@ -31,10 +31,10 @@ namespace Fem { class FemExport ConstraintPressure : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintPressure); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintPressure); public: - ConstraintPressure(void); + ConstraintPressure(); App::PropertyFloat Pressure; App::PropertyBool Reversed; @@ -42,13 +42,13 @@ public: App::PropertyVectorList Normals; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } diff --git a/src/Mod/Fem/App/FemConstraintPulley.cpp b/src/Mod/Fem/App/FemConstraintPulley.cpp index 634857523b..d6e394b41a 100644 --- a/src/Mod/Fem/App/FemConstraintPulley.cpp +++ b/src/Mod/Fem/App/FemConstraintPulley.cpp @@ -56,15 +56,15 @@ ConstraintPulley::ConstraintPulley() "First belt force"); ADD_PROPERTY_TYPE(BeltForce2,(0.0),"ConstraintPulley",App::PropertyType(App::Prop_ReadOnly|App::Prop_Output), "Second belt force"); - ForceAngle.setValue(00.0); + ForceAngle.setValue(0.0); Diameter.setValue(300.0); // calculate initial values of read-only properties onChanged(&Force); } -App::DocumentObjectExecReturn *ConstraintPulley::execute(void) +App::DocumentObjectExecReturn *ConstraintPulley::execute() { - return ConstraintBearing::execute(); + return ConstraintGear::execute(); } void ConstraintPulley::onChanged(const App::Property* prop) diff --git a/src/Mod/Fem/App/FemConstraintPulley.h b/src/Mod/Fem/App/FemConstraintPulley.h index 9d37df73ac..8ae2f331f1 100644 --- a/src/Mod/Fem/App/FemConstraintPulley.h +++ b/src/Mod/Fem/App/FemConstraintPulley.h @@ -35,11 +35,11 @@ namespace Fem class FemExport ConstraintPulley : public Fem::ConstraintGear { - PROPERTY_HEADER(Fem::ConstraintPulley); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintPulley); public: /// Constructor - ConstraintPulley(void); + ConstraintPulley(); /// Other pulley diameter App::PropertyFloat OtherDiameter; @@ -55,15 +55,15 @@ public: App::PropertyFloat BeltForce2; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemConstraintPulley"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintSpring.cpp b/src/Mod/Fem/App/FemConstraintSpring.cpp index 20ffe69338..b70a8a4c07 100644 --- a/src/Mod/Fem/App/FemConstraintSpring.cpp +++ b/src/Mod/Fem/App/FemConstraintSpring.cpp @@ -53,12 +53,12 @@ ConstraintSpring::ConstraintSpring() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintSpring::execute(void) +App::DocumentObjectExecReturn *ConstraintSpring::execute() { return Constraint::execute(); } -const char* ConstraintSpring::getViewProviderName(void) const +const char* ConstraintSpring::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintSpring"; } diff --git a/src/Mod/Fem/App/FemConstraintSpring.h b/src/Mod/Fem/App/FemConstraintSpring.h index 0a743091bb..36d0fd8344 100644 --- a/src/Mod/Fem/App/FemConstraintSpring.h +++ b/src/Mod/Fem/App/FemConstraintSpring.h @@ -31,10 +31,10 @@ namespace Fem { class FemExport ConstraintSpring : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintSpring); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintSpring); public: - ConstraintSpring(void); + ConstraintSpring(); App::PropertyFloat normalStiffness; App::PropertyFloat tangentialStiffness; @@ -42,13 +42,13 @@ public: App::PropertyVectorList Normals; /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } diff --git a/src/Mod/Fem/App/FemConstraintTemperature.cpp b/src/Mod/Fem/App/FemConstraintTemperature.cpp index ff3afc7360..ba51f39d55 100644 --- a/src/Mod/Fem/App/FemConstraintTemperature.cpp +++ b/src/Mod/Fem/App/FemConstraintTemperature.cpp @@ -60,12 +60,12 @@ ConstraintTemperature::ConstraintTemperature() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintTemperature::execute(void) +App::DocumentObjectExecReturn *ConstraintTemperature::execute() { return Constraint::execute(); } -const char* ConstraintTemperature::getViewProviderName(void) const +const char* ConstraintTemperature::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintTemperature"; } diff --git a/src/Mod/Fem/App/FemConstraintTemperature.h b/src/Mod/Fem/App/FemConstraintTemperature.h index 078d514490..38d58c0a37 100644 --- a/src/Mod/Fem/App/FemConstraintTemperature.h +++ b/src/Mod/Fem/App/FemConstraintTemperature.h @@ -34,11 +34,11 @@ namespace Fem class FemExport ConstraintTemperature : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintTemperature); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintTemperature); public: /// Constructor - ConstraintTemperature(void); + ConstraintTemperature(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyVectorList Points; @@ -51,13 +51,13 @@ public: /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemConstraintTransform.cpp b/src/Mod/Fem/App/FemConstraintTransform.cpp index dc7d06b2f1..210bbc3205 100644 --- a/src/Mod/Fem/App/FemConstraintTransform.cpp +++ b/src/Mod/Fem/App/FemConstraintTransform.cpp @@ -64,12 +64,12 @@ ConstraintTransform::ConstraintTransform() Normals.setValues(std::vector()); } -App::DocumentObjectExecReturn *ConstraintTransform::execute(void) +App::DocumentObjectExecReturn *ConstraintTransform::execute() { return Constraint::execute(); } -const char* ConstraintTransform::getViewProviderName(void) const +const char* ConstraintTransform::getViewProviderName() const { return "FemGui::ViewProviderFemConstraintTransform"; } diff --git a/src/Mod/Fem/App/FemConstraintTransform.h b/src/Mod/Fem/App/FemConstraintTransform.h index a93dc363d2..2449b7624a 100644 --- a/src/Mod/Fem/App/FemConstraintTransform.h +++ b/src/Mod/Fem/App/FemConstraintTransform.h @@ -31,11 +31,11 @@ namespace Fem class FemExport ConstraintTransform : public Fem::Constraint { - PROPERTY_HEADER(Fem::ConstraintTransform); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::ConstraintTransform); public: /// Constructor - ConstraintTransform(void); + ConstraintTransform(); // Read-only (calculated values). These trigger changes in the ViewProvider App::PropertyLinkSubList RefDispl; @@ -52,13 +52,13 @@ public: /* */ /// recalculate the object - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const; + const char* getViewProviderName() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; diff --git a/src/Mod/Fem/App/FemMesh.cpp b/src/Mod/Fem/App/FemMesh.cpp index 1995291c55..3614d3cd1e 100644 --- a/src/Mod/Fem/App/FemMesh.cpp +++ b/src/Mod/Fem/App/FemMesh.cpp @@ -1055,7 +1055,7 @@ std::list FemMesh::getElementNodes(int id) const return result; } -std::set FemMesh::getEdgesOnly(void) const +std::set FemMesh::getEdgesOnly() const { std::set resultIDs; @@ -1092,7 +1092,7 @@ std::set FemMesh::getEdgesOnly(void) const return resultIDs; } -std::set FemMesh::getFacesOnly(void) const +std::set FemMesh::getFacesOnly() const { // How it works ATM: // for each face @@ -1169,7 +1169,7 @@ protected: typedef std::shared_ptr NastranElementPtr; class GRIDElement : public NastranElement { - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddNodeWithID(node.x, node.y, node.z, element_id); } @@ -1178,7 +1178,7 @@ protected: }; class GRIDFreeFieldElement : public GRIDElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { char_separator sep(","); tokenizer > tokens(str, sep); std::vector token_results; @@ -1194,7 +1194,7 @@ class GRIDFreeFieldElement : public GRIDElement { }; class GRIDLongFieldElement : public GRIDElement { - void read(const std::string& str1, const std::string& str2) { + void read(const std::string& str1, const std::string& str2) override { element_id = atoi(str1.substr(8,24).c_str()); node.x = atof(str1.substr(40,56).c_str()); node.y = atof(str1.substr(56,72).c_str()); @@ -1203,13 +1203,13 @@ class GRIDLongFieldElement : public GRIDElement { }; class GRIDSmallFieldElement : public GRIDElement { - void read(const std::string&, const std::string&) { + void read(const std::string&, const std::string&) override { } }; class CTRIA3Element : public NastranElement { public: - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { const SMDS_MeshNode* n0 = meshds->FindNode(elements[0]); const SMDS_MeshNode* n1 = meshds->FindNode(elements[1]); const SMDS_MeshNode* n2 = meshds->FindNode(elements[2]); @@ -1232,7 +1232,7 @@ public: class CTRIA3FreeFieldElement : public CTRIA3Element { public: - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { char_separator sep(","); tokenizer > tokens(str, sep); std::vector token_results; @@ -1249,7 +1249,7 @@ public: class CTRIA3LongFieldElement : public CTRIA3Element { public: - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24,32).c_str())); elements.push_back(atoi(str.substr(32,40).c_str())); @@ -1259,13 +1259,13 @@ public: class CTRIA3SmallFieldElement : public CTRIA3Element { public: - void read(const std::string&, const std::string&) { + void read(const std::string&, const std::string&) override { } }; class CTETRAElement : public NastranElement { public: - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { const SMDS_MeshNode* n0 = meshds->FindNode(elements[1]); const SMDS_MeshNode* n1 = meshds->FindNode(elements[0]); const SMDS_MeshNode* n2 = meshds->FindNode(elements[2]); @@ -1302,7 +1302,7 @@ public: class CTETRAFreeFieldElement : public CTETRAElement { public: - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { char_separator sep(","); tokenizer > tokens(str, sep); std::vector token_results; @@ -1326,7 +1326,7 @@ public: class CTETRALongFieldElement : public CTETRAElement { public: - void read(const std::string& str1, const std::string& str2) { + void read(const std::string& str1, const std::string& str2) override { int id = atoi(str1.substr(8,16).c_str()); int offset = 0; @@ -1355,14 +1355,14 @@ public: class CTETRASmallFieldElement : public CTETRAElement { public: - void read(const std::string&, const std::string&) { + void read(const std::string&, const std::string&) override { } }; // NASTRAN-95 class GRIDNastran95Element : public GRIDElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8, 16).c_str()); node.x = atof(str.substr(24, 32).c_str()); node.y = atof(str.substr(32, 40).c_str()); @@ -1371,12 +1371,12 @@ class GRIDNastran95Element : public GRIDElement { }; class CBARElement : public NastranElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24,32).c_str())); elements.push_back(atoi(str.substr(32,40).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddEdgeWithID( elements[0], elements[1], @@ -1386,13 +1386,13 @@ class CBARElement : public NastranElement { }; class CTRMEMElement : public NastranElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24,32).c_str())); elements.push_back(atoi(str.substr(32,40).c_str())); elements.push_back(atoi(str.substr(40,48).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddFaceWithID( elements[0], elements[1], @@ -1403,13 +1403,13 @@ class CTRMEMElement : public NastranElement { }; class CTRIA1Element : public NastranElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24, 32).c_str())); elements.push_back(atoi(str.substr(32, 40).c_str())); elements.push_back(atoi(str.substr(40, 48).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddFaceWithID( elements[0], elements[1], @@ -1420,14 +1420,14 @@ class CTRIA1Element : public NastranElement { }; class CQUAD1Element : public NastranElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24, 32).c_str())); elements.push_back(atoi(str.substr(32, 40).c_str())); elements.push_back(atoi(str.substr(40, 48).c_str())); elements.push_back(atoi(str.substr(48, 56).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddFaceWithID( elements[0], elements[1], @@ -1439,14 +1439,14 @@ class CQUAD1Element : public NastranElement { }; class CTETRANastran95Element : public NastranElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24, 32).c_str())); elements.push_back(atoi(str.substr(32, 40).c_str())); elements.push_back(atoi(str.substr(40, 48).c_str())); elements.push_back(atoi(str.substr(48, 56).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddFaceWithID( elements[0], elements[1], @@ -1458,7 +1458,7 @@ class CTETRANastran95Element : public NastranElement { }; class CWEDGEElement : public NastranElement { - void read(const std::string& str, const std::string&) { + void read(const std::string& str, const std::string&) override { element_id = atoi(str.substr(8,16).c_str()); elements.push_back(atoi(str.substr(24,32).c_str())); elements.push_back(atoi(str.substr(32,40).c_str())); @@ -1467,7 +1467,7 @@ class CWEDGEElement : public NastranElement { elements.push_back(atoi(str.substr(56,64).c_str())); elements.push_back(atoi(str.substr(64,72).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddVolumeWithID( elements[0], elements[1], @@ -1481,7 +1481,7 @@ class CWEDGEElement : public NastranElement { }; class CHEXA1Element : public NastranElement { - void read(const std::string& str1, const std::string& str2) { + void read(const std::string& str1, const std::string& str2) override { element_id = atoi(str1.substr(8,16).c_str()); elements.push_back(atoi(str1.substr(24,32).c_str())); elements.push_back(atoi(str1.substr(32,40).c_str())); @@ -1493,7 +1493,7 @@ class CHEXA1Element : public NastranElement { elements.push_back(atoi(str2.substr(8,16).c_str())); elements.push_back(atoi(str2.substr(16,24).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddVolumeWithID( elements[0], elements[1], @@ -1509,7 +1509,7 @@ class CHEXA1Element : public NastranElement { }; class CHEXA2Element : public NastranElement { - void read(const std::string& str1, const std::string& str2) { + void read(const std::string& str1, const std::string& str2) override { element_id = atoi(str1.substr(8,16).c_str()); elements.push_back(atoi(str1.substr(24,32).c_str())); elements.push_back(atoi(str1.substr(32,40).c_str())); @@ -1521,7 +1521,7 @@ class CHEXA2Element : public NastranElement { elements.push_back(atoi(str2.substr(8,16).c_str())); elements.push_back(atoi(str2.substr(16,24).c_str())); } - void addToMesh(SMESHDS_Mesh* meshds) { + void addToMesh(SMESHDS_Mesh* meshds) override { meshds->AddVolumeWithID( elements[0], elements[1], @@ -1545,8 +1545,9 @@ void FemMesh::readNastran(const std::string &Filename) _Mtrx = Base::Matrix4D(); - std::ifstream inputfile; - inputfile.open(Filename.c_str()); + Base::FileInfo fi(Filename); + Base::ifstream inputfile; + inputfile.open(fi); inputfile.seekg(std::ifstream::beg); std::string line1,line2; std::vector mesh_elements; @@ -1560,7 +1561,7 @@ void FemMesh::readNastran(const std::string &Filename) do { std::getline(inputfile,line1); - if (line1.size() == 0) + if (line1.empty()) continue; if (line1.find(',') != std::string::npos) nastranFormat = Format::FreeField; @@ -1636,8 +1637,9 @@ void FemMesh::readNastran95(const std::string &Filename) _Mtrx = Base::Matrix4D(); - std::ifstream inputfile; - inputfile.open(Filename.c_str()); + Base::FileInfo fi(Filename); + Base::ifstream inputfile; + inputfile.open(fi); inputfile.seekg(std::ifstream::beg); std::string line1,line2,tcard; @@ -1650,7 +1652,7 @@ void FemMesh::readNastran95(const std::string &Filename) NastranElementPtr elem; std::getline(inputfile, line1); //cout << line1 << endl; - if (line1.size() == 0) + if (line1.empty()) continue; tcard = line1.substr(0, 8).c_str(); @@ -1674,15 +1676,15 @@ void FemMesh::readNastran95(const std::string &Filename) node = std::make_shared(); node->read(line1, ""); } - + //1D - else if (line1.substr(0,6)=="CBAR") + else if (line1.substr(0, 6) == "CBAR") { elem = std::make_shared(); elem->read(line1, ""); } //2d - else if (line1.substr(0,6)=="CTRMEM") + else if (line1.substr(0, 6) == "CTRMEM") { //D06 //CTRMEM 322 1 179 180 185 @@ -1699,40 +1701,40 @@ void FemMesh::readNastran95(const std::string &Filename) else if (line1.substr(0, 6) == "CQUAD1") { //D06 - //CTRMEM 322 1 179 180 185 + //CTRMEM 322 1 179 180 185 elem = std::make_shared(); elem->read(line1, ""); } - + //3d element else if (line1.find("CTETRA")!= std::string::npos) { - //d011121a.inp - //CTETRA 3 200 104 114 3 103 + //d011121a.inp + //CTETRA 3 200 104 114 3 103 elem = std::make_shared(); elem->read(line1, ""); } else if (line1.find("CWEDGE")!= std::string::npos) { - //d011121a.inp - //CWEDGE 11 200 6 17 16 106 117 116 + //d011121a.inp + //CWEDGE 11 200 6 17 16 106 117 116 elem = std::make_shared(); elem->read(line1, ""); } else if (line1.find("CHEXA1")!= std::string::npos) { - //d011121a.inp - //CHEXA1 1 200 1 2 13 12 101 102 +SOL1 - //+SOL1 113 112 + //d011121a.inp + //CHEXA1 1 200 1 2 13 12 101 102 +SOL1 + //+SOL1 113 112 std::getline(inputfile,line2); elem = std::make_shared(); elem->read(line1, line2); } else if (line1.find("CHEXA2")!= std::string::npos) { - //d011121a.inp - //CHEXA1 1 200 1 2 13 12 101 102 +SOL1 - //+SOL1 113 112 + //d011121a.inp + //CHEXA1 1 200 1 2 13 12 101 102 +SOL1 + //+SOL1 113 112 std::getline(inputfile,line2); elem = std::make_shared(); elem->read(line1, line2); @@ -2157,7 +2159,7 @@ void FemMesh::writeABAQUS(const std::string &Filename, int elemParam, bool group // write volumes to file - std::string elsetname = ""; + std::string elsetname; if (!elementsMapVol.empty()) { for (ElementsMap::iterator it = elementsMapVol.begin(); it != elementsMapVol.end(); ++it) { anABAQUS_Output << "** Volume elements" << std::endl; @@ -2199,7 +2201,7 @@ void FemMesh::writeABAQUS(const std::string &Filename, int elemParam, bool group anABAQUS_Output << std::endl; } } - if (elsetname == "") + if (elsetname.empty()) elsetname += "Efaces"; else elsetname += ", Efaces"; @@ -2219,7 +2221,7 @@ void FemMesh::writeABAQUS(const std::string &Filename, int elemParam, bool group anABAQUS_Output << std::endl; } } - if (elsetname == "") + if (elsetname.empty()) elsetname += "Eedges"; else elsetname += ", Eedges"; @@ -2365,7 +2367,7 @@ void FemMesh::write(const char *FileName) const // ==== Base class implementer ============================================================== -unsigned int FemMesh::getMemSize (void) const +unsigned int FemMesh::getMemSize () const { return 0; } @@ -2480,12 +2482,12 @@ void FemMesh::setTransform(const Base::Matrix4D& rclTrf) _Mtrx = rclTrf; } -Base::Matrix4D FemMesh::getTransform(void) const +Base::Matrix4D FemMesh::getTransform() const { return _Mtrx; } -Base::BoundBox3d FemMesh::getBoundBox(void) const +Base::BoundBox3d FemMesh::getBoundBox() const { Base::BoundBox3d box; @@ -2503,7 +2505,7 @@ Base::BoundBox3d FemMesh::getBoundBox(void) const return box; } -std::vector FemMesh::getElementTypes(void) const +std::vector FemMesh::getElementTypes() const { std::vector temp; temp.push_back("Vertex"); @@ -2529,7 +2531,7 @@ Data::Segment* FemMesh::getSubElement(const char* /*Type*/, unsigned long /*n*/) return nullptr; } -struct Fem::FemMesh::FemMeshInfo FemMesh::getInfo(void) const{ +struct Fem::FemMesh::FemMeshInfo FemMesh::getInfo() const{ struct FemMeshInfo rtrn; @@ -2570,7 +2572,7 @@ struct Fem::FemMesh::FemMeshInfo FemMesh::getInfo(void) const{ // ); // } -Base::Quantity FemMesh::getVolume(void)const +Base::Quantity FemMesh::getVolume()const { SMDS_VolumeIteratorPtr aVolIter = myMesh->GetMeshDS()->volumesIterator(); diff --git a/src/Mod/Fem/App/FemMesh.h b/src/Mod/Fem/App/FemMesh.h index 9b054e1301..c430e9cf25 100644 --- a/src/Mod/Fem/App/FemMesh.h +++ b/src/Mod/Fem/App/FemMesh.h @@ -51,12 +51,12 @@ typedef std::shared_ptr SMESH_HypothesisPtr; */ class FemExport FemMesh : public Data::ComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: FemMesh(); FemMesh(const FemMesh&); - ~FemMesh(); + ~FemMesh() override; FemMesh &operator=(const FemMesh&); const SMESH_Mesh* getSMesh() const; @@ -67,11 +67,11 @@ public: void compute(); // from base class - virtual unsigned int getMemSize (void) const; - virtual void Save (Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + unsigned int getMemSize () const override; + void Save (Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; /** @name Subelement management */ //@{ @@ -79,10 +79,10 @@ public: * List of different subelement types * it is NOT a list of the subelements itself */ - virtual std::vector getElementTypes(void) const; - virtual unsigned long countSubElements(const char* Type) const; + std::vector getElementTypes() const override; + unsigned long countSubElements(const char* Type) const override; /// get the subelement by type and number - virtual Data::Segment* getSubElement(const char* Type, unsigned long) const; + Data::Segment* getSubElement(const char* Type, unsigned long) const override; //@} /** @name search and retrieval */ @@ -108,27 +108,27 @@ public: /// retrieving volume IDs and CalculiX face number by face std::map getccxVolumesByFace(const TopoDS_Face &face) const; /// retrieving IDs of edges not belonging to any face (and thus not belonging to any volume too) - std::set getEdgesOnly(void) const; + std::set getEdgesOnly() const; /// retrieving IDs of faces not belonging to any volume - std::set getFacesOnly(void) const; + std::set getFacesOnly() const; //@} /** @name Placement control */ //@{ /// set the transformation - void setTransform(const Base::Matrix4D& rclTrf); + void setTransform(const Base::Matrix4D& rclTrf) override; /// get the transformation - Base::Matrix4D getTransform(void) const; + Base::Matrix4D getTransform() const override; /// Bound box from the shape - Base::BoundBox3d getBoundBox(void)const; + Base::BoundBox3d getBoundBox()const override; /// get the volume (when there are volume elements) - Base::Quantity getVolume(void)const; + Base::Quantity getVolume()const; //@} /** @name Modification */ //@{ /// Applies a transformation on the real geometric data type - void transformGeometry(const Base::Matrix4D &rclMat); + void transformGeometry(const Base::Matrix4D &rclMat) override; //@} /** @name Group management */ @@ -157,7 +157,7 @@ public: }; /// - struct FemMeshInfo getInfo(void) const; + struct FemMeshInfo getInfo() const; /// import from files void read(const char *FileName); diff --git a/src/Mod/Fem/App/FemMeshObject.cpp b/src/Mod/Fem/App/FemMeshObject.cpp index 7d53cc9ac8..662be2417c 100644 --- a/src/Mod/Fem/App/FemMeshObject.cpp +++ b/src/Mod/Fem/App/FemMeshObject.cpp @@ -20,18 +20,15 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "FemMeshObject.h" #include "FemMesh.h" #include #include #include + using namespace Fem; using namespace App; @@ -48,7 +45,7 @@ FemMeshObject::~FemMeshObject() { } -short FemMeshObject::mustExecute(void) const +short FemMeshObject::mustExecute() const { return 0; } @@ -57,7 +54,7 @@ PyObject *FemMeshObject::getPyObject() { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 - PythonObject = Py::Object(new DocumentObjectPy(this),true); + PythonObject = Py::Object(new DocumentObjectPy(this), true); } return Py::new_reference_to(PythonObject); } @@ -78,14 +75,14 @@ void FemMeshObject::onChanged(const Property* prop) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Fem::FemMeshObjectPython, Fem::FemMeshObject) -template<> const char* Fem::FemMeshObjectPython::getViewProviderName(void) const { +template<> const char* Fem::FemMeshObjectPython::getViewProviderName() const { return "FemGui::ViewProviderFemMeshPython"; } -template<> PyObject* Fem::FemMeshObjectPython::getPyObject(void) { +template<> PyObject* Fem::FemMeshObjectPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new App::FeaturePythonPyT(this),true); + PythonObject = Py::Object(new App::FeaturePythonPyT(this), true); } return Py::new_reference_to(PythonObject); } diff --git a/src/Mod/Fem/App/FemMeshObject.h b/src/Mod/Fem/App/FemMeshObject.h index acc5f28094..1850c7a2a4 100644 --- a/src/Mod/Fem/App/FemMeshObject.h +++ b/src/Mod/Fem/App/FemMeshObject.h @@ -35,28 +35,28 @@ namespace Fem class FemExport FemMeshObject : public App::GeoFeature { - PROPERTY_HEADER(Fem::FemMeshObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemMeshObject); public: /// Constructor - FemMeshObject(void); - virtual ~FemMeshObject(); + FemMeshObject(); + ~FemMeshObject() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemMesh"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; PropertyFemMesh FemMesh; protected: /// get called by the container when a property has changed - virtual void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; }; typedef App::FeaturePythonT FemMeshObjectPython; diff --git a/src/Mod/Fem/App/FemMeshProperty.cpp b/src/Mod/Fem/App/FemMeshProperty.cpp index 14a9576830..716bfef30a 100644 --- a/src/Mod/Fem/App/FemMeshProperty.cpp +++ b/src/Mod/Fem/App/FemMeshProperty.cpp @@ -67,7 +67,7 @@ void PropertyFemMesh::setValue(const FemMesh& sh) hasSetValue(); } -const FemMesh &PropertyFemMesh::getValue(void)const +const FemMesh &PropertyFemMesh::getValue()const { return *_FemMesh; } @@ -99,7 +99,7 @@ void PropertyFemMesh::transformGeometry(const Base::Matrix4D &rclMat) hasSetValue(); } -PyObject *PropertyFemMesh::getPyObject(void) +PyObject *PropertyFemMesh::getPyObject() { FemMeshPy* mesh = new FemMeshPy(&*_FemMesh); mesh->setConst(); @@ -123,7 +123,7 @@ void PropertyFemMesh::setPyObject(PyObject *value) } } -App::Property *PropertyFemMesh::Copy(void) const +App::Property *PropertyFemMesh::Copy() const { PropertyFemMesh *prop = new PropertyFemMesh(); prop->_FemMesh = this->_FemMesh; @@ -137,7 +137,7 @@ void PropertyFemMesh::Paste(const App::Property &from) hasSetValue(); } -unsigned int PropertyFemMesh::getMemSize (void) const +unsigned int PropertyFemMesh::getMemSize () const { return _FemMesh->getMemSize(); } diff --git a/src/Mod/Fem/App/FemMeshProperty.h b/src/Mod/Fem/App/FemMeshProperty.h index 77d1358cc6..a6d1af5138 100644 --- a/src/Mod/Fem/App/FemMeshProperty.h +++ b/src/Mod/Fem/App/FemMeshProperty.h @@ -37,11 +37,11 @@ namespace Fem */ class FemExport PropertyFemMesh : public App::PropertyComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyFemMesh(); - ~PropertyFemMesh(); + ~PropertyFemMesh() override; /** @name Getter/setter */ //@{ @@ -49,41 +49,41 @@ public: /// set the FemMesh shape void setValue(const FemMesh&); /// does nothing, for add property macro - void setValue(void){} + void setValue(){} /// get the FemMesh shape - const FemMesh &getValue(void) const; - const Data::ComplexGeoData* getComplexData() const; + const FemMesh &getValue() const; + const Data::ComplexGeoData* getComplexData() const override; //@} /** @name Getting basic geometric entities */ //@{ /** Returns the bounding box around the underlying mesh kernel */ - Base::BoundBox3d getBoundingBox() const; + Base::BoundBox3d getBoundingBox() const override; /// Set the placement of the geometry - void setTransform(const Base::Matrix4D& rclTrf); + void setTransform(const Base::Matrix4D& rclTrf) override; /// Get the placement of the geometry - Base::Matrix4D getTransform() const; - void transformGeometry(const Base::Matrix4D &rclMat); + Base::Matrix4D getTransform() const override; + void transformGeometry(const Base::Matrix4D &rclMat) override; //@} /** @name Python interface */ //@{ - PyObject* getPyObject(void); - void setPyObject(PyObject *value); + PyObject* getPyObject() override; + void setPyObject(PyObject *value) override; //@} /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - App::Property *Copy(void) const; - void Paste(const App::Property &from); - unsigned int getMemSize (void) const; - const char* getEditorName(void) const { return "FemGui::PropertyFemMeshItem"; } + App::Property *Copy() const override; + void Paste(const App::Property &from) override; + unsigned int getMemSize () const override; + const char* getEditorName() const override { return "FemGui::PropertyFemMeshItem"; } //@} private: diff --git a/src/Mod/Fem/App/FemMeshPyImp.cpp b/src/Mod/Fem/App/FemMeshPyImp.cpp index a3369084e7..5158d467f5 100644 --- a/src/Mod/Fem/App/FemMeshPyImp.cpp +++ b/src/Mod/Fem/App/FemMeshPyImp.cpp @@ -63,7 +63,7 @@ using namespace Fem; // returns a string which represents the object e.g. when printed in python -std::string FemMeshPy::representation(void) const +std::string FemMeshPy::representation() const { std::stringstream str; getFemMeshPtr()->getSMesh()->Dump(str); @@ -134,14 +134,14 @@ PyObject* FemMeshPy::setShape(PyObject *args) PyObject* FemMeshPy::addHypothesis(PyObject *args) { PyObject* hyp; - PyObject* shp=nullptr; + PyObject* shp = nullptr; // Since we have not a common base class for the Python binding of the // hypotheses classes we cannot pass a certain Python type if (!PyArg_ParseTuple(args, "O|O!",&hyp, &(Part::TopoShapePy::Type), &shp)) return nullptr; TopoDS_Shape shape; - if (shp == nullptr) + if (!shp) shape = getFemMeshPtr()->getSMesh()->GetShapeToMesh(); else shape = static_cast(shp)->getTopoShapePtr()->getShape(); @@ -1160,7 +1160,7 @@ PyObject* FemMeshPy::getIdByElementType(PyObject *args) // ===== Attributes ============================================================ -Py::Dict FemMeshPy::getNodes(void) const +Py::Dict FemMeshPy::getNodes() const { //int count = getFemMeshPtr()->getSMesh()->GetMeshDS()->NbNodes(); //Py::Tuple tup(count); @@ -1183,12 +1183,12 @@ Py::Dict FemMeshPy::getNodes(void) const return dict; } -Py::Long FemMeshPy::getNodeCount(void) const +Py::Long FemMeshPy::getNodeCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbNodes()); } -Py::Tuple FemMeshPy::getEdges(void) const +Py::Tuple FemMeshPy::getEdges() const { std::set ids; SMDS_EdgeIteratorPtr aEdgeIter = getFemMeshPtr()->getSMesh()->GetMeshDS()->edgesIterator(); @@ -1206,7 +1206,7 @@ Py::Tuple FemMeshPy::getEdges(void) const return tuple; } -Py::Tuple FemMeshPy::getEdgesOnly(void) const +Py::Tuple FemMeshPy::getEdgesOnly() const { std::set resultSet = getFemMeshPtr()->getEdgesOnly(); Py::Tuple tuple(resultSet.size()); @@ -1218,12 +1218,12 @@ Py::Tuple FemMeshPy::getEdgesOnly(void) const return tuple; } -Py::Long FemMeshPy::getEdgeCount(void) const +Py::Long FemMeshPy::getEdgeCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbEdges()); } -Py::Tuple FemMeshPy::getFaces(void) const +Py::Tuple FemMeshPy::getFaces() const { std::set ids; SMDS_FaceIteratorPtr aFaceIter = getFemMeshPtr()->getSMesh()->GetMeshDS()->facesIterator(); @@ -1241,7 +1241,7 @@ Py::Tuple FemMeshPy::getFaces(void) const return tuple; } -Py::Tuple FemMeshPy::getFacesOnly(void) const +Py::Tuple FemMeshPy::getFacesOnly() const { std::set resultSet = getFemMeshPtr()->getFacesOnly(); Py::Tuple tuple(resultSet.size()); @@ -1253,27 +1253,27 @@ Py::Tuple FemMeshPy::getFacesOnly(void) const return tuple; } -Py::Long FemMeshPy::getFaceCount(void) const +Py::Long FemMeshPy::getFaceCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbFaces()); } -Py::Long FemMeshPy::getTriangleCount(void) const +Py::Long FemMeshPy::getTriangleCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbTriangles()); } -Py::Long FemMeshPy::getQuadrangleCount(void) const +Py::Long FemMeshPy::getQuadrangleCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbQuadrangles()); } -Py::Long FemMeshPy::getPolygonCount(void) const +Py::Long FemMeshPy::getPolygonCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbPolygons()); } -Py::Tuple FemMeshPy::getVolumes(void) const +Py::Tuple FemMeshPy::getVolumes() const { std::set ids; SMDS_VolumeIteratorPtr aVolIter = getFemMeshPtr()->getSMesh()->GetMeshDS()->volumesIterator(); @@ -1291,47 +1291,47 @@ Py::Tuple FemMeshPy::getVolumes(void) const return tuple; } -Py::Long FemMeshPy::getVolumeCount(void) const +Py::Long FemMeshPy::getVolumeCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbVolumes()); } -Py::Long FemMeshPy::getTetraCount(void) const +Py::Long FemMeshPy::getTetraCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbTetras()); } -Py::Long FemMeshPy::getHexaCount(void) const +Py::Long FemMeshPy::getHexaCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbHexas()); } -Py::Long FemMeshPy::getPyramidCount(void) const +Py::Long FemMeshPy::getPyramidCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbPyramids()); } -Py::Long FemMeshPy::getPrismCount(void) const +Py::Long FemMeshPy::getPrismCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbPrisms()); } -Py::Long FemMeshPy::getPolyhedronCount(void) const +Py::Long FemMeshPy::getPolyhedronCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbPolyhedrons()); } -Py::Long FemMeshPy::getSubMeshCount(void) const +Py::Long FemMeshPy::getSubMeshCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbSubMesh()); } -Py::Long FemMeshPy::getGroupCount(void) const +Py::Long FemMeshPy::getGroupCount() const { return Py::Long(getFemMeshPtr()->getSMesh()->NbGroup()); } -Py::Tuple FemMeshPy::getGroups(void) const +Py::Tuple FemMeshPy::getGroups() const { std::list groupIDs = getFemMeshPtr()->getSMesh()->GetGroupIds(); @@ -1344,7 +1344,7 @@ Py::Tuple FemMeshPy::getGroups(void) const return tuple; } -Py::Object FemMeshPy::getVolume(void) const +Py::Object FemMeshPy::getVolume() const { return Py::asObject(new Base::QuantityPy(new Base::Quantity(getFemMeshPtr()->getVolume()))); diff --git a/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp b/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp index b8c587ac5e..a90d41489b 100644 --- a/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp +++ b/src/Mod/Fem/App/FemMeshShapeNetgenObject.cpp @@ -73,7 +73,7 @@ FemMeshShapeNetgenObject::~FemMeshShapeNetgenObject() { } -App::DocumentObjectExecReturn *FemMeshShapeNetgenObject::execute(void) +App::DocumentObjectExecReturn *FemMeshShapeNetgenObject::execute() { #ifdef FCWithNetgen diff --git a/src/Mod/Fem/App/FemMeshShapeNetgenObject.h b/src/Mod/Fem/App/FemMeshShapeNetgenObject.h index 38b8c418c6..14666927d3 100644 --- a/src/Mod/Fem/App/FemMeshShapeNetgenObject.h +++ b/src/Mod/Fem/App/FemMeshShapeNetgenObject.h @@ -31,12 +31,12 @@ namespace Fem class FemExport FemMeshShapeNetgenObject : public FemMeshShapeObject { - PROPERTY_HEADER(Fem::FemMeshShapeNetgenObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemMeshShapeNetgenObject); public: /// Constructor - FemMeshShapeNetgenObject(void); - virtual ~FemMeshShapeNetgenObject(); + FemMeshShapeNetgenObject(); + ~FemMeshShapeNetgenObject() override; App::PropertyFloat MaxSize; App::PropertyBool SecondOrder; @@ -47,10 +47,10 @@ public: App::PropertyBool Optimize; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemMeshShapeNetgen"; } - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; //virtual short mustExecute(void) const; //virtual PyObject *getPyObject(void); diff --git a/src/Mod/Fem/App/FemMeshShapeObject.cpp b/src/Mod/Fem/App/FemMeshShapeObject.cpp index edc896cf9d..af4e4760cb 100644 --- a/src/Mod/Fem/App/FemMeshShapeObject.cpp +++ b/src/Mod/Fem/App/FemMeshShapeObject.cpp @@ -86,7 +86,7 @@ FemMeshShapeObject::~FemMeshShapeObject() { } -App::DocumentObjectExecReturn *FemMeshShapeObject::execute(void) +App::DocumentObjectExecReturn *FemMeshShapeObject::execute() { Fem::FemMesh newMesh; diff --git a/src/Mod/Fem/App/FemMeshShapeObject.h b/src/Mod/Fem/App/FemMeshShapeObject.h index e3ecfe5c29..7f38c76d36 100644 --- a/src/Mod/Fem/App/FemMeshShapeObject.h +++ b/src/Mod/Fem/App/FemMeshShapeObject.h @@ -32,18 +32,18 @@ namespace Fem class FemExport FemMeshShapeObject : public FemMeshObject { - PROPERTY_HEADER(Fem::FemMeshShapeObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemMeshShapeObject); public: /// Constructor - FemMeshShapeObject(void); - virtual ~FemMeshShapeObject(); + FemMeshShapeObject(); + ~FemMeshShapeObject() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemMeshShape"; } - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; //virtual short mustExecute(void) const; //virtual PyObject *getPyObject(void); diff --git a/src/Mod/Fem/App/FemPostFilter.cpp b/src/Mod/Fem/App/FemPostFilter.cpp index 5853dbf658..0d8170a359 100644 --- a/src/Mod/Fem/App/FemPostFilter.cpp +++ b/src/Mod/Fem/App/FemPostFilter.cpp @@ -23,16 +23,13 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include # include #endif +#include + #include "FemPostFilter.h" #include "FemPostPipeline.h" -#include -#include -#include using namespace Fem; @@ -66,7 +63,7 @@ void FemPostFilter::setActiveFilterPipeline(std::string name) { } } -DocumentObjectExecReturn* FemPostFilter::execute(void) { +DocumentObjectExecReturn* FemPostFilter::execute() { if (!m_pipelines.empty() && !m_activePipeline.empty()) { FemPostFilter::FilterPipeline& pipe = m_pipelines[m_activePipeline]; @@ -82,7 +79,7 @@ DocumentObjectExecReturn* FemPostFilter::execute(void) { } else { pipe.source->SetInputDataObject(getInputData()); - pipe.target->Update(); + pipe.target->Update(); Data.setValue(pipe.target->GetOutputDataObject(0)); } @@ -115,7 +112,7 @@ vtkDataObject* FemPostFilter::getInputData() { // clip filter PROPERTY_SOURCE(Fem::FemPostClipFilter, Fem::FemPostFilter) -FemPostClipFilter::FemPostClipFilter(void) : FemPostFilter() { +FemPostClipFilter::FemPostClipFilter() : FemPostFilter() { ADD_PROPERTY_TYPE(Function, (nullptr), "Clip", App::Prop_None, "The function object which defines the clip regions"); ADD_PROPERTY_TYPE(InsideOut, (false), "Clip", App::Prop_None, "Invert the clip direction"); @@ -166,7 +163,7 @@ void FemPostClipFilter::onChanged(const Property* prop) { Fem::FemPostFilter::onChanged(prop); } -short int FemPostClipFilter::mustExecute(void) const { +short int FemPostClipFilter::mustExecute() const { if (Function.isTouched() || InsideOut.isTouched() || @@ -177,7 +174,7 @@ short int FemPostClipFilter::mustExecute(void) const { else return App::DocumentObject::mustExecute(); } -DocumentObjectExecReturn* FemPostClipFilter::execute(void) { +DocumentObjectExecReturn* FemPostClipFilter::execute() { if (!m_extractor->GetImplicitFunction()) return StdReturn; @@ -190,7 +187,7 @@ DocumentObjectExecReturn* FemPostClipFilter::execute(void) { // data along a line PROPERTY_SOURCE(Fem::FemPostDataAlongLineFilter, Fem::FemPostFilter) -FemPostDataAlongLineFilter::FemPostDataAlongLineFilter(void) : FemPostFilter() { +FemPostDataAlongLineFilter::FemPostDataAlongLineFilter() : FemPostFilter() { ADD_PROPERTY_TYPE(Point1, (Base::Vector3d(0.0, 0.0, 0.0)), "DataAlongLine", App::Prop_None, "The point 1 used to define end point of line"); ADD_PROPERTY_TYPE(Point2, (Base::Vector3d(0.0, 0.0, 1.0)), "DataAlongLine", App::Prop_None, "The point 2 used to define end point of line"); @@ -235,7 +232,7 @@ FemPostDataAlongLineFilter::~FemPostDataAlongLineFilter() { } -DocumentObjectExecReturn* FemPostDataAlongLineFilter::execute(void) { +DocumentObjectExecReturn* FemPostDataAlongLineFilter::execute() { //recalculate the filter return Fem::FemPostFilter::execute(); @@ -277,7 +274,7 @@ void FemPostDataAlongLineFilter::onChanged(const Property* prop) { Fem::FemPostFilter::onChanged(prop); } -short int FemPostDataAlongLineFilter::mustExecute(void) const { +short int FemPostDataAlongLineFilter::mustExecute() const { if (Point1.isTouched() || Point2.isTouched() || @@ -337,7 +334,7 @@ void FemPostDataAlongLineFilter::GetAxisData() { // data point filter PROPERTY_SOURCE(Fem::FemPostDataAtPointFilter, Fem::FemPostFilter) -FemPostDataAtPointFilter::FemPostDataAtPointFilter(void) : FemPostFilter() { +FemPostDataAtPointFilter::FemPostDataAtPointFilter() : FemPostFilter() { ADD_PROPERTY_TYPE(Center, (Base::Vector3d(0.0, 0.0, 0.0)), "DataAtPoint", App::Prop_None, "Center of the point"); ADD_PROPERTY_TYPE(Radius, (0), "DataAtPoint", App::Prop_None, "Radius around the point (unused)"); @@ -378,7 +375,7 @@ FemPostDataAtPointFilter::~FemPostDataAtPointFilter() { } -DocumentObjectExecReturn* FemPostDataAtPointFilter::execute(void) { +DocumentObjectExecReturn* FemPostDataAtPointFilter::execute() { //recalculate the filter return Fem::FemPostFilter::execute(); @@ -393,7 +390,7 @@ void FemPostDataAtPointFilter::onChanged(const Property* prop) { Fem::FemPostFilter::onChanged(prop); } -short int FemPostDataAtPointFilter::mustExecute(void) const { +short int FemPostDataAtPointFilter::mustExecute() const { if (Center.isTouched()) return 1; @@ -436,7 +433,7 @@ void FemPostDataAtPointFilter::GetPointData() { // scalar clip filter PROPERTY_SOURCE(Fem::FemPostScalarClipFilter, Fem::FemPostFilter) -FemPostScalarClipFilter::FemPostScalarClipFilter(void) : FemPostFilter() { +FemPostScalarClipFilter::FemPostScalarClipFilter() : FemPostFilter() { ADD_PROPERTY_TYPE(Value, (0), "Clip", App::Prop_None, "The scalar value used to clip the selected field"); ADD_PROPERTY_TYPE(Scalars, (long(0)), "Clip", App::Prop_None, "The field used to clip"); @@ -456,13 +453,13 @@ FemPostScalarClipFilter::~FemPostScalarClipFilter() { } -DocumentObjectExecReturn* FemPostScalarClipFilter::execute(void) { +DocumentObjectExecReturn* FemPostScalarClipFilter::execute() { std::string val; - if (m_scalarFields.hasEnums() && Scalars.getValue() >= 0) + if (Scalars.getValue() >= 0) val = Scalars.getValueAsString(); - std::vector array; + std::vector ScalarsArray; vtkSmartPointer data = getInputData(); if (!data || !data->IsA("vtkDataSet")) @@ -471,18 +468,21 @@ DocumentObjectExecReturn* FemPostScalarClipFilter::execute(void) { vtkDataSet* dset = vtkDataSet::SafeDownCast(data); vtkPointData* pd = dset->GetPointData(); + // get all scalar fields for (int i = 0; i < pd->GetNumberOfArrays(); ++i) { if (pd->GetArray(i)->GetNumberOfComponents() == 1) - array.push_back(pd->GetArrayName(i)); + ScalarsArray.emplace_back(pd->GetArrayName(i)); } App::Enumeration empty; Scalars.setValue(empty); - m_scalarFields.setEnums(array); + m_scalarFields.setEnums(ScalarsArray); Scalars.setValue(m_scalarFields); - std::vector::iterator it = std::find(array.begin(), array.end(), val); - if (!val.empty() && it != array.end()) + // search if the current field is in the available ones and set it + std::vector::iterator it = + std::find(ScalarsArray.begin(), ScalarsArray.end(), val); + if (!val.empty() && it != ScalarsArray.end()) Scalars.setValue(val.c_str()); //recalculate the filter @@ -506,15 +506,14 @@ void FemPostScalarClipFilter::onChanged(const Property* prop) { Fem::FemPostFilter::onChanged(prop); } -short int FemPostScalarClipFilter::mustExecute(void) const { +short int FemPostScalarClipFilter::mustExecute() const { if (Value.isTouched() || InsideOut.isTouched() || - Scalars.isTouched()) { - + Scalars.isTouched()) return 1; - } - else return App::DocumentObject::mustExecute(); + else + return App::DocumentObject::mustExecute(); } void FemPostScalarClipFilter::setConstraintForField() { @@ -542,7 +541,7 @@ void FemPostScalarClipFilter::setConstraintForField() { // warp vector filter PROPERTY_SOURCE(Fem::FemPostWarpVectorFilter, Fem::FemPostFilter) -FemPostWarpVectorFilter::FemPostWarpVectorFilter(void) : FemPostFilter() { +FemPostWarpVectorFilter::FemPostWarpVectorFilter() : FemPostFilter() { ADD_PROPERTY_TYPE(Factor, (0), "Warp", App::Prop_None, "The factor by which the vector is added to the node positions"); ADD_PROPERTY_TYPE(Vector, (long(0)), "Warp", App::Prop_None, "The field added to the node position"); @@ -559,13 +558,13 @@ FemPostWarpVectorFilter::~FemPostWarpVectorFilter() { } -DocumentObjectExecReturn* FemPostWarpVectorFilter::execute(void) { +DocumentObjectExecReturn* FemPostWarpVectorFilter::execute() { std::string val; - if (m_vectorFields.hasEnums() && Vector.getValue() >= 0) + if (Vector.getValue() >= 0) val = Vector.getValueAsString(); - std::vector array; + std::vector VectorArray; vtkSmartPointer data = getInputData(); if (!data || !data->IsA("vtkDataSet")) @@ -574,18 +573,21 @@ DocumentObjectExecReturn* FemPostWarpVectorFilter::execute(void) { vtkDataSet* dset = vtkDataSet::SafeDownCast(data); vtkPointData* pd = dset->GetPointData(); + // get all vector fields for (int i = 0; i < pd->GetNumberOfArrays(); ++i) { if (pd->GetArray(i)->GetNumberOfComponents() == 3) - array.push_back(pd->GetArrayName(i)); + VectorArray.emplace_back(pd->GetArrayName(i)); } App::Enumeration empty; Vector.setValue(empty); - m_vectorFields.setEnums(array); + m_vectorFields.setEnums(VectorArray); Vector.setValue(m_vectorFields); - std::vector::iterator it = std::find(array.begin(), array.end(), val); - if (!val.empty() && it != array.end()) + // search if the current field is in the available ones and set it + std::vector::iterator it = + std::find(VectorArray.begin(), VectorArray.end(), val); + if (!val.empty() && it != VectorArray.end()) Vector.setValue(val.c_str()); //recalculate the filter @@ -594,25 +596,23 @@ DocumentObjectExecReturn* FemPostWarpVectorFilter::execute(void) { void FemPostWarpVectorFilter::onChanged(const Property* prop) { - if (prop == &Factor) { - m_warp->SetScaleFactor(Factor.getValue()); - } - else if (prop == &Vector && (Vector.getValue() >= 0)) { + if (prop == &Factor) + // since our mesh is in mm, we must scale the factor + m_warp->SetScaleFactor(1000 * Factor.getValue()); + else if (prop == &Vector && (Vector.getValue() >= 0)) m_warp->SetInputArrayToProcess(0, 0, 0, vtkDataObject::FIELD_ASSOCIATION_POINTS, Vector.getValueAsString()); - } Fem::FemPostFilter::onChanged(prop); } -short int FemPostWarpVectorFilter::mustExecute(void) const { +short int FemPostWarpVectorFilter::mustExecute() const { if (Factor.isTouched() || - Vector.isTouched()) { - + Vector.isTouched()) return 1; - } - else return App::DocumentObject::mustExecute(); + else + return App::DocumentObject::mustExecute(); } @@ -620,7 +620,7 @@ short int FemPostWarpVectorFilter::mustExecute(void) const { // cut filter PROPERTY_SOURCE(Fem::FemPostCutFilter, Fem::FemPostFilter) -FemPostCutFilter::FemPostCutFilter(void) : FemPostFilter() { +FemPostCutFilter::FemPostCutFilter() : FemPostFilter() { ADD_PROPERTY_TYPE(Function, (nullptr), "Cut", App::Prop_None, "The function object which defines the clip cut function"); @@ -648,7 +648,7 @@ void FemPostCutFilter::onChanged(const Property* prop) { Fem::FemPostFilter::onChanged(prop); } -short int FemPostCutFilter::mustExecute(void) const { +short int FemPostCutFilter::mustExecute() const { if (Function.isTouched()) { @@ -657,7 +657,7 @@ short int FemPostCutFilter::mustExecute(void) const { else return App::DocumentObject::mustExecute(); } -DocumentObjectExecReturn* FemPostCutFilter::execute(void) { +DocumentObjectExecReturn* FemPostCutFilter::execute() { if (!m_cutter->GetCutFunction()) return StdReturn; diff --git a/src/Mod/Fem/App/FemPostFilter.h b/src/Mod/Fem/App/FemPostFilter.h index 22a693cb0e..553e7198c9 100644 --- a/src/Mod/Fem/App/FemPostFilter.h +++ b/src/Mod/Fem/App/FemPostFilter.h @@ -42,16 +42,16 @@ namespace Fem class FemExport FemPostFilter : public Fem::FemPostObject { - PROPERTY_HEADER(Fem::FemPostFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostFilter); public: /// Constructor - FemPostFilter(void); - virtual ~FemPostFilter(); + FemPostFilter(); + ~FemPostFilter() override; App::PropertyLink Input; - virtual App::DocumentObjectExecReturn* execute(void); + App::DocumentObjectExecReturn* execute() override; protected: vtkDataObject* getInputData(); @@ -74,24 +74,24 @@ private: class FemExport FemPostClipFilter : public FemPostFilter { - PROPERTY_HEADER(Fem::FemPostClipFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostClipFilter); public: - FemPostClipFilter(void); - virtual ~FemPostClipFilter(); + FemPostClipFilter(); + ~FemPostClipFilter() override; App::PropertyLink Function; App::PropertyBool InsideOut; App::PropertyBool CutCells; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostClip"; } - virtual short int mustExecute(void) const; - virtual App::DocumentObjectExecReturn* execute(void); + short int mustExecute() const override; + App::DocumentObjectExecReturn* execute() override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: vtkSmartPointer m_clipper; @@ -100,11 +100,11 @@ private: class FemExport FemPostDataAlongLineFilter : public FemPostFilter { - PROPERTY_HEADER(Fem::FemPostDataAlongLineFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostDataAlongLineFilter); public: - FemPostDataAlongLineFilter(void); - virtual ~FemPostDataAlongLineFilter(); + FemPostDataAlongLineFilter(); + ~FemPostDataAlongLineFilter() override; App::PropertyVectorDistance Point1; App::PropertyVectorDistance Point2; @@ -113,16 +113,16 @@ public: App::PropertyFloatList YAxisData; App::PropertyString PlotData; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostDataAlongLine"; } - virtual short int mustExecute(void) const; + short int mustExecute() const override; void GetAxisData(); protected: - virtual App::DocumentObjectExecReturn* execute(void); - virtual void onChanged(const App::Property* prop); - virtual void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop); + App::DocumentObjectExecReturn* execute() override; + void onChanged(const App::Property* prop) override; + void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; private: @@ -133,11 +133,11 @@ private: class FemExport FemPostDataAtPointFilter : public FemPostFilter { - PROPERTY_HEADER(Fem::FemPostDataAtPointFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostDataAtPointFilter); public: - FemPostDataAtPointFilter(void); - virtual ~FemPostDataAtPointFilter(); + FemPostDataAtPointFilter(); + ~FemPostDataAtPointFilter() override; App::PropertyVectorDistance Center; App::PropertyDistance Radius; @@ -145,14 +145,14 @@ public: App::PropertyFloatList PointData; App::PropertyString Unit; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostDataAtPoint"; } - virtual short int mustExecute(void) const; + short int mustExecute() const override; protected: - virtual App::DocumentObjectExecReturn* execute(void); - virtual void onChanged(const App::Property* prop); + App::DocumentObjectExecReturn* execute() override; + void onChanged(const App::Property* prop) override; void GetPointData(); private: @@ -164,24 +164,24 @@ private: class FemExport FemPostScalarClipFilter : public FemPostFilter { - PROPERTY_HEADER(Fem::FemPostScalarClipFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostScalarClipFilter); public: - FemPostScalarClipFilter(void); - virtual ~FemPostScalarClipFilter(); + FemPostScalarClipFilter(); + ~FemPostScalarClipFilter() override; App::PropertyBool InsideOut; App::PropertyFloatConstraint Value; App::PropertyEnumeration Scalars; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostScalarClip"; } - virtual short int mustExecute(void) const; + short int mustExecute() const override; protected: - virtual App::DocumentObjectExecReturn* execute(void); - virtual void onChanged(const App::Property* prop); + App::DocumentObjectExecReturn* execute() override; + void onChanged(const App::Property* prop) override; void setConstraintForField(); private: @@ -192,23 +192,23 @@ private: class FemExport FemPostWarpVectorFilter : public FemPostFilter { - PROPERTY_HEADER(Fem::FemPostWarpVectorFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostWarpVectorFilter); public: - FemPostWarpVectorFilter(void); - virtual ~FemPostWarpVectorFilter(); + FemPostWarpVectorFilter(); + ~FemPostWarpVectorFilter() override; App::PropertyFloat Factor; App::PropertyEnumeration Vector; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostWarpVector"; } - virtual short int mustExecute(void) const; + short int mustExecute() const override; protected: - virtual App::DocumentObjectExecReturn* execute(void); - virtual void onChanged(const App::Property* prop); + App::DocumentObjectExecReturn* execute() override; + void onChanged(const App::Property* prop) override; private: vtkSmartPointer m_warp; @@ -217,22 +217,22 @@ private: class FemExport FemPostCutFilter : public FemPostFilter { - PROPERTY_HEADER(Fem::FemPostCutFilter); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostCutFilter); public: - FemPostCutFilter(void); - virtual ~FemPostCutFilter(); + FemPostCutFilter(); + ~FemPostCutFilter() override; App::PropertyLink Function; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostCut"; } - virtual short int mustExecute(void) const; - virtual App::DocumentObjectExecReturn* execute(void); + short int mustExecute() const override; + App::DocumentObjectExecReturn* execute() override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: vtkSmartPointer m_cutter; diff --git a/src/Mod/Fem/App/FemPostFunction.cpp b/src/Mod/Fem/App/FemPostFunction.cpp index 0dd14db8fb..4386ed89b2 100644 --- a/src/Mod/Fem/App/FemPostFunction.cpp +++ b/src/Mod/Fem/App/FemPostFunction.cpp @@ -34,7 +34,7 @@ using namespace App; PROPERTY_SOURCE(Fem::FemPostFunctionProvider, App::DocumentObject) -FemPostFunctionProvider::FemPostFunctionProvider(void) : DocumentObject() { +FemPostFunctionProvider::FemPostFunctionProvider() : DocumentObject() { ADD_PROPERTY(Functions, (nullptr)); } @@ -58,7 +58,7 @@ FemPostFunction::~FemPostFunction() { } -DocumentObjectExecReturn* FemPostFunction::execute(void) { +DocumentObjectExecReturn* FemPostFunction::execute() { return DocumentObject::StdReturn; } @@ -68,7 +68,7 @@ DocumentObjectExecReturn* FemPostFunction::execute(void) { // plane function PROPERTY_SOURCE(Fem::FemPostPlaneFunction, Fem::FemPostFunction) -FemPostPlaneFunction::FemPostPlaneFunction(void) : FemPostFunction() { +FemPostPlaneFunction::FemPostPlaneFunction() : FemPostFunction() { ADD_PROPERTY(Origin, (Base::Vector3d(0.0, 0.0, 0.0))); ADD_PROPERTY(Normal, (Base::Vector3d(0.0, 0.0, 1.0))); @@ -108,7 +108,7 @@ void FemPostPlaneFunction::onDocumentRestored() { // sphere function PROPERTY_SOURCE(Fem::FemPostSphereFunction, Fem::FemPostFunction) -FemPostSphereFunction::FemPostSphereFunction(void) : FemPostFunction() { +FemPostSphereFunction::FemPostSphereFunction() : FemPostFunction() { ADD_PROPERTY(Radius, (5)); ADD_PROPERTY(Center, (Base::Vector3d(1.0, 0.0, 0.0))); diff --git a/src/Mod/Fem/App/FemPostFunction.h b/src/Mod/Fem/App/FemPostFunction.h index ee3bb1495b..294e9f3637 100644 --- a/src/Mod/Fem/App/FemPostFunction.h +++ b/src/Mod/Fem/App/FemPostFunction.h @@ -39,18 +39,18 @@ namespace Fem class FemExport FemPostFunction : public App::DocumentObject { - PROPERTY_HEADER(Fem::FemPostFunction); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostFunction); public: /// Constructor - FemPostFunction(void); - virtual ~FemPostFunction(); + FemPostFunction(); + ~FemPostFunction() override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostFunction"; } - virtual App::DocumentObjectExecReturn* execute(void); + App::DocumentObjectExecReturn* execute() override; //bound box handling void setBoundingBox(vtkBoundingBox b) {m_boundingBox = b;}; @@ -65,20 +65,20 @@ protected: class FemExport FemPostFunctionProvider : public App::DocumentObject { - PROPERTY_HEADER(Fem::FemPostFunctionProvider); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostFunctionProvider); public: - FemPostFunctionProvider(void); - virtual ~FemPostFunctionProvider(); + FemPostFunctionProvider(); + ~FemPostFunctionProvider() override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostFunctionProvider"; } App::PropertyLinkList Functions; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; @@ -86,24 +86,24 @@ protected: class FemExport FemPostPlaneFunction : public FemPostFunction { - PROPERTY_HEADER(Fem::FemPostPlaneFunction); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostPlaneFunction); public: - FemPostPlaneFunction(void); - virtual ~FemPostPlaneFunction(); + FemPostPlaneFunction(); + ~FemPostPlaneFunction() override; App::PropertyVector Normal; App::PropertyVectorDistance Origin; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostPlaneFunction"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; /// get called after a document has been fully restored - virtual void onDocumentRestored(); + void onDocumentRestored() override; vtkSmartPointer m_plane; }; @@ -112,22 +112,22 @@ protected: class FemExport FemPostSphereFunction : public FemPostFunction { - PROPERTY_HEADER(Fem::FemPostSphereFunction); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostSphereFunction); public: - FemPostSphereFunction(void); - virtual ~FemPostSphereFunction(); + FemPostSphereFunction(); + ~FemPostSphereFunction() override; App::PropertyDistance Radius; App::PropertyVectorDistance Center; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostSphereFunction"; } protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; vtkSmartPointer m_sphere; }; diff --git a/src/Mod/Fem/App/FemPostObject.cpp b/src/Mod/Fem/App/FemPostObject.cpp index 03ca2692aa..24a30e5a5d 100644 --- a/src/Mod/Fem/App/FemPostObject.cpp +++ b/src/Mod/Fem/App/FemPostObject.cpp @@ -23,16 +23,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include +# include #endif #include "FemPostObject.h" -#include -#include -#include -#include using namespace Fem; diff --git a/src/Mod/Fem/App/FemPostObject.h b/src/Mod/Fem/App/FemPostObject.h index 5744c1e56f..9ab784a25f 100644 --- a/src/Mod/Fem/App/FemPostObject.h +++ b/src/Mod/Fem/App/FemPostObject.h @@ -35,12 +35,12 @@ namespace Fem //poly data is the only data we can visualize, hence every post processing object needs to expose it class FemExport FemPostObject : public App::GeoFeature { - PROPERTY_HEADER(Fem::FemPostObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostObject); public: /// Constructor - FemPostObject(void); - virtual ~FemPostObject(); + FemPostObject(); + ~FemPostObject() override; Fem::PropertyPostDataObject Data; diff --git a/src/Mod/Fem/App/FemPostPipeline.cpp b/src/Mod/Fem/App/FemPostPipeline.cpp index 5fc5755c5e..15a9d17b39 100644 --- a/src/Mod/Fem/App/FemPostPipeline.cpp +++ b/src/Mod/Fem/App/FemPostPipeline.cpp @@ -23,21 +23,19 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include # include +# include # include -# include -# include -# include # include # include -# include -# include -# include -# include -# include -# include +# include +# include # include +# include +# include +# include +# include +# include #endif #include "FemPostPipeline.h" @@ -45,11 +43,10 @@ #include "FemMeshObject.h" #include "FemVTKTools.h" -#include -#include - #include -#include +#include + +#include "FemPostPipelinePy.h" using namespace Fem; @@ -73,7 +70,7 @@ FemPostPipeline::~FemPostPipeline() { } -short FemPostPipeline::mustExecute(void) const +short FemPostPipeline::mustExecute() const { if (Mode.isTouched()) return 1; @@ -81,7 +78,7 @@ short FemPostPipeline::mustExecute(void) const return FemPostFilter::mustExecute(); } -DocumentObjectExecReturn* FemPostPipeline::execute(void) { +DocumentObjectExecReturn* FemPostPipeline::execute() { //if we are the toplevel pipeline our data object is not created by filters, we are the main source if (!Input.getValue()) @@ -123,7 +120,7 @@ bool FemPostPipeline::canRead(Base::FileInfo File) { File.hasExtension("vtr") || File.hasExtension("vti") || File.hasExtension("vtu") || - File.hasExtension("pvtu")) + File.hasExtension("pvtu")) return true; return false; @@ -203,7 +200,7 @@ void FemPostPipeline::onChanged(const Property* prop) //if we have no input the filters are responsible of grabbing the pipeline data themself else { //the first filter must always grab the data - if (filter->Input.getValue() != nullptr) + if (filter->Input.getValue()) filter->Input.setValue(nullptr); //all the others need to be connected to the previous filter or grab the data, dependent on mode @@ -216,7 +213,7 @@ void FemPostPipeline::onChanged(const Property* prop) nextFilter->Input.setValue(filter); } else { //Parallel mode - if (nextFilter->Input.getValue() != nullptr) + if (nextFilter->Input.getValue()) nextFilter->Input.setValue(nullptr); } @@ -229,6 +226,12 @@ void FemPostPipeline::onChanged(const Property* prop) } +void FemPostPipeline::recomputeChildren() +{ + for (const auto &obj : Filter.getValues()) + obj->touch(); +} + FemPostObject* FemPostPipeline::getLastPostObject() { if (Filter.getValues().empty()) @@ -271,7 +274,7 @@ void FemPostPipeline::load(FemResultObject* res) { Data.setValue(grid); } -PyObject* FemPostPipeline::getPyObject(void) +PyObject* FemPostPipeline::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 diff --git a/src/Mod/Fem/App/FemPostPipeline.h b/src/Mod/Fem/App/FemPostPipeline.h index 01415cd2cf..0022a6f7c7 100644 --- a/src/Mod/Fem/App/FemPostPipeline.h +++ b/src/Mod/Fem/App/FemPostPipeline.h @@ -36,22 +36,22 @@ namespace Fem class FemExport FemPostPipeline : public Fem::FemPostFilter { - PROPERTY_HEADER(Fem::FemPostPipeline); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemPostPipeline); public: /// Constructor - FemPostPipeline(void); - virtual ~FemPostPipeline(); + FemPostPipeline(); + ~FemPostPipeline() override; App::PropertyLinkList Filter; App::PropertyLink Functions; App::PropertyEnumeration Mode; - short mustExecute(void) const; - virtual App::DocumentObjectExecReturn* execute(void); - PyObject* getPyObject(); + short mustExecute() const override; + App::DocumentObjectExecReturn* execute() override; + PyObject* getPyObject() override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderFemPostPipeline"; } @@ -64,11 +64,12 @@ public: void load(FemResultObject* res); //Pipeline handling - FemPostObject* getLastPostObject(); - bool holdsPostObject(FemPostObject* obj); + void recomputeChildren(); + FemPostObject *getLastPostObject(); + bool holdsPostObject(FemPostObject *obj); protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property *prop) override; private: static const char* ModeEnums[]; diff --git a/src/Mod/Fem/App/FemPostPipelinePy.xml b/src/Mod/Fem/App/FemPostPipelinePy.xml index fef97a33c9..70aa69a4cc 100644 --- a/src/Mod/Fem/App/FemPostPipelinePy.xml +++ b/src/Mod/Fem/App/FemPostPipelinePy.xml @@ -28,6 +28,11 @@ Load a result object + + + Recomputes all children of the pipeline + + Get the last post-processing object diff --git a/src/Mod/Fem/App/FemPostPipelinePyImp.cpp b/src/Mod/Fem/App/FemPostPipelinePyImp.cpp index e21955258a..6ceaf8af66 100644 --- a/src/Mod/Fem/App/FemPostPipelinePyImp.cpp +++ b/src/Mod/Fem/App/FemPostPipelinePyImp.cpp @@ -35,7 +35,7 @@ using namespace Fem; // returns a string which represents the object e.g. when printed in python -std::string FemPostPipelinePy::representation(void) const +std::string FemPostPipelinePy::representation() const { return std::string(""); } @@ -77,6 +77,15 @@ PyObject* FemPostPipelinePy::load(PyObject *args) Py_Return; } +PyObject *FemPostPipelinePy::recomputeChildren(PyObject *args) +{ + if (!PyArg_ParseTuple(args, "")) + return nullptr; + + getFemPostPipelinePtr()->recomputeChildren(); + Py_Return; +} + PyObject* FemPostPipelinePy::getLastPostObject(PyObject *args) { if (!PyArg_ParseTuple(args, "")) diff --git a/src/Mod/Fem/App/FemResultObject.cpp b/src/Mod/Fem/App/FemResultObject.cpp index 2c4af8b60c..5ac614326b 100644 --- a/src/Mod/Fem/App/FemResultObject.cpp +++ b/src/Mod/Fem/App/FemResultObject.cpp @@ -20,16 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - -#include "FemResultObject.h" #include #include +#include "FemResultObject.h" + + using namespace Fem; using namespace App; @@ -38,10 +36,10 @@ PROPERTY_SOURCE(Fem::FemResultObject, App::DocumentObject) FemResultObject::FemResultObject() { - ADD_PROPERTY_TYPE(Mesh,(nullptr), "General",Prop_None,"Link to the corresponding mesh"); - ADD_PROPERTY_TYPE(NodeNumbers,(0), "NodeData",Prop_None,"Numbers of the result nodes"); - ADD_PROPERTY_TYPE(Stats,(0), "Data",Prop_None,"Statistics of the results"); - ADD_PROPERTY_TYPE(Time,(0), "Data",Prop_None,"Time of analysis increment"); + ADD_PROPERTY_TYPE(Mesh, (nullptr), "General", Prop_None, "Link to the corresponding mesh"); + ADD_PROPERTY_TYPE(NodeNumbers, (0), "NodeData", Prop_None, "Numbers of the result nodes"); + ADD_PROPERTY_TYPE(Stats, (0), "Data", Prop_None, "Statistics of the results"); + ADD_PROPERTY_TYPE(Time, (0), "Data", Prop_None, "Time of analysis increment"); // make read-only for property editor NodeNumbers.setStatus(App::Property::ReadOnly, true); @@ -53,7 +51,7 @@ FemResultObject::~FemResultObject() { } -short FemResultObject::mustExecute(void) const +short FemResultObject::mustExecute() const { return 0; } @@ -72,12 +70,12 @@ PyObject *FemResultObject::getPyObject() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Fem::FemResultObjectPython, Fem::FemResultObject) -template<> const char* Fem::FemResultObjectPython::getViewProviderName(void) const { +template<> const char* Fem::FemResultObjectPython::getViewProviderName() const { return "FemGui::ViewProviderResultPython"; } /// @endcond -template<> PyObject* Fem::FemResultObjectPython::getPyObject(void) { +template<> PyObject* Fem::FemResultObjectPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new App::FeaturePythonPyT(this),true); diff --git a/src/Mod/Fem/App/FemResultObject.h b/src/Mod/Fem/App/FemResultObject.h index 2e6ed6f2ee..707d78668b 100644 --- a/src/Mod/Fem/App/FemResultObject.h +++ b/src/Mod/Fem/App/FemResultObject.h @@ -34,12 +34,12 @@ namespace Fem /// Father of all result data in a Fem Analysis class FemExport FemResultObject : public App::DocumentObject { - PROPERTY_HEADER(Fem::FemResultObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemResultObject); public: /// Constructor - FemResultObject(void); - virtual ~FemResultObject(); + FemResultObject(); + ~FemResultObject() override; App::PropertyIntegerList NodeNumbers; /// Link to the corresponding mesh @@ -51,14 +51,14 @@ public: /// Displacement vectors of analysis /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderResult"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; typedef App::FeaturePythonT FemResultObjectPython; diff --git a/src/Mod/Fem/App/FemSetElementsObject.cpp b/src/Mod/Fem/App/FemSetElementsObject.cpp index 26b53d38b8..91a5952d17 100644 --- a/src/Mod/Fem/App/FemSetElementsObject.cpp +++ b/src/Mod/Fem/App/FemSetElementsObject.cpp @@ -43,7 +43,7 @@ FemSetElementsObject::~FemSetElementsObject() { } -short FemSetElementsObject::mustExecute(void) const +short FemSetElementsObject::mustExecute() const { return 0; } diff --git a/src/Mod/Fem/App/FemSetElementsObject.h b/src/Mod/Fem/App/FemSetElementsObject.h index 07bcb2bca1..4889a892df 100644 --- a/src/Mod/Fem/App/FemSetElementsObject.h +++ b/src/Mod/Fem/App/FemSetElementsObject.h @@ -32,22 +32,22 @@ namespace Fem class FemExport FemSetElementsObject : public FemSetObject { - PROPERTY_HEADER(Fem::FemSetElementsObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemSetElementsObject); public: /// Constructor - FemSetElementsObject(void); - virtual ~FemSetElementsObject(); + FemSetElementsObject(); + ~FemSetElementsObject() override; // returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderSetElements"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; diff --git a/src/Mod/Fem/App/FemSetFacesObject.cpp b/src/Mod/Fem/App/FemSetFacesObject.cpp index 49fd003a8e..f314332507 100644 --- a/src/Mod/Fem/App/FemSetFacesObject.cpp +++ b/src/Mod/Fem/App/FemSetFacesObject.cpp @@ -44,7 +44,7 @@ FemSetFacesObject::~FemSetFacesObject() { } -short FemSetFacesObject::mustExecute(void) const +short FemSetFacesObject::mustExecute() const { return 0; } diff --git a/src/Mod/Fem/App/FemSetFacesObject.h b/src/Mod/Fem/App/FemSetFacesObject.h index 3f7b6117c3..834e8fa310 100644 --- a/src/Mod/Fem/App/FemSetFacesObject.h +++ b/src/Mod/Fem/App/FemSetFacesObject.h @@ -32,22 +32,22 @@ namespace Fem class FemExport FemSetFacesObject : public FemSetObject { - PROPERTY_HEADER(Fem::FemSetFacesObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemSetFacesObject); public: /// Constructor - FemSetFacesObject(void); - virtual ~FemSetFacesObject(); + FemSetFacesObject(); + ~FemSetFacesObject() override; // returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderSetFaces"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; } //namespace Fem diff --git a/src/Mod/Fem/App/FemSetGeometryObject.cpp b/src/Mod/Fem/App/FemSetGeometryObject.cpp index a2601b26d8..c30d5d8c2a 100644 --- a/src/Mod/Fem/App/FemSetGeometryObject.cpp +++ b/src/Mod/Fem/App/FemSetGeometryObject.cpp @@ -44,7 +44,7 @@ FemSetGeometryObject::~FemSetGeometryObject() { } -short FemSetGeometryObject::mustExecute(void) const +short FemSetGeometryObject::mustExecute() const { return 0; } diff --git a/src/Mod/Fem/App/FemSetGeometryObject.h b/src/Mod/Fem/App/FemSetGeometryObject.h index 42170c2976..4135786826 100644 --- a/src/Mod/Fem/App/FemSetGeometryObject.h +++ b/src/Mod/Fem/App/FemSetGeometryObject.h @@ -32,22 +32,22 @@ namespace Fem class FemExport FemSetGeometryObject : public FemSetObject { - PROPERTY_HEADER(Fem::FemSetGeometryObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemSetGeometryObject); public: /// Constructor - FemSetGeometryObject(void); - virtual ~FemSetGeometryObject(); + FemSetGeometryObject(); + ~FemSetGeometryObject() override; // returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderSetGeometry"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; diff --git a/src/Mod/Fem/App/FemSetNodesObject.cpp b/src/Mod/Fem/App/FemSetNodesObject.cpp index 399794463c..10ebd06d51 100644 --- a/src/Mod/Fem/App/FemSetNodesObject.cpp +++ b/src/Mod/Fem/App/FemSetNodesObject.cpp @@ -45,7 +45,7 @@ FemSetNodesObject::~FemSetNodesObject() { } -short FemSetNodesObject::mustExecute(void) const +short FemSetNodesObject::mustExecute() const { return 0; } diff --git a/src/Mod/Fem/App/FemSetNodesObject.h b/src/Mod/Fem/App/FemSetNodesObject.h index 9b59a37706..f33f780675 100644 --- a/src/Mod/Fem/App/FemSetNodesObject.h +++ b/src/Mod/Fem/App/FemSetNodesObject.h @@ -33,24 +33,24 @@ namespace Fem class FemExport FemSetNodesObject : public FemSetObject { - PROPERTY_HEADER(Fem::FemSetNodesObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemSetNodesObject); public: /// Constructor - FemSetNodesObject(void); - virtual ~FemSetNodesObject(); + FemSetNodesObject(); + ~FemSetNodesObject() override; App::PropertyIntegerSet Nodes; // returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderSetNodes"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; diff --git a/src/Mod/Fem/App/FemSetObject.cpp b/src/Mod/Fem/App/FemSetObject.cpp index 040ad89c49..56e0931109 100644 --- a/src/Mod/Fem/App/FemSetObject.cpp +++ b/src/Mod/Fem/App/FemSetObject.cpp @@ -45,7 +45,7 @@ FemSetObject::~FemSetObject() { } -short FemSetObject::mustExecute(void) const +short FemSetObject::mustExecute() const { return 0; } diff --git a/src/Mod/Fem/App/FemSetObject.h b/src/Mod/Fem/App/FemSetObject.h index 3b79ae7408..2d25a059bf 100644 --- a/src/Mod/Fem/App/FemSetObject.h +++ b/src/Mod/Fem/App/FemSetObject.h @@ -33,12 +33,12 @@ namespace Fem class FemExport FemSetObject : public App::DocumentObject { - PROPERTY_HEADER(Fem::FemSetObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemSetObject); public: /// Constructor - FemSetObject(void); - virtual ~FemSetObject(); + FemSetObject(); + ~FemSetObject() override; App::PropertyLink FemMesh; @@ -46,11 +46,11 @@ public: //virtual const char* getViewProviderName(void) const { // return "FemGui::ViewProviderFemSet"; //} - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; diff --git a/src/Mod/Fem/App/FemSolverObject.cpp b/src/Mod/Fem/App/FemSolverObject.cpp index e8dca06337..95d2028da1 100644 --- a/src/Mod/Fem/App/FemSolverObject.cpp +++ b/src/Mod/Fem/App/FemSolverObject.cpp @@ -47,7 +47,7 @@ FemSolverObject::~FemSolverObject() { } -short FemSolverObject::mustExecute(void) const +short FemSolverObject::mustExecute() const { return 0; } @@ -66,11 +66,11 @@ PyObject *FemSolverObject::getPyObject() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Fem::FemSolverObjectPython, Fem::FemSolverObject) -template<> const char* Fem::FemSolverObjectPython::getViewProviderName(void) const { +template<> const char* Fem::FemSolverObjectPython::getViewProviderName() const { return "FemGui::ViewProviderSolverPython"; } -template<> PyObject* Fem::FemSolverObjectPython::getPyObject(void) { +template<> PyObject* Fem::FemSolverObjectPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new App::FeaturePythonPyT(this),true); diff --git a/src/Mod/Fem/App/FemSolverObject.h b/src/Mod/Fem/App/FemSolverObject.h index 83045ec785..1f66432509 100644 --- a/src/Mod/Fem/App/FemSolverObject.h +++ b/src/Mod/Fem/App/FemSolverObject.h @@ -33,24 +33,24 @@ namespace Fem /// Father of all result data in a Fem Analysis class FemExport FemSolverObject : public App::DocumentObject { - PROPERTY_HEADER(Fem::FemSolverObject); + PROPERTY_HEADER_WITH_OVERRIDE(Fem::FemSolverObject); public: /// Constructor - FemSolverObject(void); - virtual ~FemSolverObject(); + FemSolverObject(); + ~FemSolverObject() override; // Attributes are implemented in the FemSolverObjectPython /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "FemGui::ViewProviderSolver"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; }; diff --git a/src/Mod/Fem/App/FemVTKTools.cpp b/src/Mod/Fem/App/FemVTKTools.cpp index abde902d02..a56fd4434b 100644 --- a/src/Mod/Fem/App/FemVTKTools.cpp +++ b/src/Mod/Fem/App/FemVTKTools.cpp @@ -689,9 +689,9 @@ std::map _getFreeCADMechResultVectorProperties() { // the following three are filled only if there is a reinforced mat object // https://forum.freecadweb.org/viewtopic.php?f=18&t=33106&start=70#p296317 // https://forum.freecadweb.org/viewtopic.php?f=18&t=33106&p=416006#p412800 - resFCVecProp["PS1Vector"] = "Major Principal Stress"; - resFCVecProp["PS2Vector"] = "Intermediate Principal Stress"; - resFCVecProp["PS3Vector"] = "Minor Principal Stress"; + resFCVecProp["PS1Vector"] = "Major Principal Stress Vector"; + resFCVecProp["PS2Vector"] = "Intermediate Principal Stress Vector"; + resFCVecProp["PS3Vector"] = "Minor Principal Stress Vector"; return resFCVecProp; } @@ -700,7 +700,7 @@ std::map _getFreeCADMechResultVectorProperties() { // some scalar list are not needed on VTK file export but they are needed for internal VTK pipeline // TODO some filter to only export the needed values to VTK file but have all in FreeCAD VTK pipline std::map _getFreeCADMechResultScalarProperties() { - // see src/Mod/Fem/femobjects/_FemResultMechanical + // see src/Mod/Fem/femobjects/result_mechanical.py // App::PropertyFloatList will be a list of scalars in vtk std::map resFCScalProp; resFCScalProp["DisplacementLengths"] = "Displacement Magnitude"; // can be plotted in Paraview as THE DISPLACEMENT MAGNITUDE @@ -726,6 +726,9 @@ std::map _getFreeCADMechResultScalarProperties() { // thus TODO they might not be exported to external file format (first I need to know how to generate them in paraview) // but there are needed anyway because the pipline in FreeCAD needs the principal stress values // https://forum.freecadweb.org/viewtopic.php?f=18&t=33106&p=416006#p412800 + resFCScalProp["PrincipalMax"] = "Major Principal Stress"; // can be plotted in Paraview as THE MAJOR PRINCIPAL STRESS MAGNITUDE + resFCScalProp["PrincipalMed"] = "Intermediate Principal Stress";// can be plotted in Paraview as THE INTERMEDIATE PRINCIPAL STRESS MAGNITUDE + resFCScalProp["PrincipalMin"] = "Minor Principal Stress"; // can be plotted in Paraview as THE MINOR PRINCIPAL STRESS MAGNITUDE resFCScalProp["vonMises"] = "von Mises Stress"; resFCScalProp["Temperature"] = "Temperature"; resFCScalProp["MohrCoulomb"] = "MohrCoulomb"; @@ -918,7 +921,6 @@ void FemVTKTools::exportFreeCADResult(const App::DocumentObject* result, vtkSmar } if ((it->first.compare("MaxShear") == 0) - || (it->first.compare("MaxShear") == 0) || (it->first.compare("NodeStressXX") == 0) || (it->first.compare("NodeStressXY") == 0) || (it->first.compare("NodeStressXZ") == 0) diff --git a/src/Mod/Fem/App/HypothesisPy.h b/src/Mod/Fem/App/HypothesisPy.h index e66d01cc14..ea810ce371 100755 --- a/src/Mod/Fem/App/HypothesisPy.h +++ b/src/Mod/Fem/App/HypothesisPy.h @@ -36,8 +36,8 @@ class HypothesisPy : public Py::PythonExtension { public: typedef Py::PythonExtension HypothesisPyBase; - HypothesisPy(std::shared_ptr); - virtual ~HypothesisPy(); + explicit HypothesisPy(std::shared_ptr); + ~HypothesisPy() override; std::shared_ptr getHypothesis() const { return hyp; } @@ -54,11 +54,11 @@ public: typedef SMESH_HypothesisPy SMESH_HypothesisPyBase; static void init_type(PyObject*); // announce properties and methods - SMESH_HypothesisPy(SMESH_Hypothesis*); - virtual ~SMESH_HypothesisPy(); + explicit SMESH_HypothesisPy(SMESH_Hypothesis*); + ~SMESH_HypothesisPy() override; - Py::Object getattr(const char *name); - Py::Object repr(); + Py::Object getattr(const char *name) override; + Py::Object repr() override; Py::Object getLibName(const Py::Tuple& args); Py::Object setLibName(const Py::Tuple& args); #if SMESH_VERSION_MAJOR < 7 @@ -387,7 +387,7 @@ class StdMeshers_Arithmetic1DPy : public SMESH_HypothesisPy @@ -418,7 +418,7 @@ class StdMeshers_MaxLengthPy : public SMESH_HypothesisPy public: static void init_type(PyObject*); StdMeshers_MaxLengthPy(int hypId, int studyId, SMESH_Gen* gen); - ~StdMeshers_MaxLengthPy(); + ~StdMeshers_MaxLengthPy() override; Py::Object setLength(const Py::Tuple& args); Py::Object getLength(const Py::Tuple& args); @@ -434,7 +434,7 @@ class StdMeshers_LocalLengthPy : public SMESH_HypothesisPy @@ -466,7 +466,7 @@ class StdMeshers_Quadrangle_2DPy : public SMESH_HypothesisPy @@ -474,7 +474,7 @@ class StdMeshers_Regular_1DPy : public SMESH_HypothesisPy @@ -482,7 +482,7 @@ class StdMeshers_UseExisting_1DPy : public SMESH_HypothesisPy @@ -490,7 +490,7 @@ class StdMeshers_UseExisting_2DPy : public SMESH_HypothesisPy @@ -498,7 +498,7 @@ class StdMeshers_CompositeSegment_1DPy : public SMESH_HypothesisPy @@ -506,7 +506,7 @@ class StdMeshers_Deflection1DPy : public SMESH_HypothesisPy public: static void init_type(PyObject*); StdMeshers_Hexa_3DPy(int hypId, int studyId, SMESH_Gen* gen); - ~StdMeshers_Hexa_3DPy(); + ~StdMeshers_Hexa_3DPy() override; }; #if SMESH_VERSION_MAJOR < 7 // ----------------------------------------------- class StdMeshers_TrianglePreferencePy : public SMESH_HypothesisPy @@ -533,7 +533,7 @@ class StdMeshers_StartEndLengthPy : public SMESH_HypothesisPy @@ -561,7 +561,7 @@ class StdMeshers_RadialPrism_3DPy : public SMESH_HypothesisPy @@ -569,7 +569,7 @@ class StdMeshers_QuadraticMeshPy : public SMESH_HypothesisPy @@ -577,7 +577,7 @@ class StdMeshers_ProjectionSource3DPy : public SMESH_HypothesisPy @@ -641,7 +641,7 @@ class StdMeshers_Projection_2DPy : public SMESH_HypothesisPy @@ -649,7 +649,7 @@ class StdMeshers_Projection_1DPy : public SMESH_HypothesisPy @@ -657,7 +657,7 @@ class StdMeshers_Prism_3DPy : public SMESH_HypothesisPy public: static void init_type(PyObject*); StdMeshers_Prism_3DPy(int hypId, int studyId, SMESH_Gen* gen); - ~StdMeshers_Prism_3DPy(); + ~StdMeshers_Prism_3DPy() override; }; class StdMeshers_NumberOfSegmentsPy : public SMESH_HypothesisPy @@ -665,7 +665,7 @@ class StdMeshers_NumberOfSegmentsPy : public SMESH_HypothesisPy @@ -693,7 +693,7 @@ class StdMeshers_MaxElementVolumePy : public SMESH_HypothesisPyGetNumberOfPoints(); i++) { double xyz[3]; points->GetPoint(i, xyz); @@ -80,24 +80,24 @@ void PropertyPostDataObject::scaleDataObject(vtkDataObject* dataObject, double s }; if (dataObject->GetDataObjectType() == VTK_POLY_DATA) { - vtkPolyData* dataSet = vtkPolyData::SafeDownCast(dataObject); + vtkPolyData *dataSet = vtkPolyData::SafeDownCast(dataObject); scalePoints(dataSet->GetPoints(), s); } else if (dataObject->GetDataObjectType() == VTK_STRUCTURED_GRID) { - vtkStructuredGrid* dataSet = vtkStructuredGrid::SafeDownCast(dataObject); + vtkStructuredGrid *dataSet = vtkStructuredGrid::SafeDownCast(dataObject); scalePoints(dataSet->GetPoints(), s); } else if (dataObject->GetDataObjectType() == VTK_UNSTRUCTURED_GRID) { - vtkUnstructuredGrid* dataSet = vtkUnstructuredGrid::SafeDownCast(dataObject); + vtkUnstructuredGrid *dataSet = vtkUnstructuredGrid::SafeDownCast(dataObject); scalePoints(dataSet->GetPoints(), s); } else if (dataObject->GetDataObjectType() == VTK_MULTIBLOCK_DATA_SET) { - vtkMultiBlockDataSet* dataSet = vtkMultiBlockDataSet::SafeDownCast(dataObject); + vtkMultiBlockDataSet *dataSet = vtkMultiBlockDataSet::SafeDownCast(dataObject); for (unsigned int i = 0; i < dataSet->GetNumberOfBlocks(); i++) scaleDataObject(dataSet->GetBlock(i), s); } else if (dataObject->GetDataObjectType() == VTK_MULTIPIECE_DATA_SET) { - vtkMultiPieceDataSet* dataSet = vtkMultiPieceDataSet::SafeDownCast(dataObject); + vtkMultiPieceDataSet *dataSet = vtkMultiPieceDataSet::SafeDownCast(dataObject); for (unsigned int i = 0; i < dataSet->GetNumberOfPieces(); i++) scaleDataObject(dataSet->GetPiece(i), s); } @@ -112,11 +112,11 @@ void PropertyPostDataObject::scale(double s) } } -void PropertyPostDataObject::setValue(const vtkSmartPointer& ds) +void PropertyPostDataObject::setValue(const vtkSmartPointer &ds) { aboutToSetValue(); - if(ds) { + if (ds) { createDataObjectByExternalType(ds); m_dataObject->DeepCopy(ds); } @@ -127,32 +127,34 @@ void PropertyPostDataObject::setValue(const vtkSmartPointer& ds) hasSetValue(); } -const vtkSmartPointer& PropertyPostDataObject::getValue(void)const +const vtkSmartPointer &PropertyPostDataObject::getValue() const { return m_dataObject; } -bool PropertyPostDataObject::isComposite() { +bool PropertyPostDataObject::isComposite() +{ return m_dataObject && !m_dataObject->IsA("vtkDataSet"); } -bool PropertyPostDataObject::isDataSet() { +bool PropertyPostDataObject::isDataSet() +{ return m_dataObject && m_dataObject->IsA("vtkDataSet"); } -int PropertyPostDataObject::getDataType() { +int PropertyPostDataObject::getDataType() +{ - if(!m_dataObject) + if (!m_dataObject) return -1; return m_dataObject->GetDataObjectType(); } - -PyObject *PropertyPostDataObject::getPyObject(void) +PyObject *PropertyPostDataObject::getPyObject() { //TODO: fetch the vtk python object from the data set and return it return Py::new_reference_to(Py::None()); @@ -162,7 +164,7 @@ void PropertyPostDataObject::setPyObject(PyObject * /*value*/) { } -App::Property *PropertyPostDataObject::Copy(void) const +App::Property *PropertyPostDataObject::Copy() const { PropertyPostDataObject *prop = new PropertyPostDataObject(); if (m_dataObject) { @@ -174,9 +176,10 @@ App::Property *PropertyPostDataObject::Copy(void) const return prop; } -void PropertyPostDataObject::createDataObjectByExternalType(vtkSmartPointer< vtkDataObject > ex) { +void PropertyPostDataObject::createDataObjectByExternalType(vtkSmartPointer ex) +{ - switch( ex->GetDataObjectType() ) { + switch (ex->GetDataObjectType()) { case VTK_POLY_DATA: m_dataObject = vtkSmartPointer::New(); @@ -211,13 +214,13 @@ void PropertyPostDataObject::createDataObjectByExternalType(vtkSmartPointer< vtk void PropertyPostDataObject::Paste(const App::Property &from) { aboutToSetValue(); - m_dataObject = dynamic_cast(from).m_dataObject; + m_dataObject = dynamic_cast(from).m_dataObject; hasSetValue(); } -unsigned int PropertyPostDataObject::getMemSize (void) const +unsigned int PropertyPostDataObject::getMemSize() const { - return m_dataObject->GetActualMemorySize(); + return m_dataObject ? m_dataObject->GetActualMemorySize() : 0; } void PropertyPostDataObject::getPaths(std::vector & /*paths*/) const @@ -234,13 +237,13 @@ void PropertyPostDataObject::getPaths(std::vector & /*pat // << App::ObjectIdentifier::Component::SimpleComponent(App::ObjectIdentifier::String("Volume"))); } -void PropertyPostDataObject::Save (Base::Writer &writer) const +void PropertyPostDataObject::Save(Base::Writer &writer) const { std::string extension; - if(!m_dataObject) + if (!m_dataObject) return; - switch( m_dataObject->GetDataObjectType() ) { + switch (m_dataObject->GetDataObjectType()) { case VTK_POLY_DATA: extension = "vtp"; @@ -255,9 +258,9 @@ void PropertyPostDataObject::Save (Base::Writer &writer) const extension = "vtu"; break; case VTK_UNIFORM_GRID: - extension = "vti"; //image data + extension = "vti";//image data break; - //TODO:multi-datasets use multiple files, this needs to be implemented specially + //TODO:multi-datasets use multiple files, this needs to be implemented specially // case VTK_COMPOSITE_DATA_SET: // prop->m_dataObject = vtkCompositeDataSet::New(); // break; @@ -271,7 +274,7 @@ void PropertyPostDataObject::Save (Base::Writer &writer) const break; }; - if(!writer.isForceXML()) { + if (!writer.isForceXML()) { std::string file = "Data." + extension; writer.Stream() << writer.ind() << "GetPiece() < 0 || dataGrid->GetNumberOfPoints() <= 0)) { std::cerr << "PropertyPostDataObject::SaveDocFile: ignore empty vtkUnstructuredGrid\n"; return; } #endif - if ( xmlWriter->Write() != 1 ) { + if (xmlWriter->Write() != 1) { // Note: Do NOT throw an exception here because if the tmp. file could // not be created we should not abort. // We only print an error message but continue writing the next files to the // stream... - App::PropertyContainer* father = this->getContainer(); + App::PropertyContainer *father = this->getContainer(); if (father && father->isDerivedFrom(App::DocumentObject::getClassTypeId())) { - App::DocumentObject* obj = static_cast(father); + App::DocumentObject *obj = static_cast(father); Base::Console().Error("Dataset of '%s' cannot be written to vtk file '%s'\n", - obj->Label.getValue(),fi.filePath().c_str()); + obj->Label.getValue(), fi.filePath().c_str()); } else { Base::Console().Error("Cannot save vtk file '%s'\n", fi.filePath().c_str()); @@ -340,8 +343,8 @@ void PropertyPostDataObject::SaveDocFile (Base::Writer &writer) const } Base::ifstream file(fi, std::ios::in | std::ios::binary); - if (file){ - std::streambuf* buf = file.rdbuf(); + if (file) { + std::streambuf *buf = file.rdbuf(); writer.Stream() << buf; } @@ -360,7 +363,7 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader &reader) Base::ofstream file(fi, std::ios::out | std::ios::binary); unsigned long ulSize = 0; if (reader) { - std::streambuf* buf = file.rdbuf(); + std::streambuf *buf = file.rdbuf(); reader >> buf; file.flush(); ulSize = buf->pubseekoff(0, std::ios::cur, std::ios::in); @@ -373,7 +376,7 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader &reader) //TODO: read in of composite data structures need to be coded, including replace of "GetOutputAsDataSet()" vtkSmartPointer xmlReader; - if(extension == "vtp") + if (extension == "vtp") xmlReader = vtkSmartPointer::New(); else if (extension == "vts") xmlReader = vtkSmartPointer::New(); @@ -392,11 +395,11 @@ void PropertyPostDataObject::RestoreDocFile(Base::Reader &reader) // not be read it's NOT an indication for an invalid input stream 'reader'. // We only print an error message but continue reading the next files from the // stream... - App::PropertyContainer* father = this->getContainer(); + App::PropertyContainer *father = this->getContainer(); if (father && father->isDerivedFrom(App::DocumentObject::getClassTypeId())) { - App::DocumentObject* obj = static_cast(father); + App::DocumentObject *obj = static_cast(father); Base::Console().Error("Dataset file '%s' with data of '%s' seems to be empty\n", - fi.filePath().c_str(),obj->Label.getValue()); + fi.filePath().c_str(), obj->Label.getValue()); } else { Base::Console().Warning("Loaded Dataset file '%s' seems to be empty\n", fi.filePath().c_str()); diff --git a/src/Mod/Fem/App/PropertyPostDataObject.h b/src/Mod/Fem/App/PropertyPostDataObject.h index 481a1ea9f8..4ae6b23bd6 100644 --- a/src/Mod/Fem/App/PropertyPostDataObject.h +++ b/src/Mod/Fem/App/PropertyPostDataObject.h @@ -39,11 +39,11 @@ namespace Fem */ class FemExport PropertyPostDataObject : public App::Property { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyPostDataObject(); - ~PropertyPostDataObject(); + ~PropertyPostDataObject() override; /** @name Getter/setter */ //@{ @@ -52,7 +52,7 @@ public: /// set the dataset void setValue(const vtkSmartPointer&); /// get the part shape - const vtkSmartPointer& getValue(void) const; + const vtkSmartPointer& getValue() const; /// check if we hold a dataset or a dataobject (which would mean a composite data structure) bool isDataSet(); bool isComposite(); @@ -61,25 +61,25 @@ public: /** @name Python interface */ //@{ - PyObject* getPyObject(void); - void setPyObject(PyObject *value); + PyObject* getPyObject() override; + void setPyObject(PyObject *value) override; //@} /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - App::Property *Copy(void) const; - void Paste(const App::Property &from); - unsigned int getMemSize (void) const; + App::Property *Copy() const override; + void Paste(const App::Property &from) override; + unsigned int getMemSize () const override; //@} /// Get valid paths for this property; used by auto completer - virtual void getPaths(std::vector & paths) const; + void getPaths(std::vector & paths) const override; private: static void scaleDataObject(vtkDataObject*, double s); diff --git a/src/Mod/Fem/CMakeLists.txt b/src/Mod/Fem/CMakeLists.txt index 0649bfa59b..340e3ba855 100755 --- a/src/Mod/Fem/CMakeLists.txt +++ b/src/Mod/Fem/CMakeLists.txt @@ -172,6 +172,7 @@ SET(FemObjects_SRCS femobjects/constraint_electrostaticpotential.py femobjects/constraint_flowvelocity.py femobjects/constraint_initialflowvelocity.py + femobjects/constraint_initialpressure.py femobjects/constraint_sectionprint.py femobjects/constraint_selfweight.py femobjects/constraint_tie.py @@ -562,10 +563,12 @@ SET(FemGuiObjects_SRCS SET(FemGuiTaskPanels_SRCS femtaskpanels/__init__.py + femtaskpanels/task_constraint_bodyheatsource.py femtaskpanels/task_constraint_centrif.py femtaskpanels/task_constraint_electrostaticpotential.py femtaskpanels/task_constraint_flowvelocity.py femtaskpanels/task_constraint_initialflowvelocity.py + femtaskpanels/task_constraint_initialpressure.py femtaskpanels/task_constraint_sectionprint.py femtaskpanels/task_constraint_tie.py femtaskpanels/task_element_fluid1D.py @@ -603,6 +606,7 @@ SET(FemGuiViewProvider_SRCS femviewprovider/view_constraint_electrostaticpotential.py femviewprovider/view_constraint_flowvelocity.py femviewprovider/view_constraint_initialflowvelocity.py + femviewprovider/view_constraint_initialpressure.py femviewprovider/view_constraint_sectionprint.py femviewprovider/view_constraint_selfweight.py femviewprovider/view_constraint_tie.py diff --git a/src/Mod/Fem/Gui/AbaqusHighlighter.h b/src/Mod/Fem/Gui/AbaqusHighlighter.h index c3122800ca..4b6d5a9e1c 100644 --- a/src/Mod/Fem/Gui/AbaqusHighlighter.h +++ b/src/Mod/Fem/Gui/AbaqusHighlighter.h @@ -35,7 +35,7 @@ namespace FemGui { class AbaqusHighlighter : public Gui::SyntaxHighlighter { public: - AbaqusHighlighter(QObject* parent); + explicit AbaqusHighlighter(QObject* parent); virtual ~AbaqusHighlighter(); protected: diff --git a/src/Mod/Fem/Gui/ActiveAnalysisObserver.h b/src/Mod/Fem/Gui/ActiveAnalysisObserver.h index 2387b1563f..86d0824fa8 100644 --- a/src/Mod/Fem/Gui/ActiveAnalysisObserver.h +++ b/src/Mod/Fem/Gui/ActiveAnalysisObserver.h @@ -48,10 +48,10 @@ public: private: ActiveAnalysisObserver(); - ~ActiveAnalysisObserver(); + ~ActiveAnalysisObserver() override; - void slotDeletedDocument(const App::Document& Doc); - void slotDeletedObject(const App::DocumentObject& Obj); + void slotDeletedDocument(const App::Document& Doc) override; + void slotDeletedObject(const App::DocumentObject& Obj) override; private: static ActiveAnalysisObserver* inst; diff --git a/src/Mod/Fem/Gui/AppFemGui.cpp b/src/Mod/Fem/Gui/AppFemGui.cpp index d1d1f8eb23..8401da4f02 100644 --- a/src/Mod/Fem/Gui/AppFemGui.cpp +++ b/src/Mod/Fem/Gui/AppFemGui.cpp @@ -76,7 +76,7 @@ // use a different name to CreateCommand() -void CreateFemCommands(void); +void CreateFemCommands(); void loadFemResource() { diff --git a/src/Mod/Fem/Gui/AppFemGuiPy.cpp b/src/Mod/Fem/Gui/AppFemGuiPy.cpp index fd9f3276e1..2f0601f7ff 100755 --- a/src/Mod/Fem/Gui/AppFemGuiPy.cpp +++ b/src/Mod/Fem/Gui/AppFemGuiPy.cpp @@ -58,10 +58,10 @@ public: initialize("This module is the FemGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_varargs(void* method_def, const Py::Tuple& args) + Py::Object invoke_method_varargs(void* method_def, const Py::Tuple& args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); @@ -125,11 +125,14 @@ private: } } - if (ext == QLatin1String("inp")) { + if ( (ext == QLatin1String("inp")) + || (ext == QLatin1String("sif")) + || (ext == QLatin1String("txt")) ) { Gui::TextEditor* editor = new Gui::TextEditor(); editor->setWindowIcon(Gui::BitmapFactory().pixmap(":/icons/fem-solver-inp-editor.svg")); Gui::EditorView* edit = new Gui::EditorView(editor, Gui::getMainWindow()); - editor->setSyntaxHighlighter(new FemGui::AbaqusHighlighter(editor)); + if (ext == QLatin1String("inp")) + editor->setSyntaxHighlighter(new FemGui::AbaqusHighlighter(editor)); edit->setDisplayName(Gui::EditorView::FileName); edit->open(fileName); edit->resize(400, 300); diff --git a/src/Mod/Fem/Gui/CMakeLists.txt b/src/Mod/Fem/Gui/CMakeLists.txt index 219ae4ebb1..f208dfda0f 100755 --- a/src/Mod/Fem/Gui/CMakeLists.txt +++ b/src/Mod/Fem/Gui/CMakeLists.txt @@ -46,11 +46,14 @@ set(FemGui_LIBS generate_from_xml(ViewProviderFemMeshPy) +generate_from_xml(ViewProviderFemPostPipelinePy) SET(Python_SRCS ViewProviderFemMeshPy.xml ViewProviderFemMeshPyImp.cpp + ViewProviderFemPostPipelinePy.xml + ViewProviderFemPostPipelinePyImp.cpp ) SOURCE_GROUP("Python" FILES ${Python_SRCS}) @@ -381,6 +384,7 @@ INSTALL(FILES ${FemGuiIcon_SVG} DESTINATION "${CMAKE_INSTALL_DATADIR}/Mod/Fem/Re # Python modules ui files, they are copied as they are, thus the need not to be added to Fem.qrc # see https://forum.freecadweb.org/viewtopic.php?f=10&t=25833 SET(FemGuiPythonUI_SRCS + Resources/ui/BodyHeatSource.ui Resources/ui/ConstraintCentrif.ui Resources/ui/ConstraintTie.ui Resources/ui/ConstraintSectionPrint.ui @@ -391,6 +395,7 @@ SET(FemGuiPythonUI_SRCS Resources/ui/ElementRotation1D.ui Resources/ui/FlowVelocity.ui Resources/ui/InitialFlowVelocity.ui + Resources/ui/InitialPressure.ui Resources/ui/Material.ui Resources/ui/MaterialReinforcement.ui Resources/ui/MeshBoundaryLayer.ui diff --git a/src/Mod/Fem/Gui/Command.cpp b/src/Mod/Fem/Gui/Command.cpp index 7a1fa85c95..237c9dbc93 100644 --- a/src/Mod/Fem/Gui/Command.cpp +++ b/src/Mod/Fem/Gui/Command.cpp @@ -314,7 +314,7 @@ void CmdFemConstraintBearing::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintBearing::isActive(void) +bool CmdFemConstraintBearing::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -359,7 +359,7 @@ void CmdFemConstraintContact::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintContact::isActive(void) +bool CmdFemConstraintContact::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -402,7 +402,7 @@ void CmdFemConstraintDisplacement::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintDisplacement::isActive(void) +bool CmdFemConstraintDisplacement::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -444,7 +444,7 @@ void CmdFemConstraintFixed::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintFixed::isActive(void) +bool CmdFemConstraintFixed::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -487,7 +487,7 @@ void CmdFemConstraintFluidBoundary::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintFluidBoundary::isActive(void) +bool CmdFemConstraintFluidBoundary::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -531,7 +531,7 @@ void CmdFemConstraintForce::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintForce::isActive(void) +bool CmdFemConstraintForce::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -572,7 +572,7 @@ void CmdFemConstraintGear::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintGear::isActive(void) +bool CmdFemConstraintGear::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -617,7 +617,7 @@ void CmdFemConstraintHeatflux::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintHeatflux::isActive(void) +bool CmdFemConstraintHeatflux::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -660,7 +660,7 @@ void CmdFemConstraintInitialTemperature::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintInitialTemperature::isActive(void) +bool CmdFemConstraintInitialTemperature::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -702,7 +702,7 @@ void CmdFemConstraintPlaneRotation::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintPlaneRotation::isActive(void) +bool CmdFemConstraintPlaneRotation::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -734,7 +734,7 @@ void CmdFemConstraintPressure::activated(int) openCommand(QT_TRANSLATE_NOOP("Command", "Make FEM constraint pressure on face")); doCommand(Doc, "App.activeDocument().addObject(\"Fem::ConstraintPressure\",\"%s\")", FeatName.c_str()); - doCommand(Doc, "App.activeDocument().%s.Pressure = 1000.0", FeatName.c_str()); //OvG: set default not equal to 0 + doCommand(Doc, "App.activeDocument().%s.Pressure = 0.1", FeatName.c_str()); //OvG: set default not equal to 0 doCommand(Doc, "App.activeDocument().%s.Reversed = False", FeatName.c_str()); //OvG: set default to False doCommand(Doc, "App.activeDocument().%s.Scale = 1", FeatName.c_str()); //OvG: set initial scale to 1 doCommand(Doc, "App.activeDocument().%s.addObject(App.activeDocument().%s)", @@ -747,7 +747,7 @@ void CmdFemConstraintPressure::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintPressure::isActive(void) +bool CmdFemConstraintPressure::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -792,7 +792,7 @@ void CmdFemConstraintSpring::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintSpring::isActive(void) +bool CmdFemConstraintSpring::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -838,7 +838,7 @@ void CmdFemConstraintPulley::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintPulley::isActive(void) +bool CmdFemConstraintPulley::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -881,7 +881,7 @@ void CmdFemConstraintTemperature::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintTemperature::isActive(void) +bool CmdFemConstraintTemperature::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -927,7 +927,7 @@ void CmdFemConstraintTransform::activated(int) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } -bool CmdFemConstraintTransform::isActive(void) +bool CmdFemConstraintTransform::isActive() { return FemGui::ActiveAnalysisObserver::instance()->hasActiveObject(); } @@ -1063,7 +1063,7 @@ void CmdFemDefineNodesSet::activated(int) } } -bool CmdFemDefineNodesSet::isActive(void) +bool CmdFemDefineNodesSet::isActive() { // Check for the selected mesh feature (all Mesh types) if (getSelection().countObjectsOfType(Fem::FemMeshObject::getClassTypeId()) != 1) @@ -1121,7 +1121,7 @@ void CmdFemCreateNodesSet::activated(int) } } -bool CmdFemCreateNodesSet::isActive(void) +bool CmdFemCreateNodesSet::isActive() { return hasActiveDocument(); } @@ -1199,9 +1199,13 @@ void setupFilter(Gui::Command* cmd, std::string Name) { cmd->doCommand(Gui::Command::Doc, "__list__.append(App.ActiveDocument.%s)", FeatName.c_str()); cmd->doCommand(Gui::Command::Doc, "App.ActiveDocument.%s.Filter = __list__", pipeline->getNameInDocument()); cmd->doCommand(Gui::Command::Doc, "del __list__"); - + // set display to assure the user sees the new object cmd->doCommand(Gui::Command::Doc, "App.activeDocument().ActiveObject.ViewObject.DisplayMode = \"Surface\""); + // Set SelectionStyle to BoundBox because the idea is that the user gets the useful result + // from the colors. The default would be to highlight the shape but then the colors are changed + // by every highlighting leading to confusions for the user. + cmd->doCommand(Gui::Command::Doc, "App.activeDocument().ActiveObject.ViewObject.SelectionStyle = \"BoundBox\""); // in case selObject is no pipeline we must set it as input object auto objFilter = App::GetApplication().getActiveDocument()->getActiveObject(); @@ -1215,7 +1219,7 @@ void setupFilter(Gui::Command* cmd, std::string Name) { } -std::string Plot() +std::string Plot() { auto xAxisLabel = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", "Thickness [mm]", "Plot X-Axis Label").toStdString(); auto yAxisLabel = QCoreApplication::translate("CmdFemPostLinearizedStressesFilter", "Stress [MPa]", "Plot Y-Axis Label").toStdString(); @@ -1307,7 +1311,7 @@ void CmdFemPostClipFilter::activated(int) setupFilter(this, "Clip"); } -bool CmdFemPostClipFilter::isActive(void) +bool CmdFemPostClipFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1350,7 +1354,7 @@ void CmdFemPostCutFilter::activated(int) setupFilter(this, "Cut"); } -bool CmdFemPostCutFilter::isActive(void) +bool CmdFemPostCutFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1393,7 +1397,7 @@ void CmdFemPostDataAlongLineFilter::activated(int) setupFilter(this, "DataAlongLine"); } -bool CmdFemPostDataAlongLineFilter::isActive(void) +bool CmdFemPostDataAlongLineFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1436,7 +1440,7 @@ void CmdFemPostDataAtPointFilter::activated(int) } -bool CmdFemPostDataAtPointFilter::isActive(void) +bool CmdFemPostDataAtPointFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1491,7 +1495,7 @@ void CmdFemPostLinearizedStressesFilter::activated(int) // names need to match with names in FemVTKTools.cpp, this is not failsafe, but ATM there is no better way for test on a stress result in vtk pipeline ) { // TODO FIXME only works if the data along the line object has the name DataAlongLine - // we should get the selected data along the line object + // we should get the selected data along the line object App::DocumentObjectT objT(DataAlongLine); std::string ObjName = objT.getObjectPython(); Gui::doCommandT(Gui::Command::Doc, "t_coords = %s.XAxisData", ObjName); @@ -1511,7 +1515,7 @@ void CmdFemPostLinearizedStressesFilter::activated(int) } } -bool CmdFemPostLinearizedStressesFilter::isActive(void) +bool CmdFemPostLinearizedStressesFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1543,7 +1547,7 @@ void CmdFemPostScalarClipFilter::activated(int) setupFilter(this, "ScalarClip"); } -bool CmdFemPostScalarClipFilter::isActive(void) +bool CmdFemPostScalarClipFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1584,7 +1588,7 @@ void CmdFemPostWarpVectorFilter::activated(int) setupFilter(this, "WarpVector"); } -bool CmdFemPostWarpVectorFilter::isActive(void) +bool CmdFemPostWarpVectorFilter::isActive() { // only allow one object if (getSelection().getSelection().size() > 1) @@ -1675,7 +1679,7 @@ void CmdFemPostFunctions::activated(int iMsg) this->updateActive(); //most of the times functions are added inside of a filter, make sure this still works - if (Gui::Application::Instance->activeDocument()->getInEdit() == nullptr) + if (!Gui::Application::Instance->activeDocument()->getInEdit()) doCommand(Gui, "Gui.activeDocument().setEdit('%s')", FeatName.c_str()); } else { @@ -1693,7 +1697,7 @@ void CmdFemPostFunctions::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action* CmdFemPostFunctions::createAction(void) +Gui::Action* CmdFemPostFunctions::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1736,7 +1740,7 @@ void CmdFemPostFunctions::languageChange() } -bool CmdFemPostFunctions::isActive(void) +bool CmdFemPostFunctions::isActive() { if (getActiveGuiDocument()) return true; @@ -1766,7 +1770,7 @@ void CmdFemPostApllyChanges::activated(int iMsg) FemGui::FemSettings().setPostAutoRecompute(iMsg == 1); } -bool CmdFemPostApllyChanges::isActive(void) +bool CmdFemPostApllyChanges::isActive() { if (getActiveGuiDocument()) return true; @@ -1774,7 +1778,7 @@ bool CmdFemPostApllyChanges::isActive(void) return false; } -Gui::Action* CmdFemPostApllyChanges::createAction(void) +Gui::Action* CmdFemPostApllyChanges::createAction() { Gui::Action* pcAction = Command::createAction(); pcAction->setCheckable(true); @@ -1849,6 +1853,10 @@ void CmdFemPostPipelineFromResult::activated(int) "App.activeDocument().getObject(\"%s\"))", results[0]->getNameInDocument()); // set display to assure the user sees the new object doCommand(Doc, "App.activeDocument().ActiveObject.ViewObject.DisplayMode = \"Surface\""); + // Set SelectionStyle to BoundBox because the idea is that the user gets the useful result + // from the colors. The default would be to highlight the shape but then the colors are changed + // by every highlighting leading to confusions for the user. + doCommand(Doc, "App.activeDocument().ActiveObject.ViewObject.SelectionStyle = \"BoundBox\""); commitCommand(); this->updateActive(); @@ -1861,7 +1869,7 @@ void CmdFemPostPipelineFromResult::activated(int) } } -bool CmdFemPostPipelineFromResult::isActive(void) +bool CmdFemPostPipelineFromResult::isActive() { // only activate if a result object is selected from which the pipeline can be loaded std::vector results = getSelection().getObjectsOfType(); @@ -1873,7 +1881,7 @@ bool CmdFemPostPipelineFromResult::isActive(void) //================================================================================================ //================================================================================================ -void CreateFemCommands(void) +void CreateFemCommands() { Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp index f3f5b5ff30..68ed8742cc 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.cpp @@ -26,6 +26,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ # include +# include #endif #include @@ -49,6 +50,9 @@ DlgSettingsFemCcxImp::DlgSettingsFemCcxImp(QWidget* parent) // hardware check might fail and then returns 0 if (processor_count > 0) ui->sb_ccx_numcpu->setMaximum(processor_count); + + connect(ui->fc_ccx_binary_path, &Gui::PrefFileChooser::fileNameChanged, + this, &DlgSettingsFemCcxImp::onfileNameChanged); } DlgSettingsFemCcxImp::~DlgSettingsFemCcxImp() @@ -135,4 +139,13 @@ void DlgSettingsFemCcxImp::changeEvent(QEvent* e) } } +void DlgSettingsFemCcxImp::onfileNameChanged(QString FileName) +{ + if (!QFileInfo::exists(FileName)) { + QMessageBox::critical(this, tr("File does not exist"), + tr("The specified executable \n'%1'\n does not exist!\n" + "Specify another file please.").arg(FileName)); + } +} + #include "moc_DlgSettingsFemCcxImp.cpp" diff --git a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.h b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.h index 0ef22f5594..8afdd7fc01 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemCcxImp.h @@ -37,13 +37,16 @@ class DlgSettingsFemCcxImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemCcxImp( QWidget* parent = nullptr ); - ~DlgSettingsFemCcxImp(); + explicit DlgSettingsFemCcxImp( QWidget* parent = nullptr ); + ~DlgSettingsFemCcxImp() override; + +protected Q_SLOTS: + void onfileNameChanged(QString FileName); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp index cc6a40dc59..57abe66272 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.cpp @@ -102,7 +102,6 @@ void DlgSettingsFemElmerImp::onfileNameChanged(QString FileName) QMessageBox::critical(this, tr("File does not exist"), tr("The specified executable \n'%1'\n does not exist!\n" "Specify another file please.").arg(FileName)); - return; } } diff --git a/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.h b/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.h index 68ec6a043a..20ffff78fb 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemElmerImp.h @@ -36,8 +36,8 @@ class DlgSettingsFemElmerImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemElmerImp( QWidget* parent = nullptr ); - ~DlgSettingsFemElmerImp(); + explicit DlgSettingsFemElmerImp( QWidget* parent = nullptr ); + ~DlgSettingsFemElmerImp() override; protected Q_SLOTS: void onfileNameChanged(QString FileName); @@ -45,9 +45,9 @@ protected Q_SLOTS: void onCoresValueChanged(int cores); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.h b/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.h index 3b8f2a971f..1a86e4a2e6 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemExportAbaqusImp.h @@ -36,13 +36,13 @@ class DlgSettingsFemExportAbaqusImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemExportAbaqusImp( QWidget* parent = nullptr ); - ~DlgSettingsFemExportAbaqusImp(); + explicit DlgSettingsFemExportAbaqusImp( QWidget* parent = nullptr ); + ~DlgSettingsFemExportAbaqusImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: Ui_DlgSettingsFemExportAbaqus* ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.h b/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.h index c0fdb0b3cd..ee6a01b8b7 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemGeneralImp.h @@ -36,13 +36,13 @@ class DlgSettingsFemGeneralImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemGeneralImp( QWidget* parent = nullptr ); - ~DlgSettingsFemGeneralImp(); + explicit DlgSettingsFemGeneralImp( QWidget* parent = nullptr ); + ~DlgSettingsFemGeneralImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp index 986df854d6..6d1881bc2b 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.cpp @@ -23,6 +23,9 @@ ***************************************************************************/ #include "PreCompiled.h" +#ifndef _PreComp_ +# include +#endif #include "DlgSettingsFemGmshImp.h" #include "ui_DlgSettingsFemGmsh.h" @@ -35,6 +38,9 @@ DlgSettingsFemGmshImp::DlgSettingsFemGmshImp(QWidget* parent) , ui(new Ui_DlgSettingsFemGmshImp) { ui->setupUi(this); + + connect(ui->fc_gmsh_binary_path, &Gui::PrefFileChooser::fileNameChanged, + this, &DlgSettingsFemGmshImp::onfileNameChanged); } DlgSettingsFemGmshImp::~DlgSettingsFemGmshImp() @@ -67,4 +73,13 @@ void DlgSettingsFemGmshImp::changeEvent(QEvent* e) } } +void DlgSettingsFemGmshImp::onfileNameChanged(QString FileName) +{ + if (!QFileInfo::exists(FileName)) { + QMessageBox::critical(this, tr("File does not exist"), + tr("The specified executable \n'%1'\n does not exist!\n" + "Specify another file please.").arg(FileName)); + } +} + #include "moc_DlgSettingsFemGmshImp.cpp" diff --git a/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.h b/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.h index cc453e70e7..5ef7e9375f 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemGmshImp.h @@ -36,13 +36,16 @@ class DlgSettingsFemGmshImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemGmshImp( QWidget* parent = nullptr ); - ~DlgSettingsFemGmshImp(); + explicit DlgSettingsFemGmshImp( QWidget* parent = nullptr ); + ~DlgSettingsFemGmshImp() override; + +protected Q_SLOTS: + void onfileNameChanged(QString FileName); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.h b/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.h index 7dd612966f..b9188e79f8 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemInOutVtkImp.h @@ -36,13 +36,13 @@ class DlgSettingsFemInOutVtkImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemInOutVtkImp( QWidget* parent = nullptr ); - ~DlgSettingsFemInOutVtkImp(); + explicit DlgSettingsFemInOutVtkImp( QWidget* parent = nullptr ); + ~DlgSettingsFemInOutVtkImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: Ui_DlgSettingsFemInOutVtk* ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemMaterialImp.h b/src/Mod/Fem/Gui/DlgSettingsFemMaterialImp.h index 39e78a9484..792b015750 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemMaterialImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemMaterialImp.h @@ -37,13 +37,13 @@ class DlgSettingsFemMaterialImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemMaterialImp( QWidget* parent = nullptr ); - ~DlgSettingsFemMaterialImp(); + explicit DlgSettingsFemMaterialImp( QWidget* parent = nullptr ); + ~DlgSettingsFemMaterialImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp b/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp index cd86381325..2884725e56 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp +++ b/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.cpp @@ -23,6 +23,9 @@ ***************************************************************************/ #include "PreCompiled.h" +#ifndef _PreComp_ +# include +#endif #include "DlgSettingsFemMystranImp.h" #include "ui_DlgSettingsFemMystran.h" @@ -35,6 +38,9 @@ DlgSettingsFemMystranImp::DlgSettingsFemMystranImp(QWidget* parent) , ui(new Ui_DlgSettingsFemMystranImp) { ui->setupUi(this); + + connect(ui->fc_mystran_binary_path, &Gui::PrefFileChooser::fileNameChanged, + this, &DlgSettingsFemMystranImp::onfileNameChanged); } DlgSettingsFemMystranImp::~DlgSettingsFemMystranImp() @@ -69,4 +75,13 @@ void DlgSettingsFemMystranImp::changeEvent(QEvent* e) } } +void DlgSettingsFemMystranImp::onfileNameChanged(QString FileName) +{ + if (!QFileInfo::exists(FileName)) { + QMessageBox::critical(this, tr("File does not exist"), + tr("The specified executable \n'%1'\n does not exist!\n" + "Specify another file please.").arg(FileName)); + } +} + #include "moc_DlgSettingsFemMystranImp.cpp" diff --git a/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.h b/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.h index 8938be99e2..e58908ed0b 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemMystranImp.h @@ -37,13 +37,16 @@ class DlgSettingsFemMystranImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemMystranImp( QWidget* parent = nullptr ); - ~DlgSettingsFemMystranImp(); + explicit DlgSettingsFemMystranImp( QWidget* parent = nullptr ); + ~DlgSettingsFemMystranImp() override; + +protected Q_SLOTS: + void onfileNameChanged(QString FileName); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.h b/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.h index a520492bb8..e90e6c045b 100644 --- a/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.h +++ b/src/Mod/Fem/Gui/DlgSettingsFemZ88Imp.h @@ -37,16 +37,16 @@ class DlgSettingsFemZ88Imp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsFemZ88Imp( QWidget* parent = nullptr ); - ~DlgSettingsFemZ88Imp(); + explicit DlgSettingsFemZ88Imp( QWidget* parent = nullptr ); + ~DlgSettingsFemZ88Imp() override; protected Q_SLOTS: void onfileNameChanged(QString FileName); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Fem/Gui/FemSelectionGate.h b/src/Mod/Fem/Gui/FemSelectionGate.h index 238a4aab30..1c39f47117 100644 --- a/src/Mod/Fem/Gui/FemSelectionGate.h +++ b/src/Mod/Fem/Gui/FemSelectionGate.h @@ -37,7 +37,7 @@ class FemSelectionGate : public Gui::SelectionFilterGate NodeElement }; - FemSelectionGate(ElemType type) + explicit FemSelectionGate(ElemType type) : Gui::SelectionFilterGate(nullPointer()),Type(type) { } @@ -45,7 +45,7 @@ class FemSelectionGate : public Gui::SelectionFilterGate ElemType Type; /// get called by the frame-work - bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName); + bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/PropertyFemMeshItem.h b/src/Mod/Fem/Gui/PropertyFemMeshItem.h index 5167ecfbc4..2609c634bf 100644 --- a/src/Mod/Fem/Gui/PropertyFemMeshItem.h +++ b/src/Mod/Fem/Gui/PropertyFemMeshItem.h @@ -34,18 +34,18 @@ namespace FemGui { class PropertyFemMeshItem : public Gui::PropertyEditor::PropertyItem { Q_OBJECT - Q_PROPERTY(int Nodes READ countNodes) - Q_PROPERTY(int Edges READ countEdges) - Q_PROPERTY(int Faces READ countFaces) - Q_PROPERTY(int Polygons READ countPolygons) - Q_PROPERTY(int Volumes READ countVolumes) - Q_PROPERTY(int Polyhedrons READ countPolyhedrons) - Q_PROPERTY(int Groups READ countGroups) + Q_PROPERTY(int Nodes READ countNodes CONSTANT) + Q_PROPERTY(int Edges READ countEdges CONSTANT) + Q_PROPERTY(int Faces READ countFaces CONSTANT) + Q_PROPERTY(int Polygons READ countPolygons CONSTANT) + Q_PROPERTY(int Volumes READ countVolumes CONSTANT) + Q_PROPERTY(int Polyhedrons READ countPolyhedrons CONSTANT) + Q_PROPERTY(int Groups READ countGroups CONSTANT) PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; int countNodes() const; int countEdges() const; @@ -56,13 +56,13 @@ class PropertyFemMeshItem : public Gui::PropertyEditor::PropertyItem int countGroups() const; protected: - virtual QVariant toolTip(const App::Property*) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toolTip(const App::Property*) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyFemMeshItem(); - void initialize(); + void initialize() override; private: Gui::PropertyEditor::PropertyIntegerItem* m_n; diff --git a/src/Mod/Fem/Gui/Resources/Fem.qrc b/src/Mod/Fem/Gui/Resources/Fem.qrc index f86bd3c1c1..247d75ab00 100755 --- a/src/Mod/Fem/Gui/Resources/Fem.qrc +++ b/src/Mod/Fem/Gui/Resources/Fem.qrc @@ -10,6 +10,7 @@ icons/FEM_ConstraintBearing.svg + icons/FEM_ConstraintBodyHeatSource.svg icons/FEM_ConstraintCentrif.svg icons/FEM_ConstraintContact.svg icons/FEM_ConstraintDisplacement.svg @@ -21,16 +22,17 @@ icons/FEM_ConstraintGear.svg icons/FEM_ConstraintHeatflux.svg icons/FEM_ConstraintInitialFlowVelocity.svg + icons/FEM_ConstraintInitialPressure.svg icons/FEM_ConstraintInitialTemperature.svg icons/FEM_ConstraintPlaneRotation.svg icons/FEM_ConstraintPressure.svg icons/FEM_ConstraintPulley.svg icons/FEM_ConstraintSectionPrint.svg icons/FEM_ConstraintSelfWeight.svg + icons/FEM_ConstraintSpring.svg icons/FEM_ConstraintTemperature.svg icons/FEM_ConstraintTie.svg icons/FEM_ConstraintTransform.svg - icons/FEM_ConstraintSpring.svg icons/FEM_ElementFluid1D.svg @@ -62,7 +64,6 @@ icons/FEM_MaterialSolid.svg - icons/FEM_PostPipelineFromResult.svg icons/FEM_PostFilterClipRegion.svg icons/FEM_PostFilterClipScalar.svg icons/FEM_PostFilterCutFunction.svg @@ -70,6 +71,7 @@ icons/FEM_PostFilterDataAtPoint.svg icons/FEM_PostFilterLinearizedStresses.svg icons/FEM_PostFilterWarp.svg + icons/FEM_PostPipelineFromResult.svg icons/FEM_ResultShow.svg icons/FEM_ResultsPurge.svg @@ -110,10 +112,12 @@ translations/Fem_af.qm translations/Fem_ar.qm + translations/Fem_bg.qm translations/Fem_ca.qm translations/Fem_cs.qm translations/Fem_de.qm translations/Fem_el.qm + translations/Fem_es-AR.qm translations/Fem_es-ES.qm translations/Fem_eu.qm translations/Fem_fi.qm @@ -125,6 +129,7 @@ translations/Fem_id.qm translations/Fem_it.qm translations/Fem_ja.qm + translations/Fem_ka.qm translations/Fem_kab.qm translations/Fem_ko.qm translations/Fem_lt.qm @@ -145,11 +150,9 @@ translations/Fem_vi.qm translations/Fem_zh-CN.qm translations/Fem_zh-TW.qm - translations/Fem_es-AR.qm - translations/Fem_bg.qm - translations/Fem_ka.qm + ui/BodyHeatSource.ui ui/ConstraintCentrif.ui ui/ConstraintSectionPrint.ui ui/ConstraintTie.ui @@ -160,6 +163,7 @@ ui/ElementRotation1D.ui ui/FlowVelocity.ui ui/InitialFlowVelocity.ui + ui/InitialPressure.ui ui/Material.ui ui/MaterialReinforcement.ui ui/MeshBoundaryLayer.ui diff --git a/src/Mod/Fem/Gui/Resources/icons/Arch_Material_Group.svg b/src/Mod/Fem/Gui/Resources/icons/Arch_Material_Group.svg index 845747139a..87a3ac3d5a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/Arch_Material_Group.svg +++ b/src/Mod/Fem/Gui/Resources/icons/Arch_Material_Group.svg @@ -1,5 +1,5 @@ - + @@ -72,7 +72,7 @@ - + @@ -82,7 +82,7 @@ - + @@ -90,7 +90,7 @@ - + @@ -99,7 +99,6 @@ image/svg+xml - [Yorik van Havre] diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_Analysis.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_Analysis.svg index 95e6ab34ac..85247ec6da 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_Analysis.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_Analysis.svg @@ -1,30 +1,26 @@ - + + - - - + + + - - + + - - + + - - - + + - - - image/svg+xml - - + [Przemo Firszt] @@ -53,10 +49,10 @@ - + - + - + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneAdd.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneAdd.svg index d693643202..c42689f4e2 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneAdd.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneAdd.svg @@ -1,169 +1 @@ - - - - - - - - image/svg+xml - - - - - [Alexander Gryson] - - - fem-clip - 2017-03-11 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/ - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - - - - - - - - - - - - + image/svg+xml [Alexander Gryson] fem-clip 2017-03-11 http://www.freecadweb.org/wiki/index.php?title=Artwork FreeCAD FreeCAD/src/Mod/ FreeCAD LGPL2+ https://www.gnu.org/copyleft/lesser.html [agryson] Alexander Gryson \ No newline at end of file diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneRemoveAll.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneRemoveAll.svg index 2a4e607f71..77ca5358bf 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneRemoveAll.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ClippingPlaneRemoveAll.svg @@ -1,31 +1,12 @@ - - + + - + image/svg+xml - - + [Alexander Gryson] @@ -54,146 +35,27 @@ - - - + + + - + - - - - - - - - - - - + + + + + + + + - - - - - - - - + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBearing.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBearing.svg index 7dd9be526d..2be60f202a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBearing.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBearing.svg @@ -1,86 +1,82 @@ - + + - - - + + + - - - + + + - - + + - - - + + - - + + - + - - + + - - - - - - - - + + + + + + + + - - - + + + - - - - - - + + + + + + - - - - + + + + - - - - - + + + + + - - - - - - - - + + + + + + + + - - - - + + + + - - - image/svg+xml - - + [Przemo Firszt] @@ -109,56 +105,56 @@ - + - - - - - - + + + + + + - - + + - - - - - + + + + + - - - - - - + + + + + + - - + + - - - - - + + + + + - + - + - - + + - + - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBodyHeatSource.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBodyHeatSource.svg new file mode 100644 index 0000000000..01ebe4eb5c --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintBodyHeatSource.svg @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + [vdwalts] + + + fem-constraint-heatflux + 2016-08-01 + http://www.freecadweb.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/icons/FEM_ConstraintCentrif.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintCentrif.svg index 001608e20c..826f1fc223 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintCentrif.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintCentrif.svg @@ -1,78 +1,78 @@ - - - - - - - - - - - - - - - - image/svg+xml - - - - [Przemo Firszt] - - - 2015-07-28 - http://www.freecadweb.org/wiki/index.php?title=Artwork - - - FreeCAD - - - FreeCAD/src/Mod/ - - - FreeCAD LGPL2+ - - - https://www.gnu.org/copyleft/lesser.html - - - [agryson] Alexander Gryson - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + image/svg+xml + + + + [Przemo Firszt] + + + 2015-07-28 + http://www.freecadweb.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/icons/FEM_ConstraintContact.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintContact.svg index e8890ddcab..84d5fdf69c 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintContact.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintContact.svg @@ -1,11 +1,10 @@ - + image/svg+xml - - + [vdwalts] @@ -35,226 +34,219 @@ - - - + + + - - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - + - - + + - - - + + + - - + + - - + + - - - - - - + + + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - - - + + + + + + - - - - + + + + - - + + - - - - - - - - - + + + + + + - - + + - - - - + + + + - - + + - + - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintDisplacement.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintDisplacement.svg index b28939c3b5..16f3e05fec 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintDisplacement.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintDisplacement.svg @@ -1,47 +1,43 @@ - + + - - - + + + - - - + + + - - + + - - - - - - - + + + + + + - - - - + + + + - - - - + + + + - - - image/svg+xml - - + [vginkeo] @@ -70,39 +66,33 @@ - - - - - - - - - - - + + +   +   +   - + - + - - - - - + + + + + - - + + - - + + - - - - + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintElectrostaticPotential.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintElectrostaticPotential.svg index 7e4199c7ee..b940461050 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintElectrostaticPotential.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintElectrostaticPotential.svg @@ -1,240 +1,67 @@ - - FEM_ConstraintElectrostaticPotential - - - - + + FEM_ConstraintElectrostaticPotential + + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - + + + - - - - - + + + + + - - - - + + + + - + - + image/svg+xml - + FEM_ConstraintElectrostaticPotential @@ -267,75 +94,21 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFixed.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFixed.svg index ac3d40c8be..31cacb71c5 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFixed.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFixed.svg @@ -1,74 +1,70 @@ - + + - + - - + + - - - - - + + + + - - - + + + - - - - - - + + + + + + - - - + + + - - - - - - + + + + + + - - - - + + + + - - - - - + + + + + - - - - + + + + - - - - + + + + - - - + + + - - - image/svg+xml - - + [Przemo Firszt] @@ -97,35 +93,35 @@ - + - - - - - + + + + + - - + + - - + + - - - - + + + + - - - - + + + + - - - + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFlowVelocity.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFlowVelocity.svg index 6c065c6c77..28124e60c5 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFlowVelocity.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFlowVelocity.svg @@ -1,180 +1,49 @@ - - FEM_ConstraintFlowVelocity - - - - + + FEM_ConstraintFlowVelocity + + + + - - - + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - + + + - - - - + + + + - + - + image/svg+xml - + FEM_ConstraintFlowVelocity @@ -207,67 +76,24 @@ - - - - - - + + + + + + - - - - - + + + + + - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFluidBoundary.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFluidBoundary.svg index ad30ba4b0c..f815c6a5b3 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFluidBoundary.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintFluidBoundary.svg @@ -1,37 +1,32 @@ - + + - - - + + + - - - + + - - + + - - - - - - - + + + + + + - + - - - image/svg+xml - - + [qingfengxia] @@ -60,26 +55,26 @@ - - - - + + + + - - + + - - + + - - - - - - - - - + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintForce.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintForce.svg index 18874f76b0..4933163584 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintForce.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintForce.svg @@ -1,55 +1,51 @@ - + + - - + + - + - - + + - - - + + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - + - - + + - - + + - - - image/svg+xml - - + [Przemo Firszt] @@ -78,29 +74,29 @@ - + - - - - - + + + + + - - + + - - + + - - - - + + + + - - + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintGear.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintGear.svg index bdd0a7e1b8..2e1c94f7a3 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintGear.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintGear.svg @@ -1,17 +1,15 @@ - + image/svg+xml - - + [Przemo Firszt] - fem-constraint-gear 2015-07-28 http://www.freecadweb.org/wiki/index.php?title=Artwork @@ -35,233 +33,226 @@ - - - + + + - - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - + - - + + - + - - + + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - + - - - - + - - - - - - + + + + + + - - + + - - - - - + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - + + + + + - - + + - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintHeatflux.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintHeatflux.svg index 8507c1e254..c0d07c9dab 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintHeatflux.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintHeatflux.svg @@ -1,49 +1,45 @@ - + + - - - + + + - + - - + + - - - + + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - + - - - image/svg+xml - - + [vdwalts] @@ -72,38 +68,38 @@ - + - - - - - + + + + + - - + + - - + + - - - - + + + + - - - - - - - - - - - - - + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialFlowVelocity.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialFlowVelocity.svg index 4aecde0e77..cd2f75de39 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialFlowVelocity.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialFlowVelocity.svg @@ -1,180 +1,49 @@ - - FEM_ConstraintInitialFlowVelocity - - - - + + FEM_ConstraintInitialFlowVelocity + + + + - - - + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - + + + - - - - + + + + - + - + image/svg+xml - + FEM_ConstraintInitialFlowVelocity @@ -207,85 +76,25 @@ - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialPressure.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialPressure.svg new file mode 100644 index 0000000000..0387e04512 --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialPressure.svg @@ -0,0 +1,112 @@ + + + FEM_ConstraintInitialFlowVelocity + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + FEM_ConstraintInitialFlowVelocity + + + [bitacovir] + + + PartDesign_MoveTip + 12-02-2021 + http://www.freecadweb.org/wiki/index.php?title=Artwork + + + FreeCAD + + + + + + FreeCAD LGPL2+ + + + https://www.gnu.org/copyleft/lesser.html + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialTemperature.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialTemperature.svg index 21369de342..a778ffa0a8 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialTemperature.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintInitialTemperature.svg @@ -1,41 +1,37 @@ - + + - + - - + + - - - + + - - + + - - - - + + + + - - - - + + + + - - + + - - - image/svg+xml - - + [vdwalts] @@ -64,22 +60,22 @@ - + - - - - - - + + + + + + - - + + - - - - + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPlaneRotation.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPlaneRotation.svg index 181a205521..4a8bc5e239 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPlaneRotation.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPlaneRotation.svg @@ -1,42 +1,38 @@ - + + - - - + + + - - + + - - - - - + + + + - - - - + + + + - - - - + + + + - + - - - image/svg+xml - - + [vdwalts] @@ -65,41 +61,35 @@ - - - - - - - - - - + +   +   +   - - - - - + + + + + - - + + - - + + - - - - + + + + - - - - - - - + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPressure.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPressure.svg index 1411753ccc..9068c32c6f 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPressure.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPressure.svg @@ -1,65 +1,61 @@ - + + - - - + + + - + - - + + - - - + + - - + + - - - - + + + + - - + + - - + + - + - - + + - + - - + + - - + + - - + + - + - - + + - - - image/svg+xml - - + [Przemo Firszt] @@ -88,33 +84,33 @@ - + - - - - - - - - - - - - + + + + + + + + + + + + - - + + - - + + - - + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPulley.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPulley.svg index 860d613bc4..54fcd22bb6 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPulley.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintPulley.svg @@ -1,11 +1,10 @@ - + image/svg+xml - - + [Przemo Firszt] @@ -35,238 +34,231 @@ - - - + + + - - - + + + - - - + + + - - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + + - + - - + + - - - + + + - - + + - + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - + + + - - - - + + + + - - - - + - - - - - - + + + + + + - - + + - - - - - + + + + + - - - - - - - - + + + + + + + + - - - - - + + + + + - - + + - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSectionPrint.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSectionPrint.svg index 78b66641b9..893fa250cf 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSectionPrint.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSectionPrint.svg @@ -1,5 +1,5 @@ - + @@ -45,7 +45,6 @@ image/svg+xml - [Bernd Hahnebach] diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSelfWeight.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSelfWeight.svg index c271a99592..633230845a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSelfWeight.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSelfWeight.svg @@ -1,41 +1,36 @@ - + + - + - - + + - - - + + - - + + - - - + + - - + + - - - - + + + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -64,24 +59,24 @@ - + - - - - - - - - - - - - + + + + + + + + + + + + - - + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSpring.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSpring.svg index d434552239..f47d5513eb 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSpring.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintSpring.svg @@ -1,133 +1,36 @@ - - - - - - - - + + + + + - - - + + + - - - - + + + + - - - - + + + + - - - - + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTemperature.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTemperature.svg index e61b292fa5..4c3c33ee7e 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTemperature.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTemperature.svg @@ -1,49 +1,45 @@ - + + - - - + + + - + - - + + - - - + + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - + - - - image/svg+xml - - + [vdwalts] @@ -72,34 +68,34 @@ - + - - - - - + + + + + - - + + - - + + - - - - + + + + - - - - - - - - - + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTie.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTie.svg index c927434c82..c71b85bd56 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTie.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTie.svg @@ -1,31 +1,10 @@ - - + + - + image/svg+xml - - + [vdwalts] @@ -54,1230 +33,220 @@ - - - - + + + + - - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + - - - - - - + + + + + + - - - + + + - - - - - - + + + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - - - + + + + + + - - - - + + + + - - + + - - - - - - - - - - - - + + + + + + + + + - - - - - - - + + + + + + + - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTransform.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTransform.svg index 1d39707896..9991731a2a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTransform.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ConstraintTransform.svg @@ -1,22 +1,18 @@ - + + - - + + - - - - image/svg+xml - - + [kgoao] @@ -45,37 +41,31 @@ - + - - - - - - - - - +   +   +   - - + + - - + + - - - - + + + + - - - - + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_CreateNodesSet.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_CreateNodesSet.svg index ddec64225b..79ef93f44a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_CreateNodesSet.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_CreateNodesSet.svg @@ -1,35 +1,31 @@ - + + - - + + - - + + - - - - - - + + + + + - - - - + + + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -58,26 +54,26 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementFluid1D.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementFluid1D.svg index 7a95db1e98..c6eeb12490 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementFluid1D.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementFluid1D.svg @@ -1,64 +1,60 @@ - + + - + - - + + - - - + + - - + + - + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - + - - + + - + - - + + - + - - + + - - - image/svg+xml - - + [kgoao] @@ -87,35 +83,35 @@ - + - - + + - - + + - - - - - + + + + + - - + + - - + + - - + + - - + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry1D.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry1D.svg index 0ba105c9fc..509412c0ea 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry1D.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry1D.svg @@ -1,60 +1,56 @@ - + + - - - + + + - - - + + + - - - + + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -83,15 +79,15 @@ - + - - - - - - - + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry2D.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry2D.svg index 875d9a8b1e..6d0bc5d3bd 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry2D.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementGeometry2D.svg @@ -1,35 +1,31 @@ - + + - - + + - - + + - - - - - - + + + + + - - - - + + + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -58,20 +54,20 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementRotation1D.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementRotation1D.svg index cafbda47fc..41d8c5e82f 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ElementRotation1D.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ElementRotation1D.svg @@ -1,458 +1,81 @@ - - - - - + + + + + - - - + + + - - - + + + - - - + + + - - - + + + - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + - - - - - - - + + + + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + + + + - - - - + - + image/svg+xml - - + [Bernd Hahnebach] @@ -481,93 +104,22 @@ - - - - - - - - - - - - - + + + + + + + + + + + + + - - + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElasticity.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElasticity.svg index abe47b1976..2e9bcbcb01 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElasticity.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElasticity.svg @@ -1,46 +1,17 @@ - - - - - + + + + + - + - + - + image/svg+xml - - + [Alexander Gryson] @@ -69,27 +40,9 @@ - - - - + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectricforce.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectricforce.svg index dcd98b6510..487a1a1149 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectricforce.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectricforce.svg @@ -1,5 +1,5 @@ - + @@ -42,7 +42,6 @@ image/svg+xml - [Alexander Gryson] diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectrostatic.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectrostatic.svg index 3de5b639df..71a42e8c3b 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectrostatic.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationElectrostatic.svg @@ -1,178 +1,43 @@ - - - - - - + + + + + - - - + + + - - - + + + - - - + + + - - - - + + + + - - - - - - + + + + + + - - - + + + - + - + image/svg+xml - - + [Alexander Gryson] @@ -201,87 +66,19 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlow.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlow.svg index 0dd00532c6..fc0f5e8705 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlow.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlow.svg @@ -1,137 +1,26 @@ - - - - - - - - + + + + + + + - - - - - - + + + + + - - - - + - + image/svg+xml - - + [qingfengxia] @@ -160,97 +49,26 @@ - - - - - - - + + + + + + + - - - - - - + + + + + + - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlux.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlux.svg index 001faf3352..d3ac2ca10c 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlux.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationFlux.svg @@ -1,5 +1,5 @@ - + @@ -36,7 +36,6 @@ image/svg+xml - [Alexander Gryson] diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationHeat.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationHeat.svg index c1092a91f5..234ebead31 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_EquationHeat.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_EquationHeat.svg @@ -1,98 +1,28 @@ - - - - - + + + + + - - - - + + + + - - - - - + + + + + - + - + - + image/svg+xml - - + [vdwalts] @@ -121,53 +51,17 @@ - - - - - - - - - - - + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_FEMMesh2Mesh.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_FEMMesh2Mesh.svg index 5e2bd7674d..4ad3b0605a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_FEMMesh2Mesh.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_FEMMesh2Mesh.svg @@ -1,22 +1,19 @@ - + + - + - - + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -45,48 +42,48 @@ - + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + - - - - - - + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialFluid.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialFluid.svg index 7e4d8882ec..2e8491976c 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialFluid.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialFluid.svg @@ -1,108 +1,75 @@ - + + - - + + - - - + + + - - - + + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - + + + + - - - - + + + - - - - - - + + + - - - + + + - - - + + + - - - + + + - - + + - - - - - + + + + + - - - + + + - - - image/svg+xml - - + [qingfengxia] @@ -131,12 +98,12 @@ - - + + - - + + - + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialMechanicalNonlinear.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialMechanicalNonlinear.svg index 1b41f03b7f..425e95a368 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialMechanicalNonlinear.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialMechanicalNonlinear.svg @@ -1,107 +1,74 @@ - + + - - - + + + - - + + - - - + + + - - - + + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - + + + + - - - - + + + - - - - - - + + + - - - + + + - - - + + + - - - + + + - - - - - + + + + + - - + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -130,14 +97,14 @@ - - - - - - - - - + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialReinforced.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialReinforced.svg index e05dd64d99..0fd578fe00 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialReinforced.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialReinforced.svg @@ -1,583 +1,80 @@ - - fem_material_reinforced - - - - + + fem_material_reinforced + + + + - - - + + + - - - + + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - + + + + - - - - + + + - - - - - - - - - - + + + + + + + - - - - - - - + + + + + + + - - - - - + + + + + - - - - - + + + + + - - - - + - + image/svg+xml - + fem_material_reinforced - + fem-material 2019-06-18 - + FreeCAD @@ -599,153 +96,35 @@ - - - - - - - - - - + + + + + + + + + + - - - - - + + + + + - - - - - - - - - - - + + + + + + + + + + + - + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialSolid.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialSolid.svg index 13ae7fdab3..1fba824dff 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialSolid.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MaterialSolid.svg @@ -1,100 +1,67 @@ - + + - - - + + + - - - + + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - + + + + - - - - + + + - - - - - - + + + - - - + + + - - - + + + - - - + + + - - - - - + + + + + - - + + - - - image/svg+xml - - + [Przemo Firszt] @@ -123,10 +90,10 @@ - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshBoundaryLayer.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshBoundaryLayer.svg index 75848ec18d..b3c9e32865 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshBoundaryLayer.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshBoundaryLayer.svg @@ -1,372 +1,77 @@ - - - - - + + + + + - - - - + + + - - + - + image/svg+xml - + - - - - - - + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + - - - + + + - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshClear.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshClear.svg index 0d739c34c6..0416f86561 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshClear.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshClear.svg @@ -1,308 +1,60 @@ - - - - - - - + + + + + + + - - - - - - - + + + + + + - - - - + + + + - - - - - + + + + + - - - - - + + + + + - - - - + + + + - - - - - - + + + + + + - - - - + + + + - - - - + - + image/svg+xml - - + [Bernd Hahnebach] @@ -331,86 +83,19 @@ - - - - - + + + + + - - - + + + - - - + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshDisplayInfo.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshDisplayInfo.svg index 489ca46b0d..9ea217ee25 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshDisplayInfo.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshDisplayInfo.svg @@ -1,30 +1,26 @@ - + + - - - + + + - - + + - - + + - - - + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -53,10 +49,10 @@ - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGmshFromShape.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGmshFromShape.svg index d3c6444026..fafbd13c72 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGmshFromShape.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGmshFromShape.svg @@ -1,40 +1,36 @@ - + + - - - + + + - - + + - - + + - - - - - - + + + + + - - - - + + + + - + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -63,27 +59,27 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGroup.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGroup.svg index b809eb5f22..0ff07b22c3 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGroup.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshGroup.svg @@ -1,5 +1,5 @@ - + @@ -43,7 +43,6 @@ image/svg+xml - [bitacobir] diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshNetgenFromShape.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshNetgenFromShape.svg index 029b8431fe..36e1ad3a16 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshNetgenFromShape.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshNetgenFromShape.svg @@ -1,46 +1,42 @@ - + + - - - + + + - - - + + + - - + + - - + + - - - - - - + + + + + - - - - + + + + - - - + + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -69,27 +65,27 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshRegion.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshRegion.svg index 9f63c431ab..09de666de7 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshRegion.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshRegion.svg @@ -1,40 +1,36 @@ - + + - - + + - - - - - - - - + + + + + + + - - - - + + + + - - - image/svg+xml - + [Bernd Hahnebach] - fem-femmesh-region 2016-12-20 http://www.freecadweb.org/wiki/index.php?title=Artwork @@ -57,31 +53,31 @@ - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + - - - + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshResult.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshResult.svg index d68fbfb0b7..42e48e21b6 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_MeshResult.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_MeshResult.svg @@ -1,5 +1,5 @@ - + @@ -54,7 +54,6 @@ image/svg+xml - [Bernd Hahnebach] diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipRegion.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipRegion.svg index f34670ca30..5a28683be1 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipRegion.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipRegion.svg @@ -1,12 +1,12 @@ - + + image/svg+xml - - + [Alexander Gryson] @@ -36,33 +36,30 @@ - - - + + + - - - + + + - - + + - - - - - + + - - - - - + + + + + - - - - - - + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipScalar.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipScalar.svg index b41ed40162..cea0cf2cd1 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipScalar.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterClipScalar.svg @@ -1,12 +1,12 @@ - + + image/svg+xml - - + [Alexander Gryson] @@ -36,36 +36,33 @@ - - - + + + - - - + + + - - + + - - - - - + + - - - - - + + + + + - - - - - - + + + + + + - + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterCutFunction.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterCutFunction.svg index 803b013d85..202aecb15b 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterCutFunction.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterCutFunction.svg @@ -1,12 +1,12 @@ - + + image/svg+xml - - + [Alexander Gryson] @@ -36,33 +36,30 @@ - - - + + + - - - + + + - - + + - - - - - - - - + + + + + - - + + - - - - - - + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAlongLine.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAlongLine.svg index b6b82915b6..96fa61315b 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAlongLine.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAlongLine.svg @@ -1,16 +1,13 @@ - - - - - + + + image/svg+xml - - + [Alexander Gryson] @@ -39,17 +36,17 @@ - - - - - - - - - - - - + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAtPoint.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAtPoint.svg index 1c8d5ed6b6..a885dd8be8 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAtPoint.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterDataAtPoint.svg @@ -1,302 +1,48 @@ - - + + - + image/svg+xml - - + - - - - + + + + - - - + + + - - - - - - - + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + - - - - - - - - + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterLinearizedStresses.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterLinearizedStresses.svg index 8012442ccd..0fdd9a1d29 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterLinearizedStresses.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterLinearizedStresses.svg @@ -1,16 +1,13 @@ - - - - - + + + image/svg+xml - - + [mkhizenz] @@ -39,44 +36,44 @@ - - - - - - - + + + + + + + - - - - + + + + - - - - - - + + + + + + - - - - + + + + - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterWarp.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterWarp.svg index 51d2f92870..3e30709139 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterWarp.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostFilterWarp.svg @@ -1,83 +1,19 @@ - - - - - + + + + + - + - - - - + - + image/svg+xml - - + [Alexander Gryson] @@ -106,34 +42,9 @@ - - - - + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_PostPipelineFromResult.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_PostPipelineFromResult.svg index ff65799433..fe7b2b467a 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_PostPipelineFromResult.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_PostPipelineFromResult.svg @@ -1,17 +1,13 @@ - - - - - - + + + image/svg+xml - - + [Alexander Gryson] @@ -40,23 +36,23 @@ - - + + - - - + + + - - - - - - - - - - - + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ResultShow.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ResultShow.svg index 369b941edb..19f3163e78 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ResultShow.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ResultShow.svg @@ -1,82 +1,78 @@ - + + - - - + + + - - - + + + - - - + + + - - - + + + - - - + + + - + - - + + - - + - - + + - + - - - + + + - - - - - + + + + + - - - + + + - - - - + + + + - - - + + + - - - + + + - + - - - image/svg+xml - - + [Przemo Firszt] @@ -105,10 +101,10 @@ - - - - - + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_ResultsPurge.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_ResultsPurge.svg index 71d2900d5b..e4c504d317 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_ResultsPurge.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_ResultsPurge.svg @@ -1,86 +1,82 @@ - + + - - - + + + - - - + + + - + - - + + - - + - - + + - + - - - + + + - - - - - - - - + + + + + + + + - - - - - - + + + + + + - - - + + + - - - + + + - + - - - + + + - + - - - + + + - - - - + + + + - - + + - - - image/svg+xml - - + [Przemo Firszt] @@ -109,22 +105,22 @@ - - - - - + + + + + - - + + - - + + - - + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverControl.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverControl.svg index 5bf4838a3e..2febe9588d 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverControl.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverControl.svg @@ -1,91 +1,58 @@ - + + - - - + + + - - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - + + + + - - - - + + + - - - - - + + - - - + + + - - + + - - + + - - + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -114,11 +81,11 @@ - - - - - - + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverElmer.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverElmer.svg index 5c31380bb5..17223d4141 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverElmer.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverElmer.svg @@ -1,98 +1,25 @@ - - + + - + image/svg+xml - - + - - - - - - - - - - - - + + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverRun.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverRun.svg index a5d18787e9..33d79eda76 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverRun.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverRun.svg @@ -1,88 +1,55 @@ - + + - - + + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - - - - - + + + - - - - - + + + + - - - - + + + - - - - - - + + + - - - + + + - - + + - - - + + + - + - - + + - - - image/svg+xml - - + [Bernd Hahnebach] @@ -111,15 +78,15 @@ - - - - - - - - - - + + + + + + + + + + diff --git a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverZ88.svg b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverZ88.svg index 19c205175a..ed5e009906 100644 --- a/src/Mod/Fem/Gui/Resources/icons/FEM_SolverZ88.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FEM_SolverZ88.svg @@ -1,12 +1,11 @@ - + image/svg+xml - diff --git a/src/Mod/Fem/Gui/Resources/icons/FemWorkbench.svg b/src/Mod/Fem/Gui/Resources/icons/FemWorkbench.svg index b3bae9cf07..dc0e29467c 100755 --- a/src/Mod/Fem/Gui/Resources/icons/FemWorkbench.svg +++ b/src/Mod/Fem/Gui/Resources/icons/FemWorkbench.svg @@ -1,5 +1,5 @@ - + @@ -102,7 +102,6 @@ image/svg+xml - [triplus] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-add-fem-mesh.svg b/src/Mod/Fem/Gui/Resources/icons/fem-add-fem-mesh.svg index 4153921684..bcd04b1e38 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-add-fem-mesh.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-add-fem-mesh.svg @@ -1,5 +1,5 @@ - + @@ -24,7 +24,6 @@ image/svg+xml - [Przemo Firszt] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-add-material.svg b/src/Mod/Fem/Gui/Resources/icons/fem-add-material.svg index 5e4e8a6b3e..4389f86a78 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-add-material.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-add-material.svg @@ -1,5 +1,5 @@ - + @@ -60,7 +60,6 @@ image/svg+xml - [Przemo Firszt] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-add-part.svg b/src/Mod/Fem/Gui/Resources/icons/fem-add-part.svg index f2b6c365d2..d588ef3982 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-add-part.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-add-part.svg @@ -1,5 +1,5 @@ - + @@ -54,7 +54,6 @@ image/svg+xml - [Przemo Firszt] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-femmesh-from-shape.svg b/src/Mod/Fem/Gui/Resources/icons/fem-femmesh-from-shape.svg index e3783340b5..00fabaecbc 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-femmesh-from-shape.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-femmesh-from-shape.svg @@ -1,5 +1,5 @@ - + @@ -24,7 +24,6 @@ image/svg+xml - [Bernd Hahnebach] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-box.svg b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-box.svg index 1aeee148e5..0628b721d0 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-box.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-box.svg @@ -1,5 +1,5 @@ - + @@ -33,7 +33,6 @@ image/svg+xml - [Stefan Tröger] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-cylinder.svg b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-cylinder.svg index 6127f8cda8..3c5ca14afc 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-cylinder.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-cylinder.svg @@ -1,5 +1,5 @@ - + @@ -22,7 +22,6 @@ image/svg+xml - [Stefan Tröger] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-isosurface.svg b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-isosurface.svg index 2326e33246..c2cea268b3 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-isosurface.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-isosurface.svg @@ -1,5 +1,5 @@ - + @@ -38,7 +38,6 @@ image/svg+xml - [Alexander Gryson] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-plane.svg b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-plane.svg index ab2ad9b7ca..ebdf4ebe08 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-plane.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-plane.svg @@ -1,5 +1,5 @@ - + @@ -21,7 +21,6 @@ image/svg+xml - [Stefan Tröger] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-sphere.svg b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-sphere.svg index 5b4636b1e9..431660b36d 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-sphere.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-post-geo-sphere.svg @@ -1,5 +1,5 @@ - + @@ -26,7 +26,6 @@ image/svg+xml - [Stefan Tröger] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-frequency.svg b/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-frequency.svg index cb2ff82e4e..6c9e47bf8c 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-frequency.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-frequency.svg @@ -1,5 +1,5 @@ - + @@ -51,7 +51,6 @@ image/svg+xml - [Przemo Firszt] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-static.svg b/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-static.svg index d035c28b77..eb604bf668 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-static.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-static.svg @@ -1,5 +1,5 @@ - + @@ -53,7 +53,6 @@ image/svg+xml - [vdwalts] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-thermomechanical.svg b/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-thermomechanical.svg index b45b0bc424..817133c299 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-thermomechanical.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-solver-analysis-thermomechanical.svg @@ -1,5 +1,5 @@ - + @@ -50,7 +50,6 @@ image/svg+xml - [vdwalts] diff --git a/src/Mod/Fem/Gui/Resources/icons/fem-solver-inp-editor.svg b/src/Mod/Fem/Gui/Resources/icons/fem-solver-inp-editor.svg index 7004bf8867..8ff6d38b01 100644 --- a/src/Mod/Fem/Gui/Resources/icons/fem-solver-inp-editor.svg +++ b/src/Mod/Fem/Gui/Resources/icons/fem-solver-inp-editor.svg @@ -1,12 +1,11 @@ - + image/svg+xml - diff --git a/src/Mod/Fem/Gui/Resources/icons/preferences-fem.svg b/src/Mod/Fem/Gui/Resources/icons/preferences-fem.svg index 8f67fe70d7..cd1fd7a483 100755 --- a/src/Mod/Fem/Gui/Resources/icons/preferences-fem.svg +++ b/src/Mod/Fem/Gui/Resources/icons/preferences-fem.svg @@ -1,5 +1,5 @@ - + @@ -102,7 +102,6 @@ image/svg+xml - [Przemo Firszt] diff --git a/src/Mod/Fem/Gui/Resources/ui/BodyHeatSource.ui b/src/Mod/Fem/Gui/Resources/ui/BodyHeatSource.ui new file mode 100644 index 0000000000..76f049dffa --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/ui/BodyHeatSource.ui @@ -0,0 +1,79 @@ + + + Form + + + + 0 + 0 + 350 + 40 + + + + Constraint Properties + + + + + + Body heat in W/kg: + + + + + + + Qt::Horizontal + + + + 130 + 19 + + + + + + + + true + + + + 100 + 20 + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + true + + + 0.000000000000000 + + + 1000000000000000000000.000000000000000 + + + 50.000000000000000 + + + 0.000000000000000 + + + + + + + + Gui::QuantitySpinBox + QWidget +
Gui/QuantitySpinBox.h
+
+
+ + +
diff --git a/src/Mod/Fem/Gui/Resources/ui/InitialPressure.ui b/src/Mod/Fem/Gui/Resources/ui/InitialPressure.ui new file mode 100644 index 0000000000..8bf1c8fee2 --- /dev/null +++ b/src/Mod/Fem/Gui/Resources/ui/InitialPressure.ui @@ -0,0 +1,82 @@ + + + Form + + + + 0 + 0 + 350 + 40 + + + + Constraint Properties + + + + + + Pressure: + + + + + + + Qt::Horizontal + + + + 130 + 19 + + + + + + + + true + + + + 100 + 20 + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + true + + + kPa + + + -1000000000000000000000.000000000000000 + + + 1000000000000000000000.000000000000000 + + + 50.000000000000000 + + + 100.000000000000000 + + + + + + + + Gui::QuantitySpinBox + QWidget +
Gui/QuantitySpinBox.h
+
+
+ + +
diff --git a/src/Mod/Fem/Gui/TaskAnalysisInfo.h b/src/Mod/Fem/Gui/TaskAnalysisInfo.h index 24f30e9f83..6d48f3db5a 100644 --- a/src/Mod/Fem/Gui/TaskAnalysisInfo.h +++ b/src/Mod/Fem/Gui/TaskAnalysisInfo.h @@ -56,8 +56,8 @@ class TaskAnalysisInfo : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskAnalysisInfo(Fem::FemAnalysis *pcObject,QWidget *parent = nullptr); - ~TaskAnalysisInfo(); + explicit TaskAnalysisInfo(Fem::FemAnalysis *pcObject,QWidget *parent = nullptr); + ~TaskAnalysisInfo() override; private Q_SLOTS: void SwitchMethod(int Value); diff --git a/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp b/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp index 91e4fecb94..bc07cd08a1 100644 --- a/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp +++ b/src/Mod/Fem/Gui/TaskCreateNodeSet.cpp @@ -92,7 +92,7 @@ TaskCreateNodeSet::TaskCreateNodeSet(Fem::FemSetNodesObject* pcObject, QWidget* } -void TaskCreateNodeSet::Poly(void) +void TaskCreateNodeSet::Poly() { Gui::Document* doc = Gui::Application::Instance->activeDocument(); Gui::MDIView* view = doc->getActiveView(); @@ -104,7 +104,7 @@ void TaskCreateNodeSet::Poly(void) } } -void TaskCreateNodeSet::Pick(void) +void TaskCreateNodeSet::Pick() { if (selectionMode == none) { selectionMode = PickElement; diff --git a/src/Mod/Fem/Gui/TaskCreateNodeSet.h b/src/Mod/Fem/Gui/TaskCreateNodeSet.h index 67527103a7..79316d668d 100644 --- a/src/Mod/Fem/Gui/TaskCreateNodeSet.h +++ b/src/Mod/Fem/Gui/TaskCreateNodeSet.h @@ -52,15 +52,15 @@ class TaskCreateNodeSet : public Gui::TaskView::TaskBox, public Gui::SelectionOb Q_OBJECT public: - TaskCreateNodeSet(Fem::FemSetNodesObject *pcObject,QWidget *parent = nullptr); - ~TaskCreateNodeSet(); + explicit TaskCreateNodeSet(Fem::FemSetNodesObject *pcObject,QWidget *parent = nullptr); + ~TaskCreateNodeSet() override; std::set tempSet; ViewProviderFemMesh * MeshViewProvider; private Q_SLOTS: - void Poly(void); - void Pick(void); + void Poly(); + void Pick(); void SwitchMethod(int Value); protected: @@ -69,7 +69,7 @@ protected: void DefineNodes(const Base::Polygon2d &polygon,const Gui::ViewVolumeProjection &proj,bool); protected: - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; enum selectionModes { none, PickElement} selectionMode; private: diff --git a/src/Mod/Fem/Gui/TaskDlgAnalysis.h b/src/Mod/Fem/Gui/TaskDlgAnalysis.h index b5c6434c4a..57852c1493 100644 --- a/src/Mod/Fem/Gui/TaskDlgAnalysis.h +++ b/src/Mod/Fem/Gui/TaskDlgAnalysis.h @@ -41,21 +41,21 @@ class TaskDlgAnalysis : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgAnalysis(Fem::FemAnalysis *); - ~TaskDlgAnalysis(); + explicit TaskDlgAnalysis(Fem::FemAnalysis *); + ~TaskDlgAnalysis() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply; } protected: diff --git a/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.h b/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.h index 29d2011ce1..3f4d34cc76 100644 --- a/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.h +++ b/src/Mod/Fem/Gui/TaskDlgCreateNodeSet.h @@ -43,21 +43,21 @@ class TaskDlgCreateNodeSet : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgCreateNodeSet(Fem::FemSetNodesObject *); - ~TaskDlgCreateNodeSet(); + explicit TaskDlgCreateNodeSet(Fem::FemSetNodesObject *); + ~TaskDlgCreateNodeSet() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } protected: diff --git a/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.h b/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.h index 324e28cf88..792b4ee461 100644 --- a/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.h +++ b/src/Mod/Fem/Gui/TaskDlgMeshShapeNetgen.h @@ -42,23 +42,23 @@ class TaskDlgMeshShapeNetgen : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgMeshShapeNetgen(FemGui::ViewProviderFemMeshShapeNetgen *); - ~TaskDlgMeshShapeNetgen(); + explicit TaskDlgMeshShapeNetgen(FemGui::ViewProviderFemMeshShapeNetgen *); + ~TaskDlgMeshShapeNetgen() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or rject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply; } protected: diff --git a/src/Mod/Fem/Gui/TaskDriver.h b/src/Mod/Fem/Gui/TaskDriver.h index 46c3eae1f1..d290d1f66c 100644 --- a/src/Mod/Fem/Gui/TaskDriver.h +++ b/src/Mod/Fem/Gui/TaskDriver.h @@ -54,8 +54,8 @@ class TaskDriver : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskDriver(Fem::FemAnalysis *pcObject,QWidget *parent = nullptr); - ~TaskDriver(); + explicit TaskDriver(Fem::FemAnalysis *pcObject,QWidget *parent = nullptr); + ~TaskDriver() override; private Q_SLOTS: diff --git a/src/Mod/Fem/Gui/TaskFemConstraint.cpp b/src/Mod/Fem/Gui/TaskFemConstraint.cpp index 5382b0d5f9..9376fea761 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraint.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraint.cpp @@ -81,7 +81,7 @@ TaskFemConstraint::TaskFemConstraint(ViewProviderFemConstraint *ConstraintView,Q selectionMode = selref; // Setup the dialog inside the Shaft Wizard dialog - if ((ConstraintView->wizardWidget != nullptr) && (ConstraintView->wizardSubLayout != nullptr)) { + if ((ConstraintView->wizardWidget) && (ConstraintView->wizardSubLayout)) { // Hide the shaft wizard table widget to make more space ConstraintView->wizardSubLayout->itemAt(0)->widget()->hide(); QGridLayout* buttons = ConstraintView->wizardSubLayout->findChild(); @@ -105,7 +105,7 @@ TaskFemConstraint::TaskFemConstraint(ViewProviderFemConstraint *ConstraintView,Q void TaskFemConstraint::keyPressEvent(QKeyEvent *ke) { - if ((ConstraintView->wizardWidget != nullptr) && (ConstraintView->wizardSubLayout != nullptr)) + if ((ConstraintView->wizardWidget) && (ConstraintView->wizardSubLayout)) // Prevent from closing this dialog AND the shaft wizard dialog // TODO: This should trigger an update in the shaft wizard but its difficult to access a python dialog from here... if (ke->key() == Qt::Key_Return) @@ -151,7 +151,7 @@ void TaskFemConstraint::setSelection(QListWidgetItem* item) { ItemName.erase(0, pos + delimiter.length()); // clear existing selection Gui::Selection().clearSelection(); - // highligh the selected item + // highlight the selected item Gui::Selection().addSelection(docName.c_str(), objName.c_str(), ItemName.c_str(), 0, 0, 0); } @@ -196,7 +196,7 @@ void TaskFemConstraint::onButtonWizOk() void TaskFemConstraint::onButtonWizCancel() { Fem::Constraint* pcConstraint = static_cast(ConstraintView->getObject()); - if (pcConstraint != nullptr) + if (pcConstraint) pcConstraint->getDocument()->removeObject(pcConstraint->getNameInDocument()); onButtonWizOk(); } diff --git a/src/Mod/Fem/Gui/TaskFemConstraint.h b/src/Mod/Fem/Gui/TaskFemConstraint.h index c117090fb2..78c51a5bec 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraint.h +++ b/src/Mod/Fem/Gui/TaskFemConstraint.h @@ -44,10 +44,10 @@ class TaskFemConstraint : public Gui::TaskView::TaskBox, public Gui::SelectionOb Q_OBJECT public: - TaskFemConstraint(ViewProviderFemConstraint *ConstraintView,QWidget *parent = nullptr,const char* pixmapname = ""); - virtual ~TaskFemConstraint() {} + explicit TaskFemConstraint(ViewProviderFemConstraint *ConstraintView,QWidget *parent = nullptr,const char* pixmapname = ""); + ~TaskFemConstraint() override {} - virtual const std::string getReferences(void) const {return std::string();} + virtual const std::string getReferences() const {return std::string();} const std::string getReferences(const std::vector& items) const; const std::string getScale() const; @@ -60,13 +60,13 @@ protected Q_SLOTS: void onButtonWizCancel(); protected: - virtual void changeEvent(QEvent *e) { TaskBox::changeEvent(e); } + void changeEvent(QEvent *e) override { TaskBox::changeEvent(e); } const QString makeRefText(const std::string& objName, const std::string& subName) const; const QString makeRefText(const App::DocumentObject* obj, const std::string& subName) const; - virtual void keyPressEvent(QKeyEvent * ke); + void keyPressEvent(QKeyEvent * ke) override; void createDeleteAction(QListWidget* parentList); bool KeyEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges&) {} + void onSelectionChanged(const Gui::SelectionChanges&) override {} protected: QWidget* proxy; @@ -89,20 +89,20 @@ class TaskDlgFemConstraint : public Gui::TaskView::TaskDialog public: /// is called the TaskView when the dialog is opened - void open(); + void open() override; /* /// is called by the framework if an button is clicked which has no accept or reject role virtual void clicked(int) {} /// is called by the framework if the dialog is accepted (Ok) */ - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); - virtual bool isAllowedAlterDocument(void) const + bool reject() override; + bool isAllowedAlterDocument() const override { return false; } /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } ViewProviderFemConstraint* getConstraintView() const diff --git a/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp b/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp index e7b2c38f62..0018997059 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintBearing.cpp @@ -94,7 +94,7 @@ TaskFemConstraintBearing::TaskFemConstraintBearing(ViewProviderFemConstraint *Co ui->listReferences->clear(); for (std::size_t i = 0; i < Objects.size(); i++) ui->listReferences->addItem(makeRefText(Objects[i], SubElements[i])); - if (Objects.size() > 0) + if (!Objects.empty()) ui->listReferences->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); ui->lineLocation->setText(loc); ui->checkAxial->setChecked(axialfree); @@ -152,7 +152,7 @@ void TaskFemConstraintBearing::onSelectionChanged(const Gui::SelectionChanges& m std::vector Objects = pcConstraint->References.getValues(); std::vector SubElements = pcConstraint->References.getSubValues(); - if (Objects.size() > 0) { + if (!Objects.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Please use only a single reference for bearing constraint")); return; } @@ -235,7 +235,7 @@ void TaskFemConstraintBearing::onCheckAxial(const bool pressed) pcConstraint->AxialFree.setValue(pressed); } -double TaskFemConstraintBearing::getDistance(void) const +double TaskFemConstraintBearing::getDistance() const { return ui->spinDistance->value(); } @@ -250,7 +250,7 @@ const std::string TaskFemConstraintBearing::getReferences() const return TaskFemConstraint::getReferences(items); } -const std::string TaskFemConstraintBearing::getLocationName(void) const +const std::string TaskFemConstraintBearing::getLocationName() const { std::string loc = ui->lineLocation->text().toStdString(); if (loc.empty()) @@ -260,7 +260,7 @@ const std::string TaskFemConstraintBearing::getLocationName(void) const return loc.substr(0, pos).c_str(); } -const std::string TaskFemConstraintBearing::getLocationObject(void) const +const std::string TaskFemConstraintBearing::getLocationObject() const { std::string loc = ui->lineLocation->text().toStdString(); if (loc.empty()) diff --git a/src/Mod/Fem/Gui/TaskFemConstraintBearing.h b/src/Mod/Fem/Gui/TaskFemConstraintBearing.h index f1be4708e2..e8f6d6e04d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintBearing.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintBearing.h @@ -47,26 +47,26 @@ class TaskFemConstraintBearing : public TaskFemConstraint Q_OBJECT public: - TaskFemConstraintBearing(ViewProviderFemConstraint *ConstraintView, QWidget *parent = nullptr, + explicit TaskFemConstraintBearing(ViewProviderFemConstraint *ConstraintView, QWidget *parent = nullptr, const char* pixmapname = "FEM_ConstraintBearing"); - virtual ~TaskFemConstraintBearing(); + ~TaskFemConstraintBearing() override; - double getDistance(void) const; - virtual const std::string getReferences() const; - const std::string getLocationName(void) const; - const std::string getLocationObject(void) const; - bool getAxial(void) const; + double getDistance() const; + const std::string getReferences() const override; + const std::string getLocationName() const; + const std::string getLocationObject() const; + bool getAxial() const; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void onDistanceChanged(double l); void onButtonLocation(const bool pressed = true); void onCheckAxial(bool); protected: - bool event(QEvent *e); - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; protected: Ui_TaskFemConstraintBearing* ui; @@ -80,10 +80,10 @@ class TaskDlgFemConstraintBearing : public TaskDlgFemConstraint public: TaskDlgFemConstraintBearing() {} - TaskDlgFemConstraintBearing(ViewProviderFemConstraintBearing *ConstraintView); + explicit TaskDlgFemConstraintBearing(ViewProviderFemConstraintBearing *ConstraintView); /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp b/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp index 88c1bfe36f..33596f254c 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintContact.cpp @@ -94,12 +94,12 @@ TaskFemConstraintContact::TaskFemConstraintContact(ViewProviderFemConstraintCont // QMessageBox::warning(this, tr("Objects.size"), QString::number(Objects.size())); if (Objects.size() == 1) { - QMessageBox::warning(this, tr("Selection error"), tr("Only one face in object! - moved to master face")); + QMessageBox::warning(this, tr("Selection error"), tr("Only one face in object! - moved to master face")); ui->lw_referencesMaster->addItem(makeRefText(Objects[0], SubElements[0])); } if (Objects.size() == 2 ) { - ui->lw_referencesMaster->addItem(makeRefText(Objects[1], SubElements[1])); + ui->lw_referencesMaster->addItem(makeRefText(Objects[1], SubElements[1])); ui->lw_referencesSlave->addItem(makeRefText(Objects[0], SubElements[0])); } @@ -141,7 +141,7 @@ void TaskFemConstraintContact::addToSelectionSlave() Gui::Selection().clearSelection(); return; } - if (selection.size() == 0){ + if (selection.empty()){ QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -197,7 +197,7 @@ void TaskFemConstraintContact::addToSelectionSlave() void TaskFemConstraintContact::removeFromSelectionSlave() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0){ + if (selection.empty()){ QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -225,7 +225,7 @@ void TaskFemConstraintContact::removeFromSelectionSlave() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0){ + while (!itemsToDel.empty()){ Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); @@ -248,7 +248,7 @@ void TaskFemConstraintContact::addToSelectionMaster() Gui::Selection().clearSelection(); return; } - if (selection.size() == 0){ + if (selection.empty()){ QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -303,7 +303,7 @@ void TaskFemConstraintContact::addToSelectionMaster() void TaskFemConstraintContact::removeFromSelectionMaster() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0){ + if (selection.empty()){ QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -331,7 +331,7 @@ void TaskFemConstraintContact::removeFromSelectionMaster() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0){ + while (!itemsToDel.empty()){ Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintContact.h b/src/Mod/Fem/Gui/TaskFemConstraintContact.h index 74d6be5916..da823f2e3f 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintContact.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintContact.h @@ -40,22 +40,22 @@ class TaskFemConstraintContact : public TaskFemConstraint Q_OBJECT public: - TaskFemConstraintContact(ViewProviderFemConstraintContact *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintContact(); - const std::string getReferences() const; + explicit TaskFemConstraintContact(ViewProviderFemConstraintContact *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintContact() override; + const std::string getReferences() const override; double get_Slope()const; double get_Friction()const; private Q_SLOTS: - void onReferenceDeletedSlave(void); - void onReferenceDeletedMaster(void); + void onReferenceDeletedSlave(); + void onReferenceDeletedMaster(); void addToSelectionSlave(); void removeFromSelectionSlave(); void addToSelectionMaster(); void removeFromSelectionMaster(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: //void onSelectionChanged(const Gui::SelectionChanges& msg); @@ -69,10 +69,10 @@ class TaskDlgFemConstraintContact : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintContact(ViewProviderFemConstraintContact *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintContact(ViewProviderFemConstraintContact *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp index 5cf222c7f6..b3270cbfa3 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.cpp @@ -127,7 +127,7 @@ TaskFemConstraintDisplacement::TaskFemConstraintDisplacement(ViewProviderFemCons for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -369,7 +369,7 @@ void TaskFemConstraintDisplacement::rotfreez(int val) { void TaskFemConstraintDisplacement::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -426,7 +426,7 @@ void TaskFemConstraintDisplacement::addToSelection() void TaskFemConstraintDisplacement::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -454,7 +454,7 @@ void TaskFemConstraintDisplacement::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h index 87a54fca67..6f85d27f53 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintDisplacement.h @@ -49,9 +49,9 @@ class TaskFemConstraintDisplacement : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintDisplacement(ViewProviderFemConstraintDisplacement *ConstraintView, QWidget *parent = nullptr); - ~TaskFemConstraintDisplacement(); - const std::string getReferences() const; + explicit TaskFemConstraintDisplacement(ViewProviderFemConstraintDisplacement *ConstraintView, QWidget *parent = nullptr); + ~TaskFemConstraintDisplacement() override; + const std::string getReferences() const override; double get_spinxDisplacement()const; double get_spinyDisplacement()const; double get_spinzDisplacement()const; @@ -72,7 +72,7 @@ public: bool get_rotzfree()const; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void x_changed(double); void y_changed(double); void z_changed(double); @@ -92,12 +92,12 @@ private Q_SLOTS: void rotfixz(int); void rotfreez(int); - void addToSelection(); - void removeFromSelection(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -111,10 +111,10 @@ class TaskDlgFemConstraintDisplacement : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintDisplacement(ViewProviderFemConstraintDisplacement *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintDisplacement(ViewProviderFemConstraintDisplacement *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp b/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp index 10097ffeea..eb392c88ac 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintFixed.cpp @@ -75,7 +75,7 @@ TaskFemConstraintFixed::TaskFemConstraintFixed(ViewProviderFemConstraintFixed* C for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -103,7 +103,7 @@ void TaskFemConstraintFixed::updateUI() void TaskFemConstraintFixed::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -160,7 +160,7 @@ void TaskFemConstraintFixed::addToSelection() void TaskFemConstraintFixed::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -188,7 +188,7 @@ void TaskFemConstraintFixed::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFixed.h b/src/Mod/Fem/Gui/TaskFemConstraintFixed.h index 64ff73060c..2efdb08e2d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFixed.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintFixed.h @@ -38,18 +38,18 @@ class TaskFemConstraintFixed : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintFixed(ViewProviderFemConstraintFixed *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintFixed(); - const std::string getReferences() const; + explicit TaskFemConstraintFixed(ViewProviderFemConstraintFixed *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintFixed() override; + const std::string getReferences() const override; private Q_SLOTS: - void onReferenceDeleted(void); - void addToSelection(); - void removeFromSelection(); + void onReferenceDeleted(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -63,10 +63,10 @@ class TaskDlgFemConstraintFixed : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintFixed(ViewProviderFemConstraintFixed *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintFixed(ViewProviderFemConstraintFixed *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp index 080975943c..7cc5549537 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.cpp @@ -178,7 +178,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary(ViewProviderFemCo else { App::Document* aDoc = pcConstraint->getDocument(); std::vector fem = aDoc->getObjectsOfType(Fem::FemAnalysis::getClassTypeId()); - if (fem.size() >= 1) { + if (!fem.empty()) { pcAnalysis = static_cast(fem[0]); // get the first } } @@ -195,7 +195,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary(ViewProviderFemCo 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 } - if (pcMesh != nullptr) { + if (pcMesh) { App::Property* prop = pcMesh->getPropertyByName("Shape"); // PropertyLink if (prop && prop->getTypeId().isDerivedFrom(App::PropertyLink::getClassTypeId())) { App::PropertyLink* pcLink = static_cast(prop); @@ -226,7 +226,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary(ViewProviderFemCo pHeatTransferring = nullptr; pTurbulenceModel = nullptr; - if (pcSolver != nullptr) { + if (pcSolver) { //if only it is CFD solver, otherwise exit by SIGSEGV error, detect getPropertyByName() != NULL if (pcSolver->getPropertyByName("HeatTransferring")) { pHeatTransferring = static_cast(pcSolver->getPropertyByName("HeatTransferring")); @@ -298,7 +298,7 @@ TaskFemConstraintFluidBoundary::TaskFemConstraintFluidBoundary(ViewProviderFemCo ui->listReferences->clear(); for (std::size_t i = 0; i < Objects.size(); i++) ui->listReferences->addItem(makeRefText(Objects[i], SubElements[i])); - if (Objects.size() > 0) + if (!Objects.empty()) ui->listReferences->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); ui->lineDirection->setText(dir.isEmpty() ? tr("") : dir); ui->checkReverse->setVisible(true); // it is still useful to swap direction of an edge @@ -551,7 +551,7 @@ void TaskFemConstraintFluidBoundary::onButtonDirection(const bool pressed) //get vector of selected objects of active document std::vector selection = Gui::Selection().getSelectionEx(); - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Empty selection"), tr("Select an edge or a face, please.")); return; } @@ -726,7 +726,7 @@ TaskFemConstraintFluidBoundary::~TaskFemConstraintFluidBoundary() void TaskFemConstraintFluidBoundary::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -784,7 +784,7 @@ void TaskFemConstraintFluidBoundary::addToSelection() void TaskFemConstraintFluidBoundary::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -812,7 +812,7 @@ void TaskFemConstraintFluidBoundary::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h index cc68776536..0b87182592 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintFluidBoundary.h @@ -49,46 +49,46 @@ class TaskFemConstraintFluidBoundary : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintFluidBoundary(ViewProviderFemConstraintFluidBoundary *ConstraintView,QWidget *parent = nullptr); - virtual ~TaskFemConstraintFluidBoundary(); + explicit TaskFemConstraintFluidBoundary(ViewProviderFemConstraintFluidBoundary *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintFluidBoundary() override; - const Fem::FemSolverObject* getFemSolver(void) const; + const Fem::FemSolverObject* getFemSolver() const; - std::string getBoundaryType(void) const; - std::string getSubtype(void) const; - double getBoundaryValue(void) const; + std::string getBoundaryType() const; + std::string getSubtype() const; + double getBoundaryValue() const; - std::string getTurbulenceModel(void) const; - std::string getTurbulenceSpecification(void) const; - double getTurbulentIntensityValue(void) const; - double getTurbulentLengthValue(void) const; + std::string getTurbulenceModel() const; + std::string getTurbulenceSpecification() const; + double getTurbulentIntensityValue() const; + double getTurbulentLengthValue() const; - bool getHeatTransferring(void) const; - std::string getThermalBoundaryType(void) const; - double getTemperatureValue(void) const; - double getHeatFluxValue(void) const; - double getHTCoeffValue(void) const; + bool getHeatTransferring() const; + std::string getThermalBoundaryType() const; + double getTemperatureValue() const; + double getHeatFluxValue() const; + double getHTCoeffValue() const; - const std::string getReferences() const; - const std::string getDirectionName(void) const; - const std::string getDirectionObject(void) const; - bool getReverse(void) const; + const std::string getReferences() const override; + const std::string getDirectionName() const; + const std::string getDirectionObject() const; + bool getReverse() const; private Q_SLOTS: - void onBoundaryTypeChanged(void); - void onSubtypeChanged(void); + void onBoundaryTypeChanged(); + void onSubtypeChanged(); void onBoundaryValueChanged(double); - void onTurbulenceSpecificationChanged(void); - void onThermalBoundaryTypeChanged(void); - void onReferenceDeleted(void); + void onTurbulenceSpecificationChanged(); + void onThermalBoundaryTypeChanged(); + void onReferenceDeleted(); void onButtonDirection(const bool pressed = true); void onCheckReverse(bool); // consider removing this slot as the UI is hidden - void addToSelection(); - void removeFromSelection(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - virtual void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -112,12 +112,12 @@ class TaskDlgFemConstraintFluidBoundary : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintFluidBoundary(ViewProviderFemConstraintFluidBoundary *ConstraintView); + explicit TaskDlgFemConstraintFluidBoundary(ViewProviderFemConstraintFluidBoundary *ConstraintView); /// is called by the framework if the dialog is accepted (Ok) - virtual void open(); - virtual bool accept(); - virtual bool reject(); + void open() override; + bool accept() override; + bool reject() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp b/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp index 8ecac686b3..a7ac51b01b 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintForce.cpp @@ -95,7 +95,7 @@ TaskFemConstraintForce::TaskFemConstraintForce(ViewProviderFemConstraintForce* C ui->listReferences->clear(); for (std::size_t i = 0; i < Objects.size(); i++) ui->listReferences->addItem(makeRefText(Objects[i], SubElements[i])); - if (Objects.size() > 0) + if (!Objects.empty()) ui->listReferences->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); ui->lineDirection->setText(dir.isEmpty() ? QString() : dir); ui->checkReverse->setChecked(reversed); @@ -124,7 +124,7 @@ void TaskFemConstraintForce::updateUI() void TaskFemConstraintForce::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -182,7 +182,7 @@ void TaskFemConstraintForce::addToSelection() void TaskFemConstraintForce::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -210,7 +210,7 @@ void TaskFemConstraintForce::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); @@ -322,7 +322,7 @@ void TaskFemConstraintForce::onCheckReverse(const bool pressed) pcConstraint->Reversed.setValue(pressed); } -double TaskFemConstraintForce::getForce(void) const +double TaskFemConstraintForce::getForce() const { return ui->spinForce->value().getValue(); } @@ -337,7 +337,7 @@ const std::string TaskFemConstraintForce::getReferences() const return TaskFemConstraint::getReferences(items); } -const std::string TaskFemConstraintForce::getDirectionName(void) const +const std::string TaskFemConstraintForce::getDirectionName() const { std::string dir = ui->lineDirection->text().toStdString(); if (dir.empty()) @@ -347,7 +347,7 @@ const std::string TaskFemConstraintForce::getDirectionName(void) const return dir.substr(0, pos).c_str(); } -const std::string TaskFemConstraintForce::getDirectionObject(void) const +const std::string TaskFemConstraintForce::getDirectionObject() const { std::string dir = ui->lineDirection->text().toStdString(); if (dir.empty()) diff --git a/src/Mod/Fem/Gui/TaskFemConstraintForce.h b/src/Mod/Fem/Gui/TaskFemConstraintForce.h index 54bc234557..9c5ca011e6 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintForce.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintForce.h @@ -48,25 +48,25 @@ class TaskFemConstraintForce : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintForce(ViewProviderFemConstraintForce *ConstraintView,QWidget *parent = nullptr); - virtual ~TaskFemConstraintForce(); - double getForce(void) const; - const std::string getReferences() const; - const std::string getDirectionName(void) const; - const std::string getDirectionObject(void) const; - bool getReverse(void) const; + explicit TaskFemConstraintForce(ViewProviderFemConstraintForce *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintForce() override; + double getForce() const; + const std::string getReferences() const override; + const std::string getDirectionName() const; + const std::string getDirectionObject() const; + bool getReverse() const; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void onForceChanged(double); void onButtonDirection(const bool pressed = false); void onCheckReverse(bool); - void addToSelection(); - void removeFromSelection(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - virtual void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -83,12 +83,12 @@ class TaskDlgFemConstraintForce : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintForce(ViewProviderFemConstraintForce *ConstraintView); + explicit TaskDlgFemConstraintForce(ViewProviderFemConstraintForce *ConstraintView); /// is called by the framework if the dialog is accepted (Ok) - virtual void open(); - virtual bool accept(); - virtual bool reject(); + void open() override; + bool accept() override; + bool reject() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp b/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp index c36e523bb4..f37ae0110d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintGear.cpp @@ -206,17 +206,17 @@ void TaskFemConstraintGear::onCheckReversed(const bool pressed) pcConstraint->Reversed.setValue(pressed); } -double TaskFemConstraintGear::getForce(void) const +double TaskFemConstraintGear::getForce() const { return ui->spinForce->value(); } -double TaskFemConstraintGear::getForceAngle(void) const +double TaskFemConstraintGear::getForceAngle() const { return ui->spinForceAngle->value(); } -const std::string TaskFemConstraintGear::getDirectionName(void) const +const std::string TaskFemConstraintGear::getDirectionName() const { std::string dir = ui->lineDirection->text().toStdString(); if (dir.empty()) @@ -226,7 +226,7 @@ const std::string TaskFemConstraintGear::getDirectionName(void) const return dir.substr(0, pos).c_str(); } -const std::string TaskFemConstraintGear::getDirectionObject(void) const +const std::string TaskFemConstraintGear::getDirectionObject() const { std::string dir = ui->lineDirection->text().toStdString(); if (dir.empty()) @@ -241,7 +241,7 @@ bool TaskFemConstraintGear::getReverse() const return ui->checkReversed->isChecked(); } -double TaskFemConstraintGear::getDiameter(void) const +double TaskFemConstraintGear::getDiameter() const { return ui->spinDiameter->value(); } diff --git a/src/Mod/Fem/Gui/TaskFemConstraintGear.h b/src/Mod/Fem/Gui/TaskFemConstraintGear.h index e217ee212a..6e06d79a23 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintGear.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintGear.h @@ -34,15 +34,15 @@ class TaskFemConstraintGear : public TaskFemConstraintBearing Q_OBJECT public: - TaskFemConstraintGear(ViewProviderFemConstraint *ConstraintView,QWidget *parent = nullptr, + explicit TaskFemConstraintGear(ViewProviderFemConstraint *ConstraintView,QWidget *parent = nullptr, const char* pixmapname = "FEM_ConstraintGear"); - double getDiameter(void) const; - double getForce(void) const; - double getForceAngle(void) const; - const std::string getDirectionName(void) const; - const std::string getDirectionObject(void) const; - bool getReverse(void) const; + double getDiameter() const; + double getForce() const; + double getForceAngle() const; + const std::string getDirectionName() const; + const std::string getDirectionObject() const; + bool getReverse() const; private Q_SLOTS: void onDiameterChanged(double dia); @@ -52,8 +52,8 @@ private Q_SLOTS: void onCheckReversed(bool); protected: - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; }; /// simulation dialog for the TaskView @@ -63,10 +63,10 @@ class TaskDlgFemConstraintGear : public TaskDlgFemConstraintBearing public: TaskDlgFemConstraintGear() {} - TaskDlgFemConstraintGear(ViewProviderFemConstraintGear *ConstraintView); + explicit TaskDlgFemConstraintGear(ViewProviderFemConstraintGear *ConstraintView); /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp index c5b99de74b..e7524966df 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.cpp @@ -112,7 +112,7 @@ TaskFemConstraintHeatflux::TaskFemConstraintHeatflux(ViewProviderFemConstraintHe for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -197,7 +197,7 @@ void TaskFemConstraintHeatflux::Flux() void TaskFemConstraintHeatflux::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -213,7 +213,7 @@ void TaskFemConstraintHeatflux::addToSelection() const std::vector& subNames = it->getSubNames(); App::DocumentObject* obj = it->getObject(); - if (subNames.size() > 0) { + if (!subNames.empty()) { for (size_t subIt = 0; subIt < (subNames.size()); ++subIt) { if (subNames[subIt].substr(0, 4) != "Face") { QMessageBox::warning(this, tr("Selection error"), tr("Selection must only consist of faces!")); @@ -250,7 +250,7 @@ void TaskFemConstraintHeatflux::addToSelection() void TaskFemConstraintHeatflux::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -267,7 +267,7 @@ void TaskFemConstraintHeatflux::removeFromSelection() const std::vector& subNames = it->getSubNames(); App::DocumentObject* obj = it->getObject(); - if (subNames.size() > 0) { + if (!subNames.empty()) { for (size_t subIt = 0; subIt < (subNames.size()); ++subIt) { if (subNames[subIt].substr(0, 4) != "Face") { QMessageBox::warning(this, tr("Selection error"), tr("Selection must only consist of faces!")); @@ -290,7 +290,7 @@ void TaskFemConstraintHeatflux::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); @@ -321,21 +321,21 @@ const std::string TaskFemConstraintHeatflux::getReferences() const return TaskFemConstraint::getReferences(items); } -double TaskFemConstraintHeatflux::getAmbientTemp(void) const +double TaskFemConstraintHeatflux::getAmbientTemp() const { Base::Quantity temperature = ui->if_ambienttemp->getQuantity(); double temperature_in_kelvin = temperature.getValueAs(Base::Quantity::Kelvin); return temperature_in_kelvin; } -double TaskFemConstraintHeatflux::getFilmCoef(void) const +double TaskFemConstraintHeatflux::getFilmCoef() const { Base::Quantity filmcoef = ui->if_filmcoef->getQuantity(); double filmcoef_in_units = filmcoef.getValueAs(Base::Quantity(1.0, Base::Unit::ThermalTransferCoefficient)); return filmcoef_in_units; } -std::string TaskFemConstraintHeatflux::get_constraint_type(void) const { +std::string TaskFemConstraintHeatflux::get_constraint_type() const { std::string type; if (ui->rb_convection->isChecked()) { type = "\"Convection\""; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h index 0d778d9bc3..e5dada8d0d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintHeatflux.h @@ -40,28 +40,28 @@ class TaskFemConstraintHeatflux : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintHeatflux(ViewProviderFemConstraintHeatflux *ConstraintView,QWidget *parent = nullptr); - virtual ~TaskFemConstraintHeatflux(); - double getAmbientTemp(void) const; + explicit TaskFemConstraintHeatflux(ViewProviderFemConstraintHeatflux *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintHeatflux() override; + double getAmbientTemp() const; /*double getFaceTemp(void) const;*/ - double getFilmCoef(void) const; - std::string get_constraint_type(void) const; - virtual const std::string getReferences() const; + double getFilmCoef() const; + std::string get_constraint_type() const; + const std::string getReferences() const override; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void onAmbientTempChanged(double val); /*void onFaceTempChanged(double val);*/ void onFilmCoefChanged(double val); void onHeatFluxChanged(double val); void Conv(); void Flux(); - void addToSelection(); - void removeFromSelection(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - virtual void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -74,10 +74,10 @@ class TaskDlgFemConstraintHeatflux : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintHeatflux(ViewProviderFemConstraintHeatflux *ConstraintView); - virtual void open(); - virtual bool accept(); - virtual bool reject(); + explicit TaskDlgFemConstraintHeatflux(ViewProviderFemConstraintHeatflux *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h b/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h index 48be1de492..9bc50b6454 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintInitialTemperature.h @@ -40,12 +40,12 @@ class TaskFemConstraintInitialTemperature : public TaskFemConstraint Q_OBJECT public: - TaskFemConstraintInitialTemperature(ViewProviderFemConstraintInitialTemperature *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintInitialTemperature(); + explicit TaskFemConstraintInitialTemperature(ViewProviderFemConstraintInitialTemperature *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintInitialTemperature() override; double get_temperature()const; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: //void onSelectionChanged(const Gui::SelectionChanges& msg); @@ -59,10 +59,10 @@ class TaskDlgFemConstraintInitialTemperature : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintInitialTemperature(ViewProviderFemConstraintInitialTemperature *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintInitialTemperature(ViewProviderFemConstraintInitialTemperature *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h b/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h index 882f7934b7..debc0e7be9 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintOnBoundary.h @@ -48,8 +48,8 @@ class TaskFemConstraintOnBoundary : public TaskFemConstraint Q_OBJECT public: - TaskFemConstraintOnBoundary(ViewProviderFemConstraint *ConstraintView, QWidget *parent = nullptr, const char* pixmapname = ""); - ~TaskFemConstraintOnBoundary(); + explicit TaskFemConstraintOnBoundary(ViewProviderFemConstraint *ConstraintView, QWidget *parent = nullptr, const char* pixmapname = ""); + ~TaskFemConstraintOnBoundary() override; protected Q_SLOTS: void onButtonToggled(QAbstractButton *button, bool checked); @@ -58,7 +58,7 @@ protected Q_SLOTS: protected: enum class SelectionChangeModes {none, refAdd, refRemove}; - virtual void onSelectionChanged(const Gui::SelectionChanges&) override; + void onSelectionChanged(const Gui::SelectionChanges&) override; virtual void clearButtons(const SelectionChangeModes notThis) = 0; protected: diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp index 6e27409c46..e60798d4e4 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.cpp @@ -81,7 +81,7 @@ TaskFemConstraintPlaneRotation::TaskFemConstraintPlaneRotation(ViewProviderFemCo for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -116,7 +116,7 @@ void TaskFemConstraintPlaneRotation::addToSelection() } else { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -177,7 +177,7 @@ void TaskFemConstraintPlaneRotation::addToSelection() void TaskFemConstraintPlaneRotation::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -205,7 +205,7 @@ void TaskFemConstraintPlaneRotation::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h index fd5613de36..d324507e6d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintPlaneRotation.h @@ -40,18 +40,18 @@ class TaskFemConstraintPlaneRotation : public TaskFemConstraint Q_OBJECT public: - TaskFemConstraintPlaneRotation(ViewProviderFemConstraintPlaneRotation *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintPlaneRotation(); - const std::string getReferences() const; + explicit TaskFemConstraintPlaneRotation(ViewProviderFemConstraintPlaneRotation *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintPlaneRotation() override; + const std::string getReferences() const override; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void addToSelection(); void removeFromSelection(); protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; private: void updateUI(); @@ -64,10 +64,10 @@ class TaskDlgFemConstraintPlaneRotation : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintPlaneRotation(ViewProviderFemConstraintPlaneRotation *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintPlaneRotation(ViewProviderFemConstraintPlaneRotation *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp index 791428f521..512438772a 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPressure.cpp @@ -84,7 +84,7 @@ TaskFemConstraintPressure::TaskFemConstraintPressure(ViewProviderFemConstraintPr for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -118,7 +118,7 @@ void TaskFemConstraintPressure::onCheckReverse(const bool pressed) void TaskFemConstraintPressure::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -164,7 +164,7 @@ void TaskFemConstraintPressure::addToSelection() void TaskFemConstraintPressure::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -192,7 +192,7 @@ void TaskFemConstraintPressure::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPressure.h b/src/Mod/Fem/Gui/TaskFemConstraintPressure.h index 2c57c2b229..b1bf50b411 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPressure.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintPressure.h @@ -40,21 +40,21 @@ class TaskFemConstraintPressure : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintPressure(ViewProviderFemConstraintPressure *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintPressure(); - const std::string getReferences() const; + explicit TaskFemConstraintPressure(ViewProviderFemConstraintPressure *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintPressure() override; + const std::string getReferences() const override; double get_Pressure()const; bool get_Reverse()const; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void onCheckReverse(bool); - void addToSelection(); - void removeFromSelection(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -68,10 +68,10 @@ class TaskDlgFemConstraintPressure : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintPressure(ViewProviderFemConstraintPressure *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintPressure(ViewProviderFemConstraintPressure *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp b/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp index 177d9172d2..aedf669322 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintPulley.cpp @@ -123,12 +123,12 @@ void TaskFemConstraintPulley::onCheckIsDriven(const bool pressed) pcConstraint->IsDriven.setValue(pressed); } -double TaskFemConstraintPulley::getTorque(void) const +double TaskFemConstraintPulley::getTorque() const { return ui->spinForce->value(); } -double TaskFemConstraintPulley::getTensionForce(void) const +double TaskFemConstraintPulley::getTensionForce() const { return ui->spinTensionForce->value(); } @@ -138,12 +138,12 @@ bool TaskFemConstraintPulley::getIsDriven() const return ui->checkIsDriven->isChecked(); } -double TaskFemConstraintPulley::getOtherDiameter(void) const +double TaskFemConstraintPulley::getOtherDiameter() const { return ui->spinOtherDiameter->value(); } -double TaskFemConstraintPulley::getCenterDistance(void) const +double TaskFemConstraintPulley::getCenterDistance() const { return ui->spinCenterDistance->value(); } diff --git a/src/Mod/Fem/Gui/TaskFemConstraintPulley.h b/src/Mod/Fem/Gui/TaskFemConstraintPulley.h index b61777044c..7ca20d7e0d 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintPulley.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintPulley.h @@ -34,13 +34,13 @@ class TaskFemConstraintPulley : public TaskFemConstraintGear Q_OBJECT public: - TaskFemConstraintPulley(ViewProviderFemConstraintPulley *ConstraintView,QWidget *parent = nullptr); + explicit TaskFemConstraintPulley(ViewProviderFemConstraintPulley *ConstraintView,QWidget *parent = nullptr); - double getOtherDiameter(void) const; - double getCenterDistance(void) const; - double getTensionForce(void) const; - double getTorque(void) const; - bool getIsDriven(void) const; + double getOtherDiameter() const; + double getCenterDistance() const; + double getTensionForce() const; + double getTorque() const; + bool getIsDriven() const; private Q_SLOTS: void onOtherDiameterChanged(double dia); @@ -49,7 +49,7 @@ private Q_SLOTS: void onCheckIsDriven(bool); protected: - virtual void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; }; /// simulation dialog for the TaskView @@ -58,11 +58,11 @@ class TaskDlgFemConstraintPulley : public TaskDlgFemConstraintGear Q_OBJECT public: - TaskDlgFemConstraintPulley(ViewProviderFemConstraintPulley *ConstraintView); + explicit TaskDlgFemConstraintPulley(ViewProviderFemConstraintPulley *ConstraintView); /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); - void open(); + bool accept() override; + void open() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp b/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp index 373915a17f..1ec9e3b085 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintSpring.cpp @@ -87,7 +87,7 @@ TaskFemConstraintSpring::TaskFemConstraintSpring(ViewProviderFemConstraintSpring for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -116,7 +116,7 @@ void TaskFemConstraintSpring::updateUI() void TaskFemConstraintSpring::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -162,7 +162,7 @@ void TaskFemConstraintSpring::addToSelection() void TaskFemConstraintSpring::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -190,7 +190,7 @@ void TaskFemConstraintSpring::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); diff --git a/src/Mod/Fem/Gui/TaskFemConstraintSpring.h b/src/Mod/Fem/Gui/TaskFemConstraintSpring.h index 7bc210e281..62da3938ca 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintSpring.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintSpring.h @@ -38,20 +38,20 @@ class TaskFemConstraintSpring : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintSpring(ViewProviderFemConstraintSpring *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintSpring(); - const std::string getReferences() const; + explicit TaskFemConstraintSpring(ViewProviderFemConstraintSpring *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintSpring() override; + const std::string getReferences() const override; double get_normalStiffness()const; double get_tangentialStiffness()const; private Q_SLOTS: - void onReferenceDeleted(void); - void addToSelection(); - void removeFromSelection(); + void onReferenceDeleted(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -65,10 +65,10 @@ class TaskDlgFemConstraintSpring : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintSpring(ViewProviderFemConstraintSpring *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintSpring(ViewProviderFemConstraintSpring *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp index 49bceba6d3..dfac163f60 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.cpp @@ -101,7 +101,7 @@ TaskFemConstraintTemperature::TaskFemConstraintTemperature(ViewProviderFemConstr for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_references->addItem(makeRefText(Objects[i], SubElements[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { ui->lw_references->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); } @@ -166,7 +166,7 @@ void TaskFemConstraintTemperature::Flux() void TaskFemConstraintTemperature::addToSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -207,7 +207,7 @@ void TaskFemConstraintTemperature::addToSelection() void TaskFemConstraintTemperature::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -235,7 +235,7 @@ void TaskFemConstraintTemperature::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); @@ -278,7 +278,7 @@ double TaskFemConstraintTemperature::get_cflux() const { return cflux_in_watt; } -std::string TaskFemConstraintTemperature::get_constraint_type(void) const { +std::string TaskFemConstraintTemperature::get_constraint_type() const { std::string type; if (ui->rb_temperature->isChecked()) { type = "\"Temperature\""; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h index ae18573b3d..c68d0bbf5c 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintTemperature.h @@ -43,24 +43,24 @@ class TaskFemConstraintTemperature : public TaskFemConstraintOnBoundary Q_OBJECT public: - TaskFemConstraintTemperature(ViewProviderFemConstraintTemperature *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintTemperature(); - const std::string getReferences() const; + explicit TaskFemConstraintTemperature(ViewProviderFemConstraintTemperature *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintTemperature() override; + const std::string getReferences() const override; double get_temperature()const; double get_cflux() const; - std::string get_constraint_type(void) const; + std::string get_constraint_type() const; private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void onTempCfluxChanged(double val); void Temp(); void Flux(); - void addToSelection(); - void removeFromSelection(); + void addToSelection() override; + void removeFromSelection() override; protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; void clearButtons(const SelectionChangeModes notThis) override; private: @@ -74,10 +74,10 @@ class TaskDlgFemConstraintTemperature : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintTemperature(ViewProviderFemConstraintTemperature *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintTemperature(ViewProviderFemConstraintTemperature *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp b/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp index 8dd05fe1b3..7fe0f70b06 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp +++ b/src/Mod/Fem/Gui/TaskFemConstraintTransform.cpp @@ -119,7 +119,7 @@ TaskFemConstraintTransform::TaskFemConstraintTransform(ViewProviderFemConstraint ui->lw_dis_cylin->addItem(makeText(nDispl[i])); } - if (Objects.size() > 0) { + if (!Objects.empty()) { for (std::size_t i = 0; i < Objects.size(); i++) { ui->lw_Rect->addItem(makeRefText(Objects[i], SubElements[i])); } @@ -137,7 +137,7 @@ TaskFemConstraintTransform::TaskFemConstraintTransform(ViewProviderFemConstraint connect(ui->btnRemove, SIGNAL(clicked()), this, SLOT(removeFromSelection())); updateUI(); - if ((p == 0) && (Objects.size() > 0)) { + if ((p == 0) && (!Objects.empty())) { QMessageBox::warning(this, tr("Constraint update error"), tr("The transformable faces have changed. Please add only the transformable faces and remove non-transformable faces!")); return; } @@ -201,7 +201,7 @@ void TaskFemConstraintTransform::Rect() { Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.%s.TransformType = %s", name.c_str(), get_transform_type().c_str()); Fem::ConstraintTransform* pcConstraint = static_cast(ConstraintView->getObject()); std::vector Objects = pcConstraint->References.getValues(); - if (Objects.size() > 0) { + if (!Objects.empty()) { setSelection(ui->lw_Rect->item(0)); removeFromSelection(); } @@ -216,7 +216,7 @@ void TaskFemConstraintTransform::Cyl() { Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.%s.TransformType = %s", name.c_str(), get_transform_type().c_str()); Fem::ConstraintTransform* pcConstraint = static_cast(ConstraintView->getObject()); std::vector Objects = pcConstraint->References.getValues(); - if (Objects.size() > 0) { + if (!Objects.empty()) { setSelection(ui->lw_Rect->item(0)); removeFromSelection(); } @@ -227,7 +227,7 @@ void TaskFemConstraintTransform::addToSelection() { int rows = ui->lw_Rect->model()->rowCount(); std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -299,7 +299,7 @@ void TaskFemConstraintTransform::addToSelection() this, SLOT(setSelection(QListWidgetItem*))); } } - if (Objects.size() == 0) { + if (Objects.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Only transformable faces can be selected! Apply displacement constraint to surface first then apply constraint to surface")); Gui::Selection().clearSelection(); return; @@ -347,7 +347,7 @@ void TaskFemConstraintTransform::addToSelection() void TaskFemConstraintTransform::removeFromSelection() { std::vector selection = Gui::Selection().getSelectionEx(); //gets vector of selected objects of active document - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(this, tr("Selection error"), tr("Nothing selected!")); return; } @@ -375,7 +375,7 @@ void TaskFemConstraintTransform::removeFromSelection() } } std::sort(itemsToDel.begin(), itemsToDel.end()); - while (itemsToDel.size() > 0) { + while (!itemsToDel.empty()) { Objects.erase(Objects.begin() + itemsToDel.back()); SubElements.erase(SubElements.begin() + itemsToDel.back()); itemsToDel.pop_back(); @@ -446,7 +446,7 @@ double TaskFemConstraintTransform::get_X_rot() const { return ui->sp_X->value(); double TaskFemConstraintTransform::get_Y_rot() const { return ui->sp_Y->value(); } double TaskFemConstraintTransform::get_Z_rot() const { return ui->sp_Z->value(); } -std::string TaskFemConstraintTransform::get_transform_type(void) const { +std::string TaskFemConstraintTransform::get_transform_type() const { std::string transform; if (ui->rb_rect->isChecked()) { transform = "\"Rectangular\""; diff --git a/src/Mod/Fem/Gui/TaskFemConstraintTransform.h b/src/Mod/Fem/Gui/TaskFemConstraintTransform.h index 9289924ab5..0e35bc2cc5 100644 --- a/src/Mod/Fem/Gui/TaskFemConstraintTransform.h +++ b/src/Mod/Fem/Gui/TaskFemConstraintTransform.h @@ -41,17 +41,17 @@ class TaskFemConstraintTransform : public TaskFemConstraint Q_OBJECT public: - TaskFemConstraintTransform(ViewProviderFemConstraintTransform *ConstraintView,QWidget *parent = nullptr); - ~TaskFemConstraintTransform(); - const std::string getReferences() const; + explicit TaskFemConstraintTransform(ViewProviderFemConstraintTransform *ConstraintView,QWidget *parent = nullptr); + ~TaskFemConstraintTransform() override; + const std::string getReferences() const override; double get_X_rot()const; double get_Y_rot()const; double get_Z_rot()const; - std::string get_transform_type(void) const; + std::string get_transform_type() const; static std::string getSurfaceReferences(const std::string showConstr); private Q_SLOTS: - void onReferenceDeleted(void); + void onReferenceDeleted(); void Rect(); void Cyl(); void addToSelection(); @@ -61,8 +61,8 @@ private Q_SLOTS: void z_Changed(int z); protected: - bool event(QEvent *e); - void changeEvent(QEvent *e); + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; const QString makeText(const App::DocumentObject* obj) const; private: @@ -75,10 +75,10 @@ class TaskDlgFemConstraintTransform : public TaskDlgFemConstraint Q_OBJECT public: - TaskDlgFemConstraintTransform(ViewProviderFemConstraintTransform *ConstraintView); - void open(); - bool accept(); - bool reject(); + explicit TaskDlgFemConstraintTransform(ViewProviderFemConstraintTransform *ConstraintView); + void open() override; + bool accept() override; + bool reject() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/TaskObjectName.h b/src/Mod/Fem/Gui/TaskObjectName.h index e5a1c6850f..39c0369eda 100644 --- a/src/Mod/Fem/Gui/TaskObjectName.h +++ b/src/Mod/Fem/Gui/TaskObjectName.h @@ -48,8 +48,8 @@ class TaskObjectName : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskObjectName(App::DocumentObject *pcObject,QWidget *parent = nullptr); - ~TaskObjectName(); + explicit TaskObjectName(App::DocumentObject *pcObject,QWidget *parent = nullptr); + ~TaskObjectName() override; std::string name; diff --git a/src/Mod/Fem/Gui/TaskPostBoxes.cpp b/src/Mod/Fem/Gui/TaskPostBoxes.cpp index f12f7fe355..4790bba647 100644 --- a/src/Mod/Fem/Gui/TaskPostBoxes.cpp +++ b/src/Mod/Fem/Gui/TaskPostBoxes.cpp @@ -32,6 +32,8 @@ # include # include +# include +# include #endif #include @@ -98,7 +100,7 @@ void PointMarker::customEvent(QEvent*) const SbVec3f& pt2 = vp->pCoords->point[1]; if (!m_name.empty()) { - PointsChanged(pt1[0], pt1[1], pt1[2], pt2[0], pt2[1], pt2[2]); + Q_EMIT PointsChanged(pt1[0], pt1[1], pt1[2], pt2[0], pt2[1], pt2[2]); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.%s.Point1 = App.Vector(%f, %f, %f)", m_name.c_str(), pt1[0], pt1[1], pt1[2]); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.%s.Point2 = App.Vector(%f, %f, %f)", m_name.c_str(), pt2[0], pt2[1], pt2[2]); } @@ -166,7 +168,7 @@ void DataMarker::customEvent(QEvent*) const SbVec3f& pt1 = vp->pCoords->point[0]; if (!m_name.empty()) { - PointsChanged(pt1[0], pt1[1], pt1[2]); + Q_EMIT PointsChanged(pt1[0], pt1[1], pt1[2]); Gui::Command::doCommand(Gui::Command::Doc, "App.ActiveDocument.%s.Center = App.Vector(%f, %f, %f)", m_name.c_str(), pt1[0], pt1[1], pt1[2]); } Gui::Command::doCommand(Gui::Command::Doc, ObjectInvisible().c_str()); @@ -223,7 +225,7 @@ TaskDlgPost::~TaskDlgPost() } -QDialogButtonBox::StandardButtons TaskDlgPost::getStandardButtons(void) const { +QDialogButtonBox::StandardButtons TaskDlgPost::getStandardButtons() const { //check if we only have gui task boxes bool guionly = true; @@ -389,6 +391,7 @@ TaskPostDisplay::TaskPostDisplay(Gui::ViewProviderDocumentObject* view, QWidget* Base::Console().Log("Transparency %i: \n", trans); // sync the trancparency slider ui->Transparency->setValue(trans); + ui->Transparency->setToolTip(QString::number(trans) + QString::fromLatin1(" %")); } TaskPostDisplay::~TaskPostDisplay() @@ -421,6 +424,9 @@ void TaskPostDisplay::on_VectorMode_activated(int i) { void TaskPostDisplay::on_Transparency_valueChanged(int i) { getTypedView()->Transparency.setValue(i); + ui->Transparency->setToolTip(QString::number(i) + QString::fromLatin1(" %")); + // highlight the tooltip + QToolTip::showText(QCursor::pos(), QString::number(i) + QString::fromLatin1(" %"), nullptr); } void TaskPostDisplay::applyPythonCode() { @@ -430,7 +436,7 @@ void TaskPostDisplay::applyPythonCode() { // *************************************************************************** // ? // the icon fem-post-geo-plane might be wrong but I do not know any better since the plane is one of the implicit functions -TaskPostFunction::TaskPostFunction(ViewProviderDocumentObject* view, QWidget* parent) +TaskPostFunction::TaskPostFunction(ViewProviderDocumentObject* view, QWidget* parent) : TaskPostBox(view, Gui::BitmapFactory().pixmap("fem-post-geo-plane"), tr("Implicit function"), parent) { @@ -830,7 +836,7 @@ void TaskPostDataAlongLine::pointCallback(void* ud, SoEventCallback* n) if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No point picked.\n"); return; } @@ -1059,7 +1065,7 @@ void TaskPostDataAtPoint::pointCallback(void* ud, SoEventCallback* n) if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint* point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No point picked.\n"); return; } @@ -1093,32 +1099,65 @@ void TaskPostDataAtPoint::on_Field_activated(int i) { return; } static_cast(getObject())->FieldName.setValue(FieldName); - if ((FieldName == "von Mises Stress") || (FieldName == "Tresca Stress") - || (FieldName == "Major Principal Stress") || (FieldName == "Intermediate Principal Stress") + + // Set the unit for the different known result types. + + // CCX names + if ( (FieldName == "von Mises Stress") || (FieldName == "Tresca Stress") + || (FieldName == "Major Principal Stress") + || (FieldName == "Intermediate Principal Stress") || (FieldName == "Minor Principal Stress") + || (FieldName == "Major Principal Stress Vector") + || (FieldName == "Intermediate Principal Stress Vector") + || (FieldName == "Minor Principal Stress Vector") || (FieldName == "Stress xx component") || (FieldName == "Stress xy component") || (FieldName == "Stress xz component") || (FieldName == "Stress yy component") - || (FieldName == "Stress yz component") || (FieldName == "Stress zz component")) { + || (FieldName == "Stress yz component") || (FieldName == "Stress zz component") ) { static_cast(getObject())->Unit.setValue("Pa"); } - else if ((FieldName == "Displacement") || (FieldName == "Displacement Magnitude")) { + // The elmer names are different. If there are EigenModes, the names are unique for + // every mode. Therefore we only check for the beginning of the name. + else if ( (FieldName.find("tresca", 0) == 0) || (FieldName.find("vonmises", 0) == 0) + || (FieldName.find("stress_", 0) == 0) || (FieldName.find("principal stress", 0) == 0) ) { + static_cast(getObject())->Unit.setValue("Pa"); + } + else if ( (FieldName == "Displacement") || (FieldName == "Displacement Magnitude") + || (FieldName.find("displacement", 0) == 0) // Elmer name + ) { static_cast(getObject())->Unit.setValue("m"); } - else if (FieldName == "Temperature") { + else if ( + // CalculiX name + FieldName == "Temperature" || + // Elmer name + ((FieldName.find("temperature", 0) == 0) && (FieldName != "temperature flux")) + ) { static_cast(getObject())->Unit.setValue("K"); } else if (FieldName == "electric field") { static_cast(getObject())->Unit.setValue("V/m"); } + else if (FieldName == "electric force density") { + static_cast(getObject())->Unit.setValue("N/m^2"); + } else if (FieldName == "potential") { static_cast(getObject())->Unit.setValue("V"); } else if (FieldName == "electric energy density") { static_cast(getObject())->Unit.setValue("J/m^3"); } - // ToDo: set a proper unit once it is known + else if (FieldName == "electric flux") { + static_cast(getObject())->Unit.setValue("A*s/m^2"); + } + else if (FieldName == "potential flux") { + static_cast(getObject())->Unit.setValue("W/m^2"); + } + // potential loads are in Coulomb: https://www.elmerfem.org/forum/viewtopic.php?t=7780 else if (FieldName == "potential loads") { - static_cast(getObject())->Unit.setValue(""); + static_cast(getObject())->Unit.setValue("C"); + } + else if (FieldName == "temperature flux") { + static_cast(getObject())->Unit.setValue("W/m^2"); } else { static_cast(getObject())->Unit.setValue(""); @@ -1188,7 +1227,7 @@ TaskPostScalarClip::TaskPostScalarClip(ViewProviderDocumentObject* view, QWidget // sync the slider // slider min = 0%, slider max = 100% // - // scalar_factor + // scalar_factor // slider_value = --------------- x 100 // max // diff --git a/src/Mod/Fem/Gui/TaskPostBoxes.h b/src/Mod/Fem/Gui/TaskPostBoxes.h index 17b7f0117a..38ace8c56c 100644 --- a/src/Mod/Fem/Gui/TaskPostBoxes.h +++ b/src/Mod/Fem/Gui/TaskPostBoxes.h @@ -60,7 +60,7 @@ class PointMarker : public QObject public: PointMarker(Gui::View3DInventorViewer* view, std::string ObjName); - ~PointMarker(); + ~PointMarker() override; void addPoint(const SbVec3f&); int countPoints() const; @@ -69,7 +69,7 @@ Q_SIGNALS: void PointsChanged(double x1, double y1, double z1, double x2, double y2, double z2); protected: - void customEvent(QEvent* e); + void customEvent(QEvent* e) override; private: Gui::View3DInventorViewer *view; @@ -81,11 +81,11 @@ private: class FemGuiExport ViewProviderPointMarker : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(FemGui::ViewProviderPointMarker); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderPointMarker); public: ViewProviderPointMarker(); - virtual ~ViewProviderPointMarker(); + ~ViewProviderPointMarker() override; protected: SoCoordinate3 * pCoords; @@ -100,7 +100,7 @@ class DataMarker : public QObject public: DataMarker(Gui::View3DInventorViewer* view, std::string ObjName); - ~DataMarker(); + ~DataMarker() override; void addPoint(const SbVec3f&); int countPoints() const; @@ -109,7 +109,7 @@ Q_SIGNALS: void PointsChanged(double x, double y, double z); protected: - void customEvent(QEvent* e); + void customEvent(QEvent* e) override; private: Gui::View3DInventorViewer *view; @@ -121,11 +121,11 @@ private: class FemGuiExport ViewProviderDataMarker : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(FemGui::ViewProviderDataMarker); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderDataMarker); public: ViewProviderDataMarker(); - virtual ~ViewProviderDataMarker(); + ~ViewProviderDataMarker() override; protected: SoCoordinate3 * pCoords; @@ -139,7 +139,7 @@ class TaskPostBox : public Gui::TaskView::TaskBox { public: TaskPostBox(Gui::ViewProviderDocumentObject* view, const QPixmap &icon, const QString &title, QWidget *parent = nullptr); - ~TaskPostBox(); + ~TaskPostBox() override; virtual void applyPythonCode() = 0; virtual bool isGuiTaskOnly() {return false;} //return true if only gui properties are manipulated @@ -179,8 +179,8 @@ class TaskDlgPost : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgPost(Gui::ViewProviderDocumentObject *view); - ~TaskDlgPost(); + explicit TaskDlgPost(Gui::ViewProviderDocumentObject *view); + ~TaskDlgPost() override; void connectSlots(); void appendBox(TaskPostBox* box); @@ -190,20 +190,20 @@ public: public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return false; } - virtual void modifyStandardButtons(QDialogButtonBox*); + void modifyStandardButtons(QDialogButtonBox*) override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const; + QDialogButtonBox::StandardButtons getStandardButtons() const override; protected: void recompute(); @@ -219,11 +219,11 @@ class TaskPostDisplay : public TaskPostBox Q_OBJECT public: - TaskPostDisplay(Gui::ViewProviderDocumentObject* view, QWidget *parent = nullptr); - ~TaskPostDisplay(); + explicit TaskPostDisplay(Gui::ViewProviderDocumentObject* view, QWidget *parent = nullptr); + ~TaskPostDisplay() override; - virtual void applyPythonCode(); - virtual bool isGuiTaskOnly() {return true;} + void applyPythonCode() override; + bool isGuiTaskOnly() override {return true;} private Q_SLOTS: void on_Representation_activated(int i); @@ -243,10 +243,10 @@ class TaskPostFunction : public TaskPostBox { Q_OBJECT public: - TaskPostFunction(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); - virtual ~TaskPostFunction(); + explicit TaskPostFunction(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); + ~TaskPostFunction() override; - virtual void applyPythonCode(); + void applyPythonCode() override; }; @@ -256,9 +256,9 @@ class TaskPostClip : public TaskPostBox { public: TaskPostClip(Gui::ViewProviderDocumentObject* view, App::PropertyLink* function, QWidget* parent = nullptr); - virtual ~TaskPostClip(); + ~TaskPostClip() override; - virtual void applyPythonCode(); + void applyPythonCode() override; private Q_SLOTS: void on_CreateButton_triggered(QAction*); @@ -284,10 +284,10 @@ class TaskPostDataAlongLine: public TaskPostBox { Q_OBJECT public: - TaskPostDataAlongLine(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); - virtual ~TaskPostDataAlongLine(); + explicit TaskPostDataAlongLine(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); + ~TaskPostDataAlongLine() override; - virtual void applyPythonCode(); + void applyPythonCode() override; static void pointCallback(void * ud, SoEventCallback * n); private Q_SLOTS: @@ -315,10 +315,10 @@ class TaskPostDataAtPoint: public TaskPostBox { Q_OBJECT public: - TaskPostDataAtPoint(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); - virtual ~TaskPostDataAtPoint(); + explicit TaskPostDataAtPoint(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); + ~TaskPostDataAtPoint() override; - virtual void applyPythonCode(); + void applyPythonCode() override; static void pointCallback(void * ud, SoEventCallback * n); private Q_SLOTS: @@ -344,10 +344,10 @@ class TaskPostScalarClip : public TaskPostBox { Q_OBJECT public: - TaskPostScalarClip(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); - virtual ~TaskPostScalarClip(); + explicit TaskPostScalarClip(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); + ~TaskPostScalarClip() override; - virtual void applyPythonCode(); + void applyPythonCode() override; private Q_SLOTS: void on_Slider_valueChanged(int v); @@ -366,10 +366,10 @@ class TaskPostWarpVector : public TaskPostBox { Q_OBJECT public: - TaskPostWarpVector(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); - virtual ~TaskPostWarpVector(); + explicit TaskPostWarpVector(Gui::ViewProviderDocumentObject* view, QWidget* parent = nullptr); + ~TaskPostWarpVector() override; - virtual void applyPythonCode(); + void applyPythonCode() override; private Q_SLOTS: void on_Slider_valueChanged(int v); @@ -390,9 +390,9 @@ class TaskPostCut : public TaskPostBox { public: TaskPostCut(Gui::ViewProviderDocumentObject* view, App::PropertyLink* function, QWidget* parent = nullptr); - virtual ~TaskPostCut(); + ~TaskPostCut() override; - virtual void applyPythonCode(); + void applyPythonCode() override; private Q_SLOTS: void on_CreateButton_triggered(QAction*); diff --git a/src/Mod/Fem/Gui/TaskPostDisplay.ui b/src/Mod/Fem/Gui/TaskPostDisplay.ui index 7fe56eac5f..4c4fb4e13e 100644 --- a/src/Mod/Fem/Gui/TaskPostDisplay.ui +++ b/src/Mod/Fem/Gui/TaskPostDisplay.ui @@ -7,7 +7,7 @@ 0 0 292 - 254 + 186 diff --git a/src/Mod/Fem/Gui/TaskTetParameter.cpp b/src/Mod/Fem/Gui/TaskTetParameter.cpp index 3f07abaf88..1a50d93f9e 100644 --- a/src/Mod/Fem/Gui/TaskTetParameter.cpp +++ b/src/Mod/Fem/Gui/TaskTetParameter.cpp @@ -147,7 +147,7 @@ void TaskTetParameter::setOptimize(int v) } -void TaskTetParameter::setInfo(void) +void TaskTetParameter::setInfo() { Fem::FemMesh::FemMeshInfo info = pcObject->FemMesh.getValue().getInfo(); //Base::BoundBox3d bndBox = pcObject->FemMesh.getValue().getBoundBox(); diff --git a/src/Mod/Fem/Gui/TaskTetParameter.h b/src/Mod/Fem/Gui/TaskTetParameter.h index 40150aa5ac..11fe5c45a0 100644 --- a/src/Mod/Fem/Gui/TaskTetParameter.h +++ b/src/Mod/Fem/Gui/TaskTetParameter.h @@ -55,10 +55,10 @@ class TaskTetParameter : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskTetParameter(Fem::FemMeshShapeNetgenObject *pcObject,QWidget *parent = nullptr); - ~TaskTetParameter(); + explicit TaskTetParameter(Fem::FemMeshShapeNetgenObject *pcObject,QWidget *parent = nullptr); + ~TaskTetParameter() override; - void setInfo(void); + void setInfo(); bool touched; private Q_SLOTS: diff --git a/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp b/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp index 5155235102..878af5b415 100644 --- a/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp +++ b/src/Mod/Fem/Gui/ViewProviderAnalysis.cpp @@ -28,6 +28,7 @@ # include # include # include +# include #endif #include @@ -55,6 +56,33 @@ using namespace FemGui; +ViewProviderFemHighlighter::ViewProviderFemHighlighter() +{ + annotate = new SoSeparator(); + annotate->ref(); +} + +ViewProviderFemHighlighter::~ViewProviderFemHighlighter() +{ + annotate->unref(); +} + +void ViewProviderFemHighlighter::attach(ViewProviderFemAnalysis *view) +{ + SoGroup *root = view->getRoot(); + root->addChild(annotate); +} + +void ViewProviderFemHighlighter::highlightView(Gui::ViewProviderDocumentObject *view) +{ + annotate->removeAllChildren(); + + if (view) { + annotate->addChild(view->getRoot()); + } +} + +// ---------------------------------------------------------------------------- /* TRANSLATOR FemGui::ViewProviderFemAnalysis */ @@ -68,25 +96,37 @@ ViewProviderFemAnalysis::ViewProviderFemAnalysis() ViewProviderFemAnalysis::~ViewProviderFemAnalysis() { +} +void ViewProviderFemAnalysis::attach(App::DocumentObject *obj) +{ + Gui::ViewProviderDocumentObjectGroup::attach(obj); + extension.attach(this); +} + +void ViewProviderFemAnalysis::highlightView(Gui::ViewProviderDocumentObject *view) +{ + extension.highlightView(view); } bool ViewProviderFemAnalysis::doubleClicked(void) { Gui::Command::assureWorkbench("FemWorkbench"); - Gui::Command::addModule(Gui::Command::Gui,"FemGui"); - Gui::Command::doCommand(Gui::Command::Gui,"FemGui.setActiveAnalysis(App.activeDocument().%s)",this->getObject()->getNameInDocument()); + Gui::Command::addModule(Gui::Command::Gui, "FemGui"); + Gui::Command::doCommand(Gui::Command::Gui, + "FemGui.setActiveAnalysis(App.activeDocument().%s)", + this->getObject()->getNameInDocument()); return true; } -std::vector ViewProviderFemAnalysis::claimChildren(void)const +std::vector ViewProviderFemAnalysis::claimChildren(void) const { return Gui::ViewProviderDocumentObjectGroup::claimChildren(); } std::vector ViewProviderFemAnalysis::getDisplayModes(void) const { - return { "Analysis" }; + return {"Analysis"}; } void ViewProviderFemAnalysis::hide(void) @@ -99,10 +139,10 @@ void ViewProviderFemAnalysis::show(void) Gui::ViewProviderDocumentObjectGroup::show(); } -void ViewProviderFemAnalysis::setupContextMenu(QMenu* menu, QObject* , const char* ) +void ViewProviderFemAnalysis::setupContextMenu(QMenu *menu, QObject *, const char *) { - Gui::ActionFunction* func = new Gui::ActionFunction(menu); - QAction* act = menu->addAction(tr("Activate analysis")); + Gui::ActionFunction *func = new Gui::ActionFunction(menu); + QAction *act = menu->addAction(tr("Activate analysis")); func->trigger(act, std::bind(&ViewProviderFemAnalysis::doubleClicked, this)); } @@ -160,7 +200,7 @@ bool ViewProviderFemAnalysis::canDragObjects() const return true; } -bool ViewProviderFemAnalysis::canDragObject(App::DocumentObject* obj) const +bool ViewProviderFemAnalysis::canDragObject(App::DocumentObject *obj) const { if (!obj) return false; @@ -188,7 +228,7 @@ bool ViewProviderFemAnalysis::canDragObject(App::DocumentObject* obj) const return false; } -void ViewProviderFemAnalysis::dragObject(App::DocumentObject* obj) +void ViewProviderFemAnalysis::dragObject(App::DocumentObject *obj) { ViewProviderDocumentObjectGroup::dragObject(obj); } @@ -198,23 +238,22 @@ bool ViewProviderFemAnalysis::canDropObjects() const return true; } -bool ViewProviderFemAnalysis::canDropObject(App::DocumentObject* obj) const +bool ViewProviderFemAnalysis::canDropObject(App::DocumentObject *obj) const { return canDragObject(obj); } -void ViewProviderFemAnalysis::dropObject(App::DocumentObject* obj) +void ViewProviderFemAnalysis::dropObject(App::DocumentObject *obj) { ViewProviderDocumentObjectGroup::dropObject(obj); } -bool ViewProviderFemAnalysis::onDelete(const std::vector&) +bool ViewProviderFemAnalysis::onDelete(const std::vector &) { // warn the user if the object has childs auto objs = claimChildren(); - if (!objs.empty()) - { + if (!objs.empty()) { // generate dialog QString bodyMessage; QTextStream bodyMessageStream(&bodyMessage); @@ -238,22 +277,23 @@ bool ViewProviderFemAnalysis::onDelete(const std::vector&) } } -bool ViewProviderFemAnalysis::canDelete(App::DocumentObject* obj) const +bool ViewProviderFemAnalysis::canDelete(App::DocumentObject *obj) const { // deletions of objects from a FemAnalysis don't necessarily destroy anything // thus we can pass this action // we can warn the user if necessary in the object's ViewProvider in the onDelete() function Q_UNUSED(obj) - return true; + return true; } // Python feature ----------------------------------------------------------------------- -namespace Gui { +namespace Gui +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(FemGui::ViewProviderFemAnalysisPython, FemGui::ViewProviderFemAnalysis) /// @endcond // explicit template instantiation template class FemGuiExport ViewProviderPythonFeatureT; -} +} // namespace Gui diff --git a/src/Mod/Fem/Gui/ViewProviderAnalysis.h b/src/Mod/Fem/Gui/ViewProviderAnalysis.h index 15f8c58924..80a99110a9 100644 --- a/src/Mod/Fem/Gui/ViewProviderAnalysis.h +++ b/src/Mod/Fem/Gui/ViewProviderAnalysis.h @@ -28,65 +28,84 @@ #include #include - namespace FemGui { +class ViewProviderFemAnalysis; +class ViewProviderFemHighlighter +{ +public: + /// Constructor + ViewProviderFemHighlighter(); + ~ViewProviderFemHighlighter(); + + void attach(ViewProviderFemAnalysis*); + void highlightView(Gui::ViewProviderDocumentObject*); + +private: + SoSeparator* annotate; +}; + class FemGuiExport ViewProviderFemAnalysis : public Gui::ViewProviderDocumentObjectGroup { Q_DECLARE_TR_FUNCTIONS(FemGui::ViewProviderFemAnalysis) - PROPERTY_HEADER(FemGui::ViewProviderAnalysis); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderAnalysis); public: /// constructor. ViewProviderFemAnalysis(); /// destructor. - virtual ~ViewProviderFemAnalysis(); + ~ViewProviderFemAnalysis() override; - virtual bool doubleClicked(void); + void attach(App::DocumentObject*) override; + bool doubleClicked() override; - virtual std::vector claimChildren(void)const; + std::vector claimChildren()const override; // handling when object is deleted - virtual bool onDelete(const std::vector&); + bool onDelete(const std::vector&) override; /// Asks the view provider if the given object can be deleted. - virtual bool canDelete(App::DocumentObject* obj) const; + bool canDelete(App::DocumentObject* obj) const override; //virtual std::vector claimChildren3D(void)const; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; /// A list of all possible display modes - virtual std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; // shows solid in the tree - virtual bool isShow(void) const { + bool isShow() const override { return Visibility.getValue(); } /// Hide the object in the view - virtual void hide(void); + void hide() override; /// Show the object in the view - virtual void show(void); + void show() override; + + void highlightView(Gui::ViewProviderDocumentObject*); /** @name Drag and drop */ //@{ /// Returns true if the view provider generally supports dragging objects - bool canDragObjects() const; + bool canDragObjects() const override; /// Check whether the object can be removed from the view provider by drag and drop - bool canDragObject(App::DocumentObject*) const; + bool canDragObject(App::DocumentObject*) const override; /// Starts to drag the object - void dragObject(App::DocumentObject*); + void dragObject(App::DocumentObject*) override; /// Returns true if the view provider generally accepts dropping of objects - bool canDropObjects() const; + bool canDropObjects() const override; /// Check whether the object can be dropped to the view provider by drag and drop - bool canDropObject(App::DocumentObject*) const; + bool canDropObject(App::DocumentObject*) const override; /// If the dropped object type is accepted the object will be added as child - void dropObject(App::DocumentObject*); + void dropObject(App::DocumentObject*) override; //@} protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; +private: + ViewProviderFemHighlighter extension; }; typedef Gui::ViewProviderPythonFeatureT ViewProviderFemAnalysisPython; diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp index 483474005f..29634cb43b 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraint.cpp @@ -60,7 +60,7 @@ using namespace FemGui; -PROPERTY_SOURCE(FemGui::ViewProviderFemConstraint, Gui::ViewProviderDocumentObject) +PROPERTY_SOURCE(FemGui::ViewProviderFemConstraint, Gui::ViewProviderGeometryObject) ViewProviderFemConstraint::ViewProviderFemConstraint() @@ -106,7 +106,7 @@ ViewProviderFemConstraint::~ViewProviderFemConstraint() void ViewProviderFemConstraint::attach(App::DocumentObject* pcObject) { - ViewProviderDocumentObject::attach(pcObject); + ViewProviderGeometryObject::attach(pcObject); SoPickStyle* ps = new SoPickStyle(); ps->style = SoPickStyle::UNPICKABLE; @@ -122,11 +122,11 @@ void ViewProviderFemConstraint::attach(App::DocumentObject* pcObject) addDisplayMaskMode(sep, "Base"); } -std::vector ViewProviderFemConstraint::getDisplayModes(void) const +std::vector ViewProviderFemConstraint::getDisplayModes() const { // add modes std::vector StrList; - StrList.push_back("Base"); + StrList.emplace_back("Base"); return StrList; } @@ -137,7 +137,7 @@ void ViewProviderFemConstraint::setDisplayMode(const char* ModeName) ViewProviderDocumentObject::setDisplayMode(ModeName); } -std::vector ViewProviderFemConstraint::claimChildren(void)const +std::vector ViewProviderFemConstraint::claimChildren()const { return std::vector(); } @@ -147,7 +147,7 @@ void ViewProviderFemConstraint::setupContextMenu(QMenu* menu, QObject* receiver, QAction* act; act = menu->addAction(QObject::tr("Edit constraint"), receiver, member); act->setData(QVariant((int)ViewProvider::Default)); - ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); + ViewProviderDocumentObject::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method } void ViewProviderFemConstraint::onChanged(const App::Property* prop) @@ -167,7 +167,7 @@ void ViewProviderFemConstraint::onChanged(const App::Property* prop) pFont->size = FontSize.getValue(); } else { - ViewProviderDocumentObject::onChanged(prop); + ViewProviderDocumentObject::onChanged(prop); // clazy:exclude=skipped-base-method } } @@ -197,7 +197,7 @@ void ViewProviderFemConstraint::unsetEdit(int ModNum) // clear the selection (convenience) Gui::Selection().clearSelection(); - if ((wizardWidget != nullptr) && (wizardSubLayout != nullptr) && (constraintDialog != nullptr)) { + if (wizardWidget && wizardSubLayout && constraintDialog) { wizardWidget = nullptr; wizardSubLayout = nullptr; delete constraintDialog; @@ -213,7 +213,7 @@ void ViewProviderFemConstraint::unsetEdit(int ModNum) Gui::Control().closeDialog(); } else { - ViewProviderDocumentObject::unsetEdit(ModNum); + ViewProviderGeometryObject::unsetEdit(ModNum); } } } @@ -489,7 +489,7 @@ QObject* ViewProviderFemConstraint::findChildByName(const QObject* parent, const return *o; if (!(*o)->children().empty()) { QObject* result = findChildByName(*o, name); - if (result != nullptr) + if (result) return result; } } @@ -502,28 +502,28 @@ void ViewProviderFemConstraint::checkForWizard() wizardWidget= nullptr; wizardSubLayout = nullptr; Gui::MainWindow* mw = Gui::getMainWindow(); - if (mw == nullptr) + if (!mw) return; QDockWidget* dw = mw->findChild(QString::fromLatin1("Combo View")); - if (dw == nullptr) + if (!dw) return; QWidget* cw = dw->findChild(QString::fromLatin1("Combo View")); - if (cw == nullptr) + if (!cw) return; QTabWidget* tw = cw->findChild(QString::fromLatin1("combiTab")); - if (tw == nullptr) + if (!tw) return; QStackedWidget* sw = tw->findChild(QString::fromLatin1("qt_tabwidget_stackedwidget")); - if (sw == nullptr) + if (!sw) return; QScrollArea* sa = sw->findChild(); - if (sa== nullptr) + if (!sa) return; QWidget* wd = sa->widget(); // This is the reason why we cannot use findChildByName() right away!!! - if (wd == nullptr) + if (!wd) return; QObject* wiz = findChildByName(wd, QString::fromLatin1("ShaftWizard")); - if (wiz != nullptr) { + if (wiz) { wizardWidget = static_cast(wiz); wizardSubLayout = wiz->findChild(QString::fromLatin1("ShaftWizardLayout")); } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraint.h b/src/Mod/Fem/Gui/ViewProviderFemConstraint.h index 1f35f4fd23..03cb068eef 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraint.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraint.h @@ -44,12 +44,12 @@ class TaskFemConstraint; class FemGuiExport ViewProviderFemConstraint : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraint); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraint); public: /// Constructor - ViewProviderFemConstraint(void); - virtual ~ViewProviderFemConstraint(); + ViewProviderFemConstraint(); + ~ViewProviderFemConstraint() override; // Display properties App::PropertyColor TextColor; @@ -59,13 +59,13 @@ public: App::PropertyFloat DistFactor; App::PropertyBool Mirror; - void attach(App::DocumentObject *); - virtual void updateData(const App::Property* prop) { Gui::ViewProviderGeometryObject::updateData(prop); } - std::vector getDisplayModes(void) const; - void setDisplayMode(const char* ModeName); + void attach(App::DocumentObject *) override; + void updateData(const App::Property* prop) override { Gui::ViewProviderGeometryObject::updateData(prop); } + std::vector getDisplayModes() const override; + void setDisplayMode(const char* ModeName) override; - std::vector claimChildren(void)const; - void setupContextMenu(QMenu*, QObject*, const char*); + std::vector claimChildren()const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; /// Highlight the references that have been selected virtual void highlightReferences(const bool /* on */) {} @@ -74,9 +74,9 @@ public: static std::string gethideMeshShowPartStr(const std::string showConstr); protected: - void onChanged(const App::Property* prop); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + void onChanged(const App::Property* prop) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; static void createPlacement(SoSeparator* sep, const SbVec3f &base, const SbRotation &r); static void updatePlacement(const SoSeparator* sep, const int idx, const SbVec3f &base, const SbRotation &r); diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp index 66cbcf935d..f3ecc15cc7 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.cpp @@ -71,7 +71,7 @@ bool ViewProviderFemConstraintBearing::setEdit(int ModNum) if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); - if ((wizardWidget == nullptr) || (wizardSubLayout == nullptr)) { + if (!wizardWidget || !wizardSubLayout) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -83,7 +83,7 @@ bool ViewProviderFemConstraintBearing::setEdit(int ModNum) Gui::Control().reject(); else return false; - } else if (constraintDialog != nullptr) { + } else if (constraintDialog) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; @@ -105,7 +105,7 @@ bool ViewProviderFemConstraintBearing::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.h index c958bdb2b9..345bc114b5 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintBearing.h @@ -32,17 +32,17 @@ namespace FemGui class FemGuiExport ViewProviderFemConstraintBearing : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintBearing); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintBearing); public: /// Constructor ViewProviderFemConstraintBearing(); - virtual ~ViewProviderFemConstraintBearing(); + ~ViewProviderFemConstraintBearing() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.cpp index f8f531bfc5..1188984884 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.cpp @@ -75,7 +75,7 @@ bool ViewProviderFemConstraintContact::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -95,7 +95,7 @@ bool ViewProviderFemConstraintContact::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.h index d404e3f6f6..b64ebba804 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintContact.h @@ -32,15 +32,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintContact : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintContact); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintContact); public: ViewProviderFemConstraintContact(); - virtual ~ViewProviderFemConstraintContact(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintContact() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp index 2ae3628eb9..5e92634a2d 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.cpp @@ -68,7 +68,7 @@ bool ViewProviderFemConstraintDisplacement::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -88,7 +88,7 @@ bool ViewProviderFemConstraintDisplacement::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.h index 8641b151f0..f2935093c6 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintDisplacement.h @@ -32,15 +32,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintDisplacement : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintDisplacement); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintDisplacement); public: ViewProviderFemConstraintDisplacement(); - virtual ~ViewProviderFemConstraintDisplacement(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintDisplacement() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.cpp index e27ed50a9a..df75f5493d 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.cpp @@ -71,7 +71,7 @@ bool ViewProviderFemConstraintFixed::setEdit(int ModNum) if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); - if ((wizardWidget == nullptr) || (wizardSubLayout == nullptr)) { + if (!wizardWidget || !wizardSubLayout) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -83,7 +83,7 @@ bool ViewProviderFemConstraintFixed::setEdit(int ModNum) Gui::Control().reject(); else return false; - } else if (constraintDialog != nullptr) { + } else if (constraintDialog) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; @@ -104,7 +104,7 @@ bool ViewProviderFemConstraintFixed::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h index 19be407be5..ad32899fc3 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintFixed.h @@ -32,17 +32,17 @@ namespace FemGui class FemGuiExport ViewProviderFemConstraintFixed : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintFixed); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintFixed); public: /// Constructor ViewProviderFemConstraintFixed(); - virtual ~ViewProviderFemConstraintFixed(); + ~ViewProviderFemConstraintFixed() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp index 6ded08293f..b8f4b7f174 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.cpp @@ -69,7 +69,7 @@ bool ViewProviderFemConstraintFluidBoundary::setEdit(int ModNum) if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); - if ((wizardWidget == nullptr) || (wizardSubLayout == nullptr)) { + if (!wizardWidget || !wizardSubLayout) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -81,7 +81,7 @@ bool ViewProviderFemConstraintFluidBoundary::setEdit(int ModNum) Gui::Control().reject(); else return false; - } else if (constraintDialog != nullptr) { + } else if (constraintDialog) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; @@ -103,7 +103,7 @@ bool ViewProviderFemConstraintFluidBoundary::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.h index 718b30779e..b33f3439bf 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintFluidBoundary.h @@ -32,17 +32,17 @@ namespace FemGui class FemGuiExport ViewProviderFemConstraintFluidBoundary : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintFluidBoundary); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintFluidBoundary); public: /// Constructor ViewProviderFemConstraintFluidBoundary(); - virtual ~ViewProviderFemConstraintFluidBoundary(); + ~ViewProviderFemConstraintFluidBoundary() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; //virtual void onChanged(const App::Property*); //no further property for viewProvider protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp index 6d8490171e..0384e77fa4 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.cpp @@ -70,7 +70,7 @@ bool ViewProviderFemConstraintForce::setEdit(int ModNum) if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); - if ((wizardWidget == nullptr) || (wizardSubLayout == nullptr)) { + if (!wizardWidget || !wizardSubLayout) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -82,7 +82,7 @@ bool ViewProviderFemConstraintForce::setEdit(int ModNum) Gui::Control().reject(); else return false; - } else if (constraintDialog != nullptr) { + } else if (constraintDialog) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; @@ -104,7 +104,7 @@ bool ViewProviderFemConstraintForce::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h index 50ece3c06a..da72e2c6c5 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintForce.h @@ -32,17 +32,17 @@ namespace FemGui class FemGuiExport ViewProviderFemConstraintForce : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintForce); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintForce); public: /// Constructor ViewProviderFemConstraintForce(); - virtual ~ViewProviderFemConstraintForce(); + ~ViewProviderFemConstraintForce() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; private: /// Direction of the force diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp index 4028c382a8..d732023331 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.cpp @@ -70,7 +70,7 @@ bool ViewProviderFemConstraintGear::setEdit(int ModNum) if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); - if ((wizardWidget == nullptr) || (wizardSubLayout == nullptr)) { + if (!wizardWidget || !wizardSubLayout) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -82,7 +82,7 @@ bool ViewProviderFemConstraintGear::setEdit(int ModNum) Gui::Control().reject(); else return false; - } else if (constraintDialog != nullptr) { + } else if (constraintDialog) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; @@ -104,7 +104,7 @@ bool ViewProviderFemConstraintGear::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.h index ce1e8d4c30..1656034bcd 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintGear.h @@ -32,17 +32,17 @@ namespace FemGui class FemGuiExport ViewProviderFemConstraintGear : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintGear); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintGear); public: /// Constructor ViewProviderFemConstraintGear(); - virtual ~ViewProviderFemConstraintGear(); + ~ViewProviderFemConstraintGear() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp index 6faf2de8dc..67b5901d47 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.cpp @@ -74,7 +74,7 @@ bool ViewProviderFemConstraintHeatflux::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -94,7 +94,7 @@ bool ViewProviderFemConstraintHeatflux::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.h index 3e01aee490..cf8bb01742 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintHeatflux.h @@ -32,15 +32,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintHeatflux : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintHeatflux); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintHeatflux); public: ViewProviderFemConstraintHeatflux(); - virtual ~ViewProviderFemConstraintHeatflux(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintHeatflux() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp index 55e2b4ccd3..96db29a990 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.cpp @@ -74,7 +74,7 @@ bool ViewProviderFemConstraintInitialTemperature::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -94,7 +94,7 @@ bool ViewProviderFemConstraintInitialTemperature::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.h index c5904505c5..b80a2b3097 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintInitialTemperature.h @@ -32,15 +32,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintInitialTemperature : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintInitialTemperature); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintInitialTemperature); public: ViewProviderFemConstraintInitialTemperature(); - virtual ~ViewProviderFemConstraintInitialTemperature(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintInitialTemperature() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h index 31bf1d4e09..f4ac82f8c5 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintOnBoundary.h @@ -32,11 +32,11 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintOnBoundary : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintOnBoundary); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintOnBoundary); public: ViewProviderFemConstraintOnBoundary(); - virtual ~ViewProviderFemConstraintOnBoundary(); + ~ViewProviderFemConstraintOnBoundary() override; void highlightReferences(const bool on) override; diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.cpp index 28d19726d4..dfc88f6f28 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.cpp @@ -76,7 +76,7 @@ bool ViewProviderFemConstraintPlaneRotation::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -96,7 +96,7 @@ bool ViewProviderFemConstraintPlaneRotation::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.h index 3ede68a48a..9a6579c537 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPlaneRotation.h @@ -32,15 +32,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintPlaneRotation : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintPlaneRotation); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintPlaneRotation); public: ViewProviderFemConstraintPlaneRotation(); - virtual ~ViewProviderFemConstraintPlaneRotation(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintPlaneRotation() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp index b6ab0d21ce..e7e769699a 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.cpp @@ -66,7 +66,7 @@ bool ViewProviderFemConstraintPressure::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -86,7 +86,7 @@ bool ViewProviderFemConstraintPressure::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h index 642f361f89..870b45eebf 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPressure.h @@ -30,15 +30,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintPressure : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintPressure); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintPressure); public: ViewProviderFemConstraintPressure(); - virtual ~ViewProviderFemConstraintPressure(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintPressure() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp index 88449e460f..558f6fae36 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.cpp @@ -69,7 +69,7 @@ bool ViewProviderFemConstraintPulley::setEdit(int ModNum) if (dlg && !constrDlg) { // This case will occur in the ShaftWizard application checkForWizard(); - if ((wizardWidget == nullptr) || (wizardSubLayout == nullptr)) { + if (!wizardWidget || !wizardSubLayout) { // No shaft wizard is running QMessageBox msgBox; msgBox.setText(QObject::tr("A dialog is already open in the task panel")); @@ -81,7 +81,7 @@ bool ViewProviderFemConstraintPulley::setEdit(int ModNum) Gui::Control().reject(); else return false; - } else if (constraintDialog != nullptr) { + } else if (constraintDialog) { // Another FemConstraint* dialog is already open inside the Shaft Wizard // Ignore the request to open another dialog return false; @@ -103,7 +103,7 @@ bool ViewProviderFemConstraintPulley::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.h index dd8cfbdab1..9749eafb56 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintPulley.h @@ -32,17 +32,17 @@ namespace FemGui class FemGuiExport ViewProviderFemConstraintPulley : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintPulley); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintPulley); public: /// Constructor ViewProviderFemConstraintPulley(); - virtual ~ViewProviderFemConstraintPulley(); + ~ViewProviderFemConstraintPulley() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp index dc9fe64542..6353872888 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.cpp @@ -66,7 +66,7 @@ bool ViewProviderFemConstraintSpring::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -86,7 +86,7 @@ bool ViewProviderFemConstraintSpring::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h index 6a79ed41f3..4b72d705d4 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintSpring.h @@ -30,15 +30,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintSpring : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintSpring); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintSpring); public: ViewProviderFemConstraintSpring(); - virtual ~ViewProviderFemConstraintSpring(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintSpring() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp index 1262b511ba..5ff8fcdc7a 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.cpp @@ -75,7 +75,7 @@ bool ViewProviderFemConstraintTemperature::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -95,7 +95,7 @@ bool ViewProviderFemConstraintTemperature::setEdit(int ModNum) return true; } else { - return ViewProviderDocumentObject::setEdit(ModNum); + return ViewProviderDocumentObject::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.h index b6c2640054..1dea8d6668 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTemperature.h @@ -32,15 +32,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintTemperature : public FemGui::ViewProviderFemConstraintOnBoundary { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintTemperature); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintTemperature); public: ViewProviderFemConstraintTemperature(); - virtual ~ViewProviderFemConstraintTemperature(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintTemperature() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp index 3054cd1cd2..1bb17c6b0e 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.cpp @@ -83,7 +83,7 @@ bool ViewProviderFemConstraintTransform::setEdit(int ModNum) if (constrDlg && constrDlg->getConstraintView() != this) constrDlg = nullptr; // another constraint left open its task panel if (dlg && !constrDlg) { - if (constraintDialog != nullptr) { + if (constraintDialog) { // Ignore the request to open another dialog return false; } else { @@ -276,7 +276,7 @@ void ViewProviderFemConstraintTransform::updateData(const App::Property* prop) return; std::vector::const_iterator n = normals.begin(); - if (points.size() > 0) { + if (!points.empty()) { Base::Vector3d base = pcConstraint->BasePoint.getValue(); Base::Vector3d axis = pcConstraint->Axis.getValue(); diff --git a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h index 4fa00e1ccb..5a66fc91ed 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h +++ b/src/Mod/Fem/Gui/ViewProviderFemConstraintTransform.h @@ -33,15 +33,15 @@ namespace FemGui { class FemGuiExport ViewProviderFemConstraintTransform : public FemGui::ViewProviderFemConstraint { - PROPERTY_HEADER(FemGui::ViewProviderFemConstraintTransform); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemConstraintTransform); public: ViewProviderFemConstraintTransform(); - virtual ~ViewProviderFemConstraintTransform(); - virtual void updateData(const App::Property*); + ~ViewProviderFemConstraintTransform() override; + void updateData(const App::Property*) override; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; } diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp index 438e1dd86f..7950a2983d 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.cpp @@ -46,7 +46,7 @@ # include #endif -#include +#include #include #include #include @@ -66,7 +66,7 @@ struct FemFace unsigned short Size; unsigned short FaceNo; bool hide; - Base::Vector3d getFirstNodePoint(void) { + Base::Vector3d getFirstNodePoint() { return Base::Vector3d(Nodes[0]->X(),Nodes[0]->Y(),Nodes[0]->Z()); } @@ -331,15 +331,15 @@ void ViewProviderFemMesh::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode(ModeName); } -std::vector ViewProviderFemMesh::getDisplayModes(void) const +std::vector ViewProviderFemMesh::getDisplayModes() const { std::vector StrList; - StrList.push_back(Private::dm_face_wire); - StrList.push_back(Private::dm_face_wire_node); - StrList.push_back(Private::dm_face); - StrList.push_back(Private::dm_wire); - StrList.push_back(Private::dm_node); - StrList.push_back(Private::dm_wire_node); + StrList.emplace_back(Private::dm_face_wire); + StrList.emplace_back(Private::dm_face_wire_node); + StrList.emplace_back(Private::dm_face); + StrList.emplace_back(Private::dm_wire); + StrList.emplace_back(Private::dm_node); + StrList.emplace_back(Private::dm_wire_node); return StrList; } @@ -493,7 +493,7 @@ void ViewProviderFemMesh::setHighlightNodes(const std::set& HighlightedNod } } -void ViewProviderFemMesh::resetHighlightNodes(void) +void ViewProviderFemMesh::resetHighlightNodes() { pcAnoCoords->point.setNum(0); vHighlightedIdx.clear(); @@ -550,7 +550,7 @@ void ViewProviderFemMesh::setColorByNodeIdHelper(const std::vector & pcShapeMaterial->diffuseColor.finishEditing(); } -void ViewProviderFemMesh::resetColorByNodeId(void) +void ViewProviderFemMesh::resetColorByNodeId() { pcMatBinding->value = SoMaterialBinding::OVERALL; pcShapeMaterial->diffuseColor.setNum(0); @@ -596,7 +596,7 @@ void ViewProviderFemMesh::setDisplacementByNodeIdHelper(const std::vector &E pcShapeMaterial->diffuseColor.finishEditing(); } -void ViewProviderFemMesh::resetColorByElementId(void) +void ViewProviderFemMesh::resetColorByElementId() { pcMatBinding->value = SoMaterialBinding::OVERALL; pcShapeMaterial->diffuseColor.setNum(0); diff --git a/src/Mod/Fem/Gui/ViewProviderFemMesh.h b/src/Mod/Fem/Gui/ViewProviderFemMesh.h index e9375b8dda..96232fbcdb 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMesh.h +++ b/src/Mod/Fem/Gui/ViewProviderFemMesh.h @@ -42,8 +42,8 @@ class ViewProviderFEMMeshBuilder : public Gui::ViewProviderBuilder { public: ViewProviderFEMMeshBuilder(){} - virtual ~ViewProviderFEMMeshBuilder(){} - virtual void buildNodes(const App::Property*, std::vector&) const; + ~ViewProviderFEMMeshBuilder() override{} + void buildNodes(const App::Property*, std::vector&) const override; void createMesh(const App::Property*, SoCoordinate3*, SoIndexedFaceSet*, @@ -58,14 +58,14 @@ public: class FemGuiExport ViewProviderFemMesh : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(FemGui::ViewProviderFemMesh); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemMesh); public: /// constructor. ViewProviderFemMesh(); /// destructor. - virtual ~ViewProviderFemMesh(); + ~ViewProviderFemMesh() override; // Display properties App::PropertyColor PointColor; @@ -75,10 +75,10 @@ public: App::PropertyBool ShowInner; App::PropertyInteger MaxFacesShowInner; - void attach(App::DocumentObject *pcObject); - void setDisplayMode(const char* ModeName); - std::vector getDisplayModes() const; - void updateData(const App::Property*); + void attach(App::DocumentObject *pcObject) override; + void setDisplayMode(const char* ModeName) override; + std::vector getDisplayModes() const override; + void updateData(const App::Property*) override; /** @name Selection handling * This group of methods do the selection handling. @@ -87,18 +87,18 @@ public: */ //@{ /// indicates if the ViewProvider use the new Selection model - virtual bool useNewSelectionModel(void) const {return true;} + bool useNewSelectionModel() const override {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; + std::string getElement(const SoDetail*) const override; + SoDetail* getDetail(const char*) const override; /// return the highlight lines for a given element or the whole shape - virtual std::vector getSelectionShape(const char* Element) const; + std::vector getSelectionShape(const char* Element) const override; //@} // interface methods void setHighlightNodes(const std::set&); std::set getHighlightNodes() const; - void resetHighlightNodes(void); + void resetHighlightNodes(); /** @name Postprocessing * this interfaces apply post processing stuff to the View- @@ -112,23 +112,23 @@ public: void setColorByNodeId(const std::vector &NodeIds,const std::vector &NodeColors); /// reset the view of the node colors - void resetColorByNodeId(void); + void resetColorByNodeId(); /// set the displacement for each node void setDisplacementByNodeId(const std::map &NodeDispMap); void setDisplacementByNodeId(const std::vector &NodeIds,const std::vector &NodeDisps); /// reset the view of the node displacement - void resetDisplacementByNodeId(void); + void resetDisplacementByNodeId(); /// reaply the node displacement with a certain factor and do a redraw void applyDisplacementToNodes(double factor); /// set the color for each element void setColorByElementId(const std::map &ElementColorMap); /// reset the view of the element colors - void resetColorByElementId(void); + void resetColorByElementId(); //@} - const std::vector &getVisibleElementFaces(void)const{return vFaceElementIdx;} + const std::vector &getVisibleElementFaces()const{return vFaceElementIdx;} - PyObject *getPyObject(); + PyObject *getPyObject() override; private: static App::PropertyFloatConstraint::Constraints floatRange; @@ -137,7 +137,7 @@ private: protected: /// get called by the container whenever a property has been changed - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; void setColorByNodeIdHelper(const std::vector &); void setDisplacementByNodeIdHelper(const std::vector& DispVector,long startId); diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp b/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp index 1953292276..b1409df22b 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshPyImp.cpp @@ -20,7 +20,7 @@ using namespace FemGui; // returns a string which represents the object e.g. when printed in python -std::string ViewProviderFemMeshPy::representation(void) const +std::string ViewProviderFemMeshPy::representation() const { return std::string(""); } @@ -150,7 +150,7 @@ PyObject* ViewProviderFemMeshPy::resetNodeDisplacement(PyObject* args) } -Py::Dict ViewProviderFemMeshPy::getNodeColor(void) const +Py::Dict ViewProviderFemMeshPy::getNodeColor() const { //return Py::List(); throw Py::AttributeError("Not yet implemented"); @@ -191,7 +191,7 @@ void ViewProviderFemMeshPy::setNodeColor(Py::Dict arg) } -Py::Dict ViewProviderFemMeshPy::getElementColor(void) const +Py::Dict ViewProviderFemMeshPy::getElementColor() const { //return Py::List(); throw Py::AttributeError("Not yet implemented"); @@ -215,7 +215,7 @@ void ViewProviderFemMeshPy::setElementColor(Py::Dict arg) } -Py::Dict ViewProviderFemMeshPy::getNodeDisplacement(void) const +Py::Dict ViewProviderFemMeshPy::getNodeDisplacement() const { //return Py::Dict(); throw Py::AttributeError("Not yet implemented"); @@ -242,7 +242,7 @@ void ViewProviderFemMeshPy::setNodeDisplacement(Py::Dict arg) } -Py::List ViewProviderFemMeshPy::getHighlightedNodes(void) const +Py::List ViewProviderFemMeshPy::getHighlightedNodes() const { Py::List list; ViewProviderFemMesh* vp = this->getViewProviderFemMeshPtr(); @@ -281,7 +281,7 @@ PyObject* ViewProviderFemMeshPy::resetHighlightedNodes(PyObject* args) } -Py::List ViewProviderFemMeshPy::getVisibleElementFaces(void) const +Py::List ViewProviderFemMeshPy::getVisibleElementFaces() const { const std::vector& visElmFc = this->getViewProviderFemMeshPtr()->getVisibleElementFaces(); std::vector trans; diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h b/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h index 2e4bd68f5e..90905295f1 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshShape.h @@ -31,14 +31,14 @@ namespace FemGui class FemGuiExport ViewProviderFemMeshShape : public ViewProviderFemMesh { - PROPERTY_HEADER(FemGui::ViewProviderFemMeshShape); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemMeshShape); public: /// constructor. ViewProviderFemMeshShape(); /// destructor. - virtual ~ViewProviderFemMeshShape(); + ~ViewProviderFemMeshShape() override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.h b/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.h index 015a5286ec..8bdf0a90ed 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.h +++ b/src/Mod/Fem/Gui/ViewProviderFemMeshShapeNetgen.h @@ -30,20 +30,20 @@ namespace FemGui class FemGuiExport ViewProviderFemMeshShapeNetgen : public ViewProviderFemMeshShape { - PROPERTY_HEADER(FemGui::ViewProviderFemMeshShapeNetgen); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemMeshShapeNetgen); public: /// constructor. ViewProviderFemMeshShapeNetgen(); /// destructor. - virtual ~ViewProviderFemMeshShapeNetgen(); + ~ViewProviderFemMeshShapeNetgen() override; - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member); - virtual bool setEdit(int ModNum); + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool setEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp index 7edfb2fadd..3e1614dd47 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.cpp @@ -22,6 +22,10 @@ #include "PreCompiled.h" +#ifndef _PreComp_ +# include +#endif + #include #include "ViewProviderFemPostFilter.h" @@ -77,6 +81,18 @@ ViewProviderFemPostDataAtPoint::ViewProviderFemPostDataAtPoint() { sPixmap = "FEM_PostFilterDataAtPoint"; } +void ViewProviderFemPostDataAtPoint::show() +{ + Gui::ViewProviderDocumentObject::show(); +} + +void ViewProviderFemPostDataAtPoint::onSelectionChanged(const Gui::SelectionChanges &) +{ + // do not do anything here + // For DataAtPoint the color bar must not be refreshed when it is selected + // because a single point does not make sense with a color range. +} + ViewProviderFemPostDataAtPoint::~ViewProviderFemPostDataAtPoint() { } diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h index 79d3eb2374..7681bded57 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFilter.h @@ -31,79 +31,81 @@ namespace FemGui class FemGuiExport ViewProviderFemPostClip : public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostClip); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostClip); public: /// constructor. ViewProviderFemPostClip(); - ~ViewProviderFemPostClip(); + ~ViewProviderFemPostClip() override; protected: - virtual void setupTaskDialog(TaskDlgPost* dlg); + void setupTaskDialog(TaskDlgPost* dlg) override; }; class FemGuiExport ViewProviderFemPostDataAlongLine : public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostDataAlongLine); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostDataAlongLine); public: /// constructor. ViewProviderFemPostDataAlongLine(); - ~ViewProviderFemPostDataAlongLine(); + ~ViewProviderFemPostDataAlongLine() override; protected: - virtual void setupTaskDialog(TaskDlgPost* dlg); + void setupTaskDialog(TaskDlgPost* dlg) override; }; class FemGuiExport ViewProviderFemPostDataAtPoint: public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostDataAtPoint); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostDataAtPoint); public: /// constructor. ViewProviderFemPostDataAtPoint(); - ~ViewProviderFemPostDataAtPoint(); + void show() override; + void onSelectionChanged(const Gui::SelectionChanges &) override; + ~ViewProviderFemPostDataAtPoint() override; protected: - virtual void setupTaskDialog(TaskDlgPost* dlg); + void setupTaskDialog(TaskDlgPost* dlg) override; }; class FemGuiExport ViewProviderFemPostScalarClip : public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostScalarClip); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostScalarClip); public: /// constructor. ViewProviderFemPostScalarClip(); - ~ViewProviderFemPostScalarClip(); + ~ViewProviderFemPostScalarClip() override; protected: - virtual void setupTaskDialog(TaskDlgPost* dlg); + void setupTaskDialog(TaskDlgPost* dlg) override; }; class FemGuiExport ViewProviderFemPostWarpVector : public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostWarpVector); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostWarpVector); public: /// constructor. ViewProviderFemPostWarpVector(); - ~ViewProviderFemPostWarpVector(); + ~ViewProviderFemPostWarpVector() override; protected: - virtual void setupTaskDialog(TaskDlgPost* dlg); + void setupTaskDialog(TaskDlgPost* dlg) override; }; class FemGuiExport ViewProviderFemPostCut : public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostCut); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostCut); public: /// constructor. ViewProviderFemPostCut(); - ~ViewProviderFemPostCut(); + ~ViewProviderFemPostCut() override; protected: - virtual void setupTaskDialog(TaskDlgPost* dlg); + void setupTaskDialog(TaskDlgPost* dlg) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp index 11fb93fdca..0e2fa7499f 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.cpp @@ -93,12 +93,12 @@ ViewProviderFemPostFunctionProvider::~ViewProviderFemPostFunctionProvider() { } -std::vector< App::DocumentObject* > ViewProviderFemPostFunctionProvider::claimChildren(void) const { +std::vector< App::DocumentObject* > ViewProviderFemPostFunctionProvider::claimChildren() const { return static_cast(getObject())->Functions.getValues(); } -std::vector< App::DocumentObject* > ViewProviderFemPostFunctionProvider::claimChildren3D(void) const { +std::vector< App::DocumentObject* > ViewProviderFemPostFunctionProvider::claimChildren3D() const { return claimChildren(); } @@ -276,7 +276,7 @@ bool ViewProviderFemPostFunction::findScaleFactor(double& scale) const return false; } -bool ViewProviderFemPostFunction::doubleClicked(void) { +bool ViewProviderFemPostFunction::doubleClicked() { Gui::Application::Instance->activeDocument()->setEdit(this, (int)ViewProvider::Default); return true; } @@ -286,10 +286,10 @@ SoTransformManip* ViewProviderFemPostFunction::setupManipulator() { return new SoCenterballManip; } -std::vector ViewProviderFemPostFunction::getDisplayModes(void) const +std::vector ViewProviderFemPostFunction::getDisplayModes() const { std::vector StrList; - StrList.push_back("Default"); + StrList.emplace_back("Default"); return StrList; } @@ -442,7 +442,7 @@ void ViewProviderFemPostPlaneFunction::onChanged(const App::Property* prop) // get current matrix SbVec3f t, s; SbRotation r, so; - SbMatrix matrix = getManipulator()->getDragger()->getMotionMatrix(); + SbMatrix matrix = getManipulator()->getDragger()->getMotionMatrix(); // clazy:exclude=rule-of-two-soft matrix.getTransform(t, r, s, so); float scale = static_cast(Scale.getValue()); diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.h b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.h index 976d60481f..c9e68f6d1b 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostFunction.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostFunction.h @@ -50,7 +50,7 @@ class FemGuiExport FunctionWidget : public QWidget { Q_OBJECT public: FunctionWidget() : m_block(false), m_view(nullptr), m_object(nullptr) {} - virtual ~FunctionWidget() {} + ~FunctionWidget() override {} virtual void applyPythonCode() = 0; virtual void setViewProvider(ViewProviderFemPostFunction* view); @@ -74,55 +74,55 @@ private: class FemGuiExport ViewProviderFemPostFunctionProvider : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostFunction); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostFunction); public: ViewProviderFemPostFunctionProvider(); - virtual ~ViewProviderFemPostFunctionProvider(); + ~ViewProviderFemPostFunctionProvider() override; App::PropertyFloat SizeX; App::PropertyFloat SizeY; App::PropertyFloat SizeZ; // handling when object is deleted - virtual bool onDelete(const std::vector&); + bool onDelete(const std::vector&) override; /// asks view provider if the given object can be deleted - virtual bool canDelete(App::DocumentObject* obj) const; + bool canDelete(App::DocumentObject* obj) const override; protected: - virtual std::vector< App::DocumentObject* > claimChildren(void) const; - virtual std::vector< App::DocumentObject* > claimChildren3D(void) const; - virtual void onChanged(const App::Property* prop); - virtual void updateData(const App::Property*); + std::vector< App::DocumentObject* > claimChildren() const override; + std::vector< App::DocumentObject* > claimChildren3D() const override; + void onChanged(const App::Property* prop) override; + void updateData(const App::Property*) override; void updateSize(); }; class FemGuiExport ViewProviderFemPostFunction : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostFunction); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostFunction); public: /// constructor. ViewProviderFemPostFunction(); - ~ViewProviderFemPostFunction(); + ~ViewProviderFemPostFunction() override; App::PropertyFloat AutoScaleFactorX; App::PropertyFloat AutoScaleFactorY; App::PropertyFloat AutoScaleFactorZ; - void attach(App::DocumentObject *pcObject); - bool doubleClicked(void); - std::vector getDisplayModes() const; + void attach(App::DocumentObject *pcObject) override; + bool doubleClicked() override; + std::vector getDisplayModes() const override; //creates the widget used in the task dalogs, either for the function itself or for //the filter using it virtual FunctionWidget* createControlWidget() {return nullptr;} protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual void onChanged(const App::Property* prop); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; + void onChanged(const App::Property* prop) override; void setAutoScale(bool value) {m_autoscale = value;} bool autoScale() {return m_autoscale;} @@ -157,11 +157,11 @@ class FemGuiExport PlaneWidget : public FunctionWidget { Q_OBJECT public: PlaneWidget(); - virtual ~PlaneWidget(); + ~PlaneWidget() override; - virtual void applyPythonCode(); - virtual void onChange(const App::Property& p); - virtual void setViewProvider(ViewProviderFemPostFunction* view); + void applyPythonCode() override; + void onChange(const App::Property& p) override; + void setViewProvider(ViewProviderFemPostFunction* view) override; private Q_SLOTS: void originChanged(double); @@ -173,21 +173,21 @@ private: class FemGuiExport ViewProviderFemPostPlaneFunction : public ViewProviderFemPostFunction { - PROPERTY_HEADER(FemGui::ViewProviderFemPostPlaneFunction); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostPlaneFunction); public: ViewProviderFemPostPlaneFunction(); - virtual ~ViewProviderFemPostPlaneFunction(); + ~ViewProviderFemPostPlaneFunction() override; App::PropertyFloatConstraint Scale; - virtual SoTransformManip* setupManipulator(); - virtual FunctionWidget* createControlWidget(); + SoTransformManip* setupManipulator() override; + FunctionWidget* createControlWidget() override; protected: - virtual void draggerUpdate(SoDragger* mat); - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property*); + void draggerUpdate(SoDragger* mat) override; + void updateData(const App::Property*) override; + void onChanged(const App::Property*) override; private: bool m_detectscale; @@ -200,11 +200,11 @@ class FemGuiExport SphereWidget : public FunctionWidget { Q_OBJECT public: SphereWidget(); - virtual ~SphereWidget(); + ~SphereWidget() override; - virtual void applyPythonCode(); - virtual void onChange(const App::Property& p); - virtual void setViewProvider(ViewProviderFemPostFunction* view); + void applyPythonCode() override; + void onChange(const App::Property& p) override; + void setViewProvider(ViewProviderFemPostFunction* view) override; private Q_SLOTS: void centerChanged(double); @@ -216,18 +216,18 @@ private: class FemGuiExport ViewProviderFemPostSphereFunction : public ViewProviderFemPostFunction { - PROPERTY_HEADER(FemGui::ViewProviderFemPostSphereFunction); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostSphereFunction); public: ViewProviderFemPostSphereFunction(); - virtual ~ViewProviderFemPostSphereFunction(); + ~ViewProviderFemPostSphereFunction() override; - virtual SoTransformManip* setupManipulator(); - virtual FunctionWidget* createControlWidget(); + SoTransformManip* setupManipulator() override; + FunctionWidget* createControlWidget() override; protected: - virtual void draggerUpdate(SoDragger* mat); - virtual void updateData(const App::Property*); + void draggerUpdate(SoDragger* mat) override; + void updateData(const App::Property*) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp index 2ddfb1a247..527b4db993 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ +# include # include # include # include @@ -43,26 +44,85 @@ # include #endif +#include #include #include #include #include #include +#include +#include #include #include +#include #include "ViewProviderFemPostObject.h" #include "TaskPostBoxes.h" using namespace FemGui; +namespace sp = std::placeholders; #ifdef VTK_CELL_ARRAY_V2 -typedef const vtkIdType* vtkIdTypePtr; +using vtkIdTypePtr = const vtkIdType*; #else -typedef vtkIdType* vtkIdTypePtr; +using vtkIdTypePtr = vtkIdType*; #endif +// ---------------------------------------------------------------------------- + +namespace { +/* + * The class FemPostObjectSelectionObserver notifies a ViewProviderFemPostObject + * only if its selection status has changed + */ +class FemPostObjectSelectionObserver +{ +public: + static FemPostObjectSelectionObserver& instance() { + static FemPostObjectSelectionObserver inst; + return inst; + } + void registerFemPostObject(ViewProviderFemPostObject* vp) { + views.insert(vp); + } + void unregisterFemPostObject(ViewProviderFemPostObject* vp) { + auto it = views.find(vp); + if (it != views.end()) + views.erase(it); + } + + void selectionChanged(const Gui::SelectionChanges& msg) { + Gui::SelectionObject obj(msg); + auto findVP = std::find_if(views.begin(), views.end(), [&obj](const auto& vp) { + return obj.getObject() == vp->getObject(); + }); + + if (findVP != views.end()) { + (*findVP)->onSelectionChanged(msg); + } + } + +private: + FemPostObjectSelectionObserver() { + this->connectSelection = Gui::Selection().signalSelectionChanged.connect( + std::bind(&FemPostObjectSelectionObserver::selectionChanged, this, sp::_1)); + } + + ~FemPostObjectSelectionObserver() = default; + FemPostObjectSelectionObserver(const FemPostObjectSelectionObserver&) = delete; + FemPostObjectSelectionObserver& operator= (const FemPostObjectSelectionObserver&) = delete; + +private: + std::set views; + typedef boost::signals2::scoped_connection Connection; + Connection connectSelection; +}; + +} + +// ---------------------------------------------------------------------------- + PROPERTY_SOURCE(FemGui::ViewProviderFemPostObject, Gui::ViewProviderDocumentObject) ViewProviderFemPostObject::ViewProviderFemPostObject() : m_blockPropertyChanges(false) @@ -130,10 +190,13 @@ ViewProviderFemPostObject::ViewProviderFemPostObject() : m_blockPropertyChanges( m_currentAlgorithm = m_outline; updateProperties(); // initialize the enums + + FemPostObjectSelectionObserver::instance().registerFemPostObject(this); } ViewProviderFemPostObject::~ViewProviderFemPostObject() { + FemPostObjectSelectionObserver::instance().unregisterFemPostObject(this); m_shapeHints->unref(); m_coordinates->unref(); m_materialBinding->unref(); @@ -191,7 +254,7 @@ void ViewProviderFemPostObject::attach(App::DocumentObject* pcObj) (void)setupPipeline(); } -SoSeparator* ViewProviderFemPostObject::getFrontRoot(void) const { +SoSeparator* ViewProviderFemPostObject::getFrontRoot() const { return m_colorRoot; } @@ -219,16 +282,16 @@ void ViewProviderFemPostObject::setDisplayMode(const char* ModeName) ViewProviderDocumentObject::setDisplayMode(ModeName); } -std::vector ViewProviderFemPostObject::getDisplayModes(void) const +std::vector ViewProviderFemPostObject::getDisplayModes() const { std::vector StrList; - StrList.push_back("Outline"); - StrList.push_back("Nodes"); + StrList.emplace_back("Outline"); + StrList.emplace_back("Nodes"); //StrList.push_back("Nodes (surface only)"); somehow this filter does not work - StrList.push_back("Surface"); - StrList.push_back("Surface with Edges"); - StrList.push_back("Wireframe"); - StrList.push_back("Wireframe (surface only)"); + StrList.emplace_back("Surface"); + StrList.emplace_back("Surface with Edges"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Wireframe (surface only)"); return StrList; } @@ -253,7 +316,7 @@ void ViewProviderFemPostObject::updateProperties() { val = Field.getValueAsString(); std::vector colorArrays; - colorArrays.push_back("None"); + colorArrays.emplace_back("None"); vtkPointData* point = poly->GetPointData(); for (int i = 0; i < point->GetNumberOfArrays(); ++i) { @@ -264,7 +327,7 @@ void ViewProviderFemPostObject::updateProperties() { vtkCellData* cell = poly->GetCellData(); for (int i = 0; i < cell->GetNumberOfArrays(); ++i) - colorArrays.push_back(cell->GetArrayName(i)); + colorArrays.emplace_back(cell->GetArrayName(i)); App::Enumeration empty; Field.setValue(empty); @@ -283,22 +346,22 @@ void ViewProviderFemPostObject::updateProperties() { colorArrays.clear(); if (Field.getValue() == 0) - colorArrays.push_back("Not a vector"); + colorArrays.emplace_back("Not a vector"); else { int array = Field.getValue() - 1; //0 is none vtkPolyData* pd = m_currentAlgorithm->GetOutput(); vtkDataArray* data = pd->GetPointData()->GetArray(array); if (data->GetNumberOfComponents() == 1) - colorArrays.push_back("Not a vector"); + colorArrays.emplace_back("Not a vector"); else { - colorArrays.push_back("Magnitude"); + colorArrays.emplace_back("Magnitude"); if (data->GetNumberOfComponents() >= 2) { - colorArrays.push_back("X"); - colorArrays.push_back("Y"); + colorArrays.emplace_back("X"); + colorArrays.emplace_back("Y"); } if (data->GetNumberOfComponents() >= 3) - colorArrays.push_back("Z"); + colorArrays.emplace_back("Z"); } } @@ -459,6 +522,11 @@ void ViewProviderFemPostObject::setRangeOfColorBar(double min, double max) } } +void ViewProviderFemPostObject::updateMaterial() +{ + WriteColorData(true); +} + void ViewProviderFemPostObject::WriteColorData(bool ResetColorBarRange) { if (!setupPipeline()) @@ -469,6 +537,9 @@ void ViewProviderFemPostObject::WriteColorData(bool ResetColorBarRange) { m_material->transparency.setValue(0.); m_materialBinding->value = SoMaterialBinding::OVERALL; m_materialBinding->touch(); + // since there is no field, set the range to the default + // range as if a new object is created + setRangeOfColorBar(-0.5, 0.5); return; }; @@ -565,7 +636,7 @@ void ViewProviderFemPostObject::onChanged(const App::Property* prop) { if (static_cast(getObject())->getTypeId() == Base::Type::fromName("Fem::FemPostDataAtPointFilter")) ResetColorBarRange = false; - else + else ResetColorBarRange = true; if (prop == &Field && setupPipeline()) { @@ -584,7 +655,7 @@ void ViewProviderFemPostObject::onChanged(const App::Property* prop) { ViewProviderDocumentObject::onChanged(prop); } -bool ViewProviderFemPostObject::doubleClicked(void) { +bool ViewProviderFemPostObject::doubleClicked() { // work around for a problem in VTK implementation: https://forum.freecadweb.org/viewtopic.php?t=10587&start=130#p125688 // check if backlight is enabled ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); @@ -654,17 +725,49 @@ void ViewProviderFemPostObject::unsetEdit(int ModNum) { } } -void ViewProviderFemPostObject::hide(void) { +void ViewProviderFemPostObject::hide() { Gui::ViewProviderDocumentObject::hide(); m_colorStyle->style = SoDrawStyle::INVISIBLE; + // The object is now hidden but the color bar is wrong + // if there are other FemPostObjects visible. + // We must therefore search for the first visible FemPostObject + // according to their order in the Tree View (excluding the point + // object FemPostDataAtPointFilter) and refresh its color bar. + + // get all objects in the document + auto docGui = Gui::Application::Instance->activeDocument(); + if (!docGui) + return; + auto doc = docGui->getDocument(); + std::vector ObjectsList = doc->getObjects(); + App::DocumentObject *firstVisiblePostObject = nullptr; + // step through the objects + for (auto it = ObjectsList.begin(); it != ObjectsList.end(); ++it) { + if ((*it)->getTypeId().isDerivedFrom(Fem::FemPostObject::getClassTypeId())) { + if (!firstVisiblePostObject && (*it)->Visibility.getValue() + && !(*it)->isDerivedFrom(Fem::FemPostDataAtPointFilter::getClassTypeId())) { + firstVisiblePostObject = *it; + break; + } + } + } + // refresh found object + if (firstVisiblePostObject) { + auto viewProvider = docGui->getViewProvider(firstVisiblePostObject); + auto FEMviewProvider = static_cast(viewProvider); + if (FEMviewProvider) + FEMviewProvider->WriteColorData(true); + } } -void ViewProviderFemPostObject::show(void) { +void ViewProviderFemPostObject::show() { Gui::ViewProviderDocumentObject::show(); m_colorStyle->style = SoDrawStyle::FILLED; + // we must update the color bar except for data point filters + // (for ViewProviderFemPostDataAtPoint show() is overridden to prevent the update) + WriteColorData(true); } - void ViewProviderFemPostObject::OnChange(Base::Subject< int >& /*rCaller*/, int /*rcReason*/) { bool ResetColorBarRange = false; WriteColorData(ResetColorBarRange); @@ -706,5 +809,17 @@ bool ViewProviderFemPostObject::canDelete(App::DocumentObject* obj) const // thus we can pass this action // we can warn the user if necessary in the object's ViewProvider in the onDelete() function Q_UNUSED(obj) - return true; + return true; +} + +void ViewProviderFemPostObject::onSelectionChanged(const Gui::SelectionChanges &sel) +{ + // If a FemPostObject is selected in the document tree we must refresh its + // color bar. + // But don't do this if the object is invisible because other objects with a + // color bar might be visible and the color bar is then wrong. + if (sel.Type == Gui::SelectionChanges::AddSelection) { + if (this->getObject()->Visibility.getValue()) + updateMaterial(); + } } diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostObject.h b/src/Mod/Fem/Gui/ViewProviderFemPostObject.h index e4e12cd61a..b25b2ab361 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostObject.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostObject.h @@ -54,6 +54,7 @@ class SoIndexedLineSet; class SoIndexedTriangleStripSet; namespace Gui { + class SelectionChanges; class SoFCColorBar; } @@ -65,41 +66,44 @@ class TaskDlgPost; class FemGuiExport ViewProviderFemPostObject : public Gui::ViewProviderDocumentObject, public Base::Observer { - PROPERTY_HEADER(FemGui::ViewProviderFemPostObject); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostObject); public: /// constructor. ViewProviderFemPostObject(); /// destructor. - ~ViewProviderFemPostObject(); + ~ViewProviderFemPostObject() override; App::PropertyEnumeration Field; App::PropertyEnumeration VectorMode; App::PropertyPercent Transparency; - void attach(App::DocumentObject *pcObject); - void setDisplayMode(const char* ModeName); - std::vector getDisplayModes() const; - void updateData(const App::Property*); - void onChanged(const App::Property* prop); + void attach(App::DocumentObject *pcObject) override; + void setDisplayMode(const char* ModeName) override; + std::vector getDisplayModes() const override; + void updateData(const App::Property*) override; + void onChanged(const App::Property* prop) override; //edit handling - virtual bool doubleClicked(void); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool doubleClicked() override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; - virtual void hide(void); - virtual void show(void); + void hide() override; + void show() override; - virtual SoSeparator* getFrontRoot(void) const; + SoSeparator* getFrontRoot() const override; - //observer for the color bar - virtual void OnChange(Base::Subject< int >& rCaller, int rcReason); + // observer for the color bar + void OnChange(Base::Subject< int >& rCaller, int rcReason) override; + // update color bar + void updateMaterial(); // handling when object is deleted - virtual bool onDelete(const std::vector&); - virtual bool canDelete(App::DocumentObject* obj) const; + bool onDelete(const std::vector&) override; + 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. diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp index ee2a3b5b32..05750af12f 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.cpp @@ -21,15 +21,26 @@ ***************************************************************************/ #include "PreCompiled.h" -#include "ViewProviderFemPostPipeline.h" -#include "ViewProviderFemPostFunction.h" -#include -#include + +#ifndef _PreComp_ +#include +#endif + +#include +#include #include +#include +#include +#include + +#include "ViewProviderFemPostPipeline.h" +#include "ViewProviderFemPostPipelinePy.h" +#include "ViewProviderAnalysis.h" +#include "ViewProviderFemPostFunction.h" + using namespace FemGui; - PROPERTY_SOURCE(FemGui::ViewProviderFemPostPipeline, FemGui::ViewProviderFemPostObject) ViewProviderFemPostPipeline::ViewProviderFemPostPipeline() @@ -41,7 +52,7 @@ ViewProviderFemPostPipeline::~ViewProviderFemPostPipeline() { } -std::vector< App::DocumentObject* > ViewProviderFemPostPipeline::claimChildren(void) const { +std::vector< App::DocumentObject* > ViewProviderFemPostPipeline::claimChildren() const { Fem::FemPostPipeline* pipeline = static_cast(getObject()); std::vector children; @@ -49,11 +60,12 @@ std::vector< App::DocumentObject* > ViewProviderFemPostPipeline::claimChildren(v if (pipeline->Functions.getValue()) children.push_back(pipeline->Functions.getValue()); - children.insert(children.end(), pipeline->Filter.getValues().begin(), pipeline->Filter.getValues().end()); + children.insert(children.end(), pipeline->Filter.getValues().begin(), + pipeline->Filter.getValues().end()); return children; } -std::vector< App::DocumentObject* > ViewProviderFemPostPipeline::claimChildren3D(void) const { +std::vector< App::DocumentObject* > ViewProviderFemPostPipeline::claimChildren3D() const { return claimChildren(); } @@ -61,10 +73,8 @@ std::vector< App::DocumentObject* > ViewProviderFemPostPipeline::claimChildren3D void ViewProviderFemPostPipeline::updateData(const App::Property* prop) { FemGui::ViewProviderFemPostObject::updateData(prop); - if (strcmp(prop->getName(), "Function") == 0) { + if (strcmp(prop->getName(), "Function") == 0) updateFunctionSize(); - } - } void ViewProviderFemPostPipeline::updateFunctionSize() { @@ -72,7 +82,8 @@ void ViewProviderFemPostPipeline::updateFunctionSize() { //we need to get the bounding box and set the function provider size Fem::FemPostPipeline* obj = static_cast(getObject()); - if (!obj->Functions.getValue() || !obj->Functions.getValue()->isDerivedFrom(Fem::FemPostFunctionProvider::getClassTypeId())) + if (!obj->Functions.getValue() + || !obj->Functions.getValue()->isDerivedFrom(Fem::FemPostFunctionProvider::getClassTypeId())) return; //get the function provider @@ -87,3 +98,118 @@ void ViewProviderFemPostPipeline::updateFunctionSize() { vp->SizeZ.setValue(box.GetLength(2) * 1.2); } } + +void ViewProviderFemPostPipeline::onSelectionChanged(const Gui::SelectionChanges &sel) +{ + auto getAnalyzeView = [](App::DocumentObject* obj) { + ViewProviderFemAnalysis* analyzeView = nullptr; + App::DocumentObject* grp = App::GroupExtension::getGroupOfObject(obj); + if (Fem::FemAnalysis* analyze = Base::freecad_dynamic_cast(grp)) { + analyzeView = Base::freecad_dynamic_cast + (Gui::Application::Instance->getViewProvider(analyze)); + } + return analyzeView; + }; + + // If a FemPostObject is selected in the document tree we must refresh its + // color bar. + // But don't do this if the object is invisible because other objects with a + // color bar might be visible and the color bar is then wrong. + if (sel.Type == Gui::SelectionChanges::AddSelection) { + if (this->getObject()->Visibility.getValue()) + updateMaterial(); + else + return; // purposely nothing should be done + + // Access analysis object + ViewProviderFemAnalysis* analyzeView = getAnalyzeView(this->getObject()); + if (analyzeView) { + analyzeView->highlightView(this); + } + } +} + +void ViewProviderFemPostPipeline::updateColorBars() +{ + + // take all visible childs and update its shape coloring + auto children = claimChildren(); + for (auto& child : children) { + if (child->Visibility.getValue()) { + auto vpObject = dynamic_cast( + Gui::Application::Instance->getViewProvider(child)); + if (vpObject) + vpObject->updateMaterial(); + } + } + + // if pipeline is visible, update it + if (this->isVisible()) + updateMaterial(); +} + +void ViewProviderFemPostPipeline::transformField(char *FieldName, double FieldFactor) +{ + Fem::FemPostPipeline *obj = static_cast(getObject()); + + vtkSmartPointer data = obj->Data.getValue(); + if (!data || !data->IsA("vtkDataSet")) + return; + + vtkDataSet *dset = vtkDataSet::SafeDownCast(data); + vtkDataArray *pdata = dset->GetPointData()->GetArray(FieldName); + if (!pdata) + return; + + auto strFieldName = std::string(FieldName); + + // for EigenModes, we need to step through all available modes + if (strFieldName.find("EigenMode") != std::string::npos) { + int modeCount; + std::string testFieldName; + // since a valid FieldName must have been passed + // we assume the mode number was < 10 and we can strip the last char + strFieldName.pop_back(); + for (modeCount = 1; pdata; ++modeCount) { + testFieldName = strFieldName + std::to_string(modeCount); + pdata = dset->GetPointData()->GetArray(testFieldName.c_str()); + if (pdata) { + scaleField(dset, pdata, FieldFactor); + } + } + } + else + scaleField(dset, pdata, FieldFactor); +} + +void ViewProviderFemPostPipeline::scaleField(vtkDataSet *dset, vtkDataArray *pdata, double FieldFactor) +{ + //safe guard + if (!dset || !pdata) + return; + + // step through all mesh points and scale them + for (int i = 0; i < dset->GetNumberOfPoints(); ++i) { + double value = 0; + if (pdata->GetNumberOfComponents() == 1) { + value = pdata->GetComponent(i, 0); + pdata->SetComponent(i, 0, value * FieldFactor); + } + // if field is a vector + else { + for (int j = 0; j < pdata->GetNumberOfComponents(); ++j) { + value = pdata->GetComponent(i, j); + pdata->SetComponent(i, j, value * FieldFactor); + } + } + } +} + +PyObject *ViewProviderFemPostPipeline::getPyObject(void) +{ + if (PythonObject.is(Py::_None())) { + // ref counter is set to 1 + PythonObject = Py::Object(new ViewProviderFemPostPipelinePy(this), true); + } + return Py::new_reference_to(PythonObject); +} diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h index 9d7126a569..f068306e68 100644 --- a/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipeline.h @@ -25,22 +25,32 @@ #define FEM_VIEWPROVIDERFEMPOSTPIPELINE_H #include "ViewProviderFemPostObject.h" +#include +#include namespace FemGui { class FemGuiExport ViewProviderFemPostPipeline : public ViewProviderFemPostObject { - PROPERTY_HEADER(FemGui::ViewProviderFemPostPipeline); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderFemPostPipeline); public: /// constructor. ViewProviderFemPostPipeline(); - ~ViewProviderFemPostPipeline(); + ~ViewProviderFemPostPipeline() override; - virtual std::vector< App::DocumentObject* > claimChildren(void) const; - virtual std::vector< App::DocumentObject* > claimChildren3D(void) const; - virtual void updateData(const App::Property* prop); + std::vector< App::DocumentObject* > claimChildren() const override; + std::vector< App::DocumentObject* > claimChildren3D() const override; + void updateData(const App::Property* prop) override; + void onSelectionChanged(const Gui::SelectionChanges &sel) override; + void updateColorBars(); + void transformField(char *FieldName, double FieldFactor); + void scaleField(vtkDataSet *dset, vtkDataArray *pdata, double FieldFactor); + PyObject *getPyObject() override; + +private: + Py::Object PythonObject; protected: void updateFunctionSize(); diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipelinePy.xml b/src/Mod/Fem/Gui/ViewProviderFemPostPipelinePy.xml new file mode 100644 index 0000000000..ad42ced3c4 --- /dev/null +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipelinePy.xml @@ -0,0 +1,29 @@ + + + + + + ViewProviderFemPostPipeline class + + + + Scales values of given result mesh field by given factor + + + + + Update coloring of pipeline and its childs + + + + diff --git a/src/Mod/Fem/Gui/ViewProviderFemPostPipelinePyImp.cpp b/src/Mod/Fem/Gui/ViewProviderFemPostPipelinePyImp.cpp new file mode 100644 index 0000000000..9ca2c15724 --- /dev/null +++ b/src/Mod/Fem/Gui/ViewProviderFemPostPipelinePyImp.cpp @@ -0,0 +1,74 @@ +/*************************************************************************** + * Copyright (c) 2022 Uwe Stöhr * + * * + * 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 "ViewProviderFemPostPipeline.h" + +// inclusion of the generated files (generated out of ViewProviderFemPostPipelinePy.xml) +#include "ViewProviderFemPostPipelinePy.h" +#include "ViewProviderFemPostPipelinePy.cpp" + + +using namespace FemGui; + +// returns a string which represents the object e.g. when printed in python +std::string ViewProviderFemPostPipelinePy::representation(void) const +{ + return std::string(""); +} + +PyObject *ViewProviderFemPostPipelinePy::updateColorBars(PyObject *args) +{ + if (!PyArg_ParseTuple(args, "")) + return nullptr; + + this->getViewProviderFemPostPipelinePtr()->updateColorBars(); + + Py_Return; +} + +PyObject *ViewProviderFemPostPipelinePy::transformField(PyObject *args) +{ + char *FieldName; + double FieldFactor; + + if (!PyArg_ParseTuple(args, "sd", &FieldName, &FieldFactor)) + return nullptr; + + this->getViewProviderFemPostPipelinePtr()->transformField(FieldName, FieldFactor); + + Py_Return; +} + +PyObject *ViewProviderFemPostPipelinePy::getCustomAttributes(const char * /*attr*/) const +{ + return nullptr; +} + +int ViewProviderFemPostPipelinePy::setCustomAttributes(const char * /*attr*/, PyObject * /*obj*/) +{ + return 0; +} diff --git a/src/Mod/Fem/Gui/ViewProviderResult.h b/src/Mod/Fem/Gui/ViewProviderResult.h index c6650dabd0..6d8d371d81 100644 --- a/src/Mod/Fem/Gui/ViewProviderResult.h +++ b/src/Mod/Fem/Gui/ViewProviderResult.h @@ -33,17 +33,17 @@ namespace FemGui class FemGuiExport ViewProviderResult : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(FemGui::ViewProviderResult); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderResult); public: /// constructor ViewProviderResult(); /// destructor - virtual ~ViewProviderResult(); + ~ViewProviderResult() override; // shows solid in the tree - virtual bool isShow(void) const + bool isShow() const override { return true; } }; diff --git a/src/Mod/Fem/Gui/ViewProviderSetElements.cpp b/src/Mod/Fem/Gui/ViewProviderSetElements.cpp index 0fd120d8ae..5e3be39f28 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetElements.cpp +++ b/src/Mod/Fem/Gui/ViewProviderSetElements.cpp @@ -33,7 +33,7 @@ using namespace FemGui; PROPERTY_SOURCE(FemGui::ViewProviderSetElements, Gui::ViewProviderGeometryObject) -bool ViewProviderSetElements::doubleClicked(void) +bool ViewProviderSetElements::doubleClicked() { //Gui::TaskView::TaskDialog* dlg = new TaskDlgCreateNodeSet(dynamic_cast(getObject())); //Gui::Control().showDialog(dlg); diff --git a/src/Mod/Fem/Gui/ViewProviderSetElements.h b/src/Mod/Fem/Gui/ViewProviderSetElements.h index 5b6bc89566..0264130c7f 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetElements.h +++ b/src/Mod/Fem/Gui/ViewProviderSetElements.h @@ -31,14 +31,14 @@ namespace FemGui class ViewProviderSetElements : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(RobotGui::ViewProviderSetElements); + PROPERTY_HEADER_WITH_OVERRIDE(RobotGui::ViewProviderSetElements); public: - virtual bool doubleClicked(void); + bool doubleClicked() override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderSetFaces.cpp b/src/Mod/Fem/Gui/ViewProviderSetFaces.cpp index 18d0dd3c4f..e3951b47fa 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetFaces.cpp +++ b/src/Mod/Fem/Gui/ViewProviderSetFaces.cpp @@ -33,7 +33,7 @@ using namespace FemGui; PROPERTY_SOURCE(FemGui::ViewProviderSetFaces, Gui::ViewProviderGeometryObject) -bool ViewProviderSetFaces::doubleClicked(void) +bool ViewProviderSetFaces::doubleClicked() { //Gui::TaskView::TaskDialog* dlg = new TaskDlgCreateNodeSet(dynamic_cast(getObject())); //Gui::Control().showDialog(dlg); diff --git a/src/Mod/Fem/Gui/ViewProviderSetFaces.h b/src/Mod/Fem/Gui/ViewProviderSetFaces.h index 7d31b8490a..bb3accf2b3 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetFaces.h +++ b/src/Mod/Fem/Gui/ViewProviderSetFaces.h @@ -31,14 +31,14 @@ namespace FemGui class ViewProviderSetFaces : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(RobotGui::ViewProviderSetFaces); + PROPERTY_HEADER_WITH_OVERRIDE(RobotGui::ViewProviderSetFaces); public: - virtual bool doubleClicked(void); + bool doubleClicked() override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderSetGeometry.cpp b/src/Mod/Fem/Gui/ViewProviderSetGeometry.cpp index 3a98972a2f..899a99dab7 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetGeometry.cpp +++ b/src/Mod/Fem/Gui/ViewProviderSetGeometry.cpp @@ -33,7 +33,7 @@ using namespace FemGui; PROPERTY_SOURCE(FemGui::ViewProviderSetGeometry, Gui::ViewProviderGeometryObject) -bool ViewProviderSetGeometry::doubleClicked(void) +bool ViewProviderSetGeometry::doubleClicked() { //Gui::TaskView::TaskDialog* dlg = new TaskDlgCreateNodeSet(dynamic_cast(getObject())); //Gui::Control().showDialog(dlg); diff --git a/src/Mod/Fem/Gui/ViewProviderSetGeometry.h b/src/Mod/Fem/Gui/ViewProviderSetGeometry.h index d046d0dd33..388c268a51 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetGeometry.h +++ b/src/Mod/Fem/Gui/ViewProviderSetGeometry.h @@ -31,14 +31,14 @@ namespace FemGui class ViewProviderSetGeometry : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(RobotGui::ViewProviderSetGeometry); + PROPERTY_HEADER_WITH_OVERRIDE(RobotGui::ViewProviderSetGeometry); public: - virtual bool doubleClicked(void); + bool doubleClicked() override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderSetNodes.cpp b/src/Mod/Fem/Gui/ViewProviderSetNodes.cpp index b4e47ddc78..08e6b237f9 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetNodes.cpp +++ b/src/Mod/Fem/Gui/ViewProviderSetNodes.cpp @@ -35,7 +35,7 @@ using namespace FemGui; PROPERTY_SOURCE(FemGui::ViewProviderSetNodes, Gui::ViewProviderGeometryObject) -bool ViewProviderSetNodes::doubleClicked(void) +bool ViewProviderSetNodes::doubleClicked() { Gui::TaskView::TaskDialog* dlg = new TaskDlgCreateNodeSet(static_cast(getObject())); Gui::Control().showDialog(dlg); diff --git a/src/Mod/Fem/Gui/ViewProviderSetNodes.h b/src/Mod/Fem/Gui/ViewProviderSetNodes.h index 14567b92fe..697e55d32b 100644 --- a/src/Mod/Fem/Gui/ViewProviderSetNodes.h +++ b/src/Mod/Fem/Gui/ViewProviderSetNodes.h @@ -31,14 +31,14 @@ namespace FemGui class ViewProviderSetNodes : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(FemGui::ViewProviderSetNodes); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderSetNodes); public: - virtual bool doubleClicked(void); + bool doubleClicked() override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } //namespace FemGui diff --git a/src/Mod/Fem/Gui/ViewProviderSolver.cpp b/src/Mod/Fem/Gui/ViewProviderSolver.cpp index 2bd586897e..3eabd41722 100644 --- a/src/Mod/Fem/Gui/ViewProviderSolver.cpp +++ b/src/Mod/Fem/Gui/ViewProviderSolver.cpp @@ -48,7 +48,7 @@ ViewProviderSolver::~ViewProviderSolver() } -std::vector ViewProviderSolver::getDisplayModes(void) const +std::vector ViewProviderSolver::getDisplayModes() const { return { "Solver" }; } diff --git a/src/Mod/Fem/Gui/ViewProviderSolver.h b/src/Mod/Fem/Gui/ViewProviderSolver.h index df61c896dc..f75361670f 100644 --- a/src/Mod/Fem/Gui/ViewProviderSolver.h +++ b/src/Mod/Fem/Gui/ViewProviderSolver.h @@ -43,25 +43,25 @@ namespace FemGui class FemGuiExport ViewProviderSolver : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(FemGui::ViewProviderSolver); + PROPERTY_HEADER_WITH_OVERRIDE(FemGui::ViewProviderSolver); public: /// constructor ViewProviderSolver(); /// destructor - ~ViewProviderSolver(); + ~ViewProviderSolver() override; // shows solid in the tree - virtual bool isShow(void) const { + bool isShow() const override { return Visibility.getValue(); } /// A list of all possible display modes - virtual std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; // handling when object is deleted - virtual bool onDelete(const std::vector&); - virtual bool canDelete(App::DocumentObject* obj) const; + bool onDelete(const std::vector&) override; + bool canDelete(App::DocumentObject* obj) const override; }; typedef Gui::ViewProviderPythonFeatureT ViewProviderSolverPython; diff --git a/src/Mod/Fem/Gui/Workbench.cpp b/src/Mod/Fem/Gui/Workbench.cpp index 4d0428f34a..22acd1a946 100755 --- a/src/Mod/Fem/Gui/Workbench.cpp +++ b/src/Mod/Fem/Gui/Workbench.cpp @@ -123,6 +123,7 @@ Gui::ToolBarItem* Workbench::setupToolBars() const fluid->setCommand("Fluid Constraints"); *fluid << "FEM_ConstraintInitialFlowVelocity" + << "FEM_ConstraintInitialPressure" << "Separator" << "FEM_ConstraintFlowVelocity"; @@ -251,6 +252,7 @@ Gui::MenuItem* Workbench::setupMenuBar() const fluid->setCommand("&Fluid Constraints"); *fluid << "FEM_ConstraintInitialFlowVelocity" + << "FEM_ConstraintInitialPressure" << "Separator" << "FEM_ConstraintFlowVelocity"; diff --git a/src/Mod/Fem/Gui/Workbench.h b/src/Mod/Fem/Gui/Workbench.h index e26748f50f..59088e8886 100755 --- a/src/Mod/Fem/Gui/Workbench.h +++ b/src/Mod/Fem/Gui/Workbench.h @@ -34,16 +34,16 @@ namespace FemGui { */ class FemGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); - void setupContextMenu(const char* recipient, Gui::MenuItem*) const; + ~Workbench() override; + void setupContextMenu(const char* recipient, Gui::MenuItem*) const override; protected: - Gui::ToolBarItem* setupToolBars() const; - Gui::MenuItem* setupMenuBar() const; + Gui::ToolBarItem* setupToolBars() const override; + Gui::MenuItem* setupMenuBar() const override; }; } // namespace FemGui diff --git a/src/Mod/Fem/Init.py b/src/Mod/Fem/Init.py index 7c755e823f..7923e61e2b 100644 --- a/src/Mod/Fem/Init.py +++ b/src/Mod/Fem/Init.py @@ -48,9 +48,8 @@ import FreeCAD from femtools.migrate_app import FemMigrateApp -if sys.version_info.major >= 3: - # migrate old FEM App objects - sys.meta_path.append(FemMigrateApp()) +# migrate old FEM App objects +sys.meta_path.append(FemMigrateApp()) # add FEM App unit tests @@ -63,8 +62,12 @@ FreeCAD.addExportType("FEM mesh Python (*.meshpy)", "feminout.importPyMesh") FreeCAD.addExportType("FEM mesh TetGen (*.poly)", "feminout.convert2TetGen") # see FemMesh::read() and FemMesh::write() methods in src/Mod/Fem/App/FemMesh.cpp -FreeCAD.addImportType("FEM mesh formats (*.bdf *.dat *.inp *.med *.unv *.vtk *.vtu *.pvtu *.z88)", "Fem") -FreeCAD.addExportType("FEM mesh formats (*.dat *.inp *.med *.stl *.unv *.vtk *.vtu *.z88)", "Fem") +FreeCAD.addImportType( + "FEM mesh formats (*.bdf *.dat *.inp *.med *.unv *.vtk *.vtu *.pvtu *.z88)", "Fem" +) +FreeCAD.addExportType( + "FEM mesh formats (*.dat *.inp *.med *.stl *.unv *.vtk *.vtu *.z88)", "Fem" +) FreeCAD.addExportType("FEM mesh Nastran (*.bdf)", "feminout.exportNastranMesh") diff --git a/src/Mod/Fem/InitGui.py b/src/Mod/Fem/InitGui.py index e17b36cd61..6b9d575ea0 100644 --- a/src/Mod/Fem/InitGui.py +++ b/src/Mod/Fem/InitGui.py @@ -50,9 +50,8 @@ from FreeCADGui import Workbench from femguiutils.migrate_gui import FemMigrateGui -if sys.version_info.major >= 3: - # migrate old FEM Gui objects - sys.meta_path.append(FemMigrateGui()) +# migrate old FEM Gui objects +sys.meta_path.append(FemMigrateGui()) # add FEM Gui unit tests diff --git a/src/Mod/Fem/ObjectsFem.py b/src/Mod/Fem/ObjectsFem.py index 5d9a8b51cd..fb9976e9e9 100644 --- a/src/Mod/Fem/ObjectsFem.py +++ b/src/Mod/Fem/ObjectsFem.py @@ -228,6 +228,21 @@ def makeConstraintInitialFlowVelocity( return obj +def makeConstraintInitialPressure( + doc, + name="ConstraintInitialPressure" +): + """makeConstraintInitialPressure(document, [name]): + makes a Fem ConstraintInitialPressure object""" + obj = doc.addObject("Fem::ConstraintPython", name) + from femobjects import constraint_initialpressure + constraint_initialpressure.ConstraintInitialPressure(obj) + if FreeCAD.GuiUp: + from femviewprovider import view_constraint_initialpressure + view_constraint_initialpressure.VPConstraintInitialPressure(obj.ViewObject) + return obj + + def makeConstraintInitialTemperature( doc, name="ConstraintInitialTemperature" diff --git a/src/Mod/Fem/femcommands/commands.py b/src/Mod/Fem/femcommands/commands.py index b9d0665e46..466f7d3963 100644 --- a/src/Mod/Fem/femcommands/commands.py +++ b/src/Mod/Fem/femcommands/commands.py @@ -177,7 +177,7 @@ class _ConstraintBodyHeatSource(CommandManager): def __init__(self): super(_ConstraintBodyHeatSource, self).__init__() - self.pixmap = "FEM_ConstraintHeatflux" # the heatflux icon is used + self.pixmap = "FEM_ConstraintBodyHeatSource" self.menutext = Qt.QT_TRANSLATE_NOOP( "FEM_ConstraintBodyHeatSource", "Constraint body heat source" @@ -187,7 +187,7 @@ class _ConstraintBodyHeatSource(CommandManager): "Creates a FEM constraint body heat source" ) self.is_active = "with_analysis" - self.do_activated = "add_obj_on_gui_noset_edit" + self.do_activated = "add_obj_on_gui_set_edit" class _ConstraintCentrif(CommandManager): @@ -258,6 +258,23 @@ class _ConstraintInitialFlowVelocity(CommandManager): self.do_activated = "add_obj_on_gui_set_edit" +class _ConstraintInitialPressure(CommandManager): + "The FEM_ConstraintInitialPressure command definition" + + def __init__(self): + super(_ConstraintInitialPressure, self).__init__() + self.menutext = Qt.QT_TRANSLATE_NOOP( + "FEM_ConstraintInitialPressure", + "Constraint initial pressure" + ) + self.tooltip = Qt.QT_TRANSLATE_NOOP( + "FEM_ConstraintInitialPressure", + "Creates a FEM constraint initial pressure" + ) + self.is_active = "with_analysis" + self.do_activated = "add_obj_on_gui_set_edit" + + class _ConstraintSectionPrint(CommandManager): "The FEM_ConstraintSectionPrint command definition" @@ -1104,6 +1121,10 @@ FreeCADGui.addCommand( "FEM_ConstraintInitialFlowVelocity", _ConstraintInitialFlowVelocity() ) +FreeCADGui.addCommand( + "FEM_ConstraintInitialPressure", + _ConstraintInitialPressure() +) FreeCADGui.addCommand( "FEM_ConstraintSectionPrint", _ConstraintSectionPrint() diff --git a/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py b/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py index fedc5e69a1..884998f4f1 100644 --- a/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py +++ b/src/Mod/Fem/femexamples/elmer_nonguitutorial01_eigenvalue_of_elastic_beam.py @@ -89,11 +89,9 @@ def setup(doc=None, solvertype="elmer"): elif solvertype == "elmer": solver_obj = ObjectsFem.makeSolverElmer(doc, "SolverElmer") eq_obj = ObjectsFem.makeEquationElasticity(doc, solver_obj) - eq_obj.LinearSolverType = "Direct" - # direct solver was used in the tutorial, thus used here too - # the iterative is much faster and gives the same results - eq_obj.DoFrequencyAnalysis = True + eq_obj.EigenAnalysis = True eq_obj.CalculateStresses = True + eq_obj.DisplaceMesh = False else: FreeCAD.Console.PrintWarning( "Not known or not supported solver type: {}. " diff --git a/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py b/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py index c2bd1deea7..fc43017ee2 100644 --- a/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py +++ b/src/Mod/Fem/femexamples/equation_electrostatics_capacitance_two_balls.py @@ -151,11 +151,6 @@ def setup(doc=None, solvertype="elmer"): con_elect_pot3.CapacitanceBodyEnabled = True analysis.addObject(con_elect_pot3) - # constant vacuum permittivity - const_vacperm = ObjectsFem.makeConstantVacuumPermittivity(doc, "ConstantVacuumPermittivity") - const_vacperm.VacuumPermittivity = "1 F/m" - analysis.addObject(const_vacperm) - # mesh from .meshes.mesh_capacitance_two_balls_tetra10 import create_nodes, create_elements fem_mesh = Fem.FemMesh() diff --git a/src/Mod/Fem/femexamples/thermomech_bimetall.py b/src/Mod/Fem/femexamples/thermomech_bimetall.py index ef4c4b2a88..8196390fb5 100644 --- a/src/Mod/Fem/femexamples/thermomech_bimetall.py +++ b/src/Mod/Fem/femexamples/thermomech_bimetall.py @@ -130,12 +130,9 @@ def setup(doc=None, solvertype="ccxtools"): solver_obj.SteadyStateMinIterations = 1 solver_obj.SteadyStateMaxIterations = 10 eq_heat = ObjectsFem.makeEquationHeat(doc, solver_obj) - eq_heat.Bubbles = True eq_heat.Priority = 2 eq_elasticity = ObjectsFem.makeEquationElasticity(doc, solver_obj) - eq_elasticity.Bubbles = True eq_elasticity.Priority = 1 - eq_elasticity.LinearSolverType = "Direct" else: FreeCAD.Console.PrintWarning( "Not known or not supported solver type: {}. " @@ -156,12 +153,12 @@ def setup(doc=None, solvertype="ccxtools"): material_obj_bottom = ObjectsFem.makeMaterialSolid(doc, "MaterialCopper") mat = material_obj_bottom.Material mat["Name"] = "Copper" - mat["YoungsModulus"] = "130000 MPa" - mat["PoissonRatio"] = "0.354" + mat["YoungsModulus"] = "119 GPa" + mat["PoissonRatio"] = "0.343" mat["SpecificHeat"] = "385 J/kg/K" - mat["ThermalConductivity"] = "200 W/m/K" - mat["ThermalExpansionCoefficient"] = "0.00002 m/m/K" - mat["Density"] = "1.00 kg/m^3" + mat["ThermalConductivity"] = "398 W/m/K" + mat["ThermalExpansionCoefficient"] = "0.0000165 m/m/K" + mat["Density"] = "8960.0 kg/m^3" material_obj_bottom.Material = mat material_obj_bottom.References = [(geom_obj, "Solid1")] analysis.addObject(material_obj_bottom) @@ -169,11 +166,12 @@ def setup(doc=None, solvertype="ccxtools"): material_obj_top = ObjectsFem.makeMaterialSolid(doc, "MaterialInvar") mat = material_obj_top.Material mat["Name"] = "Invar" - mat["YoungsModulus"] = "137000 MPa" - mat["PoissonRatio"] = "0.28" - mat["SpecificHeat"] = "510 J/kg/K" - mat["ThermalConductivity"] = "13 W/m/K" - mat["ThermalExpansionCoefficient"] = "0.0000012 m/m/K" + mat["Density"] = "8150 kg/m^3" + mat["YoungsModulus"] = "140 GPa" + mat["PoissonRatio"] = "0.29" + mat["SpecificHeat"] = "515 J/kg/K" + mat["ThermalConductivity"] = "13.5 W/m/K" + mat["ThermalExpansionCoefficient"] = "0.00000125 m/m/K" material_obj_top.Material = mat material_obj_top.References = [(geom_obj, "Solid2")] analysis.addObject(material_obj_top) @@ -192,23 +190,24 @@ def setup(doc=None, solvertype="ccxtools"): analysis.addObject(con_inittemp) # constraint temperature - con_temp = ObjectsFem.makeConstraintTemperature(doc, "ConstraintTemperature") + con_temp = ObjectsFem.makeConstraintTemperature(doc, "ConstraintTemperatureHot") con_temp.References = [ - (geom_obj, "Face1"), - (geom_obj, "Face2"), - (geom_obj, "Face3"), - (geom_obj, "Face4"), (geom_obj, "Face5"), - (geom_obj, "Face7"), - (geom_obj, "Face8"), - (geom_obj, "Face9"), - (geom_obj, "Face10"), - (geom_obj, "Face11"), + (geom_obj, "Face11") ] con_temp.Temperature = 373.0 con_temp.CFlux = 0.0 analysis.addObject(con_temp) + con_temp = ObjectsFem.makeConstraintTemperature(doc, "ConstraintTemperatureNormal") + con_temp.References = [ + (geom_obj, "Face1"), + (geom_obj, "Face7") + ] + con_temp.Temperature = 273.0 + con_temp.CFlux = 0.0 + analysis.addObject(con_temp) + # mesh from .meshes.mesh_thermomech_bimetall_tetra10 import create_nodes, create_elements fem_mesh = Fem.FemMesh() diff --git a/src/Mod/Fem/femguiutils/selection_widgets.py b/src/Mod/Fem/femguiutils/selection_widgets.py index 2194e94c99..12986efacc 100644 --- a/src/Mod/Fem/femguiutils/selection_widgets.py +++ b/src/Mod/Fem/femguiutils/selection_widgets.py @@ -30,8 +30,6 @@ __url__ = "https://www.freecadweb.org" # \ingroup FEM # \brief FreeCAD FEM FemSelectWidget -import sys - from PySide import QtGui from PySide import QtCore @@ -210,10 +208,7 @@ class SolidSelector(_Selector): foundSolids.add("Solid" + str(solidId + 1)) if len(foundSolids) == 1: it = iter(foundSolids) - if sys.version_info.major >= 3: - return next(it) - else: - return it.next() + return next(it) return None def _findSub(self, sub, subList): @@ -484,12 +479,12 @@ class GeometryElementsSelection(QtGui.QWidget): self.sel_server = FemSelectionObserver(self.selectionParser, print_message) def selectionParser(self, selection): - FreeCAD.Console.PrintMessage("Selection: {} {} {}\n".format( - selection[0].Shape.ShapeType, - selection[0].Name, - selection[1] - )) if hasattr(selection[0], "Shape") and selection[1]: + FreeCAD.Console.PrintMessage("Selection: {} {} {}\n".format( + selection[0].Shape.ShapeType, + selection[0].Name, + selection[1] + )) sobj = selection[0] elt = sobj.Shape.getElement(selection[1]) ele_ShapeType = elt.ShapeType diff --git a/src/Mod/Fem/feminout/importVTKResults.py b/src/Mod/Fem/feminout/importVTKResults.py index 82f7d8eda0..f15afbe3be 100644 --- a/src/Mod/Fem/feminout/importVTKResults.py +++ b/src/Mod/Fem/feminout/importVTKResults.py @@ -134,6 +134,9 @@ def importVtkVtkResult( ): vtk_result_obj = FreeCAD.ActiveDocument.addObject("Fem::FemPostPipeline", resultname) vtk_result_obj.read(filename) + # set display mode to "Surface" like for any other new pipeline to assure the user sees + # something after the import was done + vtk_result_obj.ViewObject.DisplayMode = "Surface" vtk_result_obj.touch() FreeCAD.ActiveDocument.recompute() return vtk_result_obj diff --git a/src/Mod/Fem/femmesh/gmshtools.py b/src/Mod/Fem/femmesh/gmshtools.py index fba0ba36db..197953d48f 100644 --- a/src/Mod/Fem/femmesh/gmshtools.py +++ b/src/Mod/Fem/femmesh/gmshtools.py @@ -29,7 +29,6 @@ __url__ = "https://www.freecadweb.org" import os import subprocess -import sys import FreeCAD from FreeCAD import Console @@ -319,8 +318,7 @@ class GmshTools(): p1 = subprocess.Popen(["which", "gmsh"], stdout=subprocess.PIPE) if p1.wait() == 0: output = p1.stdout.read() - if sys.version_info.major >= 3: - output = output.decode("utf-8") + output = output.decode("utf-8") gmsh_path = output.split("\n")[0] elif p1.wait() == 1: error_message = ( @@ -921,9 +919,7 @@ class GmshTools(): stderr=subprocess.PIPE ) output, error = p.communicate() - if sys.version_info.major >= 3: - # output = output.decode("utf-8") - error = error.decode("utf-8") + error = error.decode("utf-8") # stdout is still cut at some point # but the warnings are in stderr and thus printed :-) # print(output) diff --git a/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py b/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py index 1f69241377..e770d27717 100644 --- a/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py +++ b/src/Mod/Fem/femobjects/constant_vacuumpermittivity.py @@ -45,6 +45,8 @@ class ConstantVacuumPermittivity(base_fempythonobject.BaseFemPythonObject): "App::PropertyVacuumPermittivity", "VacuumPermittivity", "Constants", - "Set the permittivity of vacuum" + "Overwrites default permittivity of vacuum" ) - obj.VacuumPermittivity = Units.Quantity(constants.vacuum_permittivity()) + # we must set an expression so that the small value can actually be entered + permittivity = Units.Quantity(constants.vacuum_permittivity()).getValueAs("F/m") + obj.setExpression("VacuumPermittivity", str(permittivity)) diff --git a/src/Mod/Fem/femobjects/constraint_bodyheatsource.py b/src/Mod/Fem/femobjects/constraint_bodyheatsource.py index f14bf9c666..4ca679bd6a 100644 --- a/src/Mod/Fem/femobjects/constraint_bodyheatsource.py +++ b/src/Mod/Fem/femobjects/constraint_bodyheatsource.py @@ -39,10 +39,17 @@ class ConstraintBodyHeatSource(base_fempythonobject.BaseFemPythonObject): def __init__(self, obj): super(ConstraintBodyHeatSource, self).__init__(obj) + self.add_properties(obj) - obj.addProperty( - "App::PropertyFloat", - "HeatSource", - "Base", - "Body heat source" - ) + def onDocumentRestored(self, obj): + self.add_properties(obj) + + def add_properties(self, obj): + if not hasattr(obj, "HeatSource"): + obj.addProperty( + "App::PropertyFloat", + "HeatSource", + "Base", + "Body heat source" + ) + obj.HeatSource = 0.0 diff --git a/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py b/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py index 640188ad7f..33635621a7 100644 --- a/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py +++ b/src/Mod/Fem/femobjects/constraint_electrostaticpotential.py @@ -51,8 +51,10 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "Potential", "Parameter", "Electric Potential" - ), - obj.Potential = 0.0 + ) + # setting 1 V assures that the unit does not switch to mV + # and the constraint holds usually Volts + obj.Potential = "1 V" if not hasattr(obj, "PotentialEnabled"): obj.addProperty( @@ -60,8 +62,8 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "PotentialEnabled", "Parameter", "Potential Enabled" - ), - obj.PotentialEnabled = False + ) + obj.PotentialEnabled = True if not hasattr(obj, "PotentialConstant"): obj.addProperty( @@ -69,7 +71,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "PotentialConstant", "Parameter", "Potential Constant" - ), + ) obj.PotentialConstant = False if not hasattr(obj, "ElectricInfinity"): @@ -78,7 +80,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "ElectricInfinity", "Parameter", "Electric Infinity" - ), + ) obj.ElectricInfinity = False if not hasattr(obj, "ElectricForcecalculation"): @@ -87,7 +89,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "ElectricForcecalculation", "Parameter", "Electric Force Calculation" - ), + ) obj.ElectricForcecalculation = False if not hasattr(obj, "CapacitanceBody"): @@ -96,7 +98,7 @@ class ConstraintElectrostaticPotential(base_fempythonobject.BaseFemPythonObject) "CapacitanceBody", "Parameter", "Capacitance Body" - ), + ) obj.CapacitanceBody = 0 if not hasattr(obj, "CapacitanceBodyEnabled"): diff --git a/src/Mod/Fem/femobjects/constraint_flowvelocity.py b/src/Mod/Fem/femobjects/constraint_flowvelocity.py index df6e98e9bd..5625439fa7 100644 --- a/src/Mod/Fem/femobjects/constraint_flowvelocity.py +++ b/src/Mod/Fem/femobjects/constraint_flowvelocity.py @@ -43,41 +43,41 @@ class ConstraintFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyFloat", "VelocityX", "Parameter", - "Body heat flux" + "Velocity in x-direction" ) obj.addProperty( "App::PropertyBool", "VelocityXEnabled", "Parameter", - "Body heat flux" + "Use velocity in x-direction" ) obj.addProperty( "App::PropertyFloat", "VelocityY", "Parameter", - "Body heat flux" + "Velocity in y-direction" ) obj.addProperty( "App::PropertyBool", "VelocityYEnabled", "Parameter", - "Body heat flux" + "Use velocity in y-direction" ) obj.addProperty( "App::PropertyFloat", "VelocityZ", "Parameter", - "Body heat flux" + "Velocity in z-direction" ) obj.addProperty( "App::PropertyBool", "VelocityZEnabled", "Parameter", - "Body heat flux" + "Use velocity in z-direction" ) obj.addProperty( "App::PropertyBool", "NormalToBoundary", "Parameter", - "Body heat flux" + "Flow is in normal direction" ) diff --git a/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py b/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py index b7894c20ba..0598767641 100644 --- a/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py +++ b/src/Mod/Fem/femobjects/constraint_initialflowvelocity.py @@ -43,35 +43,35 @@ class ConstraintInitialFlowVelocity(base_fempythonobject.BaseFemPythonObject): "App::PropertyFloat", "VelocityX", "Parameter", - "Body heat flux" + "Velocity in x-direction" ) obj.addProperty( "App::PropertyBool", "VelocityXEnabled", "Parameter", - "Body heat flux" + "Use velocity in x-direction" ) obj.addProperty( "App::PropertyFloat", "VelocityY", "Parameter", - "Body heat flux" + "Velocity in y-direction" ) obj.addProperty( "App::PropertyBool", "VelocityYEnabled", "Parameter", - "Body heat flux" + "Use velocity in y-direction" ) obj.addProperty( "App::PropertyFloat", "VelocityZ", "Parameter", - "Body heat flux" + "Velocity in z-direction" ) obj.addProperty( "App::PropertyBool", "VelocityZEnabled", "Parameter", - "Body heat flux" + "Use velocity in z-direction" ) diff --git a/src/Mod/Fem/femobjects/constraint_initialpressure.py b/src/Mod/Fem/femobjects/constraint_initialpressure.py new file mode 100644 index 0000000000..bf31e2319f --- /dev/null +++ b/src/Mod/Fem/femobjects/constraint_initialpressure.py @@ -0,0 +1,56 @@ +# *************************************************************************** +# * Copyright (c) 2022 Uwe Stöhr * +# * * +# * 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 constraint initial pressure document object" +__author__ = "Uwe Stöhr" +__url__ = "https://www.freecadweb.org" + +## @package constraint_initialpressure +# \ingroup FEM +# \brief constraint initial pressure object + +from . import base_fempythonobject + + +class ConstraintInitialPressure(base_fempythonobject.BaseFemPythonObject): + + Type = "Fem::ConstraintInitialPressure" + + def __init__(self, obj): + super(ConstraintInitialPressure, self).__init__(obj) + self.add_properties(obj) + + def onDocumentRestored(self, obj): + self.add_properties(obj) + + def add_properties(self, obj): + if not hasattr(obj, "Pressure"): + obj.addProperty( + "App::PropertyPressure", + "Pressure", + "Parameter", + "Initial Pressure" + ) + # App::PropertyPressure is in kPa and we initialize 1 bar + obj.Pressure = 100 + diff --git a/src/Mod/Fem/femsolver/calculix/tasks.py b/src/Mod/Fem/femsolver/calculix/tasks.py index 6cce64a458..a03f07bd4f 100644 --- a/src/Mod/Fem/femsolver/calculix/tasks.py +++ b/src/Mod/Fem/femsolver/calculix/tasks.py @@ -115,7 +115,9 @@ class Solve(run.Solve): self.pushStatus("Get solver binary...\n") binary = settings.get_binary("Calculix") if binary is None: - self.fail() # a print has been made in settings module + self.pushStatus("Error: The Calculix binary has not been found!") + self.fail() + return # run solver self._process = subprocess.Popen( diff --git a/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py b/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py index 44dcdd4213..a8e534ddee 100644 --- a/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py +++ b/src/Mod/Fem/femsolver/calculix/write_constraint_temperature.py @@ -30,8 +30,9 @@ def get_analysis_types(): return ["thermomech"] +# name must substitute underscores for whitespace (#7360) def get_sets_name(): - return "constraints temperature node sets" + return "constraints_temperature_node_sets" def get_constraint_title(): diff --git a/src/Mod/Fem/femsolver/elmer/equations/elasticity.py b/src/Mod/Fem/femsolver/elmer/equations/elasticity.py index 31052da556..cf46f6cfb5 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/elasticity.py +++ b/src/Mod/Fem/femsolver/elmer/equations/elasticity.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,7 +23,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object Elasticity" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -32,6 +33,15 @@ from femtools import femutils from ... import equationbase from . import linear +EIGEN_SYSTEM_SELECT = [ + "Smallest Magnitude", + "Largest Magnitude", + "Smallest Real Part", + "Largest Real Part", + "Smallest Imag Part", + "Largest Imag Part" +] + def create(doc, name="Elasticity"): return femutils.createObject( @@ -44,44 +54,199 @@ class Proxy(linear.Proxy, equationbase.ElasticityProxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + obj.addProperty( "App::PropertyBool", - "DoFrequencyAnalysis", + "CalculatePangle", "Elasticity", - "" - ) - obj.addProperty( - "App::PropertyInteger", - "EigenmodesCount", - "Elasticity", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateStrains", - "Elasticity", - "" - ) - obj.addProperty( - "App::PropertyBool", - "CalculateStresses", - "Elasticity", - "" + "Compute principal stress angles" ) obj.addProperty( "App::PropertyBool", "CalculatePrincipal", "Elasticity", - "" + "Compute principal stress components" ) obj.addProperty( "App::PropertyBool", - "CalculatePangle", + "CalculateStrains", "Elasticity", - "" + "Compute the strain tensor" ) - obj.EigenmodesCount = 5 + obj.addProperty( + "App::PropertyBool", + "CalculateStresses", + "Elasticity", + "Compute stress tensor and vanMises" + ) + obj.addProperty( + "App::PropertyBool", + "ConstantBulkSystem", + "Elasticity", + "See Elmer manual for info" + ) + obj.addProperty( + "App::PropertyBool", + "DisplaceMesh", + "Elasticity", + ( + "If mesh is deformed by displacement field.\n" + "Set to False for 'Eigen Analysis'." + ) + ) + obj.addProperty( + "App::PropertyBool", + "EigenAnalysis", + "Eigen Values", + "If true, modal analysis" + ) + obj.addProperty( + "App::PropertyBool", + "EigenSystemComplex", + "Eigen Values", + ( + "Should be true if eigen system is complex\n" + "Must be false for a damped eigen value analysis." + ) + ) + obj.addProperty( + "App::PropertyBool", + "EigenSystemComputeResiduals", + "Eigen Values", + "Computes residuals of eigen value system" + ) + obj.addProperty( + "App::PropertyBool", + "EigenSystemDamped", + "Eigen Values", + ( + "Set a damped eigen analysis. Can only be\n" + "used if 'Linear Solver Type' is 'Iterative'." + ) + ) + obj.addProperty( + "App::PropertyIntegerConstraint", + "EigenSystemMaxIterations", + "Eigen Values", + "Max iterations for iterative eigensystem solver" + ) + obj.addProperty( + "App::PropertyEnumeration", + "EigenSystemSelect", + "Eigen Values", + "Which eigenvalues are computed" + ) + obj.addProperty( + "App::PropertyFloat", + "EigenSystemTolerance", + "Eigen Values", + ( + "Convergence tolerance for iterative eigensystem solve\n" + "Default is 100 times the 'Linear Tolerance'" + ) + ) + obj.addProperty( + "App::PropertyInteger", + "EigenSystemValues", + "Eigen Values", + "Number of lowest eigen modes" + ) + obj.addProperty( + "App::PropertyBool", + "FixDisplacement", + "Elasticity", + "If displacements or forces are set,\nthereby model lumping is used" + ) + obj.addProperty( + "App::PropertyBool", + "GeometricStiffness", + "Elasticity", + "Consider geometric stiffness" + ) + obj.addProperty( + "App::PropertyBool", + "Incompressible", + "Elasticity", + ( + "Computation of incompressible material in connection\n" + "with viscoelastic Maxwell material and a custom 'Variable'" + ) + ) + obj.addProperty( + "App::PropertyBool", + "MaxwellMaterial", + "Elasticity", + "Compute viscoelastic material model" + ) + obj.addProperty( + "App::PropertyBool", + "ModelLumping", + "Elasticity", + "Use model lumping" + ) + obj.addProperty( + "App::PropertyFile", + "ModelLumpingFilename", + "Elasticity", + "File to save results from model lumping to" + ) + obj.addProperty( + "App::PropertyBool", + "StabilityAnalysis", + "Elasticity", + ( + "If true, 'Eigen Analysis' is stability analysis.\n" + "Otherwise modal analysis is performed." + ) + ) + obj.addProperty( + "App::PropertyBool", + "UpdateTransientSystem", + "Elasticity", + "See Elmer manual for info" + ) + obj.addProperty( + "App::PropertyString", + "Variable", + "Elasticity", + ( + "Only change this if 'Incompressible' is set to true\n" + "according to the Elmer manual." + ) + ) + + obj.addProperty( + "App::PropertyBool", + "PlaneStress", + "Equation", + ( + "Computes solution according to plane\nstress situation.\n" + "Applies only for 2D geometry." + ) + ) + + obj.EigenSystemValues = 5 obj.Priority = 10 + obj.CalculatePrincipal = True + obj.DisplaceMesh = True + # according to Elmer tutorial and forum, for stresses direct solving + # is recommended -> tests showed 10 times faster and even more accurate + obj.LinearSolverType = "Direct" + obj.LinearDirectMethod = "Umfpack" + # according to Elmer manual should be true except there is damping + # we set damping by default to false + obj.EigenSystemComplex = True + # according to Elmer manual the default is 300 + obj.EigenSystemMaxIterations = (300, 1, int(1e8), 1) + # according to Elmer manual the default is Smallest magnitude + obj.EigenSystemSelect = EIGEN_SYSTEM_SELECT + obj.EigenSystemSelect = "Smallest Magnitude" + # according to Elmer manual default is 100 times the Linear Tolerance + # since this is a small value we must set an expression, see linear.py for background + for (prop, expr) in obj.ExpressionEngine: + if (prop == "LinearTolerance"): + obj.setExpression("EigenSystemTolerance", str(100 * obj.evalExpression(expr))) + obj.Variable = "Displacement" class ViewProxy(linear.ViewProxy, equationbase.ElasticityViewProxy): diff --git a/src/Mod/Fem/femsolver/elmer/equations/electricforce.py b/src/Mod/Fem/femsolver/elmer/equations/electricforce.py index 776389b73c..cb30e74507 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/electricforce.py +++ b/src/Mod/Fem/femsolver/elmer/equations/electricforce.py @@ -32,6 +32,7 @@ from femtools import femutils from ... import equationbase from . import linear +SOLVER_EXEC_METHODS = ["After Timestep", "Always"] def create(doc, name="Electricforce"): return femutils.createObject( @@ -44,6 +45,22 @@ class Proxy(linear.Proxy, equationbase.ElectricforceProxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + + obj.addProperty( + "App::PropertyEnumeration", + "ExecSolver", + "Electric Force", + ( + "That solver is only executed after solution converged\n" + "To execute always, change to 'Always'" + ) + ) + + obj.ExecSolver = SOLVER_EXEC_METHODS + obj.ExecSolver = "After Timestep" + # Electrostatic has priority 10 and Electricforce needs + # the potential field calculated by Electrostatic + # therefore set priority to 5 obj.Priority = 5 diff --git a/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py b/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py index 35e7efc342..56d7f338f1 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py +++ b/src/Mod/Fem/femsolver/elmer/equations/electrostatic.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,7 +23,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object Electrostatic" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -44,6 +45,19 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + + obj.addProperty( + "App::PropertyBool", + "CalculateCapacitanceMatrix", + "Electrostatic", + "" + ) + obj.addProperty( + "App::PropertyBool", + "CalculateElectricEnergy", + "Electrostatic", + "" + ) obj.addProperty( "App::PropertyBool", "CalculateElectricField", @@ -56,24 +70,12 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): "Electrostatic", "" ) - obj.addProperty( - "App::PropertyBool", - "CalculateElectricEnergy", - "Electrostatic", - "" - ) obj.addProperty( "App::PropertyBool", "CalculateSurfaceCharge", "Electrostatic", "" ) - obj.addProperty( - "App::PropertyBool", - "CalculateCapacitanceMatrix", - "Electrostatic", - "" - ) """ obj.addProperty( "App::PropertyInteger", @@ -82,7 +84,33 @@ class Proxy(linear.Proxy, equationbase.ElectrostaticProxy): "" ) """ + obj.addProperty( + "App::PropertyFile", + "CapacitanceMatrixFilename", + "Electrostatic", + ( + "File where capacitance matrix is being saved\n" + "Only used if 'CalculateCapacitanceMatrix' is true" + ) + ) + obj.addProperty( + "App::PropertyBool", + "ConstantWeights", + "Electrostatic", + "Use constant weighting for results" + ) + obj.addProperty( + "App::PropertyFloat", + "PotentialDifference", + "Electrostatic", + ( + "Potential difference in Volt for which capacitance is\n" + "calculated if 'CalculateCapacitanceMatrix' is false" + ) + ) + obj.CapacitanceMatrixFilename = "cmatrix.dat" + obj.PotentialDifference = 0.0 obj.Priority = 10 diff --git a/src/Mod/Fem/femsolver/elmer/equations/equation.py b/src/Mod/Fem/femsolver/elmer/equations/equation.py index f6a7a029ff..585667a0a7 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/equation.py +++ b/src/Mod/Fem/femsolver/elmer/equations/equation.py @@ -45,7 +45,11 @@ class Proxy(equationbase.BaseProxy): "App::PropertyInteger", "Priority", "Base", - "" + ( + "Number of your choice\n" + "The equation with lowest number\n" + "will be solved first." + ) ) diff --git a/src/Mod/Fem/femsolver/elmer/equations/flow.py b/src/Mod/Fem/femsolver/elmer/equations/flow.py index 2e9db83796..ec40e2dbf1 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/flow.py +++ b/src/Mod/Fem/femsolver/elmer/equations/flow.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,7 +23,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object Flow" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -32,6 +33,9 @@ from femtools import femutils from . import nonlinear from ... import equationbase +CONVECTION_TYPE = ["None", "Computed", "Constant"] +FLOW_MODEL = ["Full", "No convection", "Stokes"] + def create(doc, name="Flow"): return femutils.createObject( @@ -44,6 +48,58 @@ class Proxy(nonlinear.Proxy, equationbase.FlowProxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + + obj.addProperty( + "App::PropertyBool", + "DivDiscretization", + "Flow", + ( + "Set to true for incompressible flow for more stable\n" + "discretization when Reynolds number increases" + ) + ) + obj.addProperty( + "App::PropertyEnumeration", + "FlowModel", + "Flow", + "Flow model to be used" + ) + obj.addProperty( + "App::PropertyBool", + "GradpDiscretization", + "Flow", + ( + "If true pressure Dirichlet boundary conditions can be used.\n" + "Also mass flux is available as a natural boundary condition." + ) + ) + obj.addProperty( + "App::PropertyString", + "Variable", + "Flow", + "Only for a 2D model change the '3' to '2'" + ) + + obj.addProperty( + "App::PropertyEnumeration", + "Convection", + "Equation", + "Type of convection to be used" + ) + obj.addProperty( + "App::PropertyBool", + "MagneticInduction", + "Equation", + ( + "Magnetic induction equation will be solved\n" + "along with the Navier-Stokes equations" + ) + ) + obj.FlowModel = FLOW_MODEL + obj.FlowModel = "Full" + obj.Variable = "Flow Solution[Velocity:3 Pressure:1]" + obj.Convection = CONVECTION_TYPE + obj.Convection = "Computed" obj.Priority = 10 diff --git a/src/Mod/Fem/femsolver/elmer/equations/flux.py b/src/Mod/Fem/femsolver/elmer/equations/flux.py index 6984443131..0ebea9e022 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/flux.py +++ b/src/Mod/Fem/femsolver/elmer/equations/flux.py @@ -1,6 +1,7 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * # * Copyright (c) 2020 Bernd Hahnebach * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -23,7 +24,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object Flux" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -33,6 +34,8 @@ from femtools import femutils from ... import equationbase from . import linear +COEFFICIENTS = ["Heat Conductivity", "None"] +VARIABLES = ["Potential", "Temperature"] def create(doc, name="Flux"): return femutils.createObject( @@ -45,59 +48,93 @@ class Proxy(linear.Proxy, equationbase.FluxProxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + + obj.addProperty( + "App::PropertyBool", + "AverageWithinMaterials", + "Flux", + ( + "Enforces continuity within the same material\n" + "in the 'Discontinuous Galerkin' discretization" + ) + ) obj.addProperty( "App::PropertyBool", "CalculateFlux", "Flux", - "" + "Computes flux vector" ) - obj.addProperty( - "App::PropertyString", - "FluxVariable", - "Flux", - "Insert variable name for flux calculation" - ) - """ obj.addProperty( "App::PropertyBool", "CalculateFluxAbs", "Flux", - "Select calculation of abs of flux" + "Computes absolute of flux vector" ) obj.addProperty( "App::PropertyBool", "CalculateFluxMagnitude", "Flux", - "Select calculation of magnitude of flux" + "Computes magnitude of flux vector field" ) - """ obj.addProperty( "App::PropertyBool", "CalculateGrad", "Flux", "Select calculation of gradient" ) - """ obj.addProperty( "App::PropertyBool", "CalculateGradAbs", "Flux", - "Select calculation of abs of gradient" + "Computes absolute of gradient field" ) obj.addProperty( "App::PropertyBool", "CalculateGradMagnitude", "Flux", - "Select calculation of magnitude of gradient" + "Computes magnitude of gradient field" + ) + obj.addProperty( + "App::PropertyBool", + "DiscontinuousGalerkin", + "Flux", + ( + "Enable if standard Galerkin approximation leads to\n" + "unphysical results when there are discontinuities" + ) ) obj.addProperty( "App::PropertyBool", "EnforcePositiveMagnitude", "Flux", - "Select calculation of positive magnitude" + ( + "If true, negative values of computed magnitude fields\n" + "are a posteriori set to zero." + ) ) - """ - obj.Priority = 5 + obj.addProperty( + "App::PropertyEnumeration", + "FluxCoefficient", + "Flux", + "Proportionality coefficient\nto compute the flux" + ) + obj.addProperty( + "App::PropertyEnumeration", + "FluxVariable", + "Flux", + "Variable name for flux calculation" + ) + + obj.CalculateFlux = True + # set defaults according to the Elmer manual + obj.FluxCoefficient = COEFFICIENTS + obj.FluxCoefficient = "Heat Conductivity" + obj.FluxVariable = VARIABLES + obj.FluxVariable = "Temperature" + # Electrostatic has priority 10, Heat has 20 and Flux needs + # to be solved before these equations + # therefore set priority to 25 + obj.Priority = 25 class ViewProxy(linear.ViewProxy, equationbase.FluxViewProxy): diff --git a/src/Mod/Fem/femsolver/elmer/equations/heat.py b/src/Mod/Fem/femsolver/elmer/equations/heat.py index 7775cf3a4a..9204c2077e 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/heat.py +++ b/src/Mod/Fem/femsolver/elmer/equations/heat.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,7 +23,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object Heat" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -32,6 +33,9 @@ from femtools import femutils from . import nonlinear from ... import equationbase +CONVECTION_TYPE = ["None", "Computed", "Constant"] +PHASE_CHANGE_MODEL = ["None", "Spatial 1", "Spatial 2", "Temporal"] + def create(doc, name="Heat"): return femutils.createObject( @@ -44,6 +48,34 @@ class Proxy(nonlinear.Proxy, equationbase.HeatProxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + + # according to the Elmer models manual Bubbles is by default True + # and Stabilize is False (Stabilize is added in linear.py) + obj.addProperty( + "App::PropertyBool", + "Bubbles", + "Heat", + "" + ) + obj.addProperty( + "App::PropertyEnumeration", + "Convection", + "Equation", + "Type of convection to be used" + ) + obj.addProperty( + "App::PropertyEnumeration", + "PhaseChangeModel", + "Equation", + "Model for phase change" + ) + + obj.Bubbles = True + obj.Stabilize = False + obj.Convection = CONVECTION_TYPE + obj.Convection = "None" + obj.PhaseChangeModel = PHASE_CHANGE_MODEL + obj.PhaseChangeModel = "None" obj.Priority = 20 diff --git a/src/Mod/Fem/femsolver/elmer/equations/linear.py b/src/Mod/Fem/femsolver/elmer/equations/linear.py index b3b966ed45..ff726d839c 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/linear.py +++ b/src/Mod/Fem/femsolver/elmer/equations/linear.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,7 +23,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object _Linear" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -37,15 +38,16 @@ from . import equation LINEAR_SOLVER = ["Direct", "Iterative"] -LINEAR_DIRECT = ["Banded", "umfpack"] +LINEAR_DIRECT = ["Banded", "MUMPS", "Umfpack"] LINEAR_ITERATIVE = [ - "CG", - "CGS", "BiCGStab", "BiCGStabl", - "TFQMR", - "GMRES", + "CG", "GCR", + "CGS", + "GMRES", + "Idrs", + "TFQMR" ] LINEAR_PRECONDITIONING = [ "None", @@ -55,6 +57,7 @@ LINEAR_PRECONDITIONING = [ "ILU2", "ILU3", "ILU4", + "ILUT" ] @@ -62,32 +65,34 @@ class Proxy(equation.Proxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + obj.addProperty( - "App::PropertyEnumeration", - "LinearSolverType", + "App::PropertyIntegerConstraint", + "BiCGstablDegree", "Linear System", - "" + "Polynom degree for iterative method 'BiCGstabl'" + ) + obj.addProperty( + "App::PropertyIntegerConstraint", + "IdrsParameter", + "Linear System", + "Parameter for iterative method 'Idrs'" ) - obj.LinearSolverType = LINEAR_SOLVER - obj.LinearSolverType = "Iterative" obj.addProperty( "App::PropertyEnumeration", "LinearDirectMethod", "Linear System", "" ) - obj.LinearDirectMethod = LINEAR_DIRECT obj.addProperty( - "App::PropertyEnumeration", - "LinearIterativeMethod", + "App::PropertyIntegerConstraint", + "LinearIterations", "Linear System", "" ) - obj.LinearIterativeMethod = LINEAR_ITERATIVE - obj.LinearIterativeMethod = "BiCGStab" obj.addProperty( - "App::PropertyInteger", - "BiCGstablDegree", + "App::PropertyEnumeration", + "LinearIterativeMethod", "Linear System", "" ) @@ -97,43 +102,59 @@ class Proxy(equation.Proxy): "Linear System", "" ) - obj.LinearPreconditioning = LINEAR_PRECONDITIONING - obj.LinearPreconditioning = "ILU0" + obj.addProperty( + "App::PropertyEnumeration", + "LinearSolverType", + "Linear System", + "" + ) + obj.addProperty( + "App::PropertyBool", + "LinearSystemSolverDisabled", + "Linear System", + ( + "Disable the linear system.\n" + "Only use for special cases\n" + "and consult the Elmer docs." + ) + ) obj.addProperty( "App::PropertyFloat", "LinearTolerance", "Linear System", - "" + "Linear preconditioning method" ) - obj.LinearTolerance = 1e-8 - obj.addProperty( - "App::PropertyInteger", - "LinearIterations", - "Linear System", - "" - ) - obj.LinearIterations = 500 - obj.addProperty( - "App::PropertyFloat", - "SteadyStateTolerance", - "Steady State", - "" - ) - obj.SteadyStateTolerance = 1e-5 obj.addProperty( "App::PropertyBool", "Stabilize", "Base", "" ) - obj.Stabilize = True obj.addProperty( - "App::PropertyBool", - "Bubbles", - "Base", + "App::PropertyFloat", + "SteadyStateTolerance", + "Steady State", "" ) - obj.Bubbles = False + + obj.BiCGstablDegree = (2, 2, 10, 1) + obj.IdrsParameter = (2, 1, 10, 1) + obj.LinearDirectMethod = LINEAR_DIRECT + obj.LinearIterations = (500, 1, int(1e6), 50) + obj.LinearIterativeMethod = LINEAR_ITERATIVE + obj.LinearIterativeMethod = "BiCGStab" + obj.LinearPreconditioning = LINEAR_PRECONDITIONING + obj.LinearPreconditioning = "ILU0" + # we must set an expression because we don't have a UI, the user has to + # view and edit the tolerance via the property editor and this does not + # yet allow to view and edit small numbers in scientific notation + # forum thread: https://forum.freecadweb.org/viewtopic.php?p=613897#p613897 + obj.setExpression("LinearTolerance", "1e-10") + obj.LinearSolverType = LINEAR_SOLVER + obj.LinearSolverType = "Iterative" + # same reason to setup an expression as with LinearTolerance + obj.setExpression("SteadyStateTolerance", "1e-5") + obj.Stabilize = True class ViewProxy(equation.ViewProxy): diff --git a/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py b/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py index 2406f2e6cb..a0229a076f 100644 --- a/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py +++ b/src/Mod/Fem/femsolver/elmer/equations/nonlinear.py @@ -1,5 +1,6 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -22,7 +23,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer equation object _NonLinear" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -40,26 +41,15 @@ class Proxy(linear.Proxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + obj.addProperty( - "App::PropertyFloat", - "NonlinearTolerance", - "Nonlinear System", - "" - ) - obj.addProperty( - "App::PropertyInteger", + "App::PropertyIntegerConstraint", "NonlinearIterations", "Nonlinear System", - "" + "Maximum number of iterations" ) obj.addProperty( - "App::PropertyFloat", - "RelaxationFactor", - "Nonlinear System", - "" - ) - obj.addProperty( - "App::PropertyInteger", + "App::PropertyIntegerConstraint", "NonlinearNewtonAfterIterations", "Nonlinear System", "" @@ -70,11 +60,31 @@ class Proxy(linear.Proxy): "Nonlinear System", "" ) - obj.NonlinearTolerance = 1e-8 - obj.NonlinearIterations = 500 - obj.RelaxationFactor = 1 - obj.NonlinearNewtonAfterIterations = 3 - obj.NonlinearNewtonAfterTolerance = 1e-3 + obj.addProperty( + "App::PropertyFloat", + "NonlinearTolerance", + "Nonlinear System", + "" + ) + obj.addProperty( + "App::PropertyFloatConstraint", + "RelaxationFactor", + "Nonlinear System", + ( + "Value below 1.0 might be necessary to achieve convergence\n" + "Typical values are in the range [0.3, 1.0]" + ) + ) + + obj.NonlinearIterations = (500, 1, int(1e6), 50) + obj.NonlinearNewtonAfterIterations = (3, 1, 100, 1) + # for small numbers we must set an expression because we don't have a UI, + # the user has to view and edit the tolerance via the property editor and + # this does not yet allow to view and edit small numbers in scientific notation + # forum thread: https://forum.freecadweb.org/viewtopic.php?p=613897#p613897 + obj.setExpression("NonlinearTolerance", "1e-7") + obj.setExpression("NonlinearNewtonAfterTolerance", "1e-3") + obj.RelaxationFactor = (1.0, 0.0001, 2.0, 0.1) class ViewProxy(linear.ViewProxy): diff --git a/src/Mod/Fem/femsolver/elmer/sifio.py b/src/Mod/Fem/femsolver/elmer/sifio.py index 8ded82eb04..3bce29ce74 100644 --- a/src/Mod/Fem/femsolver/elmer/sifio.py +++ b/src/Mod/Fem/femsolver/elmer/sifio.py @@ -31,7 +31,6 @@ __url__ = "https://www.freecadweb.org" import collections import six - SIMULATION = "Simulation" CONSTANTS = "Constants" BODY = "Body" @@ -57,7 +56,6 @@ _VALID_SECTIONS = ( COMPONENT, ) - _NUMBERED_SECTIONS = ( BODY, MATERIAL, @@ -69,24 +67,21 @@ _NUMBERED_SECTIONS = ( COMPONENT, ) - _SECTION_DELIM = "End" _WHITESPACE = " " _INDENT = " " * 2 _NEWLINE = "\n" - _TYPE_REAL = "Real" _TYPE_INTEGER = "Integer" _TYPE_LOGICAL = "Logical" _TYPE_STRING = "String" _TYPE_FILE = "File" - -WARN = "Warn" -IGNORE = "Ignore" -ABORT = "Abort" -SILENT = "Silent" +WARN = "\"Warn\"" +IGNORE = "\"Ignore\"" +ABORT = "\"Abort\"" +SILENT = "\"Silent\"" def createSection(name): diff --git a/src/Mod/Fem/femsolver/elmer/solver.py b/src/Mod/Fem/femsolver/elmer/solver.py index 5b425f1004..e891e9965f 100644 --- a/src/Mod/Fem/femsolver/elmer/solver.py +++ b/src/Mod/Fem/femsolver/elmer/solver.py @@ -28,6 +28,11 @@ __url__ = "https://www.freecadweb.org" ## \addtogroup FEM # @{ +import glob +import os + +import FreeCAD + from . import tasks from .equations import elasticity from .equations import electrostatic @@ -39,6 +44,11 @@ from .. import run from .. import solverbase from femtools import femutils +if FreeCAD.GuiUp: + import FemGui + +SIMULATION_TYPE = ["Scanning", "Steady State", "Transient"] + def create(doc, name="ElmerSolver"): return femutils.createObject( @@ -62,19 +72,61 @@ class Proxy(solverbase.Proxy): def __init__(self, obj): super(Proxy, self).__init__(obj) + obj.addProperty( + "App::PropertyIntegerConstraint", + "BDFOrder", + "Timestepping", + "Order of time stepping method 'BDF'" + ) + # according to the Elmer manual recommended is order 2 + # possible ranage is 1 - 5 + obj.BDFOrder = (2, 1, 5, 1) + + obj.addProperty( + "App::PropertyIntegerList", + "TimestepIntervals", + "Timestepping", + ( + "List of maximum optimization rounds if 'Simulation Type'\n" + "is either 'Scanning' or 'Transient'" + ) + ) + obj.addProperty( + "App::PropertyFloatList", + "TimestepSizes", + "Timestepping", + ( + "List of time steps of optimization if 'Simulation Type'\n" + "is either 'Scanning' or 'Transient'" + ) + ) + # there is no universal default, it all depends on the analysis, however + # we have to set something and set 10 seconds in steps of 0.1s + obj.TimestepIntervals = [100] + obj.TimestepSizes = [0.1] + + obj.addProperty( + "App::PropertyEnumeration", + "SimulationType", + "Type", + "" + ) + obj.SimulationType = SIMULATION_TYPE + obj.SimulationType = "Steady State" + obj.addProperty( "App::PropertyInteger", "SteadyStateMaxIterations", - "Steady State", - "" + "Type", + "Maximal steady state iterations" ) obj.SteadyStateMaxIterations = 1 obj.addProperty( "App::PropertyInteger", "SteadyStateMinIterations", - "Steady State", - "" + "Type", + "Minimal steady state iterations" ) obj.SteadyStateMinIterations = 0 @@ -109,6 +161,15 @@ class Proxy(solverbase.Proxy): def isSupported(self, eqId): return eqId in self._EQUATIONS + def editSupported(self): + return True + + def edit(self, directory): + pattern = os.path.join(directory, "case.sif") + FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + f = glob.glob(pattern)[0] + FemGui.open(f) + class ViewProxy(solverbase.ViewProxy): """Proxy for FemSolverElmers View Provider.""" diff --git a/src/Mod/Fem/femsolver/elmer/tasks.py b/src/Mod/Fem/femsolver/elmer/tasks.py index 788224b900..57fe57c928 100644 --- a/src/Mod/Fem/femsolver/elmer/tasks.py +++ b/src/Mod/Fem/femsolver/elmer/tasks.py @@ -28,10 +28,10 @@ __url__ = "https://www.freecadweb.org" ## \addtogroup FEM # @{ +import cmath import os import os.path import subprocess -import sys from platform import system import FreeCAD @@ -76,6 +76,9 @@ class Prepare(run.Prepare): def run(self): # TODO print working dir to report console self.pushStatus("Preparing input files...\n") + num_cores = settings.get_cores("ElmerGrid") + self.pushStatus("Number of CPU cores to be used for the solver run: {}\n" + .format(num_cores)) if self.testmode: # test mode: neither gmsh, nor elmergrid nor elmersolver binaries needed FreeCAD.Console.PrintMessage("Machine testmode: {}\n".format(self.testmode)) @@ -86,6 +89,7 @@ class Prepare(run.Prepare): try: w.write_solver_input() self.checkHandled(w) + self.pushStatus("Writing solver input completed.") except writer.WriteError as e: self.report.error(str(e)) self.fail() @@ -123,13 +127,15 @@ class Solve(run.Solve): os.environ["LD_LIBRARY_PATH"] = "$LD_LIBRARY_PATH:{}/modules".format(solvpath) # different call depending if with multithreading or not num_cores = settings.get_cores("ElmerSolver") + self.pushStatus("Number of CPU cores to be used for the solver run: {}\n" + .format(num_cores)) args = [] - if int(num_cores) > 1: + if num_cores > 1: if system() != "Windows": args.extend(["mpirun"]) else: args.extend(["mpiexec"]) - args.extend(["-np", num_cores]) + args.extend(["-np", str(num_cores)]) args.extend([binary]) if system() == "Windows": self._process = subprocess.Popen( @@ -153,16 +159,16 @@ class Solve(run.Solve): if not self.aborted: self._updateOutput(output) else: - self.report.error("ElmerSolver executable not found.") + self.report.error("ElmerSolver binary not found.") + self.pushStatus("Error: ElmerSolver binary has not been found!") self.fail() def _updateOutput(self, output): if self.solver.ElmerOutput is None: self._createOutput() - if sys.version_info.major >= 3: - self.solver.ElmerOutput.Text = output - else: - self.solver.ElmerOutput.Text = output.decode("utf-8") + # check if eigenmodes were calculated and if so append them to output + output = self._calculateEigenfrequencies(output) + self.solver.ElmerOutput.Text = output def _createOutput(self): self.solver.ElmerOutput = self.analysis.Document.addObject( @@ -174,6 +180,66 @@ class Solve(run.Solve): self.analysis.addObject(self.solver.ElmerOutput) self.solver.Document.recompute() + def _calculateEigenfrequencies(self, output): + # takes the EigenSolve results and performs the calculation + # sqrt(aResult) / 2*PI but with aResult as complex number + + # first search the output file for the results + OutputList = output.split("\n") + modeNumber = 0 + modeCount = 0 + real = 0 + imaginary = 0 + haveImaginary = False + FrequencyList = [] + for line in OutputList: + LineList = line.split(" ") + if ( + len(LineList) > 1 + and LineList[0] == "EigenSolve:" + and LineList[1] == "Computed" + ): + # we found a result and take now the next LineList[2] lines + modeCount = int(LineList[2]) + modeNumber = modeCount + continue + if modeCount > 0: + for LineString in reversed(LineList): + # the output of Elmer may vary, we only know the last float + # is the imaginary and second to last float the real part + if self._isNumber(LineString): + if not haveImaginary: + imaginary = float(LineString) + haveImaginary = True + else: + real = float(LineString) + break + eigenFreq = complex(real, imaginary) + haveImaginary = False + # now we can perform the calculation + eigenFreq = cmath.sqrt(eigenFreq) / (2 * cmath.pi) + # create an output line + FrequencyList.append( + "Mode {}: {} Hz".format(modeNumber - modeCount + 1, eigenFreq.real) + ) + modeCount = modeCount - 1 + if modeNumber > 0: + # push the results and append to output + self.pushStatus("\n\nEigenfrequency results:") + output = output + "\n\nEigenfrequency results:" + for i in range(0, modeNumber): + output = output + "\n" + FrequencyList[i] + self.pushStatus("\n" + FrequencyList[i]) + self.pushStatus("\n") + return output + + def _isNumber(self, string): + try: + float(string) + return True + except ValueError: + return False + class Results(run.Results): @@ -181,15 +247,30 @@ class Results(run.Results): if self.solver.ElmerResult is None: self._createResults() postPath = self._getResultFile() + if postPath is None: + self.pushStatus("\nNo result file was created.\n") + self.fail() + return self.solver.ElmerResult.read(postPath) - self.solver.ElmerResult.scale(1000) - self.solver.ElmerResult.getLastPostObject().touch() + # at the moment we scale the mesh back using Elmer + # this might be changed in future, therefore leave this + # self.solver.ElmerResult.scale(1000) + + # for eigen analyses the resulting values are by a factor 1000 to high + # therefore scale all *EigenMode results + self.solver.ElmerResult.ViewObject.transformField("displacement EigenMode1", 0.001) + + self.solver.ElmerResult.recomputeChildren() self.solver.Document.recompute() + # recompute() updated the result mesh data + # but not the shape and bar coloring + self.solver.ElmerResult.ViewObject.updateColorBars() def _createResults(self): self.solver.ElmerResult = self.analysis.Document.addObject( "Fem::FemPostPipeline", self.solver.Name + "Result") self.solver.ElmerResult.Label = self.solver.Label + "Result" + self.solver.ElmerResult.ViewObject.SelectionStyle = "BoundBox" self.analysis.addObject(self.solver.ElmerResult) # to assure the user sees something, set the default to Surface self.solver.ElmerResult.ViewObject.DisplayMode = "Surface" @@ -202,16 +283,22 @@ class Results(run.Results): possible_post_file_old = os.path.join(self.directory, "case0001.vtu") possible_post_file_single = os.path.join(self.directory, "case_t0001.vtu") possible_post_file_multi = os.path.join(self.directory, "case_t0001.pvtu") - # first try the multi-thread result, then single then old name - if os.path.isfile(possible_post_file_multi): - postPath = possible_post_file_multi - elif os.path.isfile(possible_post_file_single): - postPath = possible_post_file_single - elif os.path.isfile(possible_post_file_old): - postPath = possible_post_file_old - else: - self.report.error("Result file not found.") - self.fail() + # depending on the currently set number of cores we try to load either + # the multi-thread result or the single result + if settings.get_cores("ElmerSolver") > 1: + if os.path.isfile(possible_post_file_multi): + postPath = possible_post_file_multi + else: + self.report.error("Result file not found.") + self.fail() + else: + if os.path.isfile(possible_post_file_single): + postPath = possible_post_file_single + elif os.path.isfile(possible_post_file_old): + postPath = possible_post_file_old + else: + self.report.error("Result file not found.") + self.fail() return postPath ## @} diff --git a/src/Mod/Fem/femsolver/elmer/writer.py b/src/Mod/Fem/femsolver/elmer/writer.py index 3bb37d0a81..5ea19e5105 100644 --- a/src/Mod/Fem/femsolver/elmer/writer.py +++ b/src/Mod/Fem/femsolver/elmer/writer.py @@ -1,6 +1,7 @@ # *************************************************************************** # * Copyright (c) 2017 Markus Hovorka * # * Copyright (c) 2020 Bernd Hahnebach * +# * Copyright (c) 2022 Uwe Stöhr * # * * # * This file is part of the FreeCAD CAx development system. * # * * @@ -23,7 +24,7 @@ # *************************************************************************** __title__ = "FreeCAD FEM solver Elmer writer" -__author__ = "Markus Hovorka" +__author__ = "Markus Hovorka, Uwe Stöhr" __url__ = "https://www.freecadweb.org" ## \addtogroup FEM @@ -41,11 +42,18 @@ from FreeCAD import ParamGet import Fem from . import sifio +from . import solver as solverClass from .. import settings from femmesh import gmshtools +from femmesh import meshtools from femtools import constants from femtools import femutils from femtools import membertools +from .equations import elasticity +from .equations import electricforce +from .equations import flow +from .equations import flux +from .equations import heat _STARTINFO_NAME = "ELMERSOLVER_STARTINFO" @@ -191,17 +199,6 @@ class Writer(object): "BoltzmannConstant": constants.boltzmann_constant(), } - def _getConstant(self, name, unit_dimension): - # TODO without method directly use self.constsdef[name] - return self._convert(self.constsdef[name], unit_dimension) - - def _setConstant(self, name, quantityStr): - # TODO without method directly use self.constsdef[name] - if name == "PermittivityOfVacuum": - theUnit = "s^4*A^2 / (m^3*kg)" - self.constsdef[name] = "{} {}".format(self._convert(quantityStr, theUnit), theUnit) - return True - def _writeMesh(self): mesh = self._getSingleMember("Fem::FemMeshObject") unvPath = os.path.join(self.directory, "mesh.unv") @@ -224,28 +221,27 @@ class Writer(object): argsBasic = [binary, _ELMERGRID_IFORMAT, _ELMERGRID_OFORMAT, - unvPath, - "-scale", "0.001", "0.001", "0.001"] + unvPath] args = argsBasic args.extend(["-out", self.directory]) if system() == "Windows": subprocess.call( args, - stdout=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, startupinfo=femutils.startProgramInfo("hide") ) else: subprocess.call(args, stdout=subprocess.DEVNULL) - if int(num_cores) > 1: + if num_cores > 1: args = argsBasic - args.extend(["-partdual", "-metiskway", num_cores, + args.extend(["-partdual", "-metiskway", str(num_cores), "-out", self.directory]) if system() == "Windows": - subprocess.call( - args, - stdout=subprocess.DEVNULL, - startupinfo=femutils.startProgramInfo("hide") - ) + subprocess.call( + args, + stdout=subprocess.DEVNULL, + startupinfo=femutils.startProgramInfo("hide") + ) else: subprocess.call(args, stdout=subprocess.DEVNULL) @@ -298,38 +294,101 @@ class Writer(object): """ redefine constants in self.constsdef according constant redefine objects """ - permittivity_objs = self._getMember("Fem::ConstantVacuumPermittivity") - if len(permittivity_objs) == 1: - Console.PrintLog("Constand permittivity overwriting.\n") - self._setConstant("PermittivityOfVacuum", permittivity_objs[0].VacuumPermittivity) - elif len(permittivity_objs) > 1: + objs = self._getMember("Fem::ConstantVacuumPermittivity") + if len(objs) == 1: + permittivity = float(objs[0].VacuumPermittivity.getValueAs("F/m")) + # since the base unit of FC is in mm, we must scale it to get plain SI + permittivity = permittivity * 1e-9 + Console.PrintLog("Overwriting vacuum permittivity with: {}\n".format(permittivity)) + self.constsdef["PermittivityOfVacuum"] = "{} {}".format(permittivity, "F/m") + self._handled(objs[0]) + elif len(objs) > 1: Console.PrintError( "More than one permittivity constant overwriting objects ({} objs). " "The permittivity constant overwriting is ignored.\n" - .format(len(permittivity_objs)) + .format(len(objs)) ) def _handleSimulation(self): + # check if we need to update the equation + self._updateSimulation(self.solver) + # output the equation parameters + # first check what equations we have + hasHeat = False + for equation in self.solver.Group: + if femutils.is_of_type(equation, "Fem::EquationElmerHeat"): + hasHeat = True + if hasHeat: + self._simulation("BDF Order", self.solver.BDFOrder) self._simulation("Coordinate System", "Cartesian 3D") self._simulation("Coordinate Mapping", (1, 2, 3)) - # not necessary anymore since we use SI units - # if self.unit_schema == Units.Scheme.SI2: - # self._simulation("Coordinate Scaling", 0.001) - # Console.PrintMessage( - # "'Coordinate Scaling = Real 0.001' was inserted into the solver input file.\n" - # ) - self._simulation("Simulation Type", "Steady state") - self._simulation("Steady State Max Iterations", 1) + # Elmer uses SI base units, but our mesh is in mm, therefore we must tell + # the solver that we have another scale + self._simulation("Coordinate Scaling", 0.001) self._simulation("Output Intervals", 1) - self._simulation("Timestepping Method", "BDF") - self._simulation("BDF Order", 1) + self._simulation("Simulation Type", self.solver.SimulationType) + if self.solver.SimulationType == "Steady State": + self._simulation( + "Steady State Max Iterations", + self.solver.SteadyStateMaxIterations + ) + self._simulation( + "Steady State Min Iterations", + self.solver.SteadyStateMinIterations + ) + if ( + self.solver.SimulationType == "Scanning" + or self.solver.SimulationType == "Transient" + ): + self._simulation("Timestep Intervals", self.solver.TimestepIntervals) + self._simulation("Timestep Sizes", self.solver.TimestepSizes) + # Output Intervals must be equal to Timestep Intervals + self._simulation("Output Intervals", self.solver.TimestepIntervals) + if hasHeat: + self._simulation("Timestepping Method", "BDF") self._simulation("Use Mesh Names", True) - self._simulation( - "Steady State Max Iterations", - self.solver.SteadyStateMaxIterations) - self._simulation( - "Steady State Min Iterations", - self.solver.SteadyStateMinIterations) + + def _updateSimulation(self, solver): + # updates older simulations + if not hasattr(self.solver, "BDFOrder"): + solver.addProperty( + "App::PropertyIntegerConstraint", + "BDFOrder", + "Timestepping", + "Order of time stepping method 'BDF'" + ) + solver.BDFOrder = (2, 1, 5, 1) + if not hasattr(self.solver, "SimulationType"): + solver.addProperty( + "App::PropertyEnumeration", + "SimulationType", + "Type", + "" + ) + solver.SimulationType = solverClass.SIMULATION_TYPE + solver.SimulationType = "Steady State" + if not hasattr(self.solver, "TimestepIntervals"): + solver.addProperty( + "App::PropertyIntegerList", + "TimestepIntervals", + "Timestepping", + ( + "List of maximum optimization rounds if 'Simulation Type'\n" + "is either 'Scanning' or 'Transient'" + ) + ) + solver.TimestepIntervals = [100] + if not hasattr(self.solver, "TimestepSizes"): + solver.addProperty( + "App::PropertyFloatList", + "TimestepSizes", + "Timestepping", + ( + "List of time steps of optimization if 'Simulation Type'\n" + "is either 'Scanning' or 'Transient'" + ) + ) + solver.TimestepSizes = [0.1] def _handleHeat(self): activeIn = [] @@ -342,6 +401,7 @@ class Writer(object): solverSection = self._getHeatSolver(equation) for body in activeIn: self._addSolver(body, solverSection) + self._handleHeatEquation(activeIn, equation) if activeIn: self._handleHeatConstants() self._handleHeatBndConditions() @@ -350,30 +410,74 @@ class Writer(object): self._handleHeatMaterial(activeIn) def _getHeatSolver(self, equation): + # check if we need to update the equation + self._updateHeatSolver(equation) + # output the equation parameters s = self._createNonlinearSolver(equation) s["Equation"] = equation.Name s["Procedure"] = sifio.FileAttr("HeatSolve/HeatSolver") - s["Variable"] = self._getUniqueVarName("Temperature") - s["Exec Solver"] = "Always" - s["Stabilize"] = equation.Stabilize s["Bubbles"] = equation.Bubbles + s["Exec Solver"] = "Always" s["Optimize Bandwidth"] = True + s["Stabilize"] = equation.Stabilize + s["Variable"] = self._getUniqueVarName("Temperature") return s def _handleHeatConstants(self): self._constant( "Stefan Boltzmann", - self._getConstant("StefanBoltzmann", "M/(O^4*T^3)")) + self._convert(self.constsdef["StefanBoltzmann"], "M/(O^4*T^3)") + ) + + def _handleHeatEquation(self, bodies, equation): + for b in bodies: + if equation.Convection != "None": + self._equation(b, "Convection", equation.Convection) + if equation.PhaseChangeModel != "None": + self._equation(b, "Phase Change Model", equation.PhaseChangeModel) + + def _updateHeatSolver(self, equation): + # updates older Heat equations + if not hasattr(equation, "Convection"): + equation.addProperty( + "App::PropertyEnumeration", + "Convection", + "Equation", + "Type of convection to be used" + ) + equation.Convection = heat.CONVECTION_TYPE + equation.Convection = "None" + if not hasattr(equation, "PhaseChangeModel"): + equation.addProperty( + "App::PropertyEnumeration", + "PhaseChangeModel", + "Equation", + "Model for phase change" + ) + equation.PhaseChangeModel = heat.PHASE_CHANGE_MODEL + equation.PhaseChangeModel = "None" def _handleHeatBndConditions(self): + i = -1 for obj in self._getMember("Fem::ConstraintTemperature"): + i = i + 1 + femobjects = membertools.get_several_member(self.analysis, "Fem::ConstraintTemperature") + femobjects[i]["Nodes"] = meshtools.get_femnodes_by_femobj_with_references( + self._getSingleMember("Fem::FemMeshObject").FemMesh, + femobjects[i] + ) + NumberOfNodes = len(femobjects[i]["Nodes"]) if obj.References: for name in obj.References[0][1]: if obj.ConstraintType == "Temperature": temp = self._getFromUi(obj.Temperature, "K", "O") self._boundary(name, "Temperature", temp) elif obj.ConstraintType == "CFlux": - flux = self._getFromUi(obj.CFlux, "kg*mm^2*s^-3", "M*L^2*T^-3") + # the CFLUX property stores the value in µW + # but the unit system is not aware of µW, only of mW + flux = 0.001 * self._getFromUi(obj.CFlux, "mW", "M*L^2*T^-3") + # CFLUX is the flux per mesh node + flux = flux / NumberOfNodes self._boundary(name, "Temperature Load", flux) self._handled(obj) for obj in self._getMember("Fem::ConstraintHeatflux"): @@ -398,15 +502,31 @@ class Writer(object): self._initial(name, "Temperature", temp) self._handled(obj) + def _outputHeatBodyForce(self, obj, name): + heatSource = self._getFromUi(obj.HeatSource, "W/kg", "L^2*T^-3") + if heatSource == 0.0: + # a zero heat would break Elmer (division by zero) + raise WriteError("The body heat source must not be zero!") + self._bodyForce(name, "Heat Source", heatSource) + def _handleHeatBodyForces(self, bodies): - obj = self._getSingleMember("Fem::ConstraintBodyHeatSource") - if obj is not None: - for name in bodies: - heatSource = self._getFromUi(obj.HeatSource, "W/kg", "L^2*T^-3") - # according Elmer forum W/kg is correct - # http://www.elmerfem.org/forum/viewtopic.php?f=7&t=1765 - # 1 watt = kg * m2 / s3 ... W/kg = m2 / s3 - self._bodyForce(name, "Heat Source", heatSource) + bodyHeats = self._getMember("Fem::ConstraintBodyHeatSource") + for obj in bodyHeats: + if obj.References: + for name in obj.References[0][1]: + self._outputHeatBodyForce(obj, name) + self._handled(obj) + else: + # if there is only one body heat without a reference + # add it to all bodies + if len(bodyHeats) == 1: + for name in bodies: + self._outputHeatBodyForce(obj, name) + else: + raise WriteError( + "Several body heat constraints found without reference to a body.\n" + "Please set a body for each body heat constraint." + ) self._handled(obj) def _handleHeatMaterial(self, bodies): @@ -422,12 +542,24 @@ class Writer(object): if obj.References else self._getAllBodies()) for name in (n for n in refs if n in bodies): + if "Density" not in m: + raise WriteError( + "Used material does not specify the necessary 'Density'." + ) self._material( name, "Density", self._getDensity(m)) + if "ThermalConductivity" not in m: + raise WriteError( + "Used material does not specify the necessary 'Thermal Conductivity'." + ) self._material( name, "Heat Conductivity", self._convert(m["ThermalConductivity"], "M*L/(T^3*O)")) + if "SpecificHeat" not in m: + raise WriteError( + "Used material does not specify the necessary 'Specific Heat'." + ) self._material( name, "Heat Capacity", self._convert(m["SpecificHeat"], "L^2/(T^2*O)")) @@ -451,29 +583,74 @@ class Writer(object): self._handleElectrostaticMaterial(activeIn) def _getElectrostaticSolver(self, equation): + # check if we need to update the equation + self._updateElectrostaticSolver(equation) + # output the equation parameters s = self._createLinearSolver(equation) s["Equation"] = "Stat Elec Solver" # equation.Name s["Procedure"] = sifio.FileAttr("StatElecSolve/StatElecSolver") s["Variable"] = self._getUniqueVarName("Potential") s["Variable DOFs"] = 1 - s["Calculate Electric Field"] = equation.CalculateElectricField - # s["Calculate Electric Flux"] = equation.CalculateElectricFlux - s["Calculate Electric Energy"] = equation.CalculateElectricEnergy - s["Calculate Surface Charge"] = equation.CalculateSurfaceCharge - s["Calculate Capacitance Matrix"] = equation.CalculateCapacitanceMatrix - s["Displace mesh"] = False + if equation.CalculateCapacitanceMatrix is True: + s["Calculate Capacitance Matrix"] = equation.CalculateCapacitanceMatrix + s["Capacitance Matrix Filename"] = equation.CapacitanceMatrixFilename + if equation.CalculateElectricEnergy is True: + s["Calculate Electric Energy"] = equation.CalculateElectricEnergy + if equation.CalculateElectricField is True: + s["Calculate Electric Field"] = equation.CalculateElectricField + if equation.CalculateElectricFlux is True: + s["Calculate Electric Flux"] = equation.CalculateElectricFlux + if equation.CalculateSurfaceCharge is True: + s["Calculate Surface Charge"] = equation.CalculateSurfaceCharge + if equation.ConstantWeights is True: + s["Constant Weights"] = equation.ConstantWeights s["Exec Solver"] = "Always" - s["Stabilize"] = equation.Stabilize - s["Bubbles"] = equation.Bubbles s["Optimize Bandwidth"] = True + if ( + equation.CalculateCapacitanceMatrix is False + and (equation.PotentialDifference != 0.0) + ): + s["Potential Difference"] = equation.PotentialDifference + s["Stabilize"] = equation.Stabilize return s + def _updateElectrostaticSolver(self, equation): + # updates older Electrostatic equations + if not hasattr(equation, "CapacitanceMatrixFilename"): + equation.addProperty( + "App::PropertyFile", + "CapacitanceMatrixFilename", + "Electrostatic", + ( + "File where capacitance matrix is being saved\n" + "Only used if 'CalculateCapacitanceMatrix' is true" + ) + ) + equation.CapacitanceMatrixFilename = "cmatrix.dat" + if not hasattr(equation, "ConstantWeights"): + equation.addProperty( + "App::PropertyBool", + "ConstantWeights", + "Electrostatic", + "Use constant weighting for results" + ) + if not hasattr(equation, "PotentialDifference"): + equation.addProperty( + "App::PropertyFloat", + "PotentialDifference", + "Electrostatic", + ( + "Potential difference in Volt for which capacitance is\n" + "calculated if 'CalculateCapacitanceMatrix' is false" + ) + ) + equation.PotentialDifference = 0.0 + def _handleElectrostaticConstants(self): self._constant( "Permittivity Of Vacuum", - self._getConstant("PermittivityOfVacuum", "T^4*I^2/(L^3*M)") + self._convert(self.constsdef["PermittivityOfVacuum"], "T^4*I^2/(L^3*M)") ) - # https://forum.freecadweb.org/viewtopic.php?f=18&p=400959#p400959 def _handleElectrostaticMaterial(self, bodies): for obj in self._getMember("App::MaterialObject"): @@ -495,6 +672,18 @@ class Writer(object): for name in obj.References[0][1]: if obj.PotentialEnabled: if hasattr(obj, "Potential"): + # Potential was once a float and scaled not fitting SI units + if isinstance(obj.Potential, float): + savePotential = obj.Potential + obj.removeProperty("Potential") + obj.addProperty( + "App::PropertyElectricPotential", + "Potential", + "Parameter", + "Electric Potential" + ) + # scale to match SI units + obj.Potential = savePotential * 1e6 potential = float(obj.Potential.getValueAs("V")) self._boundary(name, "Potential", potential) if obj.PotentialConstant: @@ -516,19 +705,137 @@ class Writer(object): activeIn = equation.References[0][1] else: activeIn = self._getAllBodies() - solverSection = self._getFlux(equation) + solverSection = self._getFluxSolver(equation) for body in activeIn: self._addSolver(body, solverSection) - def _getFlux(self, equation): + def _getFluxSolver(self, equation): s = self._createLinearSolver(equation) - s["Equation"] = "Flux Solver" # equation.Name + # check if we need to update the equation + self._updateFluxSolver(equation) + # output the equation parameters + s["Equation"] = equation.Name s["Procedure"] = sifio.FileAttr("FluxSolver/FluxSolver") - s["Flux Variable"] = equation.FluxVariable + if equation.AverageWithinMaterials is True: + s["Average Within Materials"] = equation.AverageWithinMaterials s["Calculate Flux"] = equation.CalculateFlux + if equation.CalculateFluxAbs is True: + s["Calculate Flux Abs"] = equation.CalculateFluxAbs + if equation.CalculateFluxMagnitude is True: + s["Calculate Flux Magnitude"] = equation.CalculateFluxMagnitude s["Calculate Grad"] = equation.CalculateGrad + if equation.CalculateGradAbs is True: + s["Calculate Grad Abs"] = equation.CalculateGradAbs + if equation.CalculateGradMagnitude is True: + s["Calculate Grad Magnitude"] = equation.CalculateGradMagnitude + if equation.DiscontinuousGalerkin is True: + s["Discontinuous Galerkin"] = equation.DiscontinuousGalerkin + if equation.EnforcePositiveMagnitude is True: + s["Enforce Positive Magnitude"] = equation.EnforcePositiveMagnitude + s["Flux Coefficient"] = equation.FluxCoefficient + s["Flux Variable"] = equation.FluxVariable + s["Stabilize"] = equation.Stabilize return s + def _updateFluxSolver(self, equation): + # updates older Flux equations + if not hasattr(equation, "AverageWithinMaterials"): + equation.addProperty( + "App::PropertyBool", + "AverageWithinMaterials", + "Flux", + ( + "Enforces continuity within the same material\n" + "in the 'Discontinuous Galerkin' discretization" + ) + ) + if hasattr(equation, "Bubbles"): + # Bubbles was removed because it is unused by Elmer for the flux solver + equation.removeProperty("Bubbles") + if not hasattr(equation, "CalculateFluxAbs"): + equation.addProperty( + "App::PropertyBool", + "CalculateFluxAbs", + "Flux", + "Computes absolute of flux vector" + ) + if not hasattr(equation, "CalculateFluxMagnitude"): + equation.addProperty( + "App::PropertyBool", + "CalculateFluxMagnitude", + "Flux", + "Computes magnitude of flux vector field" + ) + if not hasattr(equation, "CalculateGradAbs"): + equation.addProperty( + "App::PropertyBool", + "CalculateGradAbs", + "Flux", + "Computes absolute of gradient field" + ) + if not hasattr(equation, "CalculateGradMagnitude"): + equation.addProperty( + "App::PropertyBool", + "CalculateGradMagnitude", + "Flux", + "Computes magnitude of gradient field" + ) + if not hasattr(equation, "DiscontinuousGalerkin"): + equation.addProperty( + "App::PropertyBool", + "DiscontinuousGalerkin", + "Flux", + ( + "Enable if standard Galerkin approximation leads to\n" + "unphysical results when there are discontinuities" + ) + ) + if not hasattr(equation, "EnforcePositiveMagnitude"): + equation.addProperty( + "App::PropertyBool", + "EnforcePositiveMagnitude", + "Flux", + ( + "If true, negative values of computed magnitude fields\n" + "are a posteriori set to zero." + ) + ) + tempFluxCoefficient = "" + if hasattr(equation, "FluxCoefficient"): + if equation.FluxCoefficient not in flux.COEFFICIENTS: + # was an App::PropertyString and changed to + # App::PropertyEnumeration + tempFluxCoefficient = equation.FluxCoefficient + equation.removeProperty("FluxCoefficient") + if not hasattr(equation, "FluxCoefficient"): + equation.addProperty( + "App::PropertyEnumeration", + "FluxCoefficient", + "Flux", + "Name of proportionality coefficient\nto compute the flux" + ) + equation.FluxCoefficient = flux.COEFFICIENTS + if tempFluxCoefficient: + equation.FluxCoefficient = tempFluxCoefficient + else: + equation.FluxCoefficient = "None" + tempFluxVariable = "" + if hasattr(equation, "FluxVariable"): + if equation.FluxVariable not in flux.VARIABLES: + # was an App::PropertyString and changed to + # App::PropertyEnumeration + tempFluxVariable = equation.FluxVariable + equation.removeProperty("FluxVariable") + equation.addProperty( + "App::PropertyEnumeration", + "FluxVariable", + "Flux", + "Variable name for flux calculation" + ) + equation.FluxVariable = flux.VARIABLES + equation.FluxVariable = tempFluxVariable + + def _handleElectricforce(self): activeIn = [] for equation in self.solver.Group: @@ -542,22 +849,56 @@ class Writer(object): self._addSolver(body, solverSection) def _getElectricforceSolver(self, equation): - s = self._createEmptySolver(equation) + # check if we need to update the equation + self._updateElectricforceSolver(equation) + # output the equation parameters + s = self._createEmptySolver() s["Equation"] = "Electric Force" # equation.Name s["Procedure"] = sifio.FileAttr("ElectricForce/StatElecForce") + s["Exec Solver"] = equation.ExecSolver + s["Stabilize"] = equation.Stabilize return s + def _updateElectricforceSolver(self, equation): + # updates older Electricforce equations + if not hasattr(equation, "ExecSolver"): + equation.addProperty( + "App::PropertyEnumeration", + "ExecSolver", + "Electric Force", + ( + "That solver is only executed after solution converged\n" + "To execute always, change to 'Always'" + ) + ) + equation.ExecSolver = electricforce.SOLVER_EXEC_METHODS + equation.ExecSolver = "After Timestep" + + def _haveMaterialSolid(self): + for obj in self._getMember("App::MaterialObject"): + m = obj.Material + # fluid material always has KinematicViscosity defined + if not ("KinematicViscosity" in m): + return True + return False + def _handleElasticity(self): activeIn = [] for equation in self.solver.Group: if femutils.is_of_type(equation, "Fem::EquationElmerElasticity"): + if not self._haveMaterialSolid(): + raise WriteError( + "The Elasticity equation requires at least one body with a solid material!" + ) if equation.References: activeIn = equation.References[0][1] else: activeIn = self._getAllBodies() solverSection = self._getElasticitySolver(equation) for body in activeIn: - self._addSolver(body, solverSection) + if not self._isBodyMaterialFluid(body): + self._addSolver(body, solverSection) + self._handleElasticityEquation(activeIn, equation) if activeIn: self._handleElasticityConstants() self._handleElasticityBndConditions() @@ -567,23 +908,252 @@ class Writer(object): def _getElasticitySolver(self, equation): s = self._createLinearSolver(equation) - s["Equation"] = equation.Name + # check if we need to update the equation + self._updateElasticitySolver(equation) + # output the equation parameters + s["Equation"] = "Stress Solver" # equation.Name s["Procedure"] = sifio.FileAttr("StressSolve/StressSolver") - s["Variable"] = self._getUniqueVarName("Displacement") - s["Variable DOFs"] = 3 - s["Eigen Analysis"] = equation.DoFrequencyAnalysis - s["Eigen System Values"] = equation.EigenmodesCount - s["Calculate Strains"] = equation.CalculateStrains - s["Calculate Stresses"] = equation.CalculateStresses - s["Calculate Principal"] = equation.CalculatePrincipal - s["Calculate Pangle"] = equation.CalculatePangle - s["Displace mesh"] = False - s["Exec Solver"] = "Always" - s["Stabilize"] = equation.Stabilize - s["Bubbles"] = equation.Bubbles + if equation.CalculateStrains is True: + s["Calculate Strains"] = equation.CalculateStrains + if equation.CalculateStresses is True: + s["Calculate Stresses"] = equation.CalculateStresses + if equation.CalculatePrincipal is True: + s["Calculate Principal"] = equation.CalculatePrincipal + if equation.CalculatePangle is True: + s["Calculate Pangle"] = equation.CalculatePangle + if equation.ConstantBulkSystem is True: + s["Constant Bulk System"] = equation.ConstantBulkSystem + s["Displace mesh"] = equation.DisplaceMesh + s["Eigen Analysis"] = equation.EigenAnalysis + if equation.EigenAnalysis is True: + s["Eigen System Convergence Tolerance"] = \ + equation.EigenSystemTolerance + s["Eigen System Complex"] = equation.EigenSystemComplex + if equation.EigenSystemComputeResiduals is True: + s["Eigen System Compute Residuals"] = equation.EigenSystemComputeResiduals + s["Eigen System Damped"] = equation.EigenSystemDamped + s["Eigen System Max Iterations"] = equation.EigenSystemMaxIterations + s["Eigen System Select"] = equation.EigenSystemSelect + s["Eigen System Values"] = equation.EigenSystemValues + if equation.FixDisplacement is True: + s["Fix Displacement"] = equation.FixDisplacement + s["Geometric Stiffness"] = equation.GeometricStiffness + if equation.Incompressible is True: + s["Incompressible"] = equation.Incompressible + if equation.MaxwellMaterial is True: + s["Maxwell Material"] = equation.MaxwellMaterial + if equation.ModelLumping is True: + s["Model Lumping"] = equation.ModelLumping + if equation.ModelLumping is True: + s["Model Lumping Filename"] = equation.ModelLumpingFilename s["Optimize Bandwidth"] = True + if equation.StabilityAnalysis is True: + s["Stability Analysis"] = equation.StabilityAnalysis + s["Stabilize"] = equation.Stabilize + if equation.UpdateTransientSystem is True: + s["Update Transient System"] = equation.UpdateTransientSystem + s["Variable"] = equation.Variable + s["Variable DOFs"] = 3 return s + def _handleElasticityEquation(self, bodies, equation): + for b in bodies: + # not for bodies with fluid material + if not self._isBodyMaterialFluid(b): + if equation.PlaneStress: + self._equation(b, "Plane Stress", equation.PlaneStress) + + def _updateElasticitySolver(self, equation): + # updates older Elasticity equations + if not hasattr(equation, "Variable"): + equation.addProperty( + "App::PropertyString", + "Variable", + "Elasticity", + ( + "Only change this if 'Incompressible' is set to true\n" + "according to the Elmer manual." + ) + ) + equation.Variable = "Displacement" + if hasattr(equation, "Bubbles"): + # Bubbles was removed because it is unused by Elmer for the stress solver + equation.removeProperty("Bubbles") + if not hasattr(equation, "ConstantBulkSystem"): + equation.addProperty( + "App::PropertyBool", + "ConstantBulkSystem", + "Elasticity", + "See Elmer manual for info" + ) + if not hasattr(equation, "DisplaceMesh"): + equation.addProperty( + "App::PropertyBool", + "DisplaceMesh", + "Elasticity", + ( + "If mesh is deformed by displacement field.\n" + "Set to False for 'Eigen Analysis'." + ) + ) + # DisplaceMesh is true except if DoFrequencyAnalysis is true + equation.DisplaceMesh = True + if hasattr(equation, "DoFrequencyAnalysis"): + if equation.DoFrequencyAnalysis is True: + equation.DisplaceMesh = False + if not hasattr(equation, "EigenAnalysis"): + # DoFrequencyAnalysis was renamed to EigenAnalysis + # to follow the Elmer manual + equation.addProperty( + "App::PropertyBool", + "EigenAnalysis", + "Eigen Values", + "If true, modal analysis" + ) + if hasattr(equation, "DoFrequencyAnalysis"): + equation.EigenAnalysis = equation.DoFrequencyAnalysis + equation.removeProperty("DoFrequencyAnalysis") + if not hasattr(equation, "EigenSystemComplex"): + equation.addProperty( + "App::PropertyBool", + "EigenSystemComplex", + "Eigen Values", + ( + "Should be true if eigen system is complex\n" + "Must be false for a damped eigen value analysis." + ) + ) + equation.EigenSystemComplex = True + if not hasattr(equation, "EigenSystemComputeResiduals"): + equation.addProperty( + "App::PropertyBool", + "EigenSystemComputeResiduals", + "Eigen Values", + "Computes residuals of eigen value system" + ) + if not hasattr(equation, "EigenSystemDamped"): + equation.addProperty( + "App::PropertyBool", + "EigenSystemDamped", + "Eigen Values", + ( + "Set a damped eigen analysis. Can only be\n" + "used if 'Linear Solver Type' is 'Iterative'." + ) + ) + if not hasattr(equation, "EigenSystemMaxIterations"): + equation.addProperty( + "App::PropertyIntegerConstraint", + "EigenSystemMaxIterations", + "Eigen Values", + "Max iterations for iterative eigensystem solver" + ) + equation.EigenSystemMaxIterations = (300, 1, int(1e8), 1) + if not hasattr(equation, "EigenSystemSelect"): + equation.addProperty( + "App::PropertyEnumeration", + "EigenSystemSelect", + "Eigen Values", + "Which eigenvalues are computed" + ) + equation.EigenSystemSelect = elasticity.EIGEN_SYSTEM_SELECT + equation.EigenSystemSelect = "Smallest Magnitude" + if not hasattr(equation, "EigenSystemTolerance"): + equation.addProperty( + "App::PropertyFloat", + "EigenSystemTolerance", + "Eigen Values", + ( + "Convergence tolerance for iterative eigensystem solve\n" + "Default is 100 times the 'Linear Tolerance'" + ) + ) + equation.setExpression("EigenSystemTolerance", str(100 * equation.LinearTolerance)) + if not hasattr(equation, "EigenSystemValues"): + # EigenmodesCount was renamed to EigenSystemValues + # to follow the Elmer manual + equation.addProperty( + "App::PropertyInteger", + "EigenSystemValues", + "Eigen Values", + "Number of lowest eigen modes" + ) + if hasattr(equation, "EigenmodesCount"): + equation.EigenSystemValues = equation.EigenmodesCount + equation.removeProperty("EigenmodesCount") + if not hasattr(equation, "FixDisplacement"): + equation.addProperty( + "App::PropertyBool", + "FixDisplacement", + "Elasticity", + "If displacements or forces are set,\nthereby model lumping is used" + ) + if not hasattr(equation, "GeometricStiffness"): + equation.addProperty( + "App::PropertyBool", + "GeometricStiffness", + "Elasticity", + "Consider geometric stiffness" + ) + if not hasattr(equation, "Incompressible"): + equation.addProperty( + "App::PropertyBool", + "Incompressible", + "Elasticity", + ( + "Computation of incompressible material in connection\n" + "with viscoelastic Maxwell material and a custom 'Variable'" + ) + ) + if not hasattr(equation, "MaxwellMaterial"): + equation.addProperty( + "App::PropertyBool", + "MaxwellMaterial", + "Elasticity", + "Compute viscoelastic material model" + ) + if not hasattr(equation, "ModelLumping"): + equation.addProperty( + "App::PropertyBool", + "ModelLumping", + "Elasticity", + "Use model lumping" + ) + if not hasattr(equation, "ModelLumpingFilename"): + equation.addProperty( + "App::PropertyFile", + "ModelLumpingFilename", + "Elasticity", + "File to save results from model lumping to" + ) + if not hasattr(equation, "PlaneStress"): + equation.addProperty( + "App::PropertyBool", + "PlaneStress", + "Equation", + ( + "Computes solution according to plane\nstress situation.\n" + "Applies only for 2D geometry." + ) + ) + if not hasattr(equation, "StabilityAnalysis"): + equation.addProperty( + "App::PropertyBool", + "StabilityAnalysis", + "Elasticity", + ( + "If true, 'Eigen Analysis' is stability analysis.\n" + "Otherwise modal analysis is performed." + ) + ) + if not hasattr(equation, "UpdateTransientSystem"): + equation.addProperty( + "App::PropertyBool", + "UpdateTransientSystem", + "Elasticity", + "See Elmer manual for info" + ) + def _handleElasticityConstants(self): pass @@ -641,7 +1211,7 @@ class Writer(object): obj = self._getSingleMember("Fem::ConstraintSelfWeight") if obj is not None: for name in bodies: - gravity = self._getConstant("Gravity", "L/T^2") + gravity = self._convert(self.constsdef["Gravity"], "L/T^2") m = self._getBodyMaterial(name).Material densityQuantity = Units.Quantity(m["Density"]) @@ -663,8 +1233,12 @@ class Writer(object): def _getBodyMaterial(self, name): for obj in self._getMember("App::MaterialObject"): - if not obj.References or name in obj.References[0][1]: + # we can have e.g. the case there are 2 bodies and 2 materials + # body 2 has material 2 as reference while material 1 has no reference + # therefore we must not return a material when it is not referenced + if obj.References and (name in obj.References[0][1]): return obj + # 'name' was not in the reference of any material return None def _handleElasticityMaterial(self, bodies): @@ -673,7 +1247,7 @@ class Writer(object): density_needed = False for equation in self.solver.Group: if femutils.is_of_type(equation, "Fem::EquationElmerElasticity"): - if equation.DoFrequencyAnalysis is True: + if equation.EigenAnalysis is True: density_needed = True break # there could be a second equation without frequency gravObj = self._getSingleMember("Fem::ConstraintSelfWeight") @@ -685,7 +1259,7 @@ class Writer(object): refTemp = self._getFromUi(tempObj.initialTemperature, "K", "O") for name in bodies: self._material(name, "Reference Temperature", refTemp) - # get the material data for all boddies + # get the material data for all bodies for obj in self._getMember("App::MaterialObject"): m = obj.Material refs = ( @@ -694,6 +1268,18 @@ class Writer(object): else self._getAllBodies() ) for name in (n for n in refs if n in bodies): + # don't evaluate fluid material + if self._isBodyMaterialFluid(name): + break + if not "YoungsModulus" in m: + Console.PrintMessage("m: {}\n".format(m)) + # it is no fluid but also no solid + # -> user set no material reference at all + # that now material is known + raise WriteError( + "There are two or more materials with empty references.\n\n" + "Set for the materials to what solid they belong to.\n" + ) if density_needed is True: self._material( name, "Density", @@ -725,46 +1311,131 @@ class Writer(object): youngsModulus *= 1e3 return youngsModulus - def _isMaterialFlow(self, body): - m = self._getBodyMaterial(body).Material - return "KinematicViscosity" in m + def _haveMaterialFluid(self): + for obj in self._getMember("App::MaterialObject"): + m = obj.Material + # fluid material always has KinematicViscosity defined + if "KinematicViscosity" in m: + return True + return False + + def _isBodyMaterialFluid(self, body): + # we can have the case that a body has no assigned material + # then assume it is a solid + if self._getBodyMaterial(body) is not None: + m = self._getBodyMaterial(body).Material + return "KinematicViscosity" in m + return False def _handleFlow(self): activeIn = [] for equation in self.solver.Group: if femutils.is_of_type(equation, "Fem::EquationElmerFlow"): + if not self._haveMaterialFluid(): + raise WriteError( + "The Flow equation requires at least one body with a fluid material!" + ) if equation.References: activeIn = equation.References[0][1] else: activeIn = self._getAllBodies() solverSection = self._getFlowSolver(equation) for body in activeIn: - if self._isMaterialFlow(body): + if self._isBodyMaterialFluid(body): self._addSolver(body, solverSection) + self._handleFlowEquation(activeIn, equation) if activeIn: self._handleFlowConstants() self._handleFlowBndConditions() + self._handleFlowInitialPressure(activeIn) self._handleFlowInitialVelocity(activeIn) # self._handleFlowInitial(activeIn) # self._handleFlowBodyForces(activeIn) self._handleFlowMaterial(activeIn) - self._handleFlowEquation(activeIn) def _getFlowSolver(self, equation): + # check if we need to update the equation + self._updateFlowSolver(equation) + # output the equation parameters s = self._createNonlinearSolver(equation) s["Equation"] = "Navier-Stokes" - # s["Equation"] = equation.Name s["Procedure"] = sifio.FileAttr("FlowSolve/FlowSolver") + if equation.DivDiscretization is True: + s["Div Discretization"] = equation.DivDiscretization s["Exec Solver"] = "Always" + if equation.FlowModel != "Full": + s["Flow Model"] = equation.FlowModel + if equation.GradpDiscretization is True: + s["Gradp Discretization"] = equation.GradpDiscretization s["Stabilize"] = equation.Stabilize - s["Bubbles"] = equation.Bubbles s["Optimize Bandwidth"] = True + if equation.Variable != "Flow Solution[Velocity:3 Pressure:1]": + s["Variable"] = equation.Variable return s def _handleFlowConstants(self): - gravity = self._getConstant("Gravity", "L/T^2") + gravity = self._convert(self.constsdef["Gravity"], "L/T^2") self._constant("Gravity", (0.0, -1.0, 0.0, gravity)) + def _updateFlowSolver(self, equation): + # updates older Flow equations + if not hasattr(equation, "Convection"): + equation.addProperty( + "App::PropertyEnumeration", + "Convection", + "Equation", + "Type of convection to be used" + ) + equation.Convection = flow.CONVECTION_TYPE + equation.Convection = "Computed" + if not hasattr(equation, "DivDiscretization"): + equation.addProperty( + "App::PropertyBool", + "DivDiscretization", + "Flow", + ( + "Set to true for incompressible flow for more stable\n" + "discretization when Reynolds number increases" + ) + ) + if not hasattr(equation, "FlowModel"): + equation.addProperty( + "App::PropertyEnumeration", + "FlowModel", + "Flow", + "Flow model to be used" + ) + equation.FlowModel = flow.FLOW_MODEL + equation.FlowModel = "Full" + if not hasattr(equation, "GradpDiscretization"): + equation.addProperty( + "App::PropertyBool", + "GradpDiscretization", + "Flow", + ( + "If true pressure Dirichlet boundary conditions can be used.\n" + "Also mass flux is available as a natural boundary condition." + ) + ) + if not hasattr(equation, "MagneticInduction"): + equation.addProperty( + "App::PropertyBool", + "MagneticInduction", + "Equation", + ( + "Magnetic induction equation will be solved\n" + "along with the Navier-Stokes equations" + ) + ) + if not hasattr(equation, "Variable"): + equation.addProperty( + "App::PropertyString", + "Variable", + "Flow", + "Only for a 2D model change the '3' to '2'" + ) + equation.Variable = "Flow Solution[Velocity:3 Pressure:1]" + def _handleFlowMaterial(self, bodies): tempObj = self._getSingleMember("Fem::ConstraintInitialTemperature") if tempObj is not None: @@ -811,19 +1482,63 @@ class Writer(object): name, "Compressibility Model", m["CompressibilityModel"]) + def _outputInitialPressure(self, obj, name): + # initial pressure only makes sense for fluid material + if self._isBodyMaterialFluid(name): + pressure = float(obj.Pressure.getValueAs("Pa")) + self._initial(name, "Pressure", pressure) + + def _handleFlowInitialPressure(self, bodies): + initialPressures = self._getMember("Fem::ConstraintInitialPressure") + for obj in initialPressures: + if obj.References: + for name in obj.References[0][1]: + self._outputInitialPressure(obj, name) + self._handled(obj) + else: + # if there is only one initial velocity without a reference + # add it to all fluid bodies + if len(initialPressures) == 1: + for name in bodies: + self._outputInitialPressure(obj, name) + else: + raise WriteError( + "Several initial pressures found without reference to a body.\n" + "Please set a body for each initial pressure." + ) + self._handled(obj) + + def _outputInitialVelocity(self, obj, name): + # flow only makes sense for fluid material + if self._isBodyMaterialFluid(name): + if obj.VelocityXEnabled: + velocity = self._getFromUi(obj.VelocityX, "m/s", "L/T") + self._initial(name, "Velocity 1", velocity) + if obj.VelocityYEnabled: + velocity = self._getFromUi(obj.VelocityY, "m/s", "L/T") + self._initial(name, "Velocity 2", velocity) + if obj.VelocityZEnabled: + velocity = self._getFromUi(obj.VelocityZ, "m/s", "L/T") + self._initial(name, "Velocity 3", velocity) + def _handleFlowInitialVelocity(self, bodies): - obj = self._getSingleMember("Fem::ConstraintInitialFlowVelocity") - if obj is not None: - for name in bodies: - if obj.VelocityXEnabled: - velocity = self._getFromUi(obj.VelocityX, "m/s", "L/T") - self._initial(name, "Velocity 1", velocity) - if obj.VelocityYEnabled: - velocity = self._getFromUi(obj.VelocityY, "m/s", "L/T") - self._initial(name, "Velocity 2", velocity) - if obj.VelocityZEnabled: - velocity = self._getFromUi(obj.VelocityZ, "m/s", "L/T") - self._initial(name, "Velocity 3", velocity) + initialVelocities = self._getMember("Fem::ConstraintInitialFlowVelocity") + for obj in initialVelocities: + if obj.References: + for name in obj.References[0][1]: + self._outputInitialVelocity(obj, name) + self._handled(obj) + else: + # if there is only one initial velocity without a reference + # add it to all fluid bodies + if len(initialVelocities) == 1: + for name in bodies: + self._outputInitialVelocity(obj, name) + else: + raise WriteError( + "Several initial velocities found without reference to a body.\n" + "Please set a body for each initial velocity." + ) self._handled(obj) def _handleFlowBndConditions(self): @@ -842,19 +1557,72 @@ class Writer(object): if obj.NormalToBoundary: self._boundary(name, "Normal-Tangential Velocity", True) self._handled(obj) + for obj in self._getMember("Fem::ConstraintPressure"): + if obj.References: + for name in obj.References[0][1]: + pressure = self._getFromUi(obj.Pressure, "MPa", "M/(L*T^2)") + if obj.Reversed: + pressure *= -1 + self._boundary(name, "External Pressure", pressure) + self._handled(obj) - def _handleFlowEquation(self, bodies): + def _handleFlowEquation(self, bodies, equation): for b in bodies: - self._equation(b, "Convection", "Computed") + # not for bodies with solid material + if self._isBodyMaterialFluid(b): + if equation.Convection != "None": + self._equation(b, "Convection", equation.Convection) + if equation.MagneticInduction is True: + self._equation(b, "Magnetic Induction", equation.MagneticInduction) - def _createEmptySolver(self, equation): + def _createEmptySolver(self): s = sifio.createSection(sifio.SOLVER) return s + def _hasExpression(self, equation): + obj = None + exp = None + for (obj, exp) in equation.ExpressionEngine: + if obj == equation: + return exp + return None + + def _updateLinearSolver(self, equation): + if self._hasExpression(equation) != equation.LinearTolerance: + equation.setExpression("LinearTolerance", str(equation.LinearTolerance)) + if self._hasExpression(equation) != equation.SteadyStateTolerance: + equation.setExpression("SteadyStateTolerance", str(equation.SteadyStateTolerance)) + if equation.BiCGstablDegree == 0: + equation.BiCGstablDegree = 2 + if not hasattr(equation, "LinearSystemSolverDisabled"): + equation.addProperty( + "App::PropertyBool", + "LinearSystemSolverDisabled", + "Linear System", + ( + "Disable the linear system.\n" + "Only use for special cases\n" + "and consult the Elmer docs." + ) + ) + if not hasattr(equation, "IdrsParameter"): + equation.addProperty( + "App::PropertyIntegerConstraint", + "IdrsParameter", + "Linear System", + "Parameter for iterative method 'Idrs'" + ) + equation.IdrsParameter = (2, 1, 10, 1) + def _createLinearSolver(self, equation): + # first check if we have to update + self._updateLinearSolver(equation) + # write the solver s = sifio.createSection(sifio.SOLVER) s.priority = equation.Priority s["Linear System Solver"] = equation.LinearSolverType + if equation.LinearSystemSolverDisabled is True: + s["Linear System Solver Disabled"] = equation.LinearSystemSolverDisabled if equation.LinearSolverType == "Direct": s["Linear System Direct Method"] = \ equation.LinearDirectMethod @@ -864,6 +1632,9 @@ class Writer(object): if equation.LinearIterativeMethod == "BiCGStabl": s["BiCGstabl polynomial degree"] = \ equation.BiCGstablDegree + if equation.LinearIterativeMethod == "Idrs": + s["Idrs Parameter"] = \ + equation.IdrsParameter s["Linear System Max Iterations"] = \ equation.LinearIterations s["Linear System Convergence Tolerance"] = \ @@ -877,8 +1648,21 @@ class Writer(object): s["Linear System Precondition Recompute"] = 1 return s + def _updateNonlinearSolver(self, equation): + if self._hasExpression(equation) != equation.NonlinearTolerance: + equation.setExpression("NonlinearTolerance", str(equation.NonlinearTolerance)) + if self._hasExpression(equation) != equation.NonlinearNewtonAfterTolerance: + equation.setExpression( + "NonlinearNewtonAfterTolerance", + str(equation.NonlinearNewtonAfterTolerance) + ) + def _createNonlinearSolver(self, equation): + # first check if we have to update + self._updateNonlinearSolver(equation) + # write the linear solver s = self._createLinearSolver(equation) + # write the nonlinear solver s["Nonlinear System Max Iterations"] = \ equation.NonlinearIterations s["Nonlinear System Convergence Tolerance"] = \ @@ -928,6 +1712,10 @@ class Writer(object): def _addOutputSolver(self): s = sifio.createSection(sifio.SOLVER) + # Since FreeCAD meshes are in mm we let Elmer scale it + # _handleSimulation(self). + # To get it back in the original size we let Elmer scale it back + s["Coordinate Scaling Revert"] = True s["Equation"] = "ResultOutput" s["Exec Solver"] = "After simulation" s["Procedure"] = sifio.FileAttr("ResultOutputSolve/ResultOutputSolver") diff --git a/src/Mod/Fem/femsolver/settings.py b/src/Mod/Fem/femsolver/settings.py index 7ffd0ab82f..533ee485e5 100644 --- a/src/Mod/Fem/femsolver/settings.py +++ b/src/Mod/Fem/femsolver/settings.py @@ -87,14 +87,16 @@ def get_binary(name): Return the specific path set by the user in FreeCADs settings/parameter system if set or the default binary name if no specific path is set. If no path was found because the solver *name* is not supported ``None`` is - returned. This method does not check whether the binary actually exists - and is callable. + returned. + This method does not check whether the binary actually exists and is callable. + That check is done in DlgSettingsFem_Solver_Imp.cpp :param name: solver id as a ``str`` (see :mod:`femsolver.settings`) """ if name in _SOLVER_PARAM: binary = _SOLVER_PARAM[name].get_binary() - FreeCAD.Console.PrintMessage('Solver binary path: {} \n'.format(binary)) + if binary is not None: + FreeCAD.Console.PrintMessage('Solver binary path: {} \n'.format(binary)) return binary else: FreeCAD.Console.PrintError( @@ -104,6 +106,7 @@ def get_binary(name): ) return None + def get_cores(name): """ Read number of CPU cores for solver *name* honoring user settings. @@ -113,10 +116,6 @@ def get_cores(name): """ if name in _SOLVER_PARAM: cores = _SOLVER_PARAM[name].get_cores() - FreeCAD.Console.PrintMessage( - "Number of CPU cores to be used for the solvier run: {} \n" - .format(cores) - ) return cores else: FreeCAD.Console.PrintError( @@ -236,11 +235,12 @@ class _SolverDlg(object): "The binary has not been found. Full binary search path: {}\n" .format(binary) ) - FreeCAD.Console.PrintLog("Solver binary found path: {}\n".format(the_found_binary)) + else: + FreeCAD.Console.PrintLog("Found solver binary path: {}\n".format(the_found_binary)) return the_found_binary def get_cores(self): - cores = str(self.param_group.GetInt("UseNumberOfCores")) + cores = self.param_group.GetInt("UseNumberOfCores") return cores def get_write_comments(self): diff --git a/src/Mod/Fem/femsolver/solver_taskpanel.py b/src/Mod/Fem/femsolver/solver_taskpanel.py index a399ab843d..f64ee9c522 100644 --- a/src/Mod/Fem/femsolver/solver_taskpanel.py +++ b/src/Mod/Fem/femsolver/solver_taskpanel.py @@ -240,6 +240,9 @@ class ControlWidget(QtGui.QWidget): # Solver status log self._statusEdt = QtGui.QPlainTextEdit() self._statusEdt.setReadOnly(True) + # for the log we need a certain height + # set it so to almost match the size of the CCX solver panel + self._statusEdt.setMinimumHeight(300) # Elapsed time indicator timeHeaderLbl = QtGui.QLabel(self.tr("Elapsed Time:")) diff --git a/src/Mod/Fem/femsolver/z88/solver.py b/src/Mod/Fem/femsolver/z88/solver.py index 8f223cde73..089a3198b3 100644 --- a/src/Mod/Fem/femsolver/z88/solver.py +++ b/src/Mod/Fem/femsolver/z88/solver.py @@ -78,7 +78,27 @@ class Proxy(solverbase.Proxy): return True def edit(self, directory): - pattern = os.path.join(directory, "*.txt") + pattern = os.path.join(directory, "z88i1.txt") + FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + f = glob.glob(pattern)[0] + FemGui.open(f) + pattern = os.path.join(directory, "z88i2.txt") + FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + f = glob.glob(pattern)[0] + FemGui.open(f) + pattern = os.path.join(directory, "z88i5.txt") + FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + f = glob.glob(pattern)[0] + FemGui.open(f) + pattern = os.path.join(directory, "z88man.txt") + FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + f = glob.glob(pattern)[0] + FemGui.open(f) + pattern = os.path.join(directory, "z88mat.txt") + FreeCAD.Console.PrintMessage("{}\n".format(pattern)) + f = glob.glob(pattern)[0] + FemGui.open(f) + pattern = os.path.join(directory, "z88elp.txt") FreeCAD.Console.PrintMessage("{}\n".format(pattern)) f = glob.glob(pattern)[0] FemGui.open(f) diff --git a/src/Mod/Fem/femsolver/z88/tasks.py b/src/Mod/Fem/femsolver/z88/tasks.py index 0a0b15c4cc..6ba3fa968e 100644 --- a/src/Mod/Fem/femsolver/z88/tasks.py +++ b/src/Mod/Fem/femsolver/z88/tasks.py @@ -104,7 +104,9 @@ class Solve(run.Solve): self.pushStatus("Get solver binary...\n") binary = settings.get_binary("Z88") if binary is None: - self.fail() # a print has been made in settings module + self.pushStatus("Error: The z88r binary has not been found!") + self.fail() + return prefs = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Fem/Z88") solver = SOLVER_TYPES diff --git a/src/Mod/Fem/femsolver/z88/writer.py b/src/Mod/Fem/femsolver/z88/writer.py index 9b400f8851..d9a62926e1 100644 --- a/src/Mod/Fem/femsolver/z88/writer.py +++ b/src/Mod/Fem/femsolver/z88/writer.py @@ -292,13 +292,13 @@ class FemInputWriterZ88(writerbase.FemInputWriter): MaxGS = prefs.GetInt("MaxGS", 100000000) MaxKOI = prefs.GetInt("MaxKOI", 2800000) global z88_dyn_template - templateArray = z88_dyn_template.splitlines() + template_array = z88_dyn_template.splitlines() output = "" - for line in templateArray: + for line in template_array: if line.find("MAXGS") > -1: - line = " MAXGS " + str(MaxGS) + line = " MAXGS {}".format(MaxGS) if line.find("MAXKOI") > -1: - line = " MAXKOI " + str(MaxKOI) + line = " MAXKOI {}".format(MaxKOI) output += line + "\n" solver_parameter_file_path = self.file_name + ".dyn" diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py b/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py new file mode 100644 index 0000000000..96b724d363 --- /dev/null +++ b/src/Mod/Fem/femtaskpanels/task_constraint_bodyheatsource.py @@ -0,0 +1,121 @@ +# *************************************************************************** +# * Copyright (c) 2022 Uwe Stöhr * +# * * +# * 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 constraint body heat source task panel for the document object" +__author__ = "Uwe Stöhr" +__url__ = "https://www.freecadweb.org" + +## @package task_constraint_bodyheatsource +# \ingroup FEM +# \brief task panel for constraint bodyheatsource object + +import FreeCAD +import FreeCADGui + +from femguiutils import selection_widgets + +from femtools import femutils +from femtools import membertools + + +class _TaskPanel(object): + + def __init__(self, obj): + self._obj = obj + + self._paramWidget = FreeCADGui.PySideUic.loadUi( + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/BodyHeatSource.ui") + self._initParamWidget() + + # geometry selection widget + # start with Solid in list! + self._selectionWidget = selection_widgets.GeometryElementsSelection( + obj.References, + ["Solid", "Face"], + True, + False + ) + + # form made from param and selection widget + self.form = [self._paramWidget, self._selectionWidget] + + analysis = obj.getParentGroup() + self._mesh = None + self._part = None + if analysis is not None: + self._mesh = membertools.get_single_member(analysis, "Fem::FemMeshObject") + if self._mesh is not None: + self._part = femutils.get_part_to_mesh(self._mesh) + self._partVisible = None + self._meshVisible = None + + def open(self): + if self._mesh is not None and self._part is not None: + self._meshVisible = self._mesh.ViewObject.isVisible() + self._partVisible = self._part.ViewObject.isVisible() + self._mesh.ViewObject.hide() + self._part.ViewObject.show() + + def reject(self): + self._restoreVisibility() + FreeCADGui.ActiveDocument.resetEdit() + return True + + def accept(self): + if self._obj.References != self._selectionWidget.references: + self._obj.References = self._selectionWidget.references + self._applyWidgetChanges() + self._obj.Document.recompute() + FreeCADGui.ActiveDocument.resetEdit() + self._restoreVisibility() + return True + + def _restoreVisibility(self): + if self._mesh is not None and self._part is not None: + if self._meshVisible: + self._mesh.ViewObject.show() + else: + self._mesh.ViewObject.hide() + if self._partVisible: + self._part.ViewObject.show() + else: + self._part.ViewObject.hide() + + def _initParamWidget(self): + self._paramWidget.bodyheatQSB.setProperty( + 'value', self._obj.HeatSource) + self._paramWidget.bodyheatQSB.setProperty("unit", "W/kg") + FreeCADGui.ExpressionBinding(self._paramWidget.bodyheatQSB).bind(self._obj, "HeatSource") + + def _applyWidgetChanges(self): + bodyheat = None + try: + bodyheat = self._paramWidget.bodyheatQSB.property('value').getValueAs("W/kg") + except ValueError: + FreeCAD.Console.PrintMessage( + "Wrong input. Not recognised input: '{}' " + "Body heat has not been set.\n" + .format(self._paramWidget.bodyheatQSB.text()) + ) + if bodyheat is not None: + self._obj.HeatSource = float(bodyheat) diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py b/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py index 8cac07b7a1..27d13abc17 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_electrostaticpotential.py @@ -42,12 +42,23 @@ class _TaskPanel(object): def __init__(self, obj): self._obj = obj - self._refWidget = selection_widgets.BoundarySelector() - self._refWidget.setReferences(obj.References) + self._paramWidget = FreeCADGui.PySideUic.loadUi( FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/ElectrostaticPotential.ui") self._initParamWidget() - self.form = [self._refWidget, self._paramWidget] + + # geometry selection widget + # start with Solid in list! + self._selectionWidget = selection_widgets.GeometryElementsSelection( + obj.References, + ["Solid", "Face", "Edge", "Vertex"], + True, + False + ) + + # form made from param and selection widget + self.form = [self._paramWidget, self._selectionWidget] + analysis = obj.getParentGroup() self._mesh = None self._part = None @@ -71,8 +82,8 @@ class _TaskPanel(object): return True def accept(self): - if self._obj.References != self._refWidget.references(): - self._obj.References = self._refWidget.references() + if self._obj.References != self._selectionWidget.references: + self._obj.References = self._selectionWidget.references self._applyWidgetChanges() self._obj.Document.recompute() FreeCADGui.ActiveDocument.resetEdit() @@ -93,6 +104,8 @@ class _TaskPanel(object): def _initParamWidget(self): self._paramWidget.potentialQSB.setProperty( 'value', self._obj.Potential) + FreeCADGui.ExpressionBinding( + self._paramWidget.potentialQSB).bind(self._obj, "Potential") self._paramWidget.potentialBox.setChecked( not self._obj.PotentialEnabled) self._paramWidget.potentialConstantBox.setChecked( @@ -115,8 +128,6 @@ class _TaskPanel(object): self._obj.PotentialEnabled = \ not self._paramWidget.potentialBox.isChecked() if self._obj.PotentialEnabled: - # if the input widget shows not a green hook, but the user presses ok - # we could run into a syntax error on getting the quantity potential = None try: potential = self._paramWidget.potentialQSB.property('value') diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py b/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py index 3669c63bd3..7e98729b47 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_flowvelocity.py @@ -42,13 +42,24 @@ class _TaskPanel(object): def __init__(self, obj): self._obj = obj - self._refWidget = selection_widgets.BoundarySelector() - self._refWidget.setReferences(obj.References) + self._paramWidget = FreeCADGui.PySideUic.loadUi( FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/FlowVelocity.ui" ) self._initParamWidget() - self.form = [self._refWidget, self._paramWidget] + + # geometry selection widget + # start with Solid in list! + self._selectionWidget = selection_widgets.GeometryElementsSelection( + obj.References, + ["Solid", "Face", "Edge", "Vertex"], + True, + False + ) + + # form made from param and selection widget + self.form = [self._paramWidget, self._selectionWidget] + analysis = obj.getParentGroup() self._mesh = None self._part = None @@ -72,8 +83,8 @@ class _TaskPanel(object): return True def accept(self): - if self._obj.References != self._refWidget.references(): - self._obj.References = self._refWidget.references() + if self._obj.References != self._selectionWidget.references: + self._obj.References = self._selectionWidget.references self._applyWidgetChanges() self._obj.Document.recompute() FreeCADGui.ActiveDocument.resetEdit() diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py b/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py index d30b0254eb..91fafc536a 100644 --- a/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py +++ b/src/Mod/Fem/femtaskpanels/task_constraint_initialflowvelocity.py @@ -34,6 +34,7 @@ import FreeCAD import FreeCADGui from FreeCAD import Units +from femguiutils import selection_widgets from femtools import femutils from femtools import membertools @@ -42,10 +43,23 @@ class _TaskPanel(object): def __init__(self, obj): self._obj = obj + self._paramWidget = FreeCADGui.PySideUic.loadUi( FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialFlowVelocity.ui") self._initParamWidget() - self.form = [self._paramWidget] + + # geometry selection widget + # start with Solid in list! + self._selectionWidget = selection_widgets.GeometryElementsSelection( + obj.References, + ["Solid", "Face"], + True, + False + ) + + # form made from param and selection widget + self.form = [self._paramWidget, self._selectionWidget] + analysis = obj.getParentGroup() self._mesh = None self._part = None @@ -69,6 +83,8 @@ class _TaskPanel(object): return True def accept(self): + if self._obj.References != self._selectionWidget.references: + self._obj.References = self._selectionWidget.references self._applyWidgetChanges() self._obj.Document.recompute() FreeCADGui.ActiveDocument.resetEdit() diff --git a/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py b/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py new file mode 100644 index 0000000000..1a30e57b47 --- /dev/null +++ b/src/Mod/Fem/femtaskpanels/task_constraint_initialpressure.py @@ -0,0 +1,120 @@ +# *************************************************************************** +# * Copyright (c) 2022 Uwe Stöhr * +# * * +# * 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 constraint initial pressure task panel for the document object" +__author__ = "Uwe Stöhr" +__url__ = "https://www.freecadweb.org" + +## @package task_constraint_initialpressure +# \ingroup FEM +# \brief task panel for constraint initial pressure object + +import FreeCAD +import FreeCADGui +from femguiutils import selection_widgets + +from femtools import femutils +from femtools import membertools + + +class _TaskPanel(object): + + def __init__(self, obj): + self._obj = obj + + self._paramWidget = FreeCADGui.PySideUic.loadUi( + FreeCAD.getHomePath() + "Mod/Fem/Resources/ui/InitialPressure.ui") + self._initParamWidget() + + # geometry selection widget + # start with Solid in list! + self._selectionWidget = selection_widgets.GeometryElementsSelection( + obj.References, + ["Solid", "Face"], + True, + False + ) + + # form made from param and selection widget + self.form = [self._paramWidget, self._selectionWidget] + + analysis = obj.getParentGroup() + self._mesh = None + self._part = None + if analysis is not None: + self._mesh = membertools.get_single_member(analysis, "Fem::FemMeshObject") + if self._mesh is not None: + self._part = femutils.get_part_to_mesh(self._mesh) + self._partVisible = None + self._meshVisible = None + + def open(self): + if self._mesh is not None and self._part is not None: + self._meshVisible = self._mesh.ViewObject.isVisible() + self._partVisible = self._part.ViewObject.isVisible() + self._mesh.ViewObject.hide() + self._part.ViewObject.show() + + def reject(self): + self._restoreVisibility() + FreeCADGui.ActiveDocument.resetEdit() + return True + + def accept(self): + if self._obj.References != self._selectionWidget.references: + self._obj.References = self._selectionWidget.references + self._applyWidgetChanges() + self._obj.Document.recompute() + FreeCADGui.ActiveDocument.resetEdit() + self._restoreVisibility() + return True + + def _restoreVisibility(self): + if self._mesh is not None and self._part is not None: + if self._meshVisible: + self._mesh.ViewObject.show() + else: + self._mesh.ViewObject.hide() + if self._partVisible: + self._part.ViewObject.show() + else: + self._part.ViewObject.hide() + + def _initParamWidget(self): + self._paramWidget.pressureQSB.setProperty( + 'value', self._obj.Pressure) + FreeCADGui.ExpressionBinding( + self._paramWidget.pressureQSB).bind(self._obj, "Pressure") + + def _applyWidgetChanges(self): + pressure = None + try: + pressure = self._paramWidget.pressureQSB.property('value') + except ValueError: + FreeCAD.Console.PrintMessage( + "Wrong input. Not recognised input: '{}' " + "Pressure has not been set.\n" + .format(self._paramWidget.pressureQSB.text()) + ) + if pressure is not None: + self._obj.Pressure = pressure diff --git a/src/Mod/Fem/femtaskpanels/task_material_common.py b/src/Mod/Fem/femtaskpanels/task_material_common.py index 8568122972..a9f6b21487 100644 --- a/src/Mod/Fem/femtaskpanels/task_material_common.py +++ b/src/Mod/Fem/femtaskpanels/task_material_common.py @@ -31,7 +31,6 @@ __url__ = "https://www.freecadweb.org" # \brief FreeCAD FEM _ViewProviderFemMaterial # \brief task panel for common material object -import sys from PySide import QtCore from PySide import QtGui @@ -42,8 +41,7 @@ from FreeCAD import Units from femguiutils import selection_widgets -if sys.version_info.major >= 3: - unicode = str +unicode = str class _TaskPanel: @@ -138,11 +136,13 @@ class _TaskPanel: self.toggleInputFieldsReadOnly() # hide some groupBox according to material category + # note: input_fd_vol_expansion_coefficient is currently not used + # it might be used in future for solids self.parameterWidget.label_category.setText(self.obj.Category) if self.obj.Category == "Fluid": self.parameterWidget.groupBox_mechanical.setVisible(0) - self.parameterWidget.label_expansion_coefficient.setVisible(0) - self.parameterWidget.input_fd_expansion_coefficient.setVisible(0) + self.parameterWidget.label_vol_expansion_coefficient.setVisible(0) + self.parameterWidget.input_fd_vol_expansion_coefficient.setVisible(0) else: self.parameterWidget.groupBox_fluidic.setVisible(0) self.parameterWidget.label_vol_expansion_coefficient.setVisible(0) @@ -265,10 +265,9 @@ class _TaskPanel: # choose material **************************************************************************** def get_material_card(self, material): for a_mat in self.materials: + # check if every item of the current material fits to a known material card + # if all items were found we know it is the right card unmatched_items = set(self.materials[a_mat].items()) ^ set(material.items()) - # print(a_mat + " --> unmatched_items = " + str(len(unmatched_items))) - # if len(unmatched_items) < 4: - # print(unmatched_items) if len(unmatched_items) == 0: return a_mat return "" @@ -475,7 +474,7 @@ class _TaskPanel: "ThermalExpansionCoefficient not found in {}\n" .format(self.material["Name"]) ) - self.material["VolumetricThermalExpansionCoefficient"] = "0 1/K" + self.material["ThermalExpansionCoefficient"] = "0 1/K" if "VolumetricThermalExpansionCoefficient" in self.material: # unit type VolumetricThermalExpansionCoefficient is ThermalExpansionCoefficient vol_ther_ex_co = self.material["VolumetricThermalExpansionCoefficient"] @@ -487,10 +486,9 @@ class _TaskPanel: ) self.material["VolumetricThermalExpansionCoefficient"] = "0 1/K" else: - if "ThermalExpansionCoefficient" in self.material: - the_index = "VolumetricThermalExpansionCoefficient" # line was to long - self.material[the_index] = self.material["ThermalExpansionCoefficient"] - else: + # as fallback only add VolumetricThermalExpansionCoefficient if there is no + # ThermalExpansionCoefficient + if "ThermalExpansionCoefficient" not in self.material: self.material["VolumetricThermalExpansionCoefficient"] = "0 1/K" # Thermal properties if "ThermalConductivity" in self.material: diff --git a/src/Mod/Fem/femtaskpanels/task_material_reinforced.py b/src/Mod/Fem/femtaskpanels/task_material_reinforced.py index 03db15f395..59fa2986d5 100644 --- a/src/Mod/Fem/femtaskpanels/task_material_reinforced.py +++ b/src/Mod/Fem/femtaskpanels/task_material_reinforced.py @@ -29,7 +29,6 @@ __url__ = "https://www.freecadweb.org" # \ingroup FEM # \brief task panel for reinforced material object -import sys from PySide import QtCore from PySide import QtGui @@ -37,8 +36,7 @@ import FreeCAD import FreeCADGui -if sys.version_info.major >= 3: - unicode = str +unicode = str class _TaskPanel: @@ -46,8 +44,7 @@ class _TaskPanel: The editmode TaskPanel for MaterialReinforced objects """ - if sys.version_info.major >= 3: - unicode = str + unicode = str def __init__(self, obj): diff --git a/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py b/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py index a82edcdeb9..30aac36737 100644 --- a/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py +++ b/src/Mod/Fem/femtaskpanels/task_mesh_gmsh.py @@ -153,8 +153,6 @@ class _TaskPanel: self.form.cb_order.setCurrentIndex(index_order) def console_log(self, message="", color="#000000"): - if (not isinstance(message, bytes)) and (sys.version_info.major < 3): - message = message.encode("utf-8", "replace") self.console_message_gmsh = self.console_message_gmsh + ( '
{0:4.1f}: {2}
' .format(time.time() - self.Start, color, message) diff --git a/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py b/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py index b38e65bd74..06d519171c 100644 --- a/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py +++ b/src/Mod/Fem/femtaskpanels/task_solver_ccxtools.py @@ -30,7 +30,6 @@ __url__ = "https://www.freecadweb.org" # \brief task panel for solver ccx tools object import os -import sys import time from PySide import QtCore from PySide import QtGui @@ -42,9 +41,9 @@ import FreeCADGui import FemGui -if sys.version_info.major >= 3: - def unicode(text, *args): - return str(text) + +def unicode(text, *args): + return str(text) class _TaskPanel: @@ -173,8 +172,6 @@ class _TaskPanel: return def femConsoleMessage(self, message="", color="#000000"): - if sys.version_info.major < 3: - message = message.encode("utf-8", "replace") self.fem_console_message = self.fem_console_message + ( '{0:4.1f}: {2}
' .format(time.time() - self.Start, color, message) @@ -192,25 +189,9 @@ class _TaskPanel: self.femConsoleMessage("CalculiX stdout is empty", "#FF0000") return False - if sys.version_info.major >= 3: - # https://forum.freecadweb.org/viewtopic.php?f=18&t=39195 - # convert QByteArray to a binary string an decode it to "utf-8" - out = out.data().decode() # "utf-8" can be omitted - # print(type(out)) - # print(out) - else: - try: - out = unicode(out, "utf-8", "replace") - rx = QtCore.QRegExp("\\*ERROR.*\\n\\n") - # print(rx) - rx.setMinimal(True) - pos = rx.indexIn(out) - while not pos < 0: - match = rx.cap(0) - FreeCAD.Console.PrintError(match.strip().replace("\n", " ") + "\n") - pos = rx.indexIn(out, pos + 1) - except UnicodeDecodeError: - self.femConsoleMessage("Error converting stdout from CalculiX", "#FF0000") + # https://forum.freecadweb.org/viewtopic.php?f=18&t=39195 + # convert QByteArray to a binary string an decode it to "utf-8" + out = out.data().decode() # "utf-8" can be omitted out = os.linesep.join([s for s in out.splitlines() if s]) out = out.replace("\n", "
") # print(out) @@ -244,7 +225,7 @@ class _TaskPanel: def calculixStarted(self): # print("calculixStarted()") FreeCAD.Console.PrintLog("calculix state: {}\n".format(self.Calculix.state())) - self.form.pb_run_ccx.setText("Break CalculiX") + self.form.pb_run_ccx.setText("Stop CalculiX") def calculixStateChanged(self, newState): if newState == QtCore.QProcess.ProcessState.Starting: diff --git a/src/Mod/Fem/femtest/app/test_common.py b/src/Mod/Fem/femtest/app/test_common.py index 0a10b4d097..0927f9d84e 100644 --- a/src/Mod/Fem/femtest/app/test_common.py +++ b/src/Mod/Fem/femtest/app/test_common.py @@ -25,7 +25,6 @@ __title__ = "Common FEM unit tests" __author__ = "Bernd Hahnebach" __url__ = "https://www.freecadweb.org" -import sys import unittest import FreeCAD @@ -124,13 +123,6 @@ class TestFemCommon(unittest.TestCase): # import all collected modules # fcc_print(pymodules) for mod in pymodules: - # migrate modules do not import on Python 2 - if ( - mod == "femtools.migrate_app" - or mod == "femguiutils.migrate_gui" - ) and sys.version_info.major < 3: - continue - if ( mod == "femsolver.solver_taskpanel" or mod == "femexamples.examplesgui" diff --git a/src/Mod/Fem/femtest/app/test_object.py b/src/Mod/Fem/femtest/app/test_object.py index 1ec683da3e..db1ff559c9 100644 --- a/src/Mod/Fem/femtest/app/test_object.py +++ b/src/Mod/Fem/femtest/app/test_object.py @@ -213,6 +213,10 @@ class TestObjectType(unittest.TestCase): "Fem::ConstraintInitialFlowVelocity", type_of_obj(ObjectsFem.makeConstraintInitialFlowVelocity(doc)) ) + self.assertEqual( + "Fem::ConstraintInitialPressure", + type_of_obj(ObjectsFem.makeConstraintInitialPressure(doc)) + ) self.assertEqual( "Fem::ConstraintInitialTemperature", type_of_obj(ObjectsFem.makeConstraintInitialTemperature(doc)) @@ -434,6 +438,10 @@ class TestObjectType(unittest.TestCase): ObjectsFem.makeConstraintInitialFlowVelocity(doc), "Fem::ConstraintInitialFlowVelocity" )) + self.assertTrue(is_of_type( + ObjectsFem.makeConstraintInitialPressure(doc), + "Fem::ConstraintInitialPressure" + )) self.assertTrue(is_of_type( ObjectsFem.makeConstraintInitialTemperature(doc), "Fem::ConstraintInitialTemperature" @@ -820,6 +828,21 @@ class TestObjectType(unittest.TestCase): "Fem::ConstraintInitialFlowVelocity" )) + # ConstraintInitialPressure + constraint_initial_pressure = ObjectsFem.makeConstraintInitialPressure(doc) + self.assertTrue(is_derived_from( + constraint_initial_pressure, + "App::DocumentObject" + )) + self.assertTrue(is_derived_from( + constraint_initial_pressure, + "Fem::ConstraintPython" + )) + self.assertTrue(is_derived_from( + constraint_initial_pressure, + "Fem::ConstraintInitialPressure" + )) + # ConstraintInitialTemperature constraint_initial_temperature = ObjectsFem.makeConstraintInitialTemperature(doc) self.assertTrue(is_derived_from( @@ -1463,6 +1486,11 @@ class TestObjectType(unittest.TestCase): doc ).isDerivedFrom("Fem::ConstraintPython") ) + self.assertTrue( + ObjectsFem.makeConstraintInitialPressure( + doc + ).isDerivedFrom("Fem::ConstraintPython") + ) self.assertTrue( ObjectsFem.makeConstraintInitialTemperature( doc @@ -1678,6 +1706,7 @@ def create_all_fem_objects_doc( analysis.addObject(ObjectsFem.makeConstraintGear(doc)) analysis.addObject(ObjectsFem.makeConstraintHeatflux(doc)) analysis.addObject(ObjectsFem.makeConstraintInitialFlowVelocity(doc)) + analysis.addObject(ObjectsFem.makeConstraintInitialPressure(doc)) analysis.addObject(ObjectsFem.makeConstraintInitialTemperature(doc)) analysis.addObject(ObjectsFem.makeConstraintPlaneRotation(doc)) analysis.addObject(ObjectsFem.makeConstraintPressure(doc)) diff --git a/src/Mod/Fem/femtest/app/test_open.py b/src/Mod/Fem/femtest/app/test_open.py index 50a8de63f4..808119b4f6 100644 --- a/src/Mod/Fem/femtest/app/test_open.py +++ b/src/Mod/Fem/femtest/app/test_open.py @@ -25,7 +25,6 @@ __title__ = "Open files FEM App unit tests" __author__ = "Bernd Hahnebach" __url__ = "https://www.freecadweb.org" -import sys import tempfile import unittest from os.path import join @@ -129,10 +128,6 @@ class TestObjectOpen(unittest.TestCase): def test_femobjects_open_de9b3fb438( self ): - # migration modules do not import on Python 2 thus this can not work - if sys.version_info.major < 3: - return - # the number in method name is the FreeCAD commit the document was created with # https://github.com/FreeCAD/FreeCAD/commit/de9b3fb438 # the document was created by running the object create unit test diff --git a/src/Mod/Fem/femtest/app/test_solver_elmer.py b/src/Mod/Fem/femtest/app/test_solver_elmer.py index 0bdc14e9eb..3b62252ccf 100644 --- a/src/Mod/Fem/femtest/app/test_solver_elmer.py +++ b/src/Mod/Fem/femtest/app/test_solver_elmer.py @@ -25,7 +25,6 @@ __title__ = "Solver elmer FEM unit tests" __author__ = "Bernd Hahnebach" __url__ = "https://www.freecadweb.org" -import sys import unittest from os.path import join @@ -175,13 +174,6 @@ class TestSolverElmer(unittest.TestCase): def test_ccxcantilever_faceload_1_si( self ): - if sys.version_info.major < 3: - # TODO does not pass on Python 2 - # https://travis-ci.org/github/FreeCAD/FreeCAD/builds/707885742 - # https://api.travis-ci.org/v3/job/707885745/log.txt - fcc_print("Python 2: test aborted.") - return - fcc_print("") self.set_unit_schema(1) # SI-units m/kg/s from femexamples.ccx_cantilever_faceload import setup diff --git a/src/Mod/Fem/femtest/app/test_solver_z88.py b/src/Mod/Fem/femtest/app/test_solver_z88.py index 275024e689..6cd626fd7d 100644 --- a/src/Mod/Fem/femtest/app/test_solver_z88.py +++ b/src/Mod/Fem/femtest/app/test_solver_z88.py @@ -26,7 +26,6 @@ __title__ = "Solver z88 FEM unit tests" __author__ = "Bernd Hahnebach" __url__ = "https://www.freecadweb.org" -import sys import unittest from os import listdir from os.path import join @@ -115,13 +114,6 @@ class TestSolverZ88(unittest.TestCase): self, base_name ): - if sys.version_info.major < 3: - # TODO does not pass on Python 2 - # https://travis-ci.org/github/FreeCAD/FreeCAD/builds/707780320 - # https://api.travis-ci.org/v3/job/707780323/log.txt - fcc_print("Python 2: test aborted.") - return - self.document.recompute() # start diff --git a/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp b/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp index dd1f031e31..2217e283e6 100644 --- a/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp +++ b/src/Mod/Fem/femtest/data/calculix/thermomech_bimetall.inp @@ -6160,33 +6160,19 @@ Evolumes *********************************************************** ** constraints temperature node sets -** ConstraintTemperature -*NSET,NSET=ConstraintTemperature +** ConstraintTemperatureHot +*NSET,NSET=ConstraintTemperatureHot 1, -2, -3, 4, 5, -6, -7, 8, 9, 10, 11, 12, -13, -14, -15, -16, -17, 18, 19, 20, -21, -22, -23, -24, -25, 26, 27, 28, @@ -6269,85 +6255,6 @@ Evolumes 105, 106, 107, -108, -109, -110, -111, -112, -113, -114, -115, -116, -117, -118, -119, -120, -121, -122, -123, -124, -125, -126, -127, -128, -129, -130, -131, -132, -133, -134, -135, -136, -137, -138, -139, -140, -141, -142, -143, -144, -145, -146, -147, -148, -149, -150, -151, -152, -153, -154, -155, -156, -157, -158, -159, -160, -161, -162, -163, -164, -165, -166, -167, -168, -169, -170, -171, -172, -173, -174, -175, -176, -177, -178, -179, -180, -181, -182, -183, -184, -185, -186, 187, 188, 189, @@ -6427,95 +6334,12 @@ Evolumes 263, 264, 265, -266, -267, -268, -269, -270, -271, -272, -273, -274, -275, -276, -277, -278, -279, -280, -281, -282, -283, -284, -285, -286, -287, -288, -289, -290, -291, -292, -293, -294, -295, -296, -297, -298, -299, -300, -301, -302, -303, -304, -305, -306, -307, -308, -309, -310, -311, -312, -313, -314, -315, -316, -317, -318, -319, -320, -321, -322, -323, -324, -325, -326, -327, -328, -329, -330, -331, -332, -333, -334, -335, -336, -337, -338, -339, -340, -341, -342, -343, -344, -345, 346, 347, 348, -349, -350, 351, 352, 353, -354, 355, 356, 357, @@ -6674,506 +6498,6 @@ Evolumes 510, 511, 512, -513, -514, -515, -516, -517, -518, -519, -520, -521, -522, -523, -524, -525, -526, -527, -528, -529, -530, -531, -532, -533, -534, -535, -536, -537, -538, -539, -540, -541, -542, -543, -544, -545, -546, -547, -548, -549, -550, -551, -552, -553, -554, -555, -556, -557, -558, -559, -560, -561, -562, -563, -564, -565, -566, -567, -568, -569, -570, -571, -572, -573, -574, -575, -576, -577, -578, -579, -580, -581, -582, -583, -584, -585, -586, -587, -588, -589, -590, -591, -592, -593, -594, -595, -596, -597, -598, -599, -600, -601, -602, -603, -604, -605, -606, -607, -608, -609, -610, -611, -612, -613, -614, -615, -616, -617, -618, -619, -620, -621, -622, -623, -624, -625, -626, -627, -628, -629, -630, -631, -632, -633, -634, -635, -636, -637, -638, -639, -640, -641, -642, -643, -644, -645, -646, -647, -648, -649, -650, -651, -652, -653, -654, -655, -656, -657, -658, -659, -660, -661, -662, -663, -664, -665, -666, -667, -668, -669, -670, -671, -672, -673, -674, -675, -676, -677, -678, -679, -680, -681, -682, -683, -684, -685, -686, -687, -688, -689, -690, -691, -692, -693, -694, -695, -696, -697, -698, -699, -700, -701, -702, -703, -704, -705, -706, -707, -708, -709, -710, -711, -712, -713, -714, -715, -716, -717, -718, -719, -720, -721, -722, -723, -724, -725, -726, -727, -728, -729, -730, -731, -732, -733, -734, -735, -736, -737, -738, -739, -740, -741, -742, -743, -744, -745, -746, -747, -748, -749, -750, -751, -752, -753, -754, -755, -756, -757, -758, -759, -760, -761, -762, -763, -764, -765, -766, -767, -768, -769, -770, -771, -772, -773, -774, -775, -776, -777, -778, -779, -780, -781, -782, -783, -784, -785, -786, -787, -788, -789, -790, -791, -792, -793, -794, -795, -796, -797, -798, -799, -800, -801, -802, -803, -804, -805, -806, -807, -808, -809, -810, -811, -812, -813, -814, -815, -816, -817, -818, -819, -820, -821, -822, -823, -824, -825, -826, -827, -828, -829, -830, -831, -832, -833, -834, -835, -836, -837, -838, -839, -840, -841, -842, -843, -844, -845, -846, -847, -848, -849, -850, -851, -852, -853, -854, -855, -856, -857, -858, -859, -860, -861, -862, -863, -864, -865, -866, -867, -868, -869, -870, -871, -872, -873, -874, -875, -876, -877, -878, -879, -880, -881, -882, -883, -884, -885, -886, -887, -888, -889, -890, -891, -892, -893, -894, -895, -896, -897, -898, -899, -900, -901, -902, -903, -904, -905, -906, -907, -908, -909, -910, -911, -912, -913, -914, -915, -916, -917, -918, -919, -920, -921, -922, -923, -924, -925, -926, -927, -928, -929, -930, -931, -932, -933, -934, -935, -936, -937, -938, -939, -940, -941, -942, -943, -944, -945, -946, -947, -948, -949, -950, -951, -952, -953, -954, -955, -956, -957, -958, -959, -960, -961, -962, -963, -964, -965, -966, -967, -968, -969, -970, -971, -972, -973, -974, -975, -976, -977, -978, -979, -980, -981, -982, -983, -984, -985, -986, -987, -988, -989, -990, -991, -992, -993, -994, -995, -996, -997, -998, -999, -1000, -1001, -1002, -1003, -1004, -1005, -1006, -1007, -1008, -1009, -1010, -1011, -1012, 1013, 1014, 1015, @@ -7423,506 +6747,6 @@ Evolumes 1259, 1260, 1261, -1511, -1512, -1513, -1514, -1515, -1516, -1517, -1518, -1519, -1520, -1521, -1522, -1523, -1524, -1525, -1526, -1527, -1528, -1529, -1530, -1531, -1532, -1533, -1534, -1535, -1536, -1537, -1538, -1539, -1540, -1541, -1542, -1543, -1544, -1545, -1546, -1547, -1548, -1549, -1550, -1551, -1552, -1553, -1554, -1555, -1556, -1557, -1558, -1559, -1560, -1561, -1562, -1563, -1564, -1565, -1566, -1567, -1568, -1569, -1570, -1571, -1572, -1573, -1574, -1575, -1576, -1577, -1578, -1579, -1580, -1581, -1582, -1583, -1584, -1585, -1586, -1587, -1588, -1589, -1590, -1591, -1592, -1593, -1594, -1595, -1596, -1597, -1598, -1599, -1600, -1601, -1602, -1603, -1604, -1605, -1606, -1607, -1608, -1609, -1610, -1611, -1612, -1613, -1614, -1615, -1616, -1617, -1618, -1619, -1620, -1621, -1622, -1623, -1624, -1625, -1626, -1627, -1628, -1629, -1630, -1631, -1632, -1633, -1634, -1635, -1636, -1637, -1638, -1639, -1640, -1641, -1642, -1643, -1644, -1645, -1646, -1647, -1648, -1649, -1650, -1651, -1652, -1653, -1654, -1655, -1656, -1657, -1658, -1659, -1660, -1661, -1662, -1663, -1664, -1665, -1666, -1667, -1668, -1669, -1670, -1671, -1672, -1673, -1674, -1675, -1676, -1677, -1678, -1679, -1680, -1681, -1682, -1683, -1684, -1685, -1686, -1687, -1688, -1689, -1690, -1691, -1692, -1693, -1694, -1695, -1696, -1697, -1698, -1699, -1700, -1701, -1702, -1703, -1704, -1705, -1706, -1707, -1708, -1709, -1710, -1711, -1712, -1713, -1714, -1715, -1716, -1717, -1718, -1719, -1720, -1721, -1722, -1723, -1724, -1725, -1726, -1727, -1728, -1729, -1730, -1731, -1732, -1733, -1734, -1735, -1736, -1737, -1738, -1739, -1740, -1741, -1742, -1743, -1744, -1745, -1746, -1747, -1748, -1749, -1750, -1751, -1752, -1753, -1754, -1755, -1756, -1757, -1758, -1759, -1760, -1761, -1762, -1763, -1764, -1765, -1766, -1767, -1768, -1769, -1770, -1771, -1772, -1773, -1774, -1775, -1776, -1777, -1778, -1779, -1780, -1781, -1782, -1783, -1784, -1785, -1786, -1787, -1788, -1789, -1790, -1791, -1792, -1793, -1794, -1795, -1796, -1797, -1798, -1799, -1800, -1801, -1802, -1803, -1804, -1805, -1806, -1807, -1808, -1809, -1810, -1811, -1812, -1813, -1814, -1815, -1816, -1817, -1818, -1819, -1820, -1821, -1822, -1823, -1824, -1825, -1826, -1827, -1828, -1829, -1830, -1831, -1832, -1833, -1834, -1835, -1836, -1837, -1838, -1839, -1840, -1841, -1842, -1843, -1844, -1845, -1846, -1847, -1848, -1849, -1850, -1851, -1852, -1853, -1854, -1855, -1856, -1857, -1858, -1859, -1860, -1861, -1862, -1863, -1864, -1865, -1866, -1867, -1868, -1869, -1870, -1871, -1872, -1873, -1874, -1875, -1876, -1877, -1878, -1879, -1880, -1881, -1882, -1883, -1884, -1885, -1886, -1887, -1888, -1889, -1890, -1891, -1892, -1893, -1894, -1895, -1896, -1897, -1898, -1899, -1900, -1901, -1902, -1903, -1904, -1905, -1906, -1907, -1908, -1909, -1910, -1911, -1912, -1913, -1914, -1915, -1916, -1917, -1918, -1919, -1920, -1921, -1922, -1923, -1924, -1925, -1926, -1927, -1928, -1929, -1930, -1931, -1932, -1933, -1934, -1935, -1936, -1937, -1938, -1939, -1940, -1941, -1942, -1943, -1944, -1945, -1946, -1947, -1948, -1949, -1950, -1951, -1952, -1953, -1954, -1955, -1956, -1957, -1958, -1959, -1960, -1961, -1962, -1963, -1964, -1965, -1966, -1967, -1968, -1969, -1970, -1971, -1972, -1973, -1974, -1975, -1976, -1977, -1978, -1979, -1980, -1981, -1982, -1983, -1984, -1985, -1986, -1987, -1988, -1989, -1990, -1991, -1992, -1993, -1994, -1995, -1996, -1997, -1998, -1999, -2000, -2001, -2002, -2003, -2004, -2005, -2006, -2007, -2008, -2009, -2010, 2011, 2012, 2013, @@ -8172,6 +6996,49 @@ Evolumes 2257, 2258, 2259, +** ConstraintTemperatureNormal +*NSET,NSET=ConstraintTemperatureNormal +1, +2, +3, +4, +9, +10, +13, +14, +15, +16, +17, +18, +19, +20, +345, +346, +347, +348, +349, +513, +514, +515, +516, +517, +518, +519, +520, +521, +522, +523, +1511, +1512, +1513, +1514, +1515, +1516, +1517, +1518, +1519, +1520, +1521, *********************************************************** ** Materials @@ -8180,24 +7047,24 @@ Evolumes ** MaterialCopper *MATERIAL, NAME=MaterialCopper *ELASTIC -130000,0.354 +119000,0.343 *CONDUCTIVITY -200 +398 *EXPANSION -2E-05 +1.65E-05 *SPECIFIC HEAT 385000000 ** FreeCAD material name: Invar ** MaterialInvar *MATERIAL, NAME=MaterialInvar *ELASTIC -137000,0.28 +140000,0.29 *CONDUCTIVITY -13 +13.5 *EXPANSION -1.2E-06 +1.25E-06 *SPECIFIC HEAT -510000000 +515000000 *********************************************************** ** Initial temperature constraint @@ -8227,9 +7094,13 @@ ConstraintFixed,3 *********************************************************** ** Fixed temperature constraint applied -** ConstraintTemperature +** ConstraintTemperatureHot *BOUNDARY -ConstraintTemperature,11,11,373 +ConstraintTemperatureHot,11,11,373 + +** ConstraintTemperatureNormal +*BOUNDARY +ConstraintTemperatureNormal,11,11,273 *********************************************************** @@ -8249,8 +7120,8 @@ RF *********************************************************** ** CalculiX Input file -** written by --> FreeCAD 0.19.19501 (Git) -** written on --> Thu Feb 6 23:22:33 2020 +** written by --> FreeCAD 0.20.1 +** written on --> Wed Aug 10 04:21:49 2022 ** file name --> ** analysis name --> Analysis ** diff --git a/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif index 019f13df9b..ef908c06df 100644 --- a/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/box_static_0_mm.sif @@ -1,28 +1,20 @@ -Check Keywords Warn +Check Keywords "Warn" Header Mesh DB "." End Solver 1 - Bubbles = Logical False - Calculate Pangle = Logical False - Calculate Principal = Logical False - Calculate Strains = Logical False - Calculate Stresses = Logical False - Displace mesh = Logical False + Calculate Principal = Logical True + Displace mesh = Logical True Eigen Analysis = Logical False - Eigen System Values = Integer 5 - Equation = String "Elasticity" - Exec Solver = String "Always" + Equation = String "Stress Solver" + Geometric Stiffness = Logical False Linear System Abort Not Converged = Logical False - Linear System Convergence Tolerance = Real 1e-08 - Linear System Iterative Method = String "BiCGStab" - Linear System Max Iterations = Integer 500 + Linear System Direct Method = String "Umfpack" Linear System Precondition Recompute = Integer 1 - Linear System Preconditioning = String "ILU0" Linear System Residual Output = Integer 1 - Linear System Solver = String "Iterative" + Linear System Solver = String "Direct" Optimize Bandwidth = Logical True Procedure = File "StressSolve" "StressSolver" Stabilize = Logical True @@ -32,14 +24,13 @@ Solver 1 End Simulation - BDF Order = Integer 1 Coordinate Mapping(3) = Integer 1 2 3 + Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian 3D" Output Intervals = Integer 1 - Simulation Type = String "Steady state" + Simulation Type = String "Steady State" Steady State Max Iterations = Integer 1 Steady State Min Iterations = Integer 0 - Timestepping Method = String "BDF" Use Mesh Names = Logical True End @@ -62,6 +53,7 @@ Equation 1 End Solver 2 + Coordinate Scaling Revert = Logical True Equation = String "ResultOutput" Exec Solver = String "After simulation" Output File Name = File "case" diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif index b79aa295fa..84760888df 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_0_mm.sif @@ -1,28 +1,20 @@ -Check Keywords Warn +Check Keywords "Warn" Header Mesh DB "." End Solver 1 - Bubbles = Logical False - Calculate Pangle = Logical False - Calculate Principal = Logical False - Calculate Strains = Logical False - Calculate Stresses = Logical False - Displace mesh = Logical False + Calculate Principal = Logical True + Displace mesh = Logical True Eigen Analysis = Logical False - Eigen System Values = Integer 5 - Equation = String "Elasticity" - Exec Solver = String "Always" + Equation = String "Stress Solver" + Geometric Stiffness = Logical False Linear System Abort Not Converged = Logical False - Linear System Convergence Tolerance = Real 1e-08 - Linear System Iterative Method = String "BiCGStab" - Linear System Max Iterations = Integer 500 + Linear System Direct Method = String "Umfpack" Linear System Precondition Recompute = Integer 1 - Linear System Preconditioning = String "ILU0" Linear System Residual Output = Integer 1 - Linear System Solver = String "Iterative" + Linear System Solver = String "Direct" Optimize Bandwidth = Logical True Procedure = File "StressSolve" "StressSolver" Stabilize = Logical True @@ -32,14 +24,13 @@ Solver 1 End Simulation - BDF Order = Integer 1 Coordinate Mapping(3) = Integer 1 2 3 + Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian 3D" Output Intervals = Integer 1 - Simulation Type = String "Steady state" + Simulation Type = String "Steady State" Steady State Max Iterations = Integer 1 Steady State Min Iterations = Integer 0 - Timestepping Method = String "BDF" Use Mesh Names = Logical True End @@ -62,6 +53,7 @@ Equation 1 End Solver 2 + Coordinate Scaling Revert = Logical True Equation = String "ResultOutput" Exec Solver = String "After simulation" Output File Name = File "case" diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif index 3ee99cbd4e..84760888df 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_faceload_1_si.sif @@ -1,28 +1,20 @@ -Check Keywords Warn +Check Keywords "Warn" Header Mesh DB "." End Solver 1 - Bubbles = Logical False - Calculate Pangle = Logical False - Calculate Principal = Logical False - Calculate Strains = Logical False - Calculate Stresses = Logical False - Displace mesh = Logical False + Calculate Principal = Logical True + Displace mesh = Logical True Eigen Analysis = Logical False - Eigen System Values = Integer 5 - Equation = String "Elasticity" - Exec Solver = String "Always" + Equation = String "Stress Solver" + Geometric Stiffness = Logical False Linear System Abort Not Converged = Logical False - Linear System Convergence Tolerance = Real 1e-08 - Linear System Iterative Method = String "BiCGStab" - Linear System Max Iterations = Integer 500 + Linear System Direct Method = String "Umfpack" Linear System Precondition Recompute = Integer 1 - Linear System Preconditioning = String "ILU0" Linear System Residual Output = Integer 1 - Linear System Solver = String "Iterative" + Linear System Solver = String "Direct" Optimize Bandwidth = Logical True Procedure = File "StressSolve" "StressSolver" Stabilize = Logical True @@ -32,14 +24,13 @@ Solver 1 End Simulation - BDF Order = Integer 1 Coordinate Mapping(3) = Integer 1 2 3 + Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian 3D" Output Intervals = Integer 1 - Simulation Type = String "Steady state" + Simulation Type = String "Steady State" Steady State Max Iterations = Integer 1 Steady State Min Iterations = Integer 0 - Timestepping Method = String "BDF" Use Mesh Names = Logical True End diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif index 86fe574c83..92764980ec 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_nodeload_0_mm.sif @@ -1,28 +1,20 @@ -Check Keywords Warn +Check Keywords "Warn" Header Mesh DB "." End Solver 1 - Bubbles = Logical False - Calculate Pangle = Logical False - Calculate Principal = Logical False - Calculate Strains = Logical False - Calculate Stresses = Logical False - Displace mesh = Logical False + Calculate Principal = Logical True + Displace mesh = Logical True Eigen Analysis = Logical False - Eigen System Values = Integer 5 - Equation = String "Elasticity" - Exec Solver = String "Always" + Equation = String "Stress Solver" + Geometric Stiffness = Logical False Linear System Abort Not Converged = Logical False - Linear System Convergence Tolerance = Real 1e-08 - Linear System Iterative Method = String "BiCGStab" - Linear System Max Iterations = Integer 500 + Linear System Direct Method = String "Umfpack" Linear System Precondition Recompute = Integer 1 - Linear System Preconditioning = String "ILU0" Linear System Residual Output = Integer 1 - Linear System Solver = String "Iterative" + Linear System Solver = String "Direct" Optimize Bandwidth = Logical True Procedure = File "StressSolve" "StressSolver" Stabilize = Logical True @@ -32,14 +24,13 @@ Solver 1 End Simulation - BDF Order = Integer 1 Coordinate Mapping(3) = Integer 1 2 3 + Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian 3D" Output Intervals = Integer 1 - Simulation Type = String "Steady state" + Simulation Type = String "Steady State" Steady State Max Iterations = Integer 1 Steady State Min Iterations = Integer 0 - Timestepping Method = String "BDF" Use Mesh Names = Logical True End @@ -62,6 +53,7 @@ Equation 1 End Solver 2 + Coordinate Scaling Revert = Logical True Equation = String "ResultOutput" Exec Solver = String "After simulation" Output File Name = File "case" diff --git a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif index 1db19747f4..c345731432 100644 --- a/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif +++ b/src/Mod/Fem/femtest/data/elmer/ccxcantilever_prescribeddisplacement_0_mm.sif @@ -1,28 +1,20 @@ -Check Keywords Warn +Check Keywords "Warn" Header Mesh DB "." End Solver 1 - Bubbles = Logical False - Calculate Pangle = Logical False - Calculate Principal = Logical False - Calculate Strains = Logical False - Calculate Stresses = Logical False - Displace mesh = Logical False + Calculate Principal = Logical True + Displace mesh = Logical True Eigen Analysis = Logical False - Eigen System Values = Integer 5 - Equation = String "Elasticity" - Exec Solver = String "Always" + Equation = String "Stress Solver" + Geometric Stiffness = Logical False Linear System Abort Not Converged = Logical False - Linear System Convergence Tolerance = Real 1e-08 - Linear System Iterative Method = String "BiCGStab" - Linear System Max Iterations = Integer 500 + Linear System Direct Method = String "Umfpack" Linear System Precondition Recompute = Integer 1 - Linear System Preconditioning = String "ILU0" Linear System Residual Output = Integer 1 - Linear System Solver = String "Iterative" + Linear System Solver = String "Direct" Optimize Bandwidth = Logical True Procedure = File "StressSolve" "StressSolver" Stabilize = Logical True @@ -32,14 +24,13 @@ Solver 1 End Simulation - BDF Order = Integer 1 Coordinate Mapping(3) = Integer 1 2 3 + Coordinate Scaling = Real 0.001 Coordinate System = String "Cartesian 3D" Output Intervals = Integer 1 - Simulation Type = String "Steady state" + Simulation Type = String "Steady State" Steady State Max Iterations = Integer 1 Steady State Min Iterations = Integer 0 - Timestepping Method = String "BDF" Use Mesh Names = Logical True End @@ -62,6 +53,7 @@ Equation 1 End Solver 2 + Coordinate Scaling Revert = Logical True Equation = String "ResultOutput" Exec Solver = String "After simulation" Output File Name = File "case" diff --git a/src/Mod/Fem/femtest/gui/test_open.py b/src/Mod/Fem/femtest/gui/test_open.py index 454a836ce7..a185b5026a 100644 --- a/src/Mod/Fem/femtest/gui/test_open.py +++ b/src/Mod/Fem/femtest/gui/test_open.py @@ -25,7 +25,6 @@ __title__ = "Open files FEM Gui unit tests" __author__ = "Bernd Hahnebach" __url__ = "https://www.freecadweb.org" -import sys import tempfile import unittest from os.path import join @@ -126,10 +125,6 @@ class TestObjectOpen(unittest.TestCase): def test_femobjects_open_de9b3fb438( self ): - # migration modules do not import on Python 2 thus this can not work - if sys.version_info.major < 3: - return - # the number in method name is the FreeCAD commit the document was created with # https://github.com/FreeCAD/FreeCAD/commit/de9b3fb438 # the document was created by running the object create unit test diff --git a/src/Mod/Fem/femtools/ccxtools.py b/src/Mod/Fem/femtools/ccxtools.py index 17f2c9c7cd..988e4fef65 100644 --- a/src/Mod/Fem/femtools/ccxtools.py +++ b/src/Mod/Fem/femtools/ccxtools.py @@ -435,10 +435,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): elif system() in ("Linux", "Darwin"): p1 = subprocess.Popen(["which", "ccx"], stdout=subprocess.PIPE) if p1.wait() == 0: - if sys.version_info.major >= 3: - ccx_path = p1.stdout.read().decode("utf8").split("\n")[0] - else: - ccx_path = p1.stdout.read().split("\n")[0] + ccx_path = p1.stdout.read().decode("utf8").split("\n")[0] elif p1.wait() == 1: error_message = ( "FEM: CalculiX binary ccx not found in " @@ -550,9 +547,8 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): env=_env ) self.ccx_stdout, self.ccx_stderr = p.communicate() - if sys.version_info.major >= 3: - self.ccx_stdout = self.ccx_stdout.decode() - self.ccx_stderr = self.ccx_stderr.decode() + self.ccx_stdout = self.ccx_stdout.decode() + self.ccx_stderr = self.ccx_stderr.decode() os.putenv("OMP_NUM_THREADS", ont_backup) QtCore.QDir.setCurrent(cwd) return p.returncode @@ -577,9 +573,7 @@ class FemToolsCcx(QtCore.QRunnable, QtCore.QObject): startupinfo=startup_info ) ccx_stdout, ccx_stderr = p.communicate() - if sys.version_info.major >= 3: - ccx_stdout = ccx_stdout.decode() - # ccx_stderr = ccx_stderr.decode() + ccx_stdout = ccx_stdout.decode() m = re.search(r"(\d+).(\d+)", ccx_stdout) return (int(m.group(1)), int(m.group(2))) diff --git a/src/Mod/Fem/femtools/constants.py b/src/Mod/Fem/femtools/constants.py index b6aa0dacec..bdf5627aa8 100644 --- a/src/Mod/Fem/femtools/constants.py +++ b/src/Mod/Fem/femtools/constants.py @@ -45,7 +45,7 @@ def stefan_boltzmann(): def vacuum_permittivity(): # https://forum.freecadweb.org/viewtopic.php?f=18&p=400959#p400959 # https://en.wikipedia.org/wiki/Permittivity#Vacuum_permittivity - return "8.85419e-12 s^4*A^2 / (m^3*kg)" + return "8.85419e-12 F/m" def boltzmann_constant(): diff --git a/src/Mod/Fem/femtools/femutils.py b/src/Mod/Fem/femtools/femutils.py index f4a00c58cf..64951cb3c7 100644 --- a/src/Mod/Fem/femtools/femutils.py +++ b/src/Mod/Fem/femtools/femutils.py @@ -34,7 +34,6 @@ __url__ = "https://www.freecadweb.org" import os import subprocess -import sys from platform import system import FreeCAD @@ -378,16 +377,8 @@ def get_refshape_type(fem_doc_object): def pydecode(bytestring): - """ Return *bytestring* as a unicode string for python 2 and 3. - - For python 2 *bytestring* is converted to a string of type ``unicode``. For - python 3 it is returned as is because it uses unicode for it's ``str`` type - already. - """ - if sys.version_info.major < 3: - return bytestring - else: - return bytestring.decode("utf-8") + """ Return *bytestring* as a unicode string """ + return bytestring.decode("utf-8") def startProgramInfo(code): diff --git a/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py b/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py index 9d1b511a19..89083b35c8 100644 --- a/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py +++ b/src/Mod/Fem/femviewprovider/view_constraint_bodyheatsource.py @@ -30,10 +30,16 @@ __url__ = "https://www.freecadweb.org" # \ingroup FEM # \brief view provider for the constraint body heat source object +from femtaskpanels import task_constraint_bodyheatsource from . import view_base_femconstraint class VPConstraintBodyHeatSource(view_base_femconstraint.VPBaseFemConstraint): - def getIcon(self): - return ":/icons/FEM_ConstraintHeatflux.svg" # the heatflux icon is used + def setEdit(self, vobj, mode=0): + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, + vobj, + mode, + task_constraint_bodyheatsource._TaskPanel + ) diff --git a/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py b/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py new file mode 100644 index 0000000000..2e29c930d7 --- /dev/null +++ b/src/Mod/Fem/femviewprovider/view_constraint_initialpressure.py @@ -0,0 +1,44 @@ +# *************************************************************************** +# * Copyright (c) 2022 Uwe Stöhr * +# * * +# * 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 constraint initial pressure ViewProvider for the document object" +__author__ = "Uwe Stöhr" +__url__ = "https://www.freecadweb.org" + +## @package view_constraint_initialpressure +# \ingroup FEM +# \brief view provider for constraint initial pressure object + +from femtaskpanels import task_constraint_initialpressure +from . import view_base_femconstraint + + +class VPConstraintInitialPressure(view_base_femconstraint.VPBaseFemConstraint): + + def setEdit(self, vobj, mode=0): + view_base_femconstraint.VPBaseFemConstraint.setEdit( + self, + vobj, + mode, + task_constraint_initialpressure._TaskPanel + ) diff --git a/src/Mod/Image/App/AppImage.cpp b/src/Mod/Image/App/AppImage.cpp index 9bb298e64c..54d9f4eec2 100644 --- a/src/Mod/Image/App/AppImage.cpp +++ b/src/Mod/Image/App/AppImage.cpp @@ -27,7 +27,7 @@ public: initialize("This module is the Image module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Image/App/ImageBase.cpp b/src/Mod/Image/App/ImageBase.cpp index fa43004d1e..c5ad775146 100644 --- a/src/Mod/Image/App/ImageBase.cpp +++ b/src/Mod/Image/App/ImageBase.cpp @@ -201,7 +201,7 @@ int ImageBase::_setColorFormat(int format, unsigned short numSigBitsPerSample) int ImageBase::_allocate() { // Check that pixel data pointer is null - if (_pPixelData != nullptr) + if (_pPixelData) return -1; // Allocate the space needed to store the pixel data @@ -296,7 +296,7 @@ int ImageBase::pointTo(void* pSrcPixelData, unsigned long width, unsigned long h // if there is no image data int ImageBase::getSample(int x, int y, unsigned short sampleIndex, double &value) { - if ((_pPixelData == nullptr) || + if ((!_pPixelData) || (sampleIndex >= _numSamples) || (x < 0) || (x >= (int)_width) || (y < 0) || (y >= (int)_height)) diff --git a/src/Mod/Image/App/ImagePlane.h b/src/Mod/Image/App/ImagePlane.h index 8fa1b97bcd..49ba554439 100644 --- a/src/Mod/Image/App/ImagePlane.h +++ b/src/Mod/Image/App/ImagePlane.h @@ -33,19 +33,19 @@ namespace Image class ImageExport ImagePlane : public App::GeoFeature { - PROPERTY_HEADER(Image::ImagePlane); + PROPERTY_HEADER_WITH_OVERRIDE(Image::ImagePlane); public: /// Constructor ImagePlane(); - virtual ~ImagePlane(); + ~ImagePlane() override; App::PropertyFileIncluded ImageFile; App::PropertyLength XSize; App::PropertyLength YSize; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "ImageGui::ViewProviderImagePlane"; } }; diff --git a/src/Mod/Image/Gui/AppImageGuiPy.cpp b/src/Mod/Image/Gui/AppImageGuiPy.cpp index 389b3f4966..692a8299ff 100644 --- a/src/Mod/Image/Gui/AppImageGuiPy.cpp +++ b/src/Mod/Image/Gui/AppImageGuiPy.cpp @@ -53,7 +53,7 @@ public: initialize("This module is the ImageGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object open(const Py::Tuple& args) diff --git a/src/Mod/Image/Gui/CMakeLists.txt b/src/Mod/Image/Gui/CMakeLists.txt index 0132d5b9c6..a3a76ca2d7 100644 --- a/src/Mod/Image/Gui/CMakeLists.txt +++ b/src/Mod/Image/Gui/CMakeLists.txt @@ -11,6 +11,7 @@ include_directories( ${OPENCV2_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) if(MSVC) diff --git a/src/Mod/Image/Gui/ImageOrientationDialog.h b/src/Mod/Image/Gui/ImageOrientationDialog.h index b295e470fd..f9a884a730 100644 --- a/src/Mod/Image/Gui/ImageOrientationDialog.h +++ b/src/Mod/Image/Gui/ImageOrientationDialog.h @@ -35,12 +35,12 @@ class ImageOrientationDialog : public QDialog public: ImageOrientationDialog(); - ~ImageOrientationDialog(); + ~ImageOrientationDialog() override; Base::Placement Pos; int DirType; - void accept(); + void accept() override; protected Q_SLOTS: void onPreview(); diff --git a/src/Mod/Image/Gui/ImageView.cpp b/src/Mod/Image/Gui/ImageView.cpp index 548b0c1b7b..6e3a60b54b 100644 --- a/src/Mod/Image/Gui/ImageView.cpp +++ b/src/Mod/Image/Gui/ImageView.cpp @@ -332,7 +332,7 @@ void ImageView::closeEvent(QCloseEvent *e) { // ignore the close event e->ignore(); - closeEventIgnored(); // and emit a signal that we ignored it + Q_EMIT closeEventIgnored(); // and emit a signal that we ignored it } else { diff --git a/src/Mod/Image/Gui/OpenGLImageBox.cpp b/src/Mod/Image/Gui/OpenGLImageBox.cpp index 0ce37dcf5f..5a8f3d7d60 100644 --- a/src/Mod/Image/Gui/OpenGLImageBox.cpp +++ b/src/Mod/Image/Gui/OpenGLImageBox.cpp @@ -188,7 +188,7 @@ void GLImageBox::paintGL() // Emit a signal for owners to draw any graphics that is needed. if (_image.hasValidData()) - drawGraphics(); + Q_EMIT drawGraphics(); // flush the OpenGL graphical pipeline glFinish(); @@ -243,7 +243,7 @@ void GLImageBox::drawImage() glPixelTransferf(GL_BLUE_SCALE, (float)scale); // Load the color map if present - if (_pColorMap != nullptr) + if (_pColorMap) { if (!haveMesa) glPixelTransferf(GL_MAP_COLOR, 1.0); glPixelMapfv(GL_PIXEL_MAP_R_TO_R, _numMapEntries, _pColorMap); @@ -851,7 +851,7 @@ int GLImageBox::setColorMapAlphaValue(int index, float value) // Helper function to convert a pixel's value (of a sample) to the color map index (i.e. the map index that will be used for that pixel value) unsigned int GLImageBox::pixValToMapIndex(double PixVal) { - if (_pColorMap != nullptr) + if (_pColorMap) { double MaxVal = pow(2.0, _image.getNumBitsPerSample()) - 1.0; double Scale = (pow(2.0, _image.getNumBitsPerSample()) - 1.0) / (pow(2.0, _image.getNumSigBitsPerSample()) - 1.0); diff --git a/src/Mod/Image/Gui/ViewProviderImagePlane.cpp b/src/Mod/Image/Gui/ViewProviderImagePlane.cpp index eac136d5fd..18faac2da9 100644 --- a/src/Mod/Image/Gui/ViewProviderImagePlane.cpp +++ b/src/Mod/Image/Gui/ViewProviderImagePlane.cpp @@ -111,7 +111,7 @@ void ViewProviderImagePlane::setDisplayMode(const char* ModeName) std::vector ViewProviderImagePlane::getDisplayModes() const { std::vector StrList; - StrList.push_back("ImagePlane"); + StrList.emplace_back("ImagePlane"); return StrList; } diff --git a/src/Mod/Image/Gui/ViewProviderImagePlane.h b/src/Mod/Image/Gui/ViewProviderImagePlane.h index deb86e0c72..fed5a51c98 100644 --- a/src/Mod/Image/Gui/ViewProviderImagePlane.h +++ b/src/Mod/Image/Gui/ViewProviderImagePlane.h @@ -37,19 +37,19 @@ namespace ImageGui class ImageGuiExport ViewProviderImagePlane : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(RobotGui::ViewProviderImagePlane); + PROPERTY_HEADER_WITH_OVERRIDE(RobotGui::ViewProviderImagePlane); public: /// constructor. ViewProviderImagePlane(); /// destructor. - ~ViewProviderImagePlane(); + ~ViewProviderImagePlane() override; - void attach(App::DocumentObject *pcObject); - void setDisplayMode(const char* ModeName); - std::vector getDisplayModes() const; - void updateData(const App::Property*); + void attach(App::DocumentObject *pcObject) override; + void setDisplayMode(const char* ModeName) override; + std::vector getDisplayModes() const override; + void updateData(const App::Property*) override; private: bool loadSvg(const char*, float x, float y, QImage& img); diff --git a/src/Mod/Image/Gui/Workbench.h b/src/Mod/Image/Gui/Workbench.h index 5d2cb3d83e..e8a67b91d3 100644 --- a/src/Mod/Image/Gui/Workbench.h +++ b/src/Mod/Image/Gui/Workbench.h @@ -33,15 +33,15 @@ namespace ImageGui { */ class ImageGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace ImageGui diff --git a/src/Mod/Image/ImageTools/_CommandImageScaling.py b/src/Mod/Image/ImageTools/_CommandImageScaling.py index bab3261808..b06c98f2cc 100644 --- a/src/Mod/Image/ImageTools/_CommandImageScaling.py +++ b/src/Mod/Image/ImageTools/_CommandImageScaling.py @@ -108,9 +108,11 @@ def cmdCreateImageScaling(name, trackers): self.label.setObjectName(_fromUtf8("label")) self.horizontalLayout.addWidget(self.label) - self.lineEdit = QtGui.QLineEdit(Dialog) - self.lineEdit.setObjectName(_fromUtf8("lineEdit")) - self.horizontalLayout.addWidget(self.lineEdit) + self.quantity = FreeCADGui.UiLoader().createWidget("Gui::InputField") + self.quantity.setParent(Dialog) + self.quantity.setProperty('unit', 'mm') + self.quantity.setObjectName(_fromUtf8("QuantityField")) + self.horizontalLayout.addWidget(self.quantity) self.label1 = QtGui.QLabel(Dialog) self.label1.setObjectName(_fromUtf8("label1")) @@ -136,23 +138,13 @@ def cmdCreateImageScaling(name, trackers): def retranslateUi(self, Dialog): Dialog.setWindowTitle(translate("Dialog", "Scale image plane", None)) - self.label.setText(translate("Dialog", "Distance [mm]", None)) + self.label.setText(translate("Dialog", "Distance", None)) self.label1.setText(translate("Dialog", "Select first point", None)) def accept(self): sel = FreeCADGui.Selection.getSelection() try: - try: - q = FreeCAD.Units.parseQuantity(self.lineEdit.text()) - d = q.Value - if q.Unit == FreeCAD.Units.Unit(): # plain number - ok = True - elif q.Unit == FreeCAD.Units.Length: - ok = True - except Exception: - ok = False - if not ok: - raise ValueError + d = self.quantity.property('rawValue') s=d/self.distance sel[0].XSize.Value=sel[0].XSize.Value*s sel[0].YSize.Value=sel[0].YSize.Value*s diff --git a/src/Mod/Image/InitGui.py b/src/Mod/Image/InitGui.py index 168f6d2860..88bdc05343 100644 --- a/src/Mod/Image/InitGui.py +++ b/src/Mod/Image/InitGui.py @@ -53,4 +53,4 @@ class ImageWorkbench ( Workbench ): Gui.addWorkbench(ImageWorkbench()) # Append the open handler -FreeCAD.EndingAdd("Image formats (*.bmp *.jpg *.png *.xpm)","ImageGui") +FreeCAD.addImportType("Image formats (*.bmp *.jpg *.png *.xpm)","ImageGui") diff --git a/src/Mod/Import/App/AppImportPy.cpp b/src/Mod/Import/App/AppImportPy.cpp index 772d29ad2f..8fb770fb67 100644 --- a/src/Mod/Import/App/AppImportPy.cpp +++ b/src/Mod/Import/App/AppImportPy.cpp @@ -93,7 +93,7 @@ public: std::map > partColors; private: - virtual void applyFaceColors(Part::Feature* part, const std::vector& colors) override { + void applyFaceColors(Part::Feature* part, const std::vector& colors) override { partColors[part] = colors; } }; @@ -127,7 +127,7 @@ public: initialize("This module is the Import module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object importer(const Py::Tuple& args, const Py::Dict &kwds) @@ -314,9 +314,8 @@ private: } if (legacy == Py_None) { - auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Import"); - legacy = hGrp->GetBool("ExportLegacy",false) ? Py_True : Py_False; + Part::ImportExportSettings settings; + legacy = settings.getExportLegacy() ? Py_True : Py_False; } Import::ExportOCAF2 ocaf(hDoc); @@ -478,7 +477,7 @@ private: if (usePolyline == Py_True) { polyOverride = true; } - if (optionSource != nullptr) { + if (optionSource) { defaultOptions = optionSource; } @@ -527,7 +526,7 @@ private: if (usePolyline == Py_True) { polyOverride = true; } - if (optionSource != nullptr) { + if (optionSource) { defaultOptions = optionSource; } @@ -587,7 +586,7 @@ private: polyOverride = true; } - if (optionSource != nullptr) { + if (optionSource) { defaultOptions = optionSource; } @@ -641,7 +640,7 @@ private: polyOverride = true; } - if (optionSource != nullptr) { + if (optionSource) { defaultOptions = optionSource; } diff --git a/src/Mod/Import/App/CMakeLists.txt b/src/Mod/Import/App/CMakeLists.txt index 885e9b6cee..a08f727db4 100644 --- a/src/Mod/Import/App/CMakeLists.txt +++ b/src/Mod/Import/App/CMakeLists.txt @@ -8,11 +8,12 @@ endif(MSVC) include_directories( ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR} ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} - ${CMAKE_CURRENT_SOURCE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) @@ -80,7 +81,7 @@ ADD_CUSTOM_TARGET(ImportPy ALL SOURCES ${SCL_Resources} ) -fc_target_copy_resource(ImportPy +fc_target_copy_resource(ImportPy ${CMAKE_SOURCE_DIR}/src/Mod/Import/App ${CMAKE_BINARY_DIR}/Mod/Import ${SCL_Resources}) diff --git a/src/Mod/Import/App/ExportOCAF.h b/src/Mod/Import/App/ExportOCAF.h index 9491316d72..8a70aa73ea 100644 --- a/src/Mod/Import/App/ExportOCAF.h +++ b/src/Mod/Import/App/ExportOCAF.h @@ -106,7 +106,7 @@ public: } private: - virtual void findColors(Part::Feature*, std::vector&) const; + void findColors(Part::Feature*, std::vector&) const override; private: std::map > partColors; diff --git a/src/Mod/Import/App/ImportOCAF.h b/src/Mod/Import/App/ImportOCAF.h index 0ae795cc31..b433db69f6 100644 --- a/src/Mod/Import/App/ImportOCAF.h +++ b/src/Mod/Import/App/ImportOCAF.h @@ -89,7 +89,7 @@ public: } private: - void applyColors(Part::Feature* part, const std::vector& colors); + void applyColors(Part::Feature* part, const std::vector& colors) override; private: std::map > partColors; diff --git a/src/Mod/Import/App/ImportOCAF2.cpp b/src/Mod/Import/App/ImportOCAF2.cpp index 8247f080e5..f3d111418e 100644 --- a/src/Mod/Import/App/ImportOCAF2.cpp +++ b/src/Mod/Import/App/ImportOCAF2.cpp @@ -176,32 +176,29 @@ ImportOCAF2::ImportOCAF2(Handle(TDocStd_Document) h, App::Document* d, const std aShapeTool = XCAFDoc_DocumentTool::ShapeTool (pDoc->Main()); aColorTool = XCAFDoc_DocumentTool::ColorTool(pDoc->Main()); - auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Import/hSTEP"); - merge = hGrp->GetBool("ReadShapeCompoundMode", true); + Part::ImportExportSettings settings; + merge = settings.getReadShapeCompoundMode(); + useLinkGroup = settings.getUseLinkGroup(); + useBaseName = settings.getUseBaseName(); + importHidden = settings.getImportHiddenObject(); + reduceObjects = settings.getReduceObjects(); + showProgress = settings.getShowProgress(); + expandCompound = settings.getExpandCompound(); - hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Import"); - useLinkGroup = hGrp->GetBool("UseLinkGroup",true); - useBaseName = hGrp->GetBool("UseBaseName",true); - importHidden = hGrp->GetBool("ImportHiddenObject",true); - reduceObjects = hGrp->GetBool("ReduceObjects",true); - showProgress = hGrp->GetBool("ShowProgress",true); - expandCompound = hGrp->GetBool("ExpandCompound",true); - - if(d->isSaved()) { + if (d->isSaved()) { Base::FileInfo fi(d->FileName.getValue()); filePath = fi.dirPath(); } - mode = hGrp->GetInt("ImportMode",SingleDoc); + mode = static_cast(settings.getImportMode()); - hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); + auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); defaultFaceColor.setPackedValue(hGrp->GetUnsigned("DefaultShapeColor",0xCCCCCC00)); defaultFaceColor.a = 0; defaultEdgeColor.setPackedValue(hGrp->GetUnsigned("DefaultShapeLineColor",421075455UL)); defaultEdgeColor.a = 0; - if(useLinkGroup) { + if (useLinkGroup) { // Interface_Static::SetIVal("read.stepcaf.subshapes.name",1); aShapeTool->SetAutoNaming(Standard_False); } @@ -248,7 +245,7 @@ void ImportOCAF2::setObjectName(Info &info, TDF_Label label) { if(!info.obj) return; info.baseName = getLabelName(label); - if(info.baseName.size()) + if(!info.baseName.empty()) info.obj->Label.setValue(info.baseName.c_str()); else{ auto linked = info.obj->getLinkedObject(false); @@ -403,7 +400,7 @@ bool ImportOCAF2::createObject(App::Document *doc, TDF_Label label, if(aColorTool->GetColor(l, XCAFDoc_ColorCurv, aColor)) { edgeColor = convertColor(aColor); foundEdgeColor = true; - if(j==0 && foundFaceColor && faceColors.size() && edgeColor==faceColor) { + if(j==0 && foundFaceColor && !faceColors.empty() && edgeColor==faceColor) { // Do not set edge the same color as face foundEdgeColor = false; } @@ -662,7 +659,7 @@ void ImportOCAF2::getSHUOColors(TDF_Label label, ss.str(""); break; } - if(it->second.size()) + if(!it->second.empty()) ss << it->second << '.'; } if(!shuo->NbChildren()) @@ -724,7 +721,7 @@ App::DocumentObject *ImportOCAF2::loadShape(App::Document *doc, auto name = getLabelName(label); if(info.faceColor!=it->second.faceColor || info.edgeColor!=it->second.edgeColor || - (name.size() && info.baseName.size() && name!=info.baseName)) + (!name.empty() && !info.baseName.empty() && name!=info.baseName)) { auto compound = static_cast(doc->addObject("Part::Compound2","Compound")); compound->Links.setValue(info.obj); @@ -752,7 +749,7 @@ App::DocumentObject *ImportOCAF2::loadShape(App::Document *doc, applyLinkColor(link,-1,info.faceColor); myNames.emplace(label,link->getNameInDocument()); - if(shuoColors.size()) + if(!shuoColors.empty()) applyElementColors(link,shuoColors); return link; } @@ -875,7 +872,7 @@ bool ImportOCAF2::createAssembly(App::Document *_doc, if(!createGroup(doc,info,shape,children,visibilities,shuoColors.empty())) return false; - if(shuoColors.size()) + if(!shuoColors.empty()) applyElementColors(info.obj,shuoColors); return true; } @@ -888,9 +885,9 @@ ExportOCAF2::ExportOCAF2(Handle(TDocStd_Document) h, GetShapeColorsFunc func) aShapeTool = XCAFDoc_DocumentTool::ShapeTool(pDoc->Main()); aColorTool = XCAFDoc_DocumentTool::ColorTool(pDoc->Main()); - auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Import"); - exportHidden = hGrp->GetBool("ExportHiddenObject",true); - keepPlacement = hGrp->GetBool("ExportKeepPlacement",false); + Part::ImportExportSettings settings; + exportHidden = settings.getExportHiddenObject(); + keepPlacement = settings.getExportKeepPlacement(); Interface_Static::SetIVal("write.step.assembly",2); @@ -1045,7 +1042,7 @@ void ExportOCAF2::setupObject(TDF_Label label, App::DocumentObject *obj, for(auto &v : colors) { TDF_Label nodeLabel = label; - if(v.first.size()) { + if(!v.first.empty()) { TDF_LabelSequence labels; if(aShapeTool->IsComponent(label)) labels.Append(label); @@ -1289,7 +1286,7 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, } int vis = -1; if(parentGrp) { - if(groupLinks.size() + if(!groupLinks.empty() && parentGrp->getExtensionByType(true,false)) { vis = groupLinks.back()->isElementVisible(childName.c_str()); @@ -1334,7 +1331,7 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, } } - if (groupLinks.size() && groupLinks.back()==obj) + if (!groupLinks.empty() && groupLinks.back()==obj) groupLinks.pop_back(); // Finished adding components. Now retrieve the computed non-located shape @@ -1345,7 +1342,7 @@ TDF_Label ExportOCAF2::exportObject(App::DocumentObject* parentObj, for(auto link : links) myObjects.emplace(link, label); - if(!parent.IsNull() && links.size()) + if(!parent.IsNull() && !links.empty()) linked = links.back(); else linked = obj; diff --git a/src/Mod/Import/App/ImportOCAF2.h b/src/Mod/Import/App/ImportOCAF2.h index b967df5f02..a2bc23150b 100644 --- a/src/Mod/Import/App/ImportOCAF2.h +++ b/src/Mod/Import/App/ImportOCAF2.h @@ -128,12 +128,12 @@ private: private: class ImportLegacy : public ImportOCAF { public: - ImportLegacy(ImportOCAF2 &parent) + explicit ImportLegacy(ImportOCAF2 &parent) :ImportOCAF(parent.pDoc, parent.pDocument, parent.default_name),myParent(parent) {} private: - void applyColors(Part::Feature* part, const std::vector& colors) { + void applyColors(Part::Feature* part, const std::vector& colors) override { myParent.applyFaceColors(part, colors); } @@ -172,7 +172,7 @@ class ImportExport ExportOCAF2 public: typedef std::function( App::DocumentObject*, const char*)> GetShapeColorsFunc; - ExportOCAF2(Handle(TDocStd_Document) h, GetShapeColorsFunc func=GetShapeColorsFunc()); + explicit ExportOCAF2(Handle(TDocStd_Document) h, GetShapeColorsFunc func=GetShapeColorsFunc()); void setExportHiddenObject(bool enable) {exportHidden=enable;} void setKeepPlacement(bool enable) {keepPlacement=enable;} diff --git a/src/Mod/Import/App/dxf/ImpExpDxf.cpp b/src/Mod/Import/App/dxf/ImpExpDxf.cpp index e5cc1b632d..dd365efd3f 100644 --- a/src/Mod/Import/App/dxf/ImpExpDxf.cpp +++ b/src/Mod/Import/App/dxf/ImpExpDxf.cpp @@ -85,7 +85,7 @@ ImpExpDxfRead::ImpExpDxfRead(std::string filepath, App::Document *pcDoc) : CDxfR setOptions(); } -void ImpExpDxfRead::setOptions(void) +void ImpExpDxfRead::setOptions() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(getOptionSource().c_str()); optionGroupLayers = hGrp->GetBool("groupLayers",false); @@ -473,7 +473,7 @@ ImpExpDxfWrite::~ImpExpDxfWrite() { } -void ImpExpDxfWrite::setOptions(void) +void ImpExpDxfWrite::setOptions() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath(getOptionSource().c_str()); optionMaxLength = hGrp->GetFloat("maxsegmentlength",5.0); diff --git a/src/Mod/Import/App/dxf/ImpExpDxf.h b/src/Mod/Import/App/dxf/ImpExpDxf.h index 0868739537..3824b7ea30 100644 --- a/src/Mod/Import/App/dxf/ImpExpDxf.h +++ b/src/Mod/Import/App/dxf/ImpExpDxf.h @@ -38,16 +38,16 @@ namespace Import ImpExpDxfRead(std::string filepath, App::Document *pcDoc); // CDxfRead's virtual functions - void OnReadLine(const double* s, const double* e, bool hidden); - void OnReadPoint(const double* s); - void OnReadText(const double* point, const double height, const char* text); - void OnReadArc(const double* s, const double* e, const double* c, bool dir, bool hidden); - void OnReadCircle(const double* s, const double* c, bool dir, bool hidden); - void OnReadEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool dir); - void OnReadSpline(struct SplineData& sd); - void OnReadInsert(const double* point, const double* scale, const char* name, double rotation); - void OnReadDimension(const double* s, const double* e, const double* point, double rotation); - void AddGraphics() const; + void OnReadLine(const double* s, const double* e, bool hidden) override; + void OnReadPoint(const double* s) override; + void OnReadText(const double* point, const double height, const char* text) override; + void OnReadArc(const double* s, const double* e, const double* c, bool dir, bool hidden) override; + void OnReadCircle(const double* s, const double* c, bool dir, bool hidden) override; + void OnReadEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool dir) override; + void OnReadSpline(struct SplineData& sd) override; + void OnReadInsert(const double* point, const double* scale, const char* name, double rotation) override; + void OnReadDimension(const double* s, const double* e, const double* point, double rotation) override; + void AddGraphics() const override; // FreeCAD-specific functions void AddObject(Part::TopoShape *shape); //Called by OnRead functions to add Part objects @@ -55,7 +55,7 @@ namespace Import std::string getOptionSource() { return m_optionSource; } void setOptionSource(std::string s) { m_optionSource = s; } - void setOptions(void); + void setOptions(); private: gp_Pnt makePoint(const double* p); @@ -78,7 +78,7 @@ namespace Import void exportShape(const TopoDS_Shape input); std::string getOptionSource() { return m_optionSource; } void setOptionSource(std::string s) { m_optionSource = s; } - void setOptions(void); + void setOptions(); void exportText(const char* text, Base::Vector3d position1, Base::Vector3d position2, double size, int just); void exportLinearDim(Base::Vector3d textLocn, Base::Vector3d lineLocn, diff --git a/src/Mod/Import/App/dxf/dxf.h b/src/Mod/Import/App/dxf/dxf.h index 7ca2951493..fb7a853670 100644 --- a/src/Mod/Import/App/dxf/dxf.h +++ b/src/Mod/Import/App/dxf/dxf.h @@ -119,7 +119,7 @@ struct LWPolyDataOut }; //******************** -class ImportExport CDxfWrite{ +class CDxfWrite{ private: std::ofstream* m_ofs; bool m_fail; @@ -170,77 +170,77 @@ protected: std::vector m_blkRecordList; public: - CDxfWrite(const char* filepath); - ~CDxfWrite(); + ImportExport CDxfWrite(const char* filepath); + ImportExport ~CDxfWrite(); - void init(void); - void endRun(void); + ImportExport void init(void); + ImportExport void endRun(void); - bool Failed(){return m_fail;} + ImportExport bool Failed(){return m_fail;} // void setOptions(void); // bool isVersionValid(int vers); - std::string getLayerName() { return m_layerName; } - void setLayerName(std::string s); - void setVersion(int v) { m_version = v;} - void setPolyOverride(bool b) { m_polyOverride = b; } - void addBlockName(std::string s, std::string blkRecordHandle); + ImportExport std::string getLayerName() { return m_layerName; } + ImportExport void setLayerName(std::string s); + ImportExport void setVersion(int v) { m_version = v;} + ImportExport void setPolyOverride(bool b) { m_polyOverride = b; } + ImportExport void addBlockName(std::string s, std::string blkRecordHandle); - void writeLine(const double* s, const double* e); - void writePoint(const double*); - void writeArc(const double* s, const double* e, const double* c, bool dir); - void writeEllipse(const double* c, double major_radius, double minor_radius, + ImportExport void writeLine(const double* s, const double* e); + ImportExport void writePoint(const double*); + ImportExport void writeArc(const double* s, const double* e, const double* c, bool dir); + ImportExport void writeEllipse(const double* c, double major_radius, double minor_radius, double rotation, double start_angle, double end_angle, bool endIsCW); - void writeCircle(const double* c, double radius ); - void writeSpline(const SplineDataOut &sd); - void writeLWPolyLine(const LWPolyDataOut &pd); - void writePolyline(const LWPolyDataOut &pd); - void writeVertex(double x, double y, double z); - void writeText(const char* text, const double* location1, const double* location2, + ImportExport void writeCircle(const double* c, double radius ); + ImportExport void writeSpline(const SplineDataOut &sd); + ImportExport void writeLWPolyLine(const LWPolyDataOut &pd); + ImportExport void writePolyline(const LWPolyDataOut &pd); + ImportExport void writeVertex(double x, double y, double z); + ImportExport void writeText(const char* text, const double* location1, const double* location2, const double height, const int horizJust); - void writeLinearDim(const double* textMidPoint, const double* lineDefPoint, + ImportExport void writeLinearDim(const double* textMidPoint, const double* lineDefPoint, const double* extLine1, const double* extLine2, const char* dimText, int type); - void writeLinearDimBlock(const double* textMidPoint, const double* lineDefPoint, + ImportExport void writeLinearDimBlock(const double* textMidPoint, const double* lineDefPoint, const double* extLine1, const double* extLine2, const char* dimText, int type); - void writeAngularDim(const double* textMidPoint, const double* lineDefPoint, + ImportExport void writeAngularDim(const double* textMidPoint, const double* lineDefPoint, const double* startExt1, const double* endExt1, const double* startExt2, const double* endExt2, const char* dimText); - void writeAngularDimBlock(const double* textMidPoint, const double* lineDefPoint, + ImportExport void writeAngularDimBlock(const double* textMidPoint, const double* lineDefPoint, const double* startExt1, const double* endExt1, const double* startExt2, const double* endExt2, const char* dimText); - void writeRadialDim(const double* centerPoint, const double* textMidPoint, + ImportExport void writeRadialDim(const double* centerPoint, const double* textMidPoint, const double* arcPoint, const char* dimText); - void writeRadialDimBlock(const double* centerPoint, const double* textMidPoint, + ImportExport void writeRadialDimBlock(const double* centerPoint, const double* textMidPoint, const double* arcPoint, const char* dimText); - void writeDiametricDim(const double* textMidPoint, + ImportExport void writeDiametricDim(const double* textMidPoint, const double* arcPoint1, const double* arcPoint2, const char* dimText); - void writeDiametricDimBlock(const double* textMidPoint, + ImportExport void writeDiametricDimBlock(const double* textMidPoint, const double* arcPoint1, const double* arcPoint2, const char* dimText); - void writeDimBlockPreamble(); - void writeBlockTrailer(void); + ImportExport void writeDimBlockPreamble(); + ImportExport void writeBlockTrailer(void); - void writeHeaderSection(void); - void writeTablesSection(void); - void writeBlocksSection(void); - void writeEntitiesSection(void); - void writeObjectsSection(void); - void writeClassesSection(void); + ImportExport void writeHeaderSection(void); + ImportExport void writeTablesSection(void); + ImportExport void writeBlocksSection(void); + ImportExport void writeEntitiesSection(void); + ImportExport void writeObjectsSection(void); + ImportExport void writeClassesSection(void); - void makeLayerTable(void); - void makeBlockRecordTableHead(void); - void makeBlockRecordTableBody(void); - void makeBlockSectionHead(void); + ImportExport void makeLayerTable(void); + ImportExport void makeBlockRecordTableHead(void); + ImportExport void makeBlockRecordTableBody(void); + ImportExport void makeBlockSectionHead(void); }; // derive a class from this and implement it's virtual functions -class ImportExport CDxfRead{ +class CDxfRead{ private: std::ifstream* m_ifs; @@ -285,28 +285,28 @@ protected: Aci_t m_aci; // manifest color name or 256 for layer color public: - CDxfRead(const char* filepath); // this opens the file - virtual ~CDxfRead(); // this closes the file + ImportExport CDxfRead(const char* filepath); // this opens the file + ImportExport virtual ~CDxfRead(); // this closes the file - bool Failed(){return m_fail;} - void DoRead(const bool ignore_errors = false); // this reads the file and calls the following functions + ImportExport bool Failed(){return m_fail;} + ImportExport void DoRead(const bool ignore_errors = false); // this reads the file and calls the following functions - double mm( double value ) const; + ImportExport double mm( double value ) const; - bool IgnoreErrors() const { return(m_ignore_errors); } + ImportExport bool IgnoreErrors() const { return(m_ignore_errors); } - virtual void OnReadLine(const double* /*s*/, const double* /*e*/, bool /*hidden*/){} - virtual void OnReadPoint(const double* /*s*/){} - virtual void OnReadText(const double* /*point*/, const double /*height*/, const char* /*text*/){} - virtual void OnReadArc(const double* /*s*/, const double* /*e*/, const double* /*c*/, bool /*dir*/, bool /*hidden*/){} - virtual void OnReadCircle(const double* /*s*/, const double* /*c*/, bool /*dir*/, bool /*hidden*/){} - virtual void OnReadEllipse(const double* /*c*/, double /*major_radius*/, double /*minor_radius*/, double /*rotation*/, double /*start_angle*/, double /*end_angle*/, bool /*dir*/){} - virtual void OnReadSpline(struct SplineData& /*sd*/){} - virtual void OnReadInsert(const double* /*point*/, const double* /*scale*/, const char* /*name*/, double /*rotation*/){} - virtual void OnReadDimension(const double* /*s*/, const double* /*e*/, const double* /*point*/, double /*rotation*/){} - virtual void AddGraphics() const { } + ImportExport virtual void OnReadLine(const double* /*s*/, const double* /*e*/, bool /*hidden*/){} + ImportExport virtual void OnReadPoint(const double* /*s*/){} + ImportExport virtual void OnReadText(const double* /*point*/, const double /*height*/, const char* /*text*/){} + ImportExport virtual void OnReadArc(const double* /*s*/, const double* /*e*/, const double* /*c*/, bool /*dir*/, bool /*hidden*/){} + ImportExport virtual void OnReadCircle(const double* /*s*/, const double* /*c*/, bool /*dir*/, bool /*hidden*/){} + ImportExport virtual void OnReadEllipse(const double* /*c*/, double /*major_radius*/, double /*minor_radius*/, double /*rotation*/, double /*start_angle*/, double /*end_angle*/, bool /*dir*/){} + ImportExport virtual void OnReadSpline(struct SplineData& /*sd*/){} + ImportExport virtual void OnReadInsert(const double* /*point*/, const double* /*scale*/, const char* /*name*/, double /*rotation*/){} + ImportExport virtual void OnReadDimension(const double* /*s*/, const double* /*e*/, const double* /*point*/, double /*rotation*/){} + ImportExport virtual void AddGraphics() const { } - std::string LayerName() const; + ImportExport std::string LayerName() const; }; #endif diff --git a/src/Mod/Import/CMakeLists.txt b/src/Mod/Import/CMakeLists.txt index 2e7713840e..8a606109ce 100644 --- a/src/Mod/Import/CMakeLists.txt +++ b/src/Mod/Import/CMakeLists.txt @@ -42,7 +42,6 @@ SET(DXF_Plate set(Import_Scripts Init.py - gzip_utf8.py stepZ.py ) @@ -82,4 +81,4 @@ INSTALL( FILES_MATCHING PATTERN "*.rub*" ) - + diff --git a/src/Mod/Import/Gui/AppImportGui.cpp b/src/Mod/Import/Gui/AppImportGui.cpp index e851e20662..99e8aea2e9 100644 --- a/src/Mod/Import/Gui/AppImportGui.cpp +++ b/src/Mod/Import/Gui/AppImportGui.cpp @@ -32,7 +32,7 @@ // use a different name to CreateCommand() -void CreateImportCommands(void); +void CreateImportCommands(); namespace ImportGui { diff --git a/src/Mod/Import/Gui/AppImportGuiPy.cpp b/src/Mod/Import/Gui/AppImportGuiPy.cpp index eb5cddc018..7f3add3a11 100644 --- a/src/Mod/Import/Gui/AppImportGuiPy.cpp +++ b/src/Mod/Import/Gui/AppImportGuiPy.cpp @@ -122,7 +122,7 @@ namespace ImportGui { class OCAFBrowser { public: - OCAFBrowser(Handle(TDocStd_Document) h) + explicit OCAFBrowser(Handle(TDocStd_Document) h) : pDoc(h) { myGroupIcon = QApplication::style()->standardIcon(QStyle::SP_DirIcon); @@ -178,7 +178,7 @@ void OCAFBrowser::load(const TDF_Label& label, QTreeWidgetItem* item, const QStr Handle(TDataStd_Name) name; if (label.FindAttribute(TDataStd_Name::GetID(),name)) { - QString text = QString::fromLatin1("%1 %2").arg(s).arg(QString::fromUtf8(toString(name->Get()).c_str())); + QString text = QString::fromLatin1("%1 %2").arg(s, QString::fromUtf8(toString(name->Get()).c_str())); item->setText(0, text); } @@ -292,7 +292,7 @@ public: } private: - virtual void applyFaceColors(Part::Feature* part, const std::vector& colors) override { + void applyFaceColors(Part::Feature* part, const std::vector& colors) override { auto vp = dynamic_cast(Gui::Application::Instance->getViewProvider(part)); if (!vp) return; @@ -311,7 +311,7 @@ private: vp->DiffuseColor.setValues(colors); } } - virtual void applyEdgeColors(Part::Feature* part, const std::vector& colors) override { + void applyEdgeColors(Part::Feature* part, const std::vector& colors) override { auto vp = dynamic_cast(Gui::Application::Instance->getViewProvider(part)); if (!vp) return; @@ -321,7 +321,7 @@ private: else vp->LineColorArray.setValues(colors); } - virtual void applyLinkColor(App::DocumentObject *obj, int index, App::Color color) override { + void applyLinkColor(App::DocumentObject *obj, int index, App::Color color) override { auto vp = dynamic_cast(Gui::Application::Instance->getViewProvider(obj)); if(!vp) return; @@ -339,7 +339,7 @@ private: mat.diffuseColor = color; vp->MaterialList.set1Value(index,mat); } - virtual void applyElementColors(App::DocumentObject *obj, + void applyElementColors(App::DocumentObject *obj, const std::map &colors) override { auto vp = Gui::Application::Instance->getViewProvider(obj); @@ -357,7 +357,7 @@ public: : ExportOCAF(h, explicitPlacement) { } - virtual void findColors(Part::Feature* part, std::vector& colors) const + void findColors(Part::Feature* part, std::vector& colors) const override { Gui::ViewProvider* vp = Gui::Application::Instance->getViewProvider(part); if (vp && vp->isDerivedFrom(PartGui::ViewProviderPartExt::getClassTypeId())) { @@ -388,7 +388,7 @@ public: initialize("This module is the ImportGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object insert(const Py::Tuple& args, const Py::Dict &kwds) @@ -423,10 +423,7 @@ private: Handle(XCAFApp_Application) hApp = XCAFApp_Application::GetApplication(); Handle(TDocStd_Document) hDoc; - bool optionReadShapeCompoundMode = true; hApp->NewDocument(TCollection_ExtendedString("MDTV-CAF"), hDoc); - ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Import/hSTEP"); - optionReadShapeCompoundMode = hGrp->GetBool("ReadShapeCompoundMode", optionReadShapeCompoundMode); ImportOCAFExt ocaf(hDoc, pcDoc, file.fileNamePure()); FC_TIME_INIT(t); FC_DURATION_DECL_INIT2(d1,d2); @@ -586,9 +583,8 @@ private: } if (legacy == Py_None) { - auto hGrp = App::GetApplication().GetParameterGroupByPath( - "User parameter:BaseApp/Preferences/Mod/Import"); - legacy = hGrp->GetBool("ExportLegacy",false) ? Py_True : Py_False; + Part::ImportExportSettings settings; + legacy = settings.getExportLegacy() ? Py_True : Py_False; } Import::ExportOCAF2 ocaf(hDoc, &getShapeColors); diff --git a/src/Mod/Import/Gui/CMakeLists.txt b/src/Mod/Import/Gui/CMakeLists.txt index 438ff59c48..a0fae5a58d 100644 --- a/src/Mod/Import/Gui/CMakeLists.txt +++ b/src/Mod/Import/Gui/CMakeLists.txt @@ -12,6 +12,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} ) diff --git a/src/Mod/Import/Gui/Command.cpp b/src/Mod/Import/Gui/Command.cpp index a534a2cf89..ad333559bb 100644 --- a/src/Mod/Import/Gui/Command.cpp +++ b/src/Mod/Import/Gui/Command.cpp @@ -64,7 +64,7 @@ void FCCmdImportReadBREP::activated(int iMsg) commitCommand(); } -bool FCCmdImportReadBREP::isActive(void) +bool FCCmdImportReadBREP::isActive() { return getGuiApplication()->activeDocument() != nullptr; } @@ -101,7 +101,7 @@ void ImportStep::activated(int iMsg) } } -bool ImportStep::isActive(void) +bool ImportStep::isActive() { if (getActiveGuiDocument()) return true; @@ -141,7 +141,7 @@ void ImportIges::activated(int iMsg) } } -bool ImportIges::isActive(void) +bool ImportIges::isActive() { if (getActiveGuiDocument()) return true; @@ -150,7 +150,7 @@ bool ImportIges::isActive(void) } -void CreateImportCommands(void) +void CreateImportCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new FCCmdImportReadBREP()); diff --git a/src/Mod/Import/Gui/Workbench.h b/src/Mod/Import/Gui/Workbench.h index cd659cc21e..3a8271fffc 100644 --- a/src/Mod/Import/Gui/Workbench.h +++ b/src/Mod/Import/Gui/Workbench.h @@ -33,15 +33,15 @@ namespace ImportGui { */ class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace ImportGui diff --git a/src/Mod/Import/Init.py b/src/Mod/Import/Init.py index ea54ff6d1c..48baecd847 100644 --- a/src/Mod/Import/Init.py +++ b/src/Mod/Import/Init.py @@ -33,9 +33,3 @@ FreeCAD.addImportType("PLMXML files (*.plmxml)","PlmXmlParser") FreeCAD.addImportType("STEPZ Zip File Type (*.stpZ *.stpz)","stepZ") FreeCAD.addExportType("STEPZ zip File Type (*.stpZ *.stpz)","stepZ") - -# Add initial parameters value if they are not set - -paramGetV = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Import/hSTEP") -if paramGetV.GetBool("ReadShapeCompoundMode", False) != paramGetV.GetBool("ReadShapeCompoundMode", True): - paramGetV.SetBool("ReadShapeCompoundMode", True) diff --git a/src/Mod/Import/gzip_utf8.py b/src/Mod/Import/gzip_utf8.py deleted file mode 100644 index 7a99852861..0000000000 --- a/src/Mod/Import/gzip_utf8.py +++ /dev/null @@ -1,530 +0,0 @@ -"""Functions that read and write gzipped files. - -The user of the file doesn't have to worry about the compression, -but random access is not allowed.""" - -# based on Andrew Kuchling's minigzip.py distributed with the zlib module - -# License: PSF, see https://www.python.org/psf/ -# original file: gzip.py from https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz -# changed line: -# self.fileobj.write(fname + '\000') -# to: -# self.fileobj.write(fname.encode('utf-8') + '\000') -# as a workaround to gzip filenames containing utf-8 characters on win systems - -import struct, sys, time, os -import zlib -import io -from __builtin__ import open as builtin_open -try: - long -except NameError: - long = int - -__all__ = ["GzipFile","open"] - -FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16 - -READ, WRITE = 1, 2 - -def write32u(output, value): - # The L format writes the bit pattern correctly whether signed - # or unsigned. - output.write(struct.pack("' - - def _check_closed(self): - """Raises a ValueError if the underlying file object has been closed. - - """ - if self.closed: - raise ValueError('I/O operation on closed file.') - - def _init_write(self, filename): - self.name = filename - self.crc = zlib.crc32(b"") & 0xffffffff - self.size = 0 - self.writebuf = [] - self.bufsize = 0 - - def _write_gzip_header(self): - self.fileobj.write('\037\213') # magic header - self.fileobj.write('\010') # compression method - fname = os.path.basename(self.name) - if fname.endswith(".gz"): - fname = fname[:-3] - flags = 0 - if fname: - flags = FNAME - self.fileobj.write(chr(flags)) - mtime = self.mtime - if mtime is None: - mtime = time.time() - write32u(self.fileobj, long(mtime)) - self.fileobj.write('\002') - self.fileobj.write('\377') - if fname: - self.fileobj.write(fname.encode('utf-8') + '\000') - - def _init_read(self): - self.crc = zlib.crc32(b"") & 0xffffffff - self.size = 0 - - def _read_gzip_header(self): - magic = self.fileobj.read(2) - if magic != '\037\213': - raise IOError('Not a gzipped file') - method = ord( self.fileobj.read(1) ) - if method != 8: - raise IOError('Unknown compression method') - flag = ord( self.fileobj.read(1) ) - self.mtime = read32(self.fileobj) - # extraflag = self.fileobj.read(1) - # os = self.fileobj.read(1) - self.fileobj.read(2) - - if flag & FEXTRA: - # Read & discard the extra field, if present - xlen = ord(self.fileobj.read(1)) - xlen = xlen + 256*ord(self.fileobj.read(1)) - self.fileobj.read(xlen) - if flag & FNAME: - # Read and discard a null-terminated string containing the filename - while True: - s = self.fileobj.read(1) - if not s or s=='\000': - break - if flag & FCOMMENT: - # Read and discard a null-terminated string containing a comment - while True: - s = self.fileobj.read(1) - if not s or s=='\000': - break - if flag & FHCRC: - self.fileobj.read(2) # Read & discard the 16-bit header CRC - - def write(self,data): - self._check_closed() - if self.mode != WRITE: - import errno - raise IOError(errno.EBADF, "write() on read-only GzipFile object") - - if self.fileobj is None: - raise ValueError("write() on closed GzipFile object") - - # Convert data type if called by io.BufferedWriter. - if isinstance(data, memoryview): - data = data.tobytes() - - if len(data) > 0: - self.size = self.size + len(data) - self.crc = zlib.crc32(data, self.crc) & 0xffffffff - self.fileobj.write( self.compress.compress(data) ) - self.offset += len(data) - - return len(data) - - def read(self, size=-1): - self._check_closed() - if self.mode != READ: - import errno - raise IOError(errno.EBADF, "read() on write-only GzipFile object") - - if self.extrasize <= 0 and self.fileobj is None: - return '' - - readsize = 1024 - if size < 0: # get the whole thing - try: - while True: - self._read(readsize) - readsize = min(self.max_read_chunk, readsize * 2) - except EOFError: - size = self.extrasize - else: # just get some more of it - try: - while size > self.extrasize: - self._read(readsize) - readsize = min(self.max_read_chunk, readsize * 2) - except EOFError: - if size > self.extrasize: - size = self.extrasize - - offset = self.offset - self.extrastart - chunk = self.extrabuf[offset: offset + size] - self.extrasize = self.extrasize - size - - self.offset += size - return chunk - - def _unread(self, buf): - self.extrasize = len(buf) + self.extrasize - self.offset -= len(buf) - - def _read(self, size=1024): - if self.fileobj is None: - raise EOFError("Reached EOF") - - if self._new_member: - # If the _new_member flag is set, we have to - # jump to the next member, if there is one. - # - # First, check if we're at the end of the file; - # if so, it's time to stop; no more members to read. - pos = self.fileobj.tell() # Save current position - self.fileobj.seek(0, 2) # Seek to end of file - if pos == self.fileobj.tell(): - raise EOFError("Reached EOF") - else: - self.fileobj.seek( pos ) # Return to original position - - self._init_read() - self._read_gzip_header() - self.decompress = zlib.decompressobj(-zlib.MAX_WBITS) - self._new_member = False - - # Read a chunk of data from the file - buf = self.fileobj.read(size) - - # If the EOF has been reached, flush the decompression object - # and mark this object as finished. - - if buf == "": - uncompress = self.decompress.flush() - self._read_eof() - self._add_read_data( uncompress ) - raise EOFError('Reached EOF') - - uncompress = self.decompress.decompress(buf) - self._add_read_data( uncompress ) - - if self.decompress.unused_data != "": - # Ending case: we've come to the end of a member in the file, - # so seek back to the start of the unused data, finish up - # this member, and read a new gzip header. - # (The number of bytes to seek back is the length of the unused - # data, minus 8 because _read_eof() will rewind a further 8 bytes) - self.fileobj.seek( -len(self.decompress.unused_data)+8, 1) - - # Check the CRC and file size, and set the flag so we read - # a new member on the next call - self._read_eof() - self._new_member = True - - def _add_read_data(self, data): - self.crc = zlib.crc32(data, self.crc) & 0xffffffff - offset = self.offset - self.extrastart - self.extrabuf = self.extrabuf[offset:] + data - self.extrasize = self.extrasize + len(data) - self.extrastart = self.offset - self.size = self.size + len(data) - - def _read_eof(self): - # We've read to the end of the file, so we have to rewind in order - # to reread the 8 bytes containing the CRC and the file size. - # We check the that the computed CRC and size of the - # uncompressed data matches the stored values. Note that the size - # stored is the true file size mod 2**32. - self.fileobj.seek(-8, 1) - crc32 = read32(self.fileobj) - isize = read32(self.fileobj) # may exceed 2GB - if crc32 != self.crc: - raise IOError("CRC check failed %s != %s" % (hex(crc32), - hex(self.crc))) - elif isize != (self.size & 0xffffffff): - raise IOError("Incorrect length of data produced") - - # Gzip files can be padded with zeroes and still have archives. - # Consume all zero bytes and set the file position to the first - # non-zero byte. See http://www.gzip.org/#faq8 - c = "\x00" - while c == "\x00": - c = self.fileobj.read(1) - if c: - self.fileobj.seek(-1, 1) - - @property - def closed(self): - return self.fileobj is None - - def close(self): - if self.fileobj is None: - return - if self.mode == WRITE: - self.fileobj.write(self.compress.flush()) - write32u(self.fileobj, self.crc) - # self.size may exceed 2GB, or even 4GB - write32u(self.fileobj, self.size & 0xffffffff) - self.fileobj = None - elif self.mode == READ: - self.fileobj = None - if self.myfileobj: - self.myfileobj.close() - self.myfileobj = None - - def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH): - self._check_closed() - if self.mode == WRITE: - # Ensure the compressor's buffer is flushed - self.fileobj.write(self.compress.flush(zlib_mode)) - self.fileobj.flush() - - def fileno(self): - """Invoke the underlying file object's fileno() method. - - This will raise AttributeError if the underlying file object - doesn't support fileno(). - """ - return self.fileobj.fileno() - - def rewind(self): - '''Return the uncompressed stream file position indicator to the - beginning of the file''' - if self.mode != READ: - raise IOError("Can't rewind in write mode") - self.fileobj.seek(0) - self._new_member = True - self.extrabuf = "" - self.extrasize = 0 - self.extrastart = 0 - self.offset = 0 - - def readable(self): - return self.mode == READ - - def writable(self): - return self.mode == WRITE - - def seekable(self): - return True - - def seek(self, offset, whence=0): - if whence: - if whence == 1: - offset = self.offset + offset - else: - raise ValueError('Seek from end not supported') - if self.mode == WRITE: - if offset < self.offset: - raise IOError('Negative seek in write mode') - count = offset - self.offset - for i in xrange(count // 1024): - self.write(1024 * '\0') - self.write((count % 1024) * '\0') - elif self.mode == READ: - if offset < self.offset: - # for negative seek, rewind and do positive seek - self.rewind() - count = offset - self.offset - for i in xrange(count // 1024): - self.read(1024) - self.read(count % 1024) - - return self.offset - - def readline(self, size=-1): - if size < 0: - # Shortcut common case - newline found in buffer. - offset = self.offset - self.extrastart - i = self.extrabuf.find('\n', offset) + 1 - if i > 0: - self.extrasize -= i - offset - self.offset += i - offset - return self.extrabuf[offset: i] - - size = sys.maxint - readsize = self.min_readsize - else: - readsize = size - bufs = [] - while size != 0: - c = self.read(readsize) - i = c.find('\n') - - # We set i=size to break out of the loop under two - # conditions: 1) there's no newline, and the chunk is - # larger than size, or 2) there is a newline, but the - # resulting line would be longer than 'size'. - if (size <= i) or (i == -1 and len(c) > size): - i = size - 1 - - if i >= 0 or c == '': - bufs.append(c[:i + 1]) # Add portion of last chunk - self._unread(c[i + 1:]) # Push back rest of chunk - break - - # Append chunk to list, decrease 'size', - bufs.append(c) - size = size - len(c) - readsize = min(size, readsize * 2) - if readsize > self.min_readsize: - self.min_readsize = min(readsize, self.min_readsize * 2, 512) - return ''.join(bufs) # Return resulting line - - -def _test(): - # Act like gzip; with -d, act like gunzip. - # The input file is not deleted, however, nor are any other gzip - # options or features supported. - args = sys.argv[1:] - decompress = args and args[0] == "-d" - if decompress: - args = args[1:] - if not args: - args = ["-"] - for arg in args: - if decompress: - if arg == "-": - f = GzipFile(filename="", mode="rb", fileobj=sys.stdin) - g = sys.stdout - else: - if arg[-3:] != ".gz": - print("filename doesn't end in .gz:", repr(arg)) - continue - f = open(arg, "rb") - g = builtin_open(arg[:-3], "wb") - else: - if arg == "-": - f = sys.stdin - g = GzipFile(filename="", mode="wb", fileobj=sys.stdout) - else: - f = builtin_open(arg, "rb") - g = open(arg + ".gz", "wb") - while True: - chunk = f.read(1024) - if not chunk: - break - g.write(chunk) - if g is not sys.stdout: - g.close() - if f is not sys.stdin: - f.close() - -if __name__ == '__main__': - _test() diff --git a/src/Mod/Import/stepZ.py b/src/Mod/Import/stepZ.py index a6f0034a02..2b84c488a9 100644 --- a/src/Mod/Import/stepZ.py +++ b/src/Mod/Import/stepZ.py @@ -13,60 +13,46 @@ import six -import FreeCAD,FreeCADGui +import FreeCAD +import FreeCADGui import shutil -import os, re +import os +import re import ImportGui import PySide -from PySide import QtGui, QtCore +from PySide import QtCore +from PySide import QtGui import tempfile -import shutil ___stpZversion___ = "1.3.9" # support both gz and zipfile archives # Catia seems to use gz, Inventor zipfile # improved import, open and export -if six.PY3: - import gzip as gz - import builtins as builtin #py3 - import importlib -else: # six.PY2 - import gzip_utf8 as gz - import __builtin__ as builtin #py2 + +import gzip as gz +import builtins as builtin #py3 +import importlib + import zipfile as zf # import stepZ; import importlib; importlib.reload(stepZ); stepZ.open(u"C:/Temp/brick.stpz") -# import stepZ; import importlib; importlib.reload(stepZ); import gzip_utf8; importlib.reload(gzip_utf8) def mkz_string(input): - if six.PY3: - if isinstance(input, str): - return input - else: - input = input.encode('utf-8') - return input - else: # six.PY2 - if isinstance(input, six.text_type): - input = input.encode('utf-8') - return input - else: - return input + if isinstance(input, str): + return input + else: + input = input.encode('utf-8') + return input #### def mkz_unicode(input): - if six.PY3: - if isinstance(input, str): - return input - else: - input = input.decode('utf-8') - return input - else: # six.PY2 - if isinstance(input, six.text_type): - input = input.decode('utf-8') - return input - else: - return input + if isinstance(input, str): + return input + else: + input = input.decode('utf-8') + return input + #### def sayz(msg): FreeCAD.Console.PrintMessage(msg) @@ -88,7 +74,7 @@ def import_stpz(fn,fc,doc): fname=os.path.splitext(os.path.basename(fn))[0] basepath=os.path.split(fn)[0] filepath = os.path.join(basepath,fname + u'.stp') - + tempdir = tempfile.gettempdir() # get the current temporary directory tempfilepath = os.path.join(tempdir,fname + u'.stp') @@ -110,7 +96,7 @@ def import_stpz(fn,fc,doc): def open(filename,doc=None): sayz("stpZ version "+___stpZversion___) - + if zf.is_zipfile(filename): with zf.ZipFile(filename, 'r') as fz: file_names = fz.namelist() diff --git a/src/Mod/Inspection/App/AppInspection.cpp b/src/Mod/Inspection/App/AppInspection.cpp index cc3ececdd4..aef3ea4cc5 100644 --- a/src/Mod/Inspection/App/AppInspection.cpp +++ b/src/Mod/Inspection/App/AppInspection.cpp @@ -37,7 +37,7 @@ public: initialize("This module is the Inspection module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Inspection/App/CMakeLists.txt b/src/Mod/Inspection/App/CMakeLists.txt index 707df92694..78cbb20f5f 100644 --- a/src/Mod/Inspection/App/CMakeLists.txt +++ b/src/Mod/Inspection/App/CMakeLists.txt @@ -12,6 +12,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Inspection/App/InspectionFeature.cpp b/src/Mod/Inspection/App/InspectionFeature.cpp index e39b95f8e5..af329f6ea6 100644 --- a/src/Mod/Inspection/App/InspectionFeature.cpp +++ b/src/Mod/Inspection/App/InspectionFeature.cpp @@ -141,7 +141,7 @@ namespace Inspection { std::max((unsigned long)(clBBMesh.LengthZ() / fGridLen), 1)); } - void Validate (const MeshCore::MeshKernel&) + void Validate (const MeshCore::MeshKernel&) override { // do nothing } @@ -151,24 +151,24 @@ namespace Inspection { // do nothing } - bool Verify() const + bool Verify() const override { // do nothing return true; } protected: - void CalculateGridLength (unsigned long /*ulCtGrid*/, unsigned long /*ulMaxGrids*/) + void CalculateGridLength (unsigned long /*ulCtGrid*/, unsigned long /*ulMaxGrids*/) override { // do nothing } - void CalculateGridLength (int /*iCtGridPerAxis*/) + void CalculateGridLength (int /*iCtGridPerAxis*/) override { // do nothing } - unsigned long HasElements (void) const + unsigned long HasElements (void) const override { return _pclMesh->CountFacets(); } @@ -210,7 +210,7 @@ namespace Inspection { _aulGrid[ulX1][ulY1][ulZ1].insert(ulFacetIndex); } - void InitGrid (void) + void InitGrid (void) override { unsigned long i, j; @@ -238,7 +238,7 @@ namespace Inspection { } } - void RebuildGrid (void) + void RebuildGrid (void) override { _ulCtElements = _pclMesh->CountFacets(); InitGrid(); @@ -374,9 +374,9 @@ float InspectNominalFastMesh::getDistance(const Base::Vector3f& point) const unsigned long ulX, ulY, ulZ; _pGrid->Position(point, ulX, ulY, ulZ); unsigned long ulLevel = 0; - while (indices.size() == 0 && ulLevel <= max_level) + while (indices.empty() && ulLevel <= max_level) _pGrid->GetHull(ulX, ulY, ulZ, ulLevel++, indices); - if (indices.size() == 0 || ulLevel==1) + if (indices.empty() || ulLevel==1) _pGrid->GetHull(ulX, ulY, ulZ, ulLevel, indices); #endif diff --git a/src/Mod/Inspection/App/InspectionFeature.h b/src/Mod/Inspection/App/InspectionFeature.h index 3a5409d049..2efa5bdb68 100644 --- a/src/Mod/Inspection/App/InspectionFeature.h +++ b/src/Mod/Inspection/App/InspectionFeature.h @@ -59,10 +59,10 @@ public: class InspectionExport InspectActualMesh : public InspectActualGeometry { public: - InspectActualMesh(const Mesh::MeshObject& rMesh); - ~InspectActualMesh(); - virtual unsigned long countPoints() const; - virtual Base::Vector3f getPoint(unsigned long) const; + explicit InspectActualMesh(const Mesh::MeshObject& rMesh); + ~InspectActualMesh() override; + unsigned long countPoints() const override; + Base::Vector3f getPoint(unsigned long) const override; private: const MeshCore::MeshKernel& _mesh; @@ -73,9 +73,9 @@ private: class InspectionExport InspectActualPoints : public InspectActualGeometry { public: - InspectActualPoints(const Points::PointKernel&); - virtual unsigned long countPoints() const; - virtual Base::Vector3f getPoint(unsigned long) const; + explicit InspectActualPoints(const Points::PointKernel&); + unsigned long countPoints() const override; + Base::Vector3f getPoint(unsigned long) const override; private: const Points::PointKernel& _rKernel; @@ -84,9 +84,9 @@ private: class InspectionExport InspectActualShape : public InspectActualGeometry { public: - InspectActualShape(const Part::TopoShape&); - virtual unsigned long countPoints() const; - virtual Base::Vector3f getPoint(unsigned long) const; + explicit InspectActualShape(const Part::TopoShape&); + unsigned long countPoints() const override; + Base::Vector3f getPoint(unsigned long) const override; private: const Part::TopoShape& _rShape; @@ -106,8 +106,8 @@ class InspectionExport InspectNominalMesh : public InspectNominalGeometry { public: InspectNominalMesh(const Mesh::MeshObject& rMesh, float offset); - ~InspectNominalMesh(); - virtual float getDistance(const Base::Vector3f&) const; + ~InspectNominalMesh() override; + float getDistance(const Base::Vector3f&) const override; private: const MeshCore::MeshKernel& _mesh; @@ -121,8 +121,8 @@ class InspectionExport InspectNominalFastMesh : public InspectNominalGeometry { public: InspectNominalFastMesh(const Mesh::MeshObject& rMesh, float offset); - ~InspectNominalFastMesh(); - virtual float getDistance(const Base::Vector3f&) const; + ~InspectNominalFastMesh() override; + float getDistance(const Base::Vector3f&) const override; protected: const MeshCore::MeshKernel& _mesh; @@ -137,8 +137,8 @@ class InspectionExport InspectNominalPoints : public InspectNominalGeometry { public: InspectNominalPoints(const Points::PointKernel&, float offset); - ~InspectNominalPoints(); - virtual float getDistance(const Base::Vector3f&) const; + ~InspectNominalPoints() override; + float getDistance(const Base::Vector3f&) const override; private: const Points::PointKernel& _rKernel; @@ -149,8 +149,8 @@ class InspectionExport InspectNominalShape : public InspectNominalGeometry { public: InspectNominalShape(const TopoDS_Shape&, float offset); - ~InspectNominalShape(); - virtual float getDistance(const Base::Vector3f&) const; + ~InspectNominalShape() override; + float getDistance(const Base::Vector3f&) const override; private: BRepExtrema_DistShapeShape* distss; @@ -160,7 +160,7 @@ private: class InspectionExport PropertyDistanceList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: @@ -174,10 +174,10 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyDistanceList(); + ~PropertyDistanceList() override; - virtual void setSize(int newSize); - virtual int getSize(void) const; + void setSize(int newSize) override; + int getSize() const override; /** Sets the property */ @@ -189,20 +189,20 @@ public: void set1Value (const int idx, float value){_lValueList.operator[] (idx) = value;} void setValues (const std::vector& values); - const std::vector &getValues(void) const{return _lValueList;} + const std::vector &getValues() const{return _lValueList;} - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); - virtual unsigned int getMemSize (void) const; + Property *Copy() const override; + void Paste(const Property &from) override; + unsigned int getMemSize () const override; private: std::vector _lValueList; @@ -215,12 +215,12 @@ private: */ class InspectionExport Feature : public App::DocumentObject { - PROPERTY_HEADER(Inspection::Feature); + PROPERTY_HEADER_WITH_OVERRIDE(Inspection::Feature); public: /// Constructor - Feature(void); - virtual ~Feature(); + Feature(); + ~Feature() override; /** @name Properties */ //@{ @@ -233,27 +233,27 @@ public: /** @name Actions */ //@{ - short mustExecute() const; + short mustExecute() const override; /// recalculate the Feature - App::DocumentObjectExecReturn* execute(void); + App::DocumentObjectExecReturn* execute() override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const + const char* getViewProviderName() const override { return "InspectionGui::ViewProviderInspection"; } }; class InspectionExport Group : public App::DocumentObjectGroup { - PROPERTY_HEADER(Inspection::Group); + PROPERTY_HEADER_WITH_OVERRIDE(Inspection::Group); public: /// Constructor - Group(void); - virtual ~Group(); + Group(); + ~Group() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const + const char* getViewProviderName() const override { return "InspectionGui::ViewProviderInspectionGroup"; } }; diff --git a/src/Mod/Inspection/Gui/AppInspectionGui.cpp b/src/Mod/Inspection/Gui/AppInspectionGui.cpp index 7052a0e6eb..405d4c788a 100644 --- a/src/Mod/Inspection/Gui/AppInspectionGui.cpp +++ b/src/Mod/Inspection/Gui/AppInspectionGui.cpp @@ -44,7 +44,7 @@ public: initialize("This module is the InspectionGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Inspection/Gui/CMakeLists.txt b/src/Mod/Inspection/Gui/CMakeLists.txt index 1e9e655a43..657f842c46 100644 --- a/src/Mod/Inspection/Gui/CMakeLists.txt +++ b/src/Mod/Inspection/Gui/CMakeLists.txt @@ -4,6 +4,7 @@ include_directories( ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ) diff --git a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp index 5581059b28..a52625bbe2 100644 --- a/src/Mod/Inspection/Gui/ViewProviderInspection.cpp +++ b/src/Mod/Inspection/Gui/ViewProviderInspection.cpp @@ -128,13 +128,13 @@ void ViewProviderInspection::onChanged(const App::Property* prop) } } -void ViewProviderInspection::hide(void) +void ViewProviderInspection::hide() { inherited::hide(); pcColorStyle->style = SoDrawStyle::INVISIBLE; } -void ViewProviderInspection::show(void) +void ViewProviderInspection::show() { inherited::show(); pcColorStyle->style = SoDrawStyle::FILLED; @@ -296,7 +296,7 @@ void ViewProviderInspection::updateData(const App::Property* prop) } } -SoSeparator* ViewProviderInspection::getFrontRoot(void) const +SoSeparator* ViewProviderInspection::getFrontRoot() const { return pcColorRoot; } @@ -376,11 +376,11 @@ void ViewProviderInspection::setDisplayMode(const char* ModeName) inherited::setDisplayMode(ModeName); } -std::vector ViewProviderInspection::getDisplayModes(void) const +std::vector ViewProviderInspection::getDisplayModes() const { // add modes std::vector StrList; - StrList.push_back("Visual Inspection"); + StrList.emplace_back("Visual Inspection"); return StrList; } @@ -394,9 +394,9 @@ namespace InspectionGui { class ViewProviderProxyObject : public QObject { public: - ViewProviderProxyObject(QWidget* w) : QObject(nullptr), widget(w) {} - ~ViewProviderProxyObject() {} - void customEvent(QEvent *) + explicit ViewProviderProxyObject(QWidget* w) : QObject(nullptr), widget(w) {} + ~ViewProviderProxyObject() override {} + void customEvent(QEvent *) override { if (!widget.isNull()) { QList flags = widget->findChildren(); @@ -479,7 +479,7 @@ void ViewProviderInspection::inspectCallback(void * ud, SoEventCallback * n) } else if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::UP) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No point picked.\n"); return; } diff --git a/src/Mod/Inspection/Gui/ViewProviderInspection.h b/src/Mod/Inspection/Gui/ViewProviderInspection.h index 74a7be1a3c..3d98313326 100644 --- a/src/Mod/Inspection/Gui/ViewProviderInspection.h +++ b/src/Mod/Inspection/Gui/ViewProviderInspection.h @@ -49,36 +49,36 @@ class ViewProviderInspection : public Gui::ViewProviderDocumentObject, public Base::Observer{ typedef ViewProviderDocumentObject inherited; - PROPERTY_HEADER(InspectionGui::ViewProviderInspection); + PROPERTY_HEADER_WITH_OVERRIDE(InspectionGui::ViewProviderInspection); public: ViewProviderInspection(); - virtual ~ViewProviderInspection(); + ~ViewProviderInspection() override; App::PropertyBool OutsideGrayed; App::PropertyFloatConstraint PointSize; - void attach(App::DocumentObject *pcFeat); + void attach(App::DocumentObject *pcFeat) override; /// Sets the viewing mode - void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; /// Returns a list of all possible modes - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; /// Update colorbar after recomputation of distances. - void updateData(const App::Property*); + void updateData(const App::Property*) override; /// Once the color bar settings has been changed this method gets called to update the feature's representation - void OnChange(Base::Subject &rCaller,int rcReason); - QIcon getIcon() const; + void OnChange(Base::Subject &rCaller,int rcReason) override; + QIcon getIcon() const override; /// Returns a color bar - SoSeparator* getFrontRoot(void) const; + SoSeparator* getFrontRoot() const override; /// Hide the object in the view - virtual void hide(void); + void hide() override; /// Show the object in the view - virtual void show(void); + void show() override; static void inspectCallback(void * ud, SoEventCallback * n); protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; void setDistances(); QString inspectDistance(const SoPickedPoint* pp) const; @@ -100,14 +100,14 @@ private: class ViewProviderInspectionGroup : public Gui::ViewProviderDocumentObjectGroup { - PROPERTY_HEADER(InspectionGui::ViewProviderInspectionGroup); + PROPERTY_HEADER_WITH_OVERRIDE(InspectionGui::ViewProviderInspectionGroup); public: /// constructor ViewProviderInspectionGroup(); /// destructor - virtual ~ViewProviderInspectionGroup(); - QIcon getIcon() const; + ~ViewProviderInspectionGroup() override; + QIcon getIcon() const override; }; } // namespace InspectionGui diff --git a/src/Mod/Inspection/Gui/VisualInspection.cpp b/src/Mod/Inspection/Gui/VisualInspection.cpp index 604b40ec43..3dfab3c51f 100644 --- a/src/Mod/Inspection/Gui/VisualInspection.cpp +++ b/src/Mod/Inspection/Gui/VisualInspection.cpp @@ -44,17 +44,17 @@ namespace InspectionGui { class SingleSelectionItem : public QTreeWidgetItem { public: - SingleSelectionItem (QTreeWidget* parent) + explicit SingleSelectionItem (QTreeWidget* parent) : QTreeWidgetItem(parent), _compItem(nullptr) { } - SingleSelectionItem (QTreeWidgetItem* parent) + explicit SingleSelectionItem (QTreeWidgetItem* parent) : QTreeWidgetItem (parent), _compItem(nullptr) { } - ~SingleSelectionItem () + ~SingleSelectionItem () override { } diff --git a/src/Mod/Inspection/Gui/VisualInspection.h b/src/Mod/Inspection/Gui/VisualInspection.h index d13f56035b..ea22dd40fc 100644 --- a/src/Mod/Inspection/Gui/VisualInspection.h +++ b/src/Mod/Inspection/Gui/VisualInspection.h @@ -36,10 +36,10 @@ class VisualInspection : public QDialog Q_OBJECT public: - VisualInspection(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~ VisualInspection(); + explicit VisualInspection(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~ VisualInspection() override; - void accept(); + void accept() override; protected Q_SLOTS: void onActivateItem(QTreeWidgetItem*); diff --git a/src/Mod/Inspection/Gui/Workbench.h b/src/Mod/Inspection/Gui/Workbench.h index e545fc2270..3706b88e67 100644 --- a/src/Mod/Inspection/Gui/Workbench.h +++ b/src/Mod/Inspection/Gui/Workbench.h @@ -30,15 +30,15 @@ namespace InspectionGui { class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; }; } // namespace InspectionGui diff --git a/src/Mod/Material/CMakeLists.txt b/src/Mod/Material/CMakeLists.txt index 6d93edd9fe..6ecd5d83c8 100644 --- a/src/Mod/Material/CMakeLists.txt +++ b/src/Mod/Material/CMakeLists.txt @@ -28,13 +28,16 @@ SET (MaterialLib_Files StandardMaterial/AlMg3F24.FCMat StandardMaterial/AlMgSi1F31.FCMat StandardMaterial/Aluminum-6061-T6.FCMat + StandardMaterial/Aluminum-Generic.FCMat StandardMaterial/AlZn4-5Mg1F35.FCMat StandardMaterial/CalculiX-Steel.FCMat StandardMaterial/Concrete-Generic.FCMat + StandardMaterial/Copper-Generic.FCMat StandardMaterial/Glass-E-GlassFibre.FCMat StandardMaterial/Glass-Generic.FCMat StandardMaterial/Glass-S2-GlassFibre.FCMat StandardMaterial/Graphite.FCMat + StandardMaterial/Invar-Generic.FCMat StandardMaterial/PA6-Generic.FCMat StandardMaterial/PET-Generic.FCMat StandardMaterial/PLA-Generic.FCMat diff --git a/src/Mod/Material/FluidMaterial/Water.FCMat b/src/Mod/Material/FluidMaterial/Water.FCMat index 6a854d4757..a277dfaaa6 100644 --- a/src/Mod/Material/FluidMaterial/Water.FCMat +++ b/src/Mod/Material/FluidMaterial/Water.FCMat @@ -17,7 +17,7 @@ PrandtlNumber = 7.56 SpecificHeat = 4182 J/kg/K ThermalConductivity = 0.591 W/m/K ; https://en.wikipedia.org/wiki/Water -VolumetricThermalExpansionCoefficient = 2.07e-4 m/m/K +ThermalExpansionCoefficient = 2.07e-4 m/m/K [Electrical] RelativePermittivity = 80.0 diff --git a/src/Mod/Material/Material.py b/src/Mod/Material/Material.py index 18ad48eacc..c111c2592c 100644 --- a/src/Mod/Material/Material.py +++ b/src/Mod/Material/Material.py @@ -71,10 +71,7 @@ def importFCMat(fileName): ) Config = configparser.RawConfigParser() Config.optionxform = str - if sys.version_info.major >= 3: - Config.read(fileName, encoding='utf-8') # respect unicode filenames - else: - Config.read(fileName) + Config.read(fileName, encoding='utf-8') # respect unicode filenames dict1 = {} for section in Config.sections(): options = Config.options(section) diff --git a/src/Mod/Material/MaterialEditor.py b/src/Mod/Material/MaterialEditor.py index c546ab199c..ad7353a690 100644 --- a/src/Mod/Material/MaterialEditor.py +++ b/src/Mod/Material/MaterialEditor.py @@ -25,7 +25,6 @@ __author__ = "Yorik van Havre, Bernd Hahnebach" __url__ = "http://www.freecadweb.org" import os -import sys from PySide import QtCore, QtGui, QtSvg import FreeCAD @@ -33,8 +32,7 @@ import FreeCADGui # import Material_rc # is this still needed after the move to card utils??? -if sys.version_info.major >= 3: - unicode = str +unicode = str # ************************************************************************************************ @@ -543,9 +541,6 @@ class MaterialEditor: group = item.parent() it = group.child(item.row(), 1) name = it.text() - if sys.version_info.major < 3: - if isinstance(name, unicode): - name = name.encode("utf8") if not name: name = "Material" filetuple = QtGui.QFileDialog.getSaveFileName( diff --git a/src/Mod/Material/StandardMaterial/Aluminum-Generic.FCMat b/src/Mod/Material/StandardMaterial/Aluminum-Generic.FCMat new file mode 100644 index 0000000000..bc2953e950 --- /dev/null +++ b/src/Mod/Material/StandardMaterial/Aluminum-Generic.FCMat @@ -0,0 +1,25 @@ +; Aluminum-Generic +; Uwe Stöhr +; information about the content of such cards can be found on the wiki: +; https://www.freecadweb.org/wiki/Material +; file created by FreeCAD 0.21.29751 (Git) + +[General] +Name = Aluminum Generic +Father = Metal +KindOfMaterial = Aluminium + +[Mechanical] +Density = 2700 kg/m^3 +PoissonRatio = 0.35 +ShearModulus = 25.0 GPa +UltimateTensileStrength = 310 MPa +YoungsModulus = 70000 MPa + +[Thermal] +SpecificHeat = 897.0 J/kg/K +ThermalConductivity = 237.0 W/m/K +ThermalExpansionCoefficient = 23.1 µm/m/K + +[Electrical] +ElectricalConductivity = 370370.4 S/m diff --git a/src/Mod/Material/StandardMaterial/Copper-Generic.FCMat b/src/Mod/Material/StandardMaterial/Copper-Generic.FCMat new file mode 100644 index 0000000000..3ad69c6c3c --- /dev/null +++ b/src/Mod/Material/StandardMaterial/Copper-Generic.FCMat @@ -0,0 +1,26 @@ +; Copper Generic +; Uwe Stöhr +; information about the content of such cards can be found on the wiki: +; https://www.freecadweb.org/wiki/Material +; file created by FreeCAD 0.21.30044 (Git) + +[General] +Name = Copper Generic +Father = Metal +KindOfMaterial = Copper + +[Mechanical] +Density = 8960 kg/m^3 +PoissonRatio = 0.343 +ShearModulus = 46.0 GPa +UltimateTensileStrength = 210 MPa +YieldStrength = 33.3 MPa +YoungsModulus = 119 GPa + +[Thermal] +SpecificHeat = 385.0 J/kg/K +ThermalConductivity = 398.0 W/m/K +ThermalExpansionCoefficient = 16.5 µm/m/K + +[Electrical] +ElectricalConductivity = 588235.3 S/m diff --git a/src/Mod/Material/StandardMaterial/Invar-Generic.FCMat b/src/Mod/Material/StandardMaterial/Invar-Generic.FCMat new file mode 100644 index 0000000000..b16ca7eeef --- /dev/null +++ b/src/Mod/Material/StandardMaterial/Invar-Generic.FCMat @@ -0,0 +1,25 @@ +; Invar Generic +; Uwe Stöhr +; information about the content of such cards can be found on the wiki: +; https://www.freecadweb.org/wiki/Material +; file created by FreeCAD 0.21.30044 (Git) + +[General] +Name = Invar Generic +Father = Metal +KindOfMaterial = Nickel Iron Alloy + +[Mechanical] +Density = 8150 kg/m^3 +PoissonRatio = 0.29 +ShearModulus = 56.0 GPa +UltimateTensileStrength = 600 MPa +YoungsModulus = 140.0 GPa + +[Thermal] +SpecificHeat = 515.0 J/kg/K +ThermalConductivity = 13.5 W/m/K +ThermalExpansionCoefficient = 1.25 µm/m/K + +[Electrical] +ElectricalConductivity = 1250000 S/m diff --git a/src/Mod/Material/materialtools/cardutils.py b/src/Mod/Material/materialtools/cardutils.py index 2518bdc4e6..ef85c558f0 100644 --- a/src/Mod/Material/materialtools/cardutils.py +++ b/src/Mod/Material/materialtools/cardutils.py @@ -24,14 +24,12 @@ __author__ = "Bernd Hahnebach" __url__ = "http://www.freecadweb.org" import os -import sys from os.path import join import FreeCAD -if sys.version_info.major >= 3: - unicode = str +unicode = str # TODO: diff --git a/src/Mod/Measure/App/AppMeasure.cpp b/src/Mod/Measure/App/AppMeasure.cpp index ea53a54bd9..acab353ae4 100644 --- a/src/Mod/Measure/App/AppMeasure.cpp +++ b/src/Mod/Measure/App/AppMeasure.cpp @@ -38,7 +38,7 @@ public: initialize("This module is the Measure module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Measure/App/Measurement.cpp b/src/Mod/Measure/App/Measurement.cpp index b58f97ae96..f9fd8fd562 100644 --- a/src/Mod/Measure/App/Measurement.cpp +++ b/src/Mod/Measure/App/Measurement.cpp @@ -90,7 +90,7 @@ int Measurement::addReference3D(App::DocumentObject *obj, const char* subName) std::vector subElements = References3D.getSubValues(); objects.push_back(obj); - subElements.push_back(subName); + subElements.emplace_back(subName); References3D.setValues(objects, subElements); @@ -496,12 +496,12 @@ Base::Vector3d Measurement::massCenter() const return result; } -unsigned int Measurement::getMemSize(void) const +unsigned int Measurement::getMemSize() const { return 0; } -PyObject *Measurement::getPyObject(void) +PyObject *Measurement::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 diff --git a/src/Mod/Measure/App/Measurement.h b/src/Mod/Measure/App/Measurement.h index 001758fc66..bd191c9919 100644 --- a/src/Mod/Measure/App/Measurement.h +++ b/src/Mod/Measure/App/Measurement.h @@ -47,14 +47,14 @@ namespace Measure }; class MeasureExport Measurement : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: App::PropertyLinkSubList References3D; public: Measurement(); - ~Measurement(); + ~Measurement() override; void clear(); bool has3DReferences(); @@ -66,8 +66,8 @@ public: MeasureType getType(); // from base class - virtual PyObject *getPyObject(void); - virtual unsigned int getMemSize(void) const; + PyObject *getPyObject() override; + virtual unsigned int getMemSize() const; public: // Methods for distances (edge length, two points, edge and a point diff --git a/src/Mod/Measure/App/MeasurementPyImp.cpp b/src/Mod/Measure/App/MeasurementPyImp.cpp index 14c3781cad..3fe1967146 100644 --- a/src/Mod/Measure/App/MeasurementPyImp.cpp +++ b/src/Mod/Measure/App/MeasurementPyImp.cpp @@ -38,7 +38,7 @@ using namespace Measure; // returns a string which represents the object e.g. when printed in python -std::string MeasurementPy::representation(void) const +std::string MeasurementPy::representation() const { return ""; } diff --git a/src/Mod/Mesh/App/AppMeshPy.cpp b/src/Mod/Mesh/App/AppMeshPy.cpp index 5066b4212d..749c1d4223 100644 --- a/src/Mod/Mesh/App/AppMeshPy.cpp +++ b/src/Mod/Mesh/App/AppMeshPy.cpp @@ -138,10 +138,10 @@ public: "\n"); } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) + Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); diff --git a/src/Mod/Mesh/App/CMakeLists.txt b/src/Mod/Mesh/App/CMakeLists.txt index ea7df721d3..43351fdd9f 100644 --- a/src/Mod/Mesh/App/CMakeLists.txt +++ b/src/Mod/Mesh/App/CMakeLists.txt @@ -8,6 +8,7 @@ include_directories( ${CMAKE_SOURCE_DIR}/src/3rdParty/libkdtree ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} ) diff --git a/src/Mod/Mesh/App/Core/Algorithm.cpp b/src/Mod/Mesh/App/Core/Algorithm.cpp index 99587fe246..23627423d2 100644 --- a/src/Mod/Mesh/App/Core/Algorithm.cpp +++ b/src/Mod/Mesh/App/Core/Algorithm.cpp @@ -360,7 +360,7 @@ void MeshAlgorithm::GetFacetBorders (const std::vector &raulInd, } } - if (aclEdges.size() == 0) + if (aclEdges.empty()) return; // no borders found (=> solid) // search for edges in the unsorted list @@ -373,7 +373,7 @@ void MeshAlgorithm::GetFacetBorders (const std::vector &raulInd, clBorder.push_back(ulFirst); clBorder.push_back(ulLast); - while (aclEdges.size() > 0) { + while (!aclEdges.empty()) { // get adjacent edge std::list >::iterator pEI; for (pEI = aclEdges.begin(); pEI != aclEdges.end(); ++pEI) { @@ -417,7 +417,7 @@ void MeshAlgorithm::GetFacetBorders (const std::vector &raulInd, rclBorders.emplace_back(clBorder.begin(), clBorder.end()); clBorder.clear(); - if (aclEdges.size() > 0) { + if (!aclEdges.empty()) { // start new boundary ulFirst = aclEdges.begin()->first; ulLast = aclEdges.begin()->second; diff --git a/src/Mod/Mesh/App/Core/Algorithm.h b/src/Mod/Mesh/App/Core/Algorithm.h index 4ab6700ac8..32634c4ddb 100644 --- a/src/Mod/Mesh/App/Core/Algorithm.h +++ b/src/Mod/Mesh/App/Core/Algorithm.h @@ -56,7 +56,7 @@ class MeshExport MeshAlgorithm { public: /// Construction - MeshAlgorithm (const MeshKernel &rclM) : _rclMesh(rclM) { } + explicit MeshAlgorithm (const MeshKernel &rclM) : _rclMesh(rclM) { } /// Destruction ~MeshAlgorithm () { } @@ -353,9 +353,9 @@ public: class MeshExport PointCollector : public MeshCollector { public: - PointCollector(std::vector& ind) : indices(ind){} - virtual ~PointCollector(){} - virtual void Append(const MeshCore::MeshKernel& kernel, FacetIndex index) + explicit PointCollector(std::vector& ind) : indices(ind){} + ~PointCollector() override{} + void Append(const MeshCore::MeshKernel& kernel, FacetIndex index) override { PointIndex ulP1, ulP2, ulP3; kernel.GetFacetPoints(index, ulP1, ulP2, ulP3); @@ -371,9 +371,9 @@ private: class MeshExport FacetCollector : public MeshCollector { public: - FacetCollector(std::vector& ind) : indices(ind){} - virtual ~FacetCollector(){} - void Append(const MeshCore::MeshKernel&, FacetIndex index) + explicit FacetCollector(std::vector& ind) : indices(ind){} + ~FacetCollector() override{} + void Append(const MeshCore::MeshKernel&, FacetIndex index) override { indices.push_back(index); } @@ -392,7 +392,7 @@ class MeshExport MeshRefPointToFacets { public: /// Construction - MeshRefPointToFacets (const MeshKernel &rclM) : _rclMesh(rclM) + explicit MeshRefPointToFacets (const MeshKernel &rclM) : _rclMesh(rclM) { Rebuild(); } /// Destruction ~MeshRefPointToFacets () @@ -431,7 +431,7 @@ class MeshExport MeshRefFacetToFacets { public: /// Construction - MeshRefFacetToFacets (const MeshKernel &rclM) : _rclMesh(rclM) + explicit MeshRefFacetToFacets (const MeshKernel &rclM) : _rclMesh(rclM) { Rebuild(); } /// Destruction ~MeshRefFacetToFacets () @@ -460,7 +460,7 @@ class MeshExport MeshRefPointToPoints { public: /// Construction - MeshRefPointToPoints (const MeshKernel &rclM) : _rclMesh(rclM) + explicit MeshRefPointToPoints (const MeshKernel &rclM) : _rclMesh(rclM) { Rebuild(); } /// Destruction ~MeshRefPointToPoints () @@ -489,7 +489,7 @@ class MeshExport MeshRefEdgeToFacets { public: /// Construction - MeshRefEdgeToFacets (const MeshKernel &rclM) : _rclMesh(rclM) + explicit MeshRefEdgeToFacets (const MeshKernel &rclM) : _rclMesh(rclM) { Rebuild(); } /// Destruction ~MeshRefEdgeToFacets () @@ -528,7 +528,7 @@ class MeshExport MeshRefNormalToPoints { public: /// Construction - MeshRefNormalToPoints (const MeshKernel &rclM) : _rclMesh(rclM) + explicit MeshRefNormalToPoints (const MeshKernel &rclM) : _rclMesh(rclM) { Rebuild(); } /// Destruction ~MeshRefNormalToPoints () @@ -537,6 +537,9 @@ public: /// Rebuilds up data structure void Rebuild (); const Base::Vector3f& operator[] (PointIndex) const; + const std::vector& GetValues() const { + return _norm; + } protected: const MeshKernel &_rclMesh; /**< The mesh kernel. */ diff --git a/src/Mod/Mesh/App/Core/Approximation.h b/src/Mod/Mesh/App/Core/Approximation.h index 524fca7d25..ec2f2d34df 100644 --- a/src/Mod/Mesh/App/Core/Approximation.h +++ b/src/Mod/Mesh/App/Core/Approximation.h @@ -53,7 +53,7 @@ template class PolynomialSurface : public ImplicitSurface { public: - PolynomialSurface (const Real afCoeff[6]) + explicit PolynomialSurface (const Real afCoeff[6]) { for (int i=0; i<6; i++) m_afCoeff[i] = afCoeff[i]; } virtual ~PolynomialSurface () {} @@ -194,7 +194,7 @@ public: /** * Destruction */ - virtual ~PlaneFit(); + ~PlaneFit() override; Base::Vector3f GetBase() const; Base::Vector3f GetDirU() const; Base::Vector3f GetDirV() const; @@ -207,7 +207,7 @@ public: * Fit a plane into the given points. We must have at least three non-collinear points * to succeed. If the fit fails FLOAT_MAX is returned. */ - float Fit(); + float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted plane. If Fit() has not been * called FLOAT_MAX is returned. @@ -274,7 +274,7 @@ public: /** * Destruction */ - virtual ~QuadraticFit(){} + ~QuadraticFit() override{} /** * Get the quadric coefficients * @param ulIndex Number of coefficient (0..9) @@ -291,7 +291,7 @@ public: * Invocation of fitting algorithm * @return float Quality of fit. */ - float Fit(); + float Fit() override; void CalcZValues(double x, double y, double &dZ1, double &dZ2) const; /** @@ -349,12 +349,12 @@ public: /** * Destruction */ - virtual ~SurfaceFit(){} + ~SurfaceFit() override{} bool GetCurvatureInfo(double x, double y, double z, double &rfCurv0, double &rfCurv1, Base::Vector3f &rkDir0, Base::Vector3f &rkDir1, double &dDistance); bool GetCurvatureInfo(double x, double y, double z, double &rfCurv0, double &rfcurv1); - float Fit(); + float Fit() override; double Value(double x, double y) const; void GetCoefficients(double& a,double& b,double& c,double& d,double& e,double& f) const; /** @@ -393,7 +393,7 @@ public: /** * Destruction */ - virtual ~CylinderFit(); + ~CylinderFit() override; float GetRadius() const; Base::Vector3f GetBase() const; void SetInitialValues(const Base::Vector3f&, const Base::Vector3f&); @@ -409,7 +409,7 @@ public: /** * Fit a cylinder into the given points. If the fit fails FLOAT_MAX is returned. */ - float Fit(); + float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted cylinder. If Fit() has not been * called FLOAT_MAX is returned. @@ -452,13 +452,13 @@ public: /** * Destruction */ - virtual ~SphereFit(); + ~SphereFit() override; float GetRadius() const; Base::Vector3f GetCenter() const; /** * Fit a sphere into the given points. If the fit fails FLOAT_MAX is returned. */ - float Fit(); + float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted sphere. If Fit() has not been * called FLOAT_MAX is returned. @@ -498,7 +498,7 @@ public: * @param pKoef Pointer to the quadric coefficients * (double [10]) */ - FunctionContainer(const double *pKoef) + explicit FunctionContainer(const double *pKoef) { Assign( pKoef ); pImplSurf = new Wm4::QuadricSurface( dKoeff ); @@ -662,8 +662,8 @@ public: /** * Destruction */ - virtual ~PolynomialFit(); - float Fit(); + ~PolynomialFit() override; + float Fit() override; float Value(float x, float y) const; protected: diff --git a/src/Mod/Mesh/App/Core/Builder.h b/src/Mod/Mesh/App/Core/Builder.h index 81415b1d56..e71f8da5f2 100644 --- a/src/Mod/Mesh/App/Core/Builder.h +++ b/src/Mod/Mesh/App/Core/Builder.h @@ -114,7 +114,7 @@ private: void RemoveUnreferencedPoints(); public: - MeshBuilder(MeshKernel &rclM); + explicit MeshBuilder(MeshKernel &rclM); ~MeshBuilder(); /** @@ -190,7 +190,7 @@ private: public: typedef int size_type; - MeshFastBuilder(MeshKernel &rclM); + explicit MeshFastBuilder(MeshKernel &rclM); ~MeshFastBuilder(); /** Initializes the class. Must be done before adding facets diff --git a/src/Mod/Mesh/App/Core/Curvature.cpp b/src/Mod/Mesh/App/Core/Curvature.cpp index 846268ffc4..1f9c632eb3 100644 --- a/src/Mod/Mesh/App/Core/Curvature.cpp +++ b/src/Mod/Mesh/App/Core/Curvature.cpp @@ -343,8 +343,8 @@ namespace MeshCore { class FitPointCollector : public MeshCollector { public: - FitPointCollector(std::set& ind) : indices(ind){} - virtual void Append(const MeshCore::MeshKernel& kernel, FacetIndex index) + explicit FitPointCollector(std::set& ind) : indices(ind){} + void Append(const MeshCore::MeshKernel& kernel, FacetIndex index) override { PointIndex ulP1, ulP2, ulP3; kernel.GetFacetPoints(index, ulP1, ulP2, ulP3); diff --git a/src/Mod/Mesh/App/Core/Curvature.h b/src/Mod/Mesh/App/Core/Curvature.h index 2e3bc6e63b..111c855a76 100644 --- a/src/Mod/Mesh/App/Core/Curvature.h +++ b/src/Mod/Mesh/App/Core/Curvature.h @@ -55,7 +55,7 @@ private: class MeshExport MeshCurvature { public: - MeshCurvature(const MeshKernel& kernel); + explicit MeshCurvature(const MeshKernel& kernel); MeshCurvature(const MeshKernel& kernel, const std::vector& segm); float GetRadius() const { return myRadius; } void SetRadius(float r) { myRadius = r; } diff --git a/src/Mod/Mesh/App/Core/CylinderFit.cpp b/src/Mod/Mesh/App/Core/CylinderFit.cpp index 81b5db65f2..e4e9b967e4 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.cpp +++ b/src/Mod/Mesh/App/Core/CylinderFit.cpp @@ -27,21 +27,21 @@ // (X0i,Y0i,Z0i) = (Xc,Yc,Zc) + s(L,M,N) // where s is the distance from (Xc,Yc,Zc) to (X0i,Y0i,Z0i) when (L,M,N) is // of unit length (normalized). -// The distance between a cylinder surface point (Xi,Yi,Zi) and its +// The distance between a cylinder surface point (Xi,Yi,Zi) and its // projection onto the axis (X0i,Y0i,Z0i) is the radius: // (Xi - X0i)^2 + (Yi - Y0i)^2 + (Zi - Z0i)^2 = R^2 -// Also the vector to a cylinder surface point (Xi,Yi,Zi) from its +// Also the vector to a cylinder surface point (Xi,Yi,Zi) from its // projection onto the axis (X0i,Y0i,Z0i) is orthogonal to the axis so we can // write: // (Xi - X0i, Yi - Y0i, Zi - Z0i).(L,M,N) = 0 or // L(Xi - X0i) + M(Yi - Y0i) + N(Zi - Z0i) = 0 -// If we substitute these various equations into each other and further add -// the constraint that L^2 + M^2 + N^2 = 1 then we can arrive at a single +// If we substitute these various equations into each other and further add +// the constraint that L^2 + M^2 + N^2 = 1 then we can arrive at a single // equation for the cylinder surface points: // (Xi - Xc + L*L*(Xc - Xi) + L*M*(Yc - Yi) + L*N*(Zc - Zi))^2 + // (Yi - Yc + M*L*(Xc - Xi) + M*M*(Yc - Yi) + M*N*(Zc - Zi))^2 + // (Zi - Zc + N*L*(Xc - Xi) + N*M*(Yc - Yi) + N*N*(Zc - Zi))^2 - R^2 = 0 -// This equation is what is used in the least squares solution below. Because +// This equation is what is used in the least squares solution below. Because // we are constraining the direction vector to a unit length and also because // we need to stop the axis point from moving along the axis we need to fix one // of the ordinates in the solution. So from our initial approximations for the @@ -58,7 +58,7 @@ #ifndef _PreComp_ # include # include -# include +# include #endif #include "CylinderFit.h" @@ -106,7 +106,7 @@ void CylinderFit::SetApproximations(const Base::Vector3d &base, const Base::Vect _vAxis = axis; _vAxis.Normalize(); _dRadius = 0.0; - if (_vPoints.size() > 0) + if (!_vPoints.empty()) { for (std::list< Base::Vector3f >::const_iterator cIt = _vPoints.begin(); cIt != _vPoints.end(); ++cIt) _dRadius += Base::Vector3d(cIt->x, cIt->y, cIt->z).DistanceToLine(_vBase, _vAxis); @@ -226,7 +226,7 @@ void CylinderFit::ProjectToCylinder() } } -// Compute approximations for the parameters using all points by computing a +// Compute approximations for the parameters using all points by computing a // line through the points. This doesn't work well if the points are only from // one small surface area. // In that case rather use SetApproximations() with a better estimate. @@ -238,7 +238,7 @@ void CylinderFit::ComputeApproximationsLine() _vBase.Set(0.0, 0.0, 0.0); _vAxis.Set(0.0, 0.0, 0.0); _dRadius = 0.0; - if (_vPoints.size() > 0) + if (!_vPoints.empty()) { std::vector input; std::transform(_vPoints.begin(), _vPoints.end(), std::back_inserter(input), @@ -388,7 +388,7 @@ void CylinderFit::findBestSolDirection(SolutionD &solDir) double CylinderFit::meanXObs() { double mx = 0.0; - if (_vPoints.size() > 0) + if (!_vPoints.empty()) { for (std::list::const_iterator cIt = _vPoints.begin(); cIt != _vPoints.end(); ++cIt) mx += cIt->x; @@ -400,7 +400,7 @@ double CylinderFit::meanXObs() double CylinderFit::meanYObs() { double my = 0.0; - if (_vPoints.size() > 0) + if (!_vPoints.empty()) { for (std::list::const_iterator cIt = _vPoints.begin(); cIt != _vPoints.end(); ++cIt) my += cIt->y; @@ -412,7 +412,7 @@ double CylinderFit::meanYObs() double CylinderFit::meanZObs() { double mz = 0.0; - if (_vPoints.size() > 0) + if (!_vPoints.empty()) { for (std::list::const_iterator cIt = _vPoints.begin(); cIt != _vPoints.end(); ++cIt) mz += cIt->z; @@ -430,8 +430,8 @@ void CylinderFit::setupNormalEquationMatrices(SolutionD solDir, const std::vecto atpa.setZero(); atpl.setZero(); - // For each point, setup the observation equation coefficients and add their - // contribution into the the normal equation matrices + // For each point, setup the observation equation coefficients and add their + // contribution into the normal equation matrices double a[5], b[3]; double f0, qw; std::vector< Base::Vector3d >::const_iterator vIt = residuals.begin(); @@ -446,7 +446,7 @@ void CylinderFit::setupNormalEquationMatrices(SolutionD solDir, const std::vecto setLowerPart(atpa); } -// Sets up contributions of given observation to the quasi parameteric +// Sets up contributions of given observation to the quasi parameteric // normal equation matrices. Assumes uncorrelated coordinates. // point ... point // residual ... residual for this point computed from previous iteration (zero for first iteration) @@ -456,13 +456,13 @@ void CylinderFit::setupNormalEquationMatrices(SolutionD solDir, const std::vecto // b[3] ... observation partials void CylinderFit::setupObservation(SolutionD solDir, const Base::Vector3f &point, const Base::Vector3d &residual, double a[5], double &f0, double &qw, double b[3]) const { - // This adjustment requires an update of the observation approximations + // This adjustment requires an update of the observation approximations // because the residuals do not have a linear relationship. // New estimates for the observations: double xEstimate = (double)point.x + residual.x; double yEstimate = (double)point.y + residual.y; double zEstimate = (double)point.z + residual.z; - + // intermediate parameters double lambda = _vAxis.x * (xEstimate - _vBase.x) + _vAxis.y * (yEstimate - _vBase.y) + _vAxis.z * (zEstimate - _vBase.z); double x0 = _vBase.x + lambda * _vAxis.x; @@ -493,7 +493,7 @@ void CylinderFit::setupObservation(SolutionD solDir, const Base::Vector3f &point ddzdm = -(_vAxis.y * _vAxis.z / _vAxis.x) * dx00 + _vAxis.z * dy00; ddxdn = -2.0 * _vAxis.z * dx00 - (_vAxis.y * _vAxis.z / _vAxis.x) * dy00 + (_vAxis.x - _vAxis.z * _vAxis.z / _vAxis.x) * dz00; ddydn = -(_vAxis.y * _vAxis.z / _vAxis.x) * dx00 + _vAxis.y * dz00; - ddzdn = (_vAxis.x - _vAxis.z * _vAxis.z / _vAxis.x) * dx00 + _vAxis.y * dy00 + 2.0 * _vAxis.z * dz00; + ddzdn = (_vAxis.x - _vAxis.z * _vAxis.z / _vAxis.x) * dx00 + _vAxis.y * dy00 + 2.0 * _vAxis.z * dz00; a[0] = -b[1]; a[1] = -b[2]; a[2] = 2.0 * (dx * ddxdm + dy * ddydm + dz * ddzdm); @@ -529,10 +529,10 @@ void CylinderFit::setupObservation(SolutionD solDir, const Base::Vector3f &point a[4] = -2.0 * _dRadius; break; } - + // free term f0 = _dRadius * _dRadius - dx * dx - dy * dy - dz * dz + b[0] * residual.x + b[1] * residual.y + b[2] * residual.z; - + // quasi weight (using equal weights for cylinder point coordinate observations) //w[0] = 1.0; //w[1] = 1.0; @@ -618,7 +618,7 @@ bool CylinderFit::computeResiduals(SolutionD solDir, const Eigen::VectorXd &x, s //sigma0 += v.x * w[0] * v.x + v.y * w[1] * v.y + v.z * w[2] * v.z; sigma0 += v.x * v.x + v.y * v.y + v.z * v.z; - + if ((dVx > vConvLimit) || (dVy > vConvLimit) || (dVz > vConvLimit)) vConverged = false; @@ -650,7 +650,7 @@ bool CylinderFit::computeResiduals(SolutionD solDir, const Eigen::VectorXd &x, s // Update the parameters after solving the normal equations bool CylinderFit::updateParameters(SolutionD solDir, const Eigen::VectorXd &x) -{ +{ // Update the parameters used as unknowns in the solution switch (solDir) { diff --git a/src/Mod/Mesh/App/Core/CylinderFit.h b/src/Mod/Mesh/App/Core/CylinderFit.h index 6837ea509e..ac69574289 100644 --- a/src/Mod/Mesh/App/Core/CylinderFit.h +++ b/src/Mod/Mesh/App/Core/CylinderFit.h @@ -52,7 +52,7 @@ public: /** * Destruction */ - virtual ~CylinderFit(); + ~CylinderFit() override; /** * Set approximations before calling Fit() @@ -87,7 +87,7 @@ public: /** * Fit a cylinder into the given points. If the fit fails FLOAT_MAX is returned. */ - float Fit(); + float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted cylinder. If Fit() has not been * called FLOAT_MAX is returned. diff --git a/src/Mod/Mesh/App/Core/Decimation.h b/src/Mod/Mesh/App/Core/Decimation.h index 60eb24df7c..4dde8ab640 100644 --- a/src/Mod/Mesh/App/Core/Decimation.h +++ b/src/Mod/Mesh/App/Core/Decimation.h @@ -33,7 +33,7 @@ class MeshKernel; class MeshExport MeshSimplify { public: - MeshSimplify(MeshKernel&); + MeshSimplify(MeshKernel&);//explicit bombs ~MeshSimplify(); void simplify(float tolerance, float reduction); void simplify(int targetSize); diff --git a/src/Mod/Mesh/App/Core/Degeneration.h b/src/Mod/Mesh/App/Core/Degeneration.h index 80e6bf8fb6..89d29e25c2 100644 --- a/src/Mod/Mesh/App/Core/Degeneration.h +++ b/src/Mod/Mesh/App/Core/Degeneration.h @@ -50,15 +50,15 @@ public: /** * Construction. */ - MeshEvalInvalids (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalInvalids (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalInvalids () { } + ~MeshEvalInvalids () override { } /** * Searches for as 'Invalid' marked points or facets. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all invalid facets or facets whose points are invalid. */ @@ -76,15 +76,15 @@ public: /** * Construction. */ - MeshFixInvalids (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixInvalids (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixInvalids () { } + ~MeshFixInvalids () override { } /** * Remove invalid elements. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -101,15 +101,15 @@ public: /** * Construction. */ - MeshEvalDuplicatePoints (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalDuplicatePoints (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalDuplicatePoints () { } + ~MeshEvalDuplicatePoints () override { } /** * Merges points to one if the distance between them is less than the global \a MeshDefinitions::_fMinPointDistanceD1. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all duplicated points. */ @@ -127,15 +127,15 @@ public: /** * Construction. */ - MeshFixDuplicatePoints (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixDuplicatePoints (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixDuplicatePoints () { } + ~MeshFixDuplicatePoints () override { } /** * Merges duplicated points. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -149,15 +149,15 @@ public: /** * Construction. */ - MeshEvalNaNPoints (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalNaNPoints (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalNaNPoints () { } + ~MeshEvalNaNPoints () override { } /** * Returns false if a point with NaN coordinate is found. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all NaN points. */ @@ -175,15 +175,15 @@ public: /** * Construction. */ - MeshFixNaNPoints (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixNaNPoints (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixNaNPoints () { } + ~MeshFixNaNPoints () override { } /** * Merges duplicated points. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -199,15 +199,15 @@ public: /** * Construction. */ - MeshEvalDuplicateFacets (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalDuplicateFacets (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalDuplicateFacets () { } + ~MeshEvalDuplicateFacets () override { } /** * Searches for duplicated facets. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all duplicated facets. */ @@ -225,15 +225,15 @@ public: /** * Construction. */ - MeshFixDuplicateFacets (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixDuplicateFacets (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixDuplicateFacets () { } + ~MeshFixDuplicateFacets () override { } /** * Removes duplicated facets. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -246,15 +246,15 @@ public: /** * Construction. */ - MeshEvalInternalFacets (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalInternalFacets (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalInternalFacets () { } + ~MeshEvalInternalFacets () override { } /** * Identify internal facets. */ - bool Evaluate (); + bool Evaluate () override; /** * Return the indices. */ @@ -285,11 +285,11 @@ public: /** * Destruction. */ - ~MeshEvalDegeneratedFacets () { } + ~MeshEvalDegeneratedFacets () override { } /** * Searches degenerated facets. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the number of facets with an edge smaller than \a fMinEdgeLength. */ @@ -319,11 +319,11 @@ public: /** * Destruction. */ - ~MeshFixDegeneratedFacets () { } + ~MeshFixDegeneratedFacets () override { } /** * Removes degenerated facets. */ - bool Fixup (); + bool Fixup () override; private: float fEpsilon; @@ -345,17 +345,17 @@ public: * It defines the amount of perimeter of a triangle for which the shortest * edge is considered for removal. */ - MeshRemoveNeedles (MeshKernel &rclM, float fMinEdgeLen = 0.05f) + explicit MeshRemoveNeedles (MeshKernel &rclM, float fMinEdgeLen = 0.05f) : MeshValidation(rclM), fMinEdgeLength(std::min(fMinEdgeLen, 0.25f)) {} /** * Destruction. */ - ~MeshRemoveNeedles () { } + ~MeshRemoveNeedles () override { } /** * Removes all facets with an edge smaller than \a fMinEdgeLength without leaving holes or gaps * in the mesh. */ - bool Fixup (); + bool Fixup () override; private: float fMinEdgeLength; @@ -377,15 +377,15 @@ public: /** * Construction. The \arg fFactor must be in the range of 0.0 and 0.5. */ - MeshFixCaps (MeshKernel &rclM, float fMaxAng = 2.61f, float fFactor = 0.25f) // ~150 degree + explicit MeshFixCaps (MeshKernel &rclM, float fMaxAng = 2.61f, float fFactor = 0.25f) // ~150 degree : MeshValidation(rclM), fMaxAngle(fMaxAng), fSplitFactor(fFactor) { } /** * Destruction. */ - ~MeshFixCaps () { } + ~MeshFixCaps () override { } /** */ - bool Fixup (); + bool Fixup () override; private: float fMaxAngle; @@ -409,11 +409,11 @@ public: /** * Destruction. */ - ~MeshEvalDeformedFacets () { } + ~MeshEvalDeformedFacets () override { } /** * Searches deformed facets. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of deformed facets. */ @@ -443,11 +443,11 @@ public: /** * Destruction. */ - ~MeshFixDeformedFacets () { } + ~MeshFixDeformedFacets () override { } /** * Removes deformed facets. */ - bool Fixup (); + bool Fixup () override; private: float fMinAngle; /**< If an angle of a facet is lower than fMinAngle it's considered as deformed. */ @@ -470,16 +470,16 @@ public: /** * Construction. */ - MeshFixMergeFacets (MeshKernel &rclM) + explicit MeshFixMergeFacets (MeshKernel &rclM) : MeshValidation(rclM) { } /** * Destruction. */ - ~MeshFixMergeFacets () { } + ~MeshFixMergeFacets () override { } /** * Removes deformed facets. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -489,10 +489,10 @@ public: class MeshExport MeshEvalDentsOnSurface : public MeshEvaluation { public: - MeshEvalDentsOnSurface (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } - ~MeshEvalDentsOnSurface() {} + explicit MeshEvalDentsOnSurface (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + ~MeshEvalDentsOnSurface() override {} - bool Evaluate(); + bool Evaluate() override; std::vector GetIndices() const; private: @@ -502,10 +502,10 @@ private: class MeshExport MeshFixDentsOnSurface : public MeshValidation { public: - MeshFixDentsOnSurface (MeshKernel &rclM) : MeshValidation( rclM ) { } - ~MeshFixDentsOnSurface() {} + explicit MeshFixDentsOnSurface (MeshKernel &rclM) : MeshValidation( rclM ) { } + ~MeshFixDentsOnSurface() override {} - bool Fixup(); + bool Fixup() override; }; /** @@ -516,10 +516,10 @@ public: class MeshExport MeshEvalFoldsOnSurface : public MeshEvaluation { public: - MeshEvalFoldsOnSurface (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } - ~MeshEvalFoldsOnSurface() {} + explicit MeshEvalFoldsOnSurface (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + ~MeshEvalFoldsOnSurface() override {} - bool Evaluate(); + bool Evaluate() override; std::vector GetIndices() const; private: @@ -535,10 +535,10 @@ private: class MeshExport MeshEvalFoldsOnBoundary : public MeshEvaluation { public: - MeshEvalFoldsOnBoundary (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } - ~MeshEvalFoldsOnBoundary() {} + explicit MeshEvalFoldsOnBoundary (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + ~MeshEvalFoldsOnBoundary() override {} - bool Evaluate(); + bool Evaluate() override; std::vector GetIndices() const; private: @@ -548,10 +548,10 @@ private: class MeshExport MeshFixFoldsOnBoundary : public MeshValidation { public: - MeshFixFoldsOnBoundary (MeshKernel &rclM) : MeshValidation( rclM ) { } - ~MeshFixFoldsOnBoundary() {} + explicit MeshFixFoldsOnBoundary (MeshKernel &rclM) : MeshValidation( rclM ) { } + ~MeshFixFoldsOnBoundary() override {} - bool Fixup(); + bool Fixup() override; }; /** @@ -561,10 +561,10 @@ public: class MeshExport MeshEvalFoldOversOnSurface : public MeshEvaluation { public: - MeshEvalFoldOversOnSurface (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } - ~MeshEvalFoldOversOnSurface() {} + explicit MeshEvalFoldOversOnSurface (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + ~MeshEvalFoldOversOnSurface() override {} - bool Evaluate(); + bool Evaluate() override; std::vector GetIndices() const { return this->indices; } @@ -582,8 +582,8 @@ class MeshExport MeshEvalBorderFacet : public MeshEvaluation public: MeshEvalBorderFacet (const MeshKernel &rclB, std::vector& f) : MeshEvaluation(rclB), _facets(f) {} - virtual ~MeshEvalBorderFacet () {} - bool Evaluate(); + ~MeshEvalBorderFacet () override {} + bool Evaluate() override; protected: std::vector& _facets; @@ -606,15 +606,15 @@ public: /** * Construction. */ - MeshEvalRangeFacet (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalRangeFacet (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalRangeFacet () { } + ~MeshEvalRangeFacet () override { } /** * Searches for facets that has neighbour facet indices out of range. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all facets with invalid neighbour indices. */ @@ -632,15 +632,15 @@ public: /** * Construction. */ - MeshFixRangeFacet (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixRangeFacet (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixRangeFacet () { } + ~MeshFixRangeFacet () override { } /** * Fixes facets with neighbour indices out of range. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -654,15 +654,15 @@ public: /** * Construction. */ - MeshEvalRangePoint (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalRangePoint (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalRangePoint () { } + ~MeshEvalRangePoint () override { } /** * Searches for facets that has point indices out of range. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all facets with invalid point indices. */ @@ -680,15 +680,15 @@ public: /** * Construction. */ - MeshFixRangePoint (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixRangePoint (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixRangePoint () { } + ~MeshFixRangePoint () override { } /** * Fixes facets with point indices out of range. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -703,15 +703,15 @@ public: /** * Construction. */ - MeshEvalCorruptedFacets (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalCorruptedFacets (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalCorruptedFacets () { } + ~MeshEvalCorruptedFacets () override { } /** * Searches for corrupted facets. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all corrupt facets. */ @@ -730,15 +730,15 @@ public: /** * Construction. */ - MeshFixCorruptedFacets (MeshKernel &rclM) : MeshValidation( rclM ) { } + explicit MeshFixCorruptedFacets (MeshKernel &rclM) : MeshValidation( rclM ) { } /** * Destruction. */ - ~MeshFixCorruptedFacets () { } + ~MeshFixCorruptedFacets () override { } /** * Removes corrupted facets. */ - bool Fixup (); + bool Fixup () override; }; /** @@ -752,15 +752,15 @@ public: /** * Construction. */ - MeshEvalPointOnEdge (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } + explicit MeshEvalPointOnEdge (const MeshKernel &rclM) : MeshEvaluation( rclM ) { } /** * Destruction. */ - ~MeshEvalPointOnEdge () { } + ~MeshEvalPointOnEdge () override { } /** * Searches for points that lie on edge of triangle. */ - bool Evaluate (); + bool Evaluate () override; /** * Returns the indices of all points on edge. */ @@ -786,15 +786,15 @@ public: /** * Construction. */ - MeshFixPointOnEdge (MeshKernel &rclM, bool fill = false) : MeshValidation( rclM ), fillBoundary(fill) { } + explicit MeshFixPointOnEdge (MeshKernel &rclM, bool fill = false) : MeshValidation( rclM ), fillBoundary(fill) { } /** * Destruction. */ - ~MeshFixPointOnEdge () { } + ~MeshFixPointOnEdge () override { } /** * Removes points that lie on edges of triangles. */ - bool Fixup (); + bool Fixup () override; private: void MarkBoundaries(const std::vector& facetsIndices); diff --git a/src/Mod/Mesh/App/Core/Elements.cpp b/src/Mod/Mesh/App/Core/Elements.cpp index a10ca0a416..f3580aeb28 100644 --- a/src/Mod/Mesh/App/Core/Elements.cpp +++ b/src/Mod/Mesh/App/Core/Elements.cpp @@ -1030,7 +1030,7 @@ void MeshGeomFacet::SubSample (float fStep, std::vector &rclPoin } // if couldn't subsample the facet take gravity center - if (clPoints.size() == 0) + if (clPoints.empty()) clPoints.push_back(this->GetGravityPoint()); rclPoints.insert(rclPoints.end(), clPoints.begin(), clPoints.end()); diff --git a/src/Mod/Mesh/App/Core/Elements.h b/src/Mod/Mesh/App/Core/Elements.h index b3c5c5aebf..0dd476e1b9 100644 --- a/src/Mod/Mesh/App/Core/Elements.h +++ b/src/Mod/Mesh/App/Core/Elements.h @@ -110,7 +110,7 @@ public: //@{ MeshPoint () : _ucFlag(0), _ulProp(0) { } inline MeshPoint (float x, float y, float z); - inline MeshPoint (const Base::Vector3f &rclPt); + inline MeshPoint (const Base::Vector3f &rclPt);//explicit bombs inline MeshPoint (const MeshPoint &rclPt); ~MeshPoint () { } //@} @@ -328,6 +328,12 @@ public: */ bool HasNeighbour (unsigned short usSide) const { return (_aulNeighbours[usSide] != FACET_INDEX_MAX); } + /** + * Checks if the given index is a neighbour facet. + */ + bool IsNeighbour(FacetIndex index) const { + return Side(index) < 3; + } /** Counts the number of edges without neighbour. */ inline unsigned short CountOpenEdges() const; /** Returns true if there is an edge without neighbour, otherwise false. */ @@ -577,7 +583,7 @@ public: // constructor MeshPointArray () { } // constructor - MeshPointArray (PointIndex ulSize) : TMeshPointArray(ulSize) { } + explicit MeshPointArray (PointIndex ulSize) : TMeshPointArray(ulSize) { } /// copy-constructor MeshPointArray (const MeshPointArray&); // Destructor @@ -631,7 +637,7 @@ public: /// constructor MeshFacetArray () { } /// constructor - MeshFacetArray (FacetIndex ulSize) : TMeshFacetArray(ulSize) { } + explicit MeshFacetArray (FacetIndex ulSize) : TMeshFacetArray(ulSize) { } /// copy-constructor MeshFacetArray (const MeshFacetArray&); /// destructor @@ -678,7 +684,7 @@ public: class MeshExport MeshPointModifier { public: - MeshPointModifier(MeshPointArray& points) + explicit MeshPointModifier(MeshPointArray& points) : rPoints(points) { } @@ -699,7 +705,7 @@ private: class MeshExport MeshFacetModifier { public: - MeshFacetModifier(MeshFacetArray& facets) + explicit MeshFacetModifier(MeshFacetArray& facets) : rFacets(facets) { } diff --git a/src/Mod/Mesh/App/Core/Evaluation.cpp b/src/Mod/Mesh/App/Core/Evaluation.cpp index 4070b1b090..3c97275700 100644 --- a/src/Mod/Mesh/App/Core/Evaluation.cpp +++ b/src/Mod/Mesh/App/Core/Evaluation.cpp @@ -572,7 +572,7 @@ bool MeshEvalSingleFacet::Evaluate () _aclManifoldList.push_back(aulManifolds); } */ - return (nonManifoldList.size() == 0); + return (nonManifoldList.empty()); } bool MeshFixSingleFacet::Fixup () @@ -619,7 +619,7 @@ bool MeshEvalSelfIntersection::Evaluate () clGridIter.GetElements(aulGridElements); seq.next(); - if (aulGridElements.size()==0) + if (aulGridElements.empty()) continue; MeshGeomFacet facet1, facet2; @@ -716,7 +716,7 @@ void MeshEvalSelfIntersection::GetIntersections(std::vector& aulComplement); /** Returns always true and collects the indices with wrong orientation. */ - bool Visit (const MeshFacet &, const MeshFacet &, FacetIndex , unsigned long); + bool Visit (const MeshFacet &, const MeshFacet &, FacetIndex , unsigned long) override; private: std::vector& _aulIndices; @@ -127,9 +127,9 @@ private: class MeshExport MeshSameOrientationCollector : public MeshOrientationVisitor { public: - MeshSameOrientationCollector(std::vector& aulIndices); + explicit MeshSameOrientationCollector(std::vector& aulIndices); /** Returns always true and collects the indices with wrong orientation. */ - bool Visit (const MeshFacet &, const MeshFacet &, FacetIndex , unsigned long); + bool Visit (const MeshFacet &, const MeshFacet &, FacetIndex , unsigned long) override; private: std::vector& _aulIndices; @@ -142,9 +142,9 @@ private: class MeshExport MeshEvalOrientation : public MeshEvaluation { public: - MeshEvalOrientation (const MeshKernel& rclM); - ~MeshEvalOrientation(); - bool Evaluate (); + explicit MeshEvalOrientation (const MeshKernel& rclM); + ~MeshEvalOrientation() override; + bool Evaluate () override; std::vector GetIndices() const; private: @@ -158,9 +158,9 @@ private: class MeshExport MeshFixOrientation : public MeshValidation { public: - MeshFixOrientation (MeshKernel& rclM); - ~MeshFixOrientation(); - bool Fixup(); + explicit MeshFixOrientation (MeshKernel& rclM); + ~MeshFixOrientation() override; + bool Fixup() override; }; // ---------------------------------------------------- @@ -172,9 +172,9 @@ public: class MeshExport MeshEvalSolid : public MeshEvaluation { public: - MeshEvalSolid (const MeshKernel& rclM); - ~MeshEvalSolid(); - bool Evaluate (); + explicit MeshEvalSolid (const MeshKernel& rclM); + ~MeshEvalSolid() override; + bool Evaluate () override; }; // ---------------------------------------------------- @@ -188,9 +188,9 @@ public: class MeshExport MeshEvalTopology : public MeshEvaluation { public: - MeshEvalTopology (const MeshKernel &rclB) : MeshEvaluation(rclB) {} - virtual ~MeshEvalTopology () {} - virtual bool Evaluate (); + explicit MeshEvalTopology (const MeshKernel &rclB) : MeshEvaluation(rclB) {} + ~MeshEvalTopology () override {} + bool Evaluate () override; void GetFacetManifolds (std::vector &raclFacetIndList) const; unsigned long CountManifolds() const; @@ -211,8 +211,8 @@ class MeshExport MeshFixTopology : public MeshValidation public: MeshFixTopology (MeshKernel &rclB, const std::list >& mf) : MeshValidation(rclB), nonManifoldList(mf) {} - virtual ~MeshFixTopology () {} - bool Fixup(); + ~MeshFixTopology () override {} + bool Fixup() override; const std::vector& GetDeletedFaces() const { return deletedFaces; } @@ -232,9 +232,9 @@ protected: class MeshExport MeshEvalPointManifolds : public MeshEvaluation { public: - MeshEvalPointManifolds (const MeshKernel &rclB) : MeshEvaluation(rclB) {} - virtual ~MeshEvalPointManifolds () {} - virtual bool Evaluate (); + explicit MeshEvalPointManifolds (const MeshKernel &rclB) : MeshEvaluation(rclB) {} + ~MeshEvalPointManifolds () override {} + bool Evaluate () override; void GetFacetIndices (std::vector &facets) const; const std::list >& GetFacetIndices () const { return facetsOfNonManifoldPoints; } @@ -258,9 +258,9 @@ protected: class MeshExport MeshEvalSingleFacet : public MeshEvalTopology { public: - MeshEvalSingleFacet (const MeshKernel &rclB) : MeshEvalTopology(rclB) {} - virtual ~MeshEvalSingleFacet () {} - bool Evaluate (); + explicit MeshEvalSingleFacet (const MeshKernel &rclB) : MeshEvalTopology(rclB) {} + ~MeshEvalSingleFacet () override {} + bool Evaluate () override; }; /** @@ -272,8 +272,8 @@ class MeshExport MeshFixSingleFacet : public MeshValidation public: MeshFixSingleFacet (MeshKernel &rclB, const std::vector >& mf) : MeshValidation(rclB), _raclManifoldList(mf) {} - virtual ~MeshFixSingleFacet () {} - bool Fixup(); + ~MeshFixSingleFacet () override {} + bool Fixup() override; protected: const std::vector >& _raclManifoldList; @@ -288,10 +288,10 @@ protected: class MeshExport MeshEvalSelfIntersection : public MeshEvaluation { public: - MeshEvalSelfIntersection (const MeshKernel &rclB) : MeshEvaluation(rclB) {} - virtual ~MeshEvalSelfIntersection () {} + explicit MeshEvalSelfIntersection (const MeshKernel &rclB) : MeshEvaluation(rclB) {} + ~MeshEvalSelfIntersection () override {} /// Evaluate the mesh and return if true if there are self intersections - bool Evaluate (); + bool Evaluate () override; /// collect all intersection lines void GetIntersections(const std::vector >&, std::vector >&) const; @@ -308,9 +308,9 @@ class MeshExport MeshFixSelfIntersection : public MeshValidation public: MeshFixSelfIntersection (MeshKernel &rclB, const std::vector >& si) : MeshValidation(rclB), selfIntersectons(si) {} - virtual ~MeshFixSelfIntersection () {} + ~MeshFixSelfIntersection () override {} std::vector GetFacets() const; - bool Fixup(); + bool Fixup() override; private: const std::vector >& selfIntersectons; @@ -326,9 +326,9 @@ private: class MeshExport MeshEvalNeighbourhood : public MeshEvaluation { public: - MeshEvalNeighbourhood (const MeshKernel &rclB) : MeshEvaluation(rclB) {} - ~MeshEvalNeighbourhood () {} - bool Evaluate (); + explicit MeshEvalNeighbourhood (const MeshKernel &rclB) : MeshEvaluation(rclB) {} + ~MeshEvalNeighbourhood () override {} + bool Evaluate () override; std::vector GetIndices() const; }; @@ -339,9 +339,9 @@ public: class MeshExport MeshFixNeighbourhood : public MeshValidation { public: - MeshFixNeighbourhood (MeshKernel &rclB) : MeshValidation(rclB) {} - ~MeshFixNeighbourhood () {} - bool Fixup(); + explicit MeshFixNeighbourhood (MeshKernel &rclB) : MeshValidation(rclB) {} + ~MeshFixNeighbourhood () override {} + bool Fixup() override; }; // ---------------------------------------------------- @@ -357,8 +357,8 @@ public: class MeshExport MeshEigensystem : public MeshEvaluation { public: - MeshEigensystem (const MeshKernel &rclB); - virtual ~MeshEigensystem () {} + explicit MeshEigensystem (const MeshKernel &rclB); + ~MeshEigensystem () override {} /** Returns the transformation matrix. */ Base::Matrix4D Transform() const; @@ -367,7 +367,7 @@ public: */ Base::Vector3f GetBoundings() const; - bool Evaluate(); + bool Evaluate() override; /** * Calculates the local coordinate system defined by \a u, \a v, \a w * and \a c. diff --git a/src/Mod/Mesh/App/Core/Grid.cpp b/src/Mod/Mesh/App/Core/Grid.cpp index 2e8cbe3280..7515ed6328 100644 --- a/src/Mod/Mesh/App/Core/Grid.cpp +++ b/src/Mod/Mesh/App/Core/Grid.cpp @@ -91,7 +91,7 @@ void MeshGrid::Rebuild (int iCtGridPerAxis) void MeshGrid::InitGrid () { - assert(_pclMesh != nullptr); + assert(_pclMesh); unsigned long i, j; @@ -646,7 +646,7 @@ unsigned long MeshGrid::GetElements (unsigned long ulX, unsigned long ulY, unsig std::set &raclInd) const { const std::set &rclSet = _aulGrid[ulX][ulY][ulZ]; - if (rclSet.size() > 0) + if (!rclSet.empty()) { raclInd.insert(rclSet.begin(), rclSet.end()); return rclSet.size(); @@ -730,7 +730,7 @@ void MeshFacetGrid::Validate (const MeshKernel &rclMesh) void MeshFacetGrid::Validate () { - if (_pclMesh == nullptr) + if (!_pclMesh) return; if (_pclMesh->CountFacets() != _ulCtElements) @@ -1072,7 +1072,7 @@ void MeshPointGrid::Validate (const MeshKernel &rclMesh) void MeshPointGrid::Validate () { - if (_pclMesh == nullptr) + if (!_pclMesh) return; if (_pclMesh->CountPoints() != _ulCtElements) diff --git a/src/Mod/Mesh/App/Core/Grid.h b/src/Mod/Mesh/App/Core/Grid.h index e368184bbb..da9e198181 100644 --- a/src/Mod/Mesh/App/Core/Grid.h +++ b/src/Mod/Mesh/App/Core/Grid.h @@ -58,7 +58,7 @@ protected: /** @name Construction */ //@{ /// Construction - MeshGrid (const MeshKernel &rclM); + explicit MeshGrid (const MeshKernel &rclM); /// Construction MeshGrid (); //@} @@ -184,7 +184,7 @@ public: /** @name Construction */ //@{ /// Construction - MeshFacetGrid (const MeshKernel &rclM); + explicit MeshFacetGrid (const MeshKernel &rclM); /// Construction MeshFacetGrid () : MeshGrid() { } /// Construction @@ -194,7 +194,7 @@ public: /// Construction MeshFacetGrid (const MeshKernel &rclM, float fGridLen); /// Destruction - virtual ~MeshFacetGrid () { } + ~MeshFacetGrid () override { } //@} /** @name Search */ @@ -213,11 +213,11 @@ public: //@} /** Validates the grid structure and rebuilds it if needed. */ - virtual void Validate (const MeshKernel &rclM); + void Validate (const MeshKernel &rclM) override; /** Validates the grid structure and rebuilds it if needed. */ virtual void Validate (); /** Verifies the grid structure and returns false if inconsistencies are found. */ - virtual bool Verify() const; + bool Verify() const override; protected: /** Returns the grid numbers to the given point \a rclPoint. */ @@ -229,10 +229,10 @@ protected: * the facet. */ inline void AddFacet (const MeshGeomFacet &rclFacet, ElementIndex ulFacetIndex, float fEpsilon = 0.0f); /** Returns the number of stored elements. */ - unsigned long HasElements () const + unsigned long HasElements () const override { return _pclMesh->CountFacets(); } /** Rebuilds the grid structure. */ - virtual void RebuildGrid (); + void RebuildGrid () override; }; /** @@ -247,7 +247,7 @@ public: /// Construction MeshPointGrid (); /// Construction - MeshPointGrid (const MeshKernel &rclM); + explicit MeshPointGrid (const MeshKernel &rclM); /// Construction MeshPointGrid (const MeshKernel &rclM, int iCtGridPerAxis); /// Construction @@ -255,17 +255,17 @@ public: /// Construction MeshPointGrid (const MeshKernel &rclM, unsigned long ulX, unsigned long ulY, unsigned long ulZ); /// Destruction - virtual ~MeshPointGrid () {} + ~MeshPointGrid () override {} //@} /** Finds all points that lie in the same grid as the point \a rclPoint. */ unsigned long FindElements(const Base::Vector3f &rclPoint, std::set& aulElements) const; /** Validates the grid structure and rebuilds it if needed. */ - virtual void Validate (const MeshKernel &rclM); + void Validate (const MeshKernel &rclM) override; /** Validates the grid structure and rebuilds it if needed. */ virtual void Validate (); /** Verifies the grid structure and returns false if inconsistencies are found. */ - virtual bool Verify() const; + bool Verify() const override; protected: /** Adds a new point element to the grid structure. \a rclPt is the geometric point and \a ulPtIndex @@ -274,10 +274,10 @@ protected: /** Returns the grid numbers to the given point \a rclPoint. */ void Pos(const Base::Vector3f &rclPoint, unsigned long &rulX, unsigned long &rulY, unsigned long &rulZ) const; /** Returns the number of stored elements. */ - unsigned long HasElements () const + unsigned long HasElements () const override { return _pclMesh->CountPoints(); } /** Rebuilds the grid structure. */ - virtual void RebuildGrid (); + void RebuildGrid () override; }; /** @@ -288,7 +288,7 @@ class MeshExport MeshGridIterator { public: /// Construction - MeshGridIterator (const MeshGrid &rclG); + explicit MeshGridIterator (const MeshGrid &rclG); /** Returns the bounding box of the current grid element. */ Base::BoundBox3f GetBoundBox () const { return _rclGrid.GetBoundBox(_ulX, _ulY, _ulZ); } diff --git a/src/Mod/Mesh/App/Core/Info.h b/src/Mod/Mesh/App/Core/Info.h index 166d595ed7..4da36098ee 100644 --- a/src/Mod/Mesh/App/Core/Info.h +++ b/src/Mod/Mesh/App/Core/Info.h @@ -36,7 +36,7 @@ class MeshKernel; class MeshExport MeshInfo { public: - MeshInfo (const MeshKernel &rclM); + explicit MeshInfo (const MeshKernel &rclM); virtual ~MeshInfo () {} /** * Writes general information about the mesh structure into the stream. diff --git a/src/Mod/Mesh/App/Core/Iterator.h b/src/Mod/Mesh/App/Core/Iterator.h index e687b323f4..d2d79ee31e 100644 --- a/src/Mod/Mesh/App/Core/Iterator.h +++ b/src/Mod/Mesh/App/Core/Iterator.h @@ -51,7 +51,7 @@ public: /** @name Construction */ //@{ /// construction - inline MeshFacetIterator (const MeshKernel &rclM); + inline explicit MeshFacetIterator (const MeshKernel &rclM); /// construction inline MeshFacetIterator (const MeshKernel &rclM, FacetIndex ulPos); /// construction @@ -175,7 +175,7 @@ class MeshExport MeshPointIterator public: /** @name Construction */ //@{ - inline MeshPointIterator (const MeshKernel &rclM); + inline explicit MeshPointIterator (const MeshKernel &rclM); inline MeshPointIterator (const MeshKernel &rclM, PointIndex ulPos); inline MeshPointIterator (const MeshPointIterator &rclI); //@} @@ -271,7 +271,7 @@ protected: class MeshFastFacetIterator { public: - inline MeshFastFacetIterator (const MeshKernel &rclM); + inline explicit MeshFastFacetIterator (const MeshKernel &rclM); virtual ~MeshFastFacetIterator () {} void Init () { _clIter = _rclFAry.begin(); } diff --git a/src/Mod/Mesh/App/Core/KDTree.h b/src/Mod/Mesh/App/Core/KDTree.h index 0ed64ae82e..cf78a00a6f 100644 --- a/src/Mod/Mesh/App/Core/KDTree.h +++ b/src/Mod/Mesh/App/Core/KDTree.h @@ -33,8 +33,8 @@ class MeshExport MeshKDTree { public: MeshKDTree(); - MeshKDTree(const std::vector& points); - MeshKDTree(const MeshPointArray& points); + explicit MeshKDTree(const std::vector& points); + explicit MeshKDTree(const MeshPointArray& points); ~MeshKDTree(); void AddPoint(Base::Vector3f& point); diff --git a/src/Mod/Mesh/App/Core/MeshIO.cpp b/src/Mod/Mesh/App/Core/MeshIO.cpp index bc7439576f..b75777f418 100644 --- a/src/Mod/Mesh/App/Core/MeshIO.cpp +++ b/src/Mod/Mesh/App/Core/MeshIO.cpp @@ -29,6 +29,7 @@ #include "MeshIO.h" #include "Algorithm.h" #include "Builder.h" +#include "Degeneration.h" #include #include @@ -262,8 +263,8 @@ bool MeshInput::LoadSTL (std::istream &rstrIn) boost::algorithm::to_upper(szBuf); try { - if ((strstr(szBuf, "SOLID") == nullptr) && (strstr(szBuf, "FACET") == nullptr) && (strstr(szBuf, "NORMAL") == nullptr) && - (strstr(szBuf, "VERTEX") == nullptr) && (strstr(szBuf, "ENDFACET") == nullptr) && (strstr(szBuf, "ENDLOOP") == nullptr)) { + if (!strstr(szBuf, "SOLID") && !strstr(szBuf, "FACET") && !strstr(szBuf, "NORMAL") && + !strstr(szBuf, "VERTEX") && !strstr(szBuf, "ENDFACET") && !strstr(szBuf, "ENDLOOP")) { // probably binary STL buf->pubseekoff(0, std::ios::beg, std::ios::in); return LoadBinarySTL(rstrIn); @@ -1485,145 +1486,45 @@ void MeshInput::LoadXML (Base::XMLReader &reader) } /** Loads an OpenInventor file. */ -bool MeshInput::LoadInventor (std::istream &rstrIn) +bool MeshInput::LoadInventor (std::istream &inp) { - if (!rstrIn || rstrIn.bad()) + Base::InventorLoader loader(inp); + if (!loader.read()) return false; - boost::regex rx_p("\\s*([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s+([-+]?[0-9]*)\\.?([0-9]+([eE][-+]?[0-9]+)?)" - "\\s*[\\,\\]]\\s*"); - boost::regex rx_f("\\s*([0-9]+)\\s*\\,\\s*" - "\\s+([0-9]+)\\s*\\,\\s*" - "\\s+([0-9]+)\\s*\\,\\s*"); - boost::cmatch what; - - // get file size and estimate the number of lines - std::streamoff ulSize = 0; - std::streambuf* buf = rstrIn.rdbuf(); - if (!buf) + if (!loader.isValid()) return false; - std::streamoff ulCurr; - ulCurr = buf->pubseekoff(0, std::ios::cur, std::ios::in); - ulSize = buf->pubseekoff(0, std::ios::end, std::ios::in); - buf->pubseekoff(ulCurr, std::ios::beg, std::ios::in); + const auto& points = loader.getPoints(); + const auto& faces = loader.getFaces(); - std::string line; - MeshGeomFacet clFacet; - std::vector clFacetAry; - std::vector aclPoints; + MeshPointArray meshPoints; + meshPoints.reserve(points.size()); + std::transform(points.begin(), points.end(), std::back_inserter(meshPoints), + [](const Base::Vector3f& v) { + return MeshPoint(v); + }); - // We have approx. 30 characters per line - Base::SequencerLauncher seq("Loading...", ulSize/30); - bool flag = false; - bool normals = false; - bool points = false; - bool facets = false; - while (std::getline(rstrIn, line) && !facets) { - boost::algorithm::to_upper(line); + MeshFacetArray meshFacets; + meshFacets.reserve(faces.size()); + std::transform(faces.begin(), faces.end(), std::back_inserter(meshFacets), + [](const Base::InventorLoader::Face& f) { + return MeshFacet(f.p1, f.p2, f.p3); + }); - // read the normals if they are defined - if (!normals && line.find("NORMAL {") != std::string::npos) { - float fX, fY, fZ; - normals = true; // okay, the normals are set by an SoNormal node - flag = true; - // Get the next line and check for the normal field which might begin - // with the first vector already i.e. it's of the form 'vector [ 0.0 0.0 1.0,' - // This is a special case to support also file formats directly written by - // Inventor 2.1 classes. - std::getline(rstrIn, line); - boost::algorithm::to_upper(line); - std::string::size_type pos = line.find("VECTOR ["); - if (pos != std::string::npos) - line = line.substr(pos+8); // 8 = length of 'VECTOR [' - do { - if (boost::regex_match(line.c_str(), what, rx_p)) { - fX = (float)std::atof(what[1].first); - fY = (float)std::atof(what[4].first); - fZ = (float)std::atof(what[7].first); - clFacet.SetNormal(Base::Vector3f(fX, fY, fZ)); - clFacetAry.push_back(clFacet); - seq.next(true); // allow to cancel - } else - flag = false; - } while (std::getline(rstrIn, line) && flag); - } - // read the coordinates - else if (!points && line.find("COORDINATE3 {") != std::string::npos) { - Base::Vector3f clPoint; - points = true; // the SoCoordinate3 node - flag = true; - // Get the next line and check for the points field which might begin - // with the first point already i.e. it's of the form 'point [ 0.0 0.0 0.0,' - // This is a special case to support also file formats directly written by - // Inventor 2.1 classes. - std::getline(rstrIn, line); - boost::algorithm::to_upper(line); - std::string::size_type pos = line.find("POINT ["); - if (pos != std::string::npos) - line = line.substr(pos+7); // 7 = length of 'POINT [' - do { - if (boost::regex_match(line.c_str(), what, rx_p)) { - clPoint.x = (float)std::atof(what[1].first); - clPoint.y = (float)std::atof(what[4].first); - clPoint.z = (float)std::atof(what[7].first); - aclPoints.push_back(clPoint); - seq.next(true); // allow to cancel - } else - flag = false; - } while (std::getline(rstrIn, line) && flag); - } - // read the point indices of the facets - else if (points && line.find("INDEXEDFACESET {") != std::string::npos) { - PointIndex ulPoints[3]; - facets = true; - unsigned long ulCt = 0; - // Get the next line and check for the index field which might begin - // with the first index already. - // This is a special case to support also file formats directly written by - // Inventor 2.1 classes. - // Furthermore we must check whether more than one triple is given per line, which - // is handled in the while-loop. - std::getline(rstrIn, line); - boost::algorithm::to_upper(line); - std::string::size_type pos = line.find("COORDINDEX ["); - if (pos != std::string::npos) - line = line.substr(pos+12); // 12 = length of 'COORDINDEX [' - do { - flag = false; - std::string::size_type pos = line.find("-1"); - while (pos != std::string::npos) { - std::string part = line.substr(0, pos); - pos = line.find_first_of(",]", pos); - line = line.substr(pos+1); - pos = line.find("-1"); - if (boost::regex_match(part.c_str(), what, rx_f)) { - flag = true; - ulPoints[0] = std::atol(what[1].first); - ulPoints[1] = std::atol(what[2].first); - ulPoints[2] = std::atol(what[3].first); - if (normals) { - // get a reference to the facet with defined normal - MeshGeomFacet& rclFacet = clFacetAry[ulCt++]; - for (int i = 0; i < 3; i++) - rclFacet._aclPoints[i] = aclPoints[ulPoints[i]]; - } - else { - for (int i = 0; i < 3; i++) - clFacet._aclPoints[i] = aclPoints[ulPoints[i]]; - clFacetAry.push_back(clFacet); - } - seq.next(true); // allow to cancel - } - } - } while (std::getline(rstrIn, line) && flag); + MeshCleanup meshCleanup(meshPoints, meshFacets); + meshCleanup.RemoveInvalids(); + MeshPointFacetAdjacency meshAdj(meshPoints.size(), meshFacets); + meshAdj.SetFacetNeighbourhood(); + this->_rclMesh.Adopt(meshPoints, meshFacets); + + if (loader.isNonIndexed()) { + if (!MeshEvalDuplicatePoints(this->_rclMesh).Evaluate()) { + MeshFixDuplicatePoints(this->_rclMesh).Fixup(); } } - _rclMesh = clFacetAry; - return (rstrIn?true:false); + return true; } /** Loads a Nastran file. */ diff --git a/src/Mod/Mesh/App/Core/MeshIO.h b/src/Mod/Mesh/App/Core/MeshIO.h index acd08f446b..4dccd093ad 100644 --- a/src/Mod/Mesh/App/Core/MeshIO.h +++ b/src/Mod/Mesh/App/Core/MeshIO.h @@ -92,7 +92,7 @@ struct MeshExport Group class MeshExport MeshInput { public: - MeshInput (MeshKernel &rclM) + explicit MeshInput (MeshKernel &rclM) : _rclMesh(rclM), _material(nullptr){} MeshInput (MeshKernel &rclM, Material* m) : _rclMesh(rclM), _material(m){} @@ -151,7 +151,7 @@ protected: class MeshExport MeshOutput { public: - MeshOutput (const MeshKernel &rclM) + explicit MeshOutput (const MeshKernel &rclM) : _rclMesh(rclM), _material(nullptr), apply_transform(false){} MeshOutput (const MeshKernel &rclM, const Material* m) : _rclMesh(rclM), _material(m), apply_transform(false){} diff --git a/src/Mod/Mesh/App/Core/Projection.h b/src/Mod/Mesh/App/Core/Projection.h index 0ce76df03e..3f8b686c3f 100644 --- a/src/Mod/Mesh/App/Core/Projection.h +++ b/src/Mod/Mesh/App/Core/Projection.h @@ -46,7 +46,7 @@ class MeshGeomFacet; class MeshExport MeshProjection { public: - MeshProjection(const MeshKernel&); + explicit MeshProjection(const MeshKernel&); ~MeshProjection(); bool projectLineOnMesh(const MeshFacetGrid& grid, const Base::Vector3f& p1, FacetIndex f1, diff --git a/src/Mod/Mesh/App/Core/Segmentation.h b/src/Mod/Mesh/App/Core/Segmentation.h index f17593a35d..de3237502e 100644 --- a/src/Mod/Mesh/App/Core/Segmentation.h +++ b/src/Mod/Mesh/App/Core/Segmentation.h @@ -40,7 +40,7 @@ typedef std::vector MeshSegment; class MeshExport MeshSurfaceSegment { public: - MeshSurfaceSegment(unsigned long minFacets) + explicit MeshSurfaceSegment(unsigned long minFacets) : minFacets(minFacets) {} virtual ~MeshSurfaceSegment() {} virtual bool TestFacet (const MeshFacet &rclFacet) const = 0; @@ -75,11 +75,11 @@ class MeshExport MeshDistancePlanarSegment : public MeshDistanceSurfaceSegment { public: MeshDistancePlanarSegment(const MeshKernel& mesh, unsigned long minFacets, float tol); - virtual ~MeshDistancePlanarSegment(); - bool TestFacet (const MeshFacet& rclFacet) const; - const char* GetType() const { return "Plane"; } - void Initialize(FacetIndex); - void AddFacet(const MeshFacet& rclFacet); + ~MeshDistancePlanarSegment() override; + bool TestFacet (const MeshFacet& rclFacet) const override; + const char* GetType() const override { return "Plane"; } + void Initialize(FacetIndex) override; + void AddFacet(const MeshFacet& rclFacet) override; protected: Base::Vector3f basepoint; @@ -107,15 +107,15 @@ class MeshExport PlaneSurfaceFit : public AbstractSurfaceFit public: PlaneSurfaceFit(); PlaneSurfaceFit(const Base::Vector3f& b, const Base::Vector3f& n); - ~PlaneSurfaceFit(); - const char* GetType() const { return "Plane"; } - void Initialize(const MeshGeomFacet&); - bool TestTriangle(const MeshGeomFacet&) const; - void AddTriangle(const MeshGeomFacet&); - bool Done() const; - float Fit(); - float GetDistanceToSurface(const Base::Vector3f&) const; - std::vector Parameters() const; + ~PlaneSurfaceFit() override; + const char* GetType() const override { return "Plane"; } + void Initialize(const MeshGeomFacet&) override; + bool TestTriangle(const MeshGeomFacet&) const override; + void AddTriangle(const MeshGeomFacet&) override; + bool Done() const override; + float Fit() override; + float GetDistanceToSurface(const Base::Vector3f&) const override; + std::vector Parameters() const override; private: Base::Vector3f basepoint; @@ -128,15 +128,15 @@ class MeshExport CylinderSurfaceFit : public AbstractSurfaceFit public: CylinderSurfaceFit(); CylinderSurfaceFit(const Base::Vector3f& b, const Base::Vector3f& a, float r); - ~CylinderSurfaceFit(); - const char* GetType() const { return "Cylinder"; } - void Initialize(const MeshGeomFacet&); - bool TestTriangle(const MeshGeomFacet&) const; - void AddTriangle(const MeshGeomFacet&); - bool Done() const; - float Fit(); - float GetDistanceToSurface(const Base::Vector3f&) const; - std::vector Parameters() const; + ~CylinderSurfaceFit() override; + const char* GetType() const override { return "Cylinder"; } + void Initialize(const MeshGeomFacet&) override; + bool TestTriangle(const MeshGeomFacet&) const override; + void AddTriangle(const MeshGeomFacet&) override; + bool Done() const override; + float Fit() override; + float GetDistanceToSurface(const Base::Vector3f&) const override; + std::vector Parameters() const override; private: Base::Vector3f basepoint; @@ -150,15 +150,15 @@ class MeshExport SphereSurfaceFit : public AbstractSurfaceFit public: SphereSurfaceFit(); SphereSurfaceFit(const Base::Vector3f& c, float r); - ~SphereSurfaceFit(); - const char* GetType() const { return "Sphere"; } - void Initialize(const MeshGeomFacet&); - bool TestTriangle(const MeshGeomFacet&) const; - void AddTriangle(const MeshGeomFacet&); - bool Done() const; - float Fit(); - float GetDistanceToSurface(const Base::Vector3f&) const; - std::vector Parameters() const; + ~SphereSurfaceFit() override; + const char* GetType() const override { return "Sphere"; } + void Initialize(const MeshGeomFacet&) override; + bool TestTriangle(const MeshGeomFacet&) const override; + void AddTriangle(const MeshGeomFacet&) override; + bool Done() const override; + float Fit() override; + float GetDistanceToSurface(const Base::Vector3f&) const override; + std::vector Parameters() const override; private: Base::Vector3f center; @@ -171,12 +171,12 @@ class MeshExport MeshDistanceGenericSurfaceFitSegment : public MeshDistanceSurfa public: MeshDistanceGenericSurfaceFitSegment(AbstractSurfaceFit*, const MeshKernel& mesh, unsigned long minFacets, float tol); - virtual ~MeshDistanceGenericSurfaceFitSegment(); - bool TestFacet (const MeshFacet& rclFacet) const; - const char* GetType() const { return fitter->GetType(); } - void Initialize(FacetIndex); - bool TestInitialFacet(FacetIndex) const; - void AddFacet(const MeshFacet& rclFacet); + ~MeshDistanceGenericSurfaceFitSegment() override; + bool TestFacet (const MeshFacet& rclFacet) const override; + const char* GetType() const override { return fitter->GetType(); } + void Initialize(FacetIndex) override; + bool TestInitialFacet(FacetIndex) const override; + void AddFacet(const MeshFacet& rclFacet) override; std::vector Parameters() const; protected: @@ -200,8 +200,8 @@ class MeshExport MeshCurvaturePlanarSegment : public MeshCurvatureSurfaceSegment public: MeshCurvaturePlanarSegment(const std::vector& ci, unsigned long minFacets, float tol) : MeshCurvatureSurfaceSegment(ci, minFacets), tolerance(tol) {} - virtual bool TestFacet (const MeshFacet &rclFacet) const; - virtual const char* GetType() const { return "Plane"; } + bool TestFacet (const MeshFacet &rclFacet) const override; + const char* GetType() const override { return "Plane"; } private: float tolerance; @@ -213,8 +213,8 @@ public: MeshCurvatureCylindricalSegment(const std::vector& ci, unsigned long minFacets, float tolMin, float tolMax, float curv) : MeshCurvatureSurfaceSegment(ci, minFacets), toleranceMin(tolMin), toleranceMax(tolMax) { curvature = curv;} - virtual bool TestFacet (const MeshFacet &rclFacet) const; - virtual const char* GetType() const { return "Cylinder"; } + bool TestFacet (const MeshFacet &rclFacet) const override; + const char* GetType() const override { return "Cylinder"; } private: float curvature; @@ -227,8 +227,8 @@ class MeshExport MeshCurvatureSphericalSegment : public MeshCurvatureSurfaceSegm public: MeshCurvatureSphericalSegment(const std::vector& ci, unsigned long minFacets, float tol, float curv) : MeshCurvatureSurfaceSegment(ci, minFacets), tolerance(tol) { curvature = curv;} - virtual bool TestFacet (const MeshFacet &rclFacet) const; - virtual const char* GetType() const { return "Sphere"; } + bool TestFacet (const MeshFacet &rclFacet) const override; + const char* GetType() const override { return "Sphere"; } private: float curvature; @@ -242,8 +242,8 @@ public: float tolMin, float tolMax, float c1, float c2) : MeshCurvatureSurfaceSegment(ci, minFacets), c1(c1), c2(c2), toleranceMin(tolMin), toleranceMax(tolMax) {} - virtual bool TestFacet (const MeshFacet &rclFacet) const; - virtual const char* GetType() const { return "Freeform"; } + bool TestFacet (const MeshFacet &rclFacet) const override; + const char* GetType() const override { return "Freeform"; } private: float c1, c2; @@ -255,11 +255,11 @@ class MeshExport MeshSurfaceVisitor : public MeshFacetVisitor { public: MeshSurfaceVisitor (MeshSurfaceSegment& segm, std::vector &indices); - virtual ~MeshSurfaceVisitor (); + ~MeshSurfaceVisitor () override; bool AllowVisit (const MeshFacet& face, const MeshFacet&, - FacetIndex, unsigned long, unsigned short neighbourIndex); + FacetIndex, unsigned long, unsigned short neighbourIndex) override; bool Visit (const MeshFacet & face, const MeshFacet &, - FacetIndex ulFInd, unsigned long); + FacetIndex ulFInd, unsigned long) override; protected: std::vector &indices; @@ -269,7 +269,7 @@ protected: class MeshExport MeshSegmentAlgorithm { public: - MeshSegmentAlgorithm(const MeshKernel& kernel) : myKernel(kernel) {} + explicit MeshSegmentAlgorithm(const MeshKernel& kernel) : myKernel(kernel) {} void FindSegments(std::vector&); private: diff --git a/src/Mod/Mesh/App/Core/SetOperations.cpp b/src/Mod/Mesh/App/Core/SetOperations.cpp index 463b6fb620..140c50d73e 100644 --- a/src/Mod/Mesh/App/Core/SetOperations.cpp +++ b/src/Mod/Mesh/App/Core/SetOperations.cpp @@ -192,7 +192,7 @@ void SetOperations::Cut (std::set& facetsCuttingEdge0, std::set vecFacets2; grid2.Inside(grid1.GetBoundBox(gx1, gy1, gz1), vecFacets2); - if (vecFacets2.size() > 0) + if (!vecFacets2.empty()) { std::set vecFacets1; grid1.GetElements(gx1, gy1, gz1, vecFacets1); diff --git a/src/Mod/Mesh/App/Core/SetOperations.h b/src/Mod/Mesh/App/Core/SetOperations.h index d2943bf994..155a6f2177 100644 --- a/src/Mod/Mesh/App/Core/SetOperations.h +++ b/src/Mod/Mesh/App/Core/SetOperations.h @@ -155,8 +155,8 @@ private: Base::Builder3D& _builder; CollectFacetVisitor (const MeshKernel& mesh, std::vector& facets, std::map& edges, int side, float mult, Base::Builder3D& builder); - bool Visit (const MeshFacet &rclFacet, const MeshFacet &rclFrom, FacetIndex ulFInd, unsigned long ulLevel); - bool AllowVisit (const MeshFacet& rclFacet, const MeshFacet& rclFrom, FacetIndex ulFInd, unsigned long ulLevel, unsigned short neighbourIndex); + bool Visit (const MeshFacet &rclFacet, const MeshFacet &rclFrom, FacetIndex ulFInd, unsigned long ulLevel) override; + bool AllowVisit (const MeshFacet& rclFacet, const MeshFacet& rclFrom, FacetIndex ulFInd, unsigned long ulLevel, unsigned short neighbourIndex) override; }; /** all points from cut */ diff --git a/src/Mod/Mesh/App/Core/Smoothing.cpp b/src/Mod/Mesh/App/Core/Smoothing.cpp index e0345cd9f1..05a0fa5dc2 100644 --- a/src/Mod/Mesh/App/Core/Smoothing.cpp +++ b/src/Mod/Mesh/App/Core/Smoothing.cpp @@ -31,6 +31,7 @@ #include "Elements.h" #include "Iterator.h" #include "Approximation.h" +#include using namespace MeshCore; @@ -38,7 +39,6 @@ using namespace MeshCore; AbstractSmoothing::AbstractSmoothing(MeshKernel& m) : kernel(m) - , tolerance(0) , component(Normal) , continuity(C0) { @@ -56,6 +56,7 @@ void AbstractSmoothing::initialize(Component comp, Continuity cont) PlaneFitSmoothing::PlaneFitSmoothing(MeshKernel& m) : AbstractSmoothing(m) + , maximum(FLT_MAX) { } @@ -102,7 +103,7 @@ void PlaneFitSmoothing::Smooth(unsigned int iterations) N.Scale(-1.0, -1.0, -1.0); // maximum value to move is distance to mean plane - float d = std::min(fabs(this->tolerance),fabs(N*L)); + float d = std::min(fabs(this->maximum),fabs(N*L)); N.Scale(d,d,d); PointArray[v_it.Position()].Set(v_it->x - N.x, v_it->y - N.y, v_it->z - N.z); @@ -156,7 +157,7 @@ void PlaneFitSmoothing::SmoothPoints(unsigned int iterations, const std::vector< N.Scale(-1.0, -1.0, -1.0); // maximum value to move is distance to mean plane - float d = std::min(fabs(this->tolerance),fabs(N*L)); + float d = std::min(fabs(this->maximum),fabs(N*L)); N.Scale(d,d,d); PointArray[v_it.Position()].Set(v_it->x - N.x, v_it->y - N.y, v_it->z - N.z); @@ -304,3 +305,128 @@ void TaubinSmoothing::SmoothPoints(unsigned int iterations, const std::vector; +inline Base::Vector3d find_median(std::vector &container) +{ + auto compare_angle_normal = [](const AngleNormal& an1, const AngleNormal& an2) { + return an1.first < an2.first; + }; + size_t n = container.size() / 2; + std::nth_element(container.begin(), container.begin() + n, container.end(), compare_angle_normal); + + if ((container.size() % 2) == 1) { + return container[n].second; + } + else { + // even sized vector -> average the two middle values + auto max_it = std::max_element(container.begin(), container.begin() + n, compare_angle_normal); + Base::Vector3d vec = (max_it->second + container[n].second) / 2.0; + vec.Normalize(); + return vec; + } +} +} + +MedianFilterSmoothing::MedianFilterSmoothing(MeshKernel& m) + : AbstractSmoothing(m), weights(1) +{ +} + +MedianFilterSmoothing::~MedianFilterSmoothing() +{ +} + +void MedianFilterSmoothing::Smooth(unsigned int iterations) +{ + std::vector point_indices(kernel.CountPoints()); + std::generate(point_indices.begin(), point_indices.end(), Base::iotaGen(0)); + MeshCore::MeshRefFacetToFacets ff_it(kernel); + MeshCore::MeshRefPointToFacets vf_it(kernel); + + for (unsigned int i=0; i& point_indices) +{ + MeshCore::MeshRefFacetToFacets ff_it(kernel); + MeshCore::MeshRefPointToFacets vf_it(kernel); + + for (unsigned int i=0; i& point_indices) +{ + const MeshCore::MeshPointArray& points = kernel.GetPoints(); + const MeshCore::MeshFacetArray& facets = kernel.GetFacets(); + + // Initialize the array with the real normals + std::vector faceNormals; + faceNormals.reserve(facets.size()); + MeshCore::MeshFacetIterator iter(kernel); + for (iter.Init(); iter.More(); iter.Next()) { + faceNormals.emplace_back(Base::toVector(iter->GetNormal())); + } + + // Step 1: determine face normals + for (FacetIndex pos = 0; pos < facets.size(); pos++) { + iter.Set(pos); + Base::Vector3d refNormal = Base::toVector(iter->GetNormal()); + const std::set& cv = ff_it[pos]; + const MeshCore::MeshFacet& facet = facets[pos]; + + std::vector anglesWithFaces; + for (auto fi : cv) { + iter.Set(fi); + Base::Vector3d faceNormal = Base::toVector(iter->GetNormal()); + double angle = refNormal.GetAngle(faceNormal); + + int absWeight = std::abs(weights); + if (absWeight > 1 && facet.IsNeighbour(fi)) { + if (weights < 0) { + angle = -angle; + } + for (int i = 0; i < absWeight; i++) { + anglesWithFaces.emplace_back(angle, faceNormal); + } + } + else { + anglesWithFaces.emplace_back(angle, faceNormal); + } + } + + faceNormals[pos] = find_median(anglesWithFaces); + } + + // Step 2: move vertices + for (auto pos : point_indices) { + Base::Vector3d P = Base::toVector(points[pos]); + const std::set& cv = vf_it[pos]; + + double totalArea = 0.0; + Base::Vector3d totalvT; + for (auto it : cv) { + iter.Set(it); + + double faceArea = iter->Area(); + totalArea += faceArea; + + Base::Vector3d C = Base::toVector(iter->GetGravityPoint()); + + Base::Vector3d PC = C - P; + Base::Vector3d mT = faceNormals[it]; + Base::Vector3d vT = (PC * mT) * mT; + totalvT += vT * faceArea; + } + + P = P + totalvT / totalArea; + kernel.SetPoint(pos, Base::toVector(P)); + } +} diff --git a/src/Mod/Mesh/App/Core/Smoothing.h b/src/Mod/Mesh/App/Core/Smoothing.h index 300d97b1d5..7dffab3073 100644 --- a/src/Mod/Mesh/App/Core/Smoothing.h +++ b/src/Mod/Mesh/App/Core/Smoothing.h @@ -32,6 +32,7 @@ namespace MeshCore class MeshKernel; class MeshRefPointToPoints; class MeshRefPointToFacets; +class MeshRefFacetToFacets; /** Base class for smoothing algorithms. */ class MeshExport AbstractSmoothing @@ -49,7 +50,7 @@ public: C2 }; - AbstractSmoothing(MeshKernel&); + explicit AbstractSmoothing(MeshKernel&); virtual ~AbstractSmoothing(); void initialize(Component comp, Continuity cont); @@ -60,7 +61,6 @@ public: protected: MeshKernel& kernel; - float tolerance; Component component; Continuity continuity; }; @@ -68,19 +68,25 @@ protected: class MeshExport PlaneFitSmoothing : public AbstractSmoothing { public: - PlaneFitSmoothing(MeshKernel&); - virtual ~PlaneFitSmoothing(); - void Smooth(unsigned int); - void SmoothPoints(unsigned int, const std::vector&); + explicit PlaneFitSmoothing(MeshKernel&); + ~PlaneFitSmoothing() override; + void SetMaximum(float max) { + maximum = max; + } + void Smooth(unsigned int) override; + void SmoothPoints(unsigned int, const std::vector&) override; + +private: + float maximum; }; class MeshExport LaplaceSmoothing : public AbstractSmoothing { public: - LaplaceSmoothing(MeshKernel&); - virtual ~LaplaceSmoothing(); - void Smooth(unsigned int); - void SmoothPoints(unsigned int, const std::vector&); + explicit LaplaceSmoothing(MeshKernel&); + ~LaplaceSmoothing() override; + void Smooth(unsigned int) override; + void SmoothPoints(unsigned int, const std::vector&) override; void SetLambda(double l) { lambda = l;} protected: @@ -97,16 +103,41 @@ protected: class MeshExport TaubinSmoothing : public LaplaceSmoothing { public: - TaubinSmoothing(MeshKernel&); - virtual ~TaubinSmoothing(); - void Smooth(unsigned int); - void SmoothPoints(unsigned int, const std::vector&); + explicit TaubinSmoothing(MeshKernel&); + ~TaubinSmoothing() override; + void Smooth(unsigned int) override; + void SmoothPoints(unsigned int, const std::vector&) override; void SetMicro(double m) { micro = m;} protected: double micro; }; +/*! + * \brief The MedianFilterSmoothing class + * Smoothing based on median filter from the paper: + * Mesh Median Filter for Smoothing 3-D Polygonal Surfaces + */ +class MeshExport MedianFilterSmoothing : public AbstractSmoothing +{ +public: + explicit MedianFilterSmoothing(MeshKernel&); + ~MedianFilterSmoothing() override; + void SetWeight(int w) { + weights = w; + } + void Smooth(unsigned int) override; + void SmoothPoints(unsigned int, const std::vector&) override; + +private: + void UpdatePoints(const MeshRefFacetToFacets&, + const MeshRefPointToFacets&, + const std::vector&); + +private: + int weights; +}; + } // namespace MeshCore diff --git a/src/Mod/Mesh/App/Core/SphereFit.cpp b/src/Mod/Mesh/App/Core/SphereFit.cpp index 473e0237e7..9b54cb007a 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.cpp +++ b/src/Mod/Mesh/App/Core/SphereFit.cpp @@ -25,7 +25,7 @@ #ifndef _PreComp_ # include # include -# include +# include #endif #include "SphereFit.h" @@ -130,8 +130,8 @@ void SphereFit::ProjectToSphere() Base::Vector3f& cPnt = *it; // Compute unit vector from sphere centre to point. - // Because this vector is orthogonal to the sphere's surface at the - // intersection point we can easily compute the projection point on the + // Because this vector is orthogonal to the sphere's surface at the + // intersection point we can easily compute the projection point on the // closest surface point using the radius of the sphere Base::Vector3d diff((double)cPnt.x - _vCenter.x, (double)cPnt.y - _vCenter.y, (double)cPnt.z - _vCenter.z); double length = diff.Length(); @@ -162,7 +162,7 @@ void SphereFit::ComputeApproximations() _numIter = 0; _vCenter.Set(0.0, 0.0, 0.0); _dRadius = 0.0; - if (_vPoints.size() > 0) + if (!_vPoints.empty()) { std::list< Base::Vector3f >::const_iterator cIt; for (cIt = _vPoints.begin(); cIt != _vPoints.end(); ++cIt) @@ -210,7 +210,7 @@ float SphereFit::Fit() // Set up the quasi parameteric normal equations setupNormalEquationMatrices(residuals, atpa, atpl); - + // Solve the equations for the unknown corrections Eigen::LLT< Matrix4x4 > llt(atpa); if (llt.info() != Eigen::Success) @@ -256,8 +256,8 @@ void SphereFit::setupNormalEquationMatrices(const std::vector< Base::Vector3d > atpa.setZero(); atpl.setZero(); - // For each point, setup the observation equation coefficients and add their - // contribution into the the normal equation matrices + // For each point, setup the observation equation coefficients and add their + // contribution into the normal equation matrices double a[4], b[3]; double f0, qw; std::vector< Base::Vector3d >::const_iterator vIt = residuals.begin(); @@ -272,7 +272,7 @@ void SphereFit::setupNormalEquationMatrices(const std::vector< Base::Vector3d > setLowerPart(atpa); } -// Sets up contributions of given observation to the quasi parameteric +// Sets up contributions of given observation to the quasi parameteric // normal equation matrices. Assumes uncorrelated coordinates. // point ... point // residual ... residual for this point computed from previous iteration (zero for first iteration) @@ -282,7 +282,7 @@ void SphereFit::setupNormalEquationMatrices(const std::vector< Base::Vector3d > // b[3] ... observation partials void SphereFit::setupObservation(const Base::Vector3f &point, const Base::Vector3d &residual, double a[4], double &f0, double &qw, double b[3]) const { - // This adjustment requires an update of the observation approximations + // This adjustment requires an update of the observation approximations // because the residuals do not have a linear relationship. // New estimates for the observations: double xEstimate = (double)point.x + residual.x; @@ -393,7 +393,7 @@ bool SphereFit::computeResiduals(const Eigen::VectorXd &x, std::vector< Base::Ve //sigma0 += v.x * w[0] * v.x + v.y * w[1] * v.y + v.z * w[2] * v.z; sigma0 += v.x * v.x + v.y * v.y + v.z * v.z; - + if ((dVx > vConvLimit) || (dVy > vConvLimit) || (dVz > vConvLimit)) vConverged = false; diff --git a/src/Mod/Mesh/App/Core/SphereFit.h b/src/Mod/Mesh/App/Core/SphereFit.h index 1b475f36a0..2064849f7e 100644 --- a/src/Mod/Mesh/App/Core/SphereFit.h +++ b/src/Mod/Mesh/App/Core/SphereFit.h @@ -45,7 +45,7 @@ public: /** * Destruction */ - virtual ~SphereFit(); + ~SphereFit() override; /** * Set approximations before calling Fit() @@ -75,7 +75,7 @@ public: /** * Fit a sphere onto the given points. If the fit fails FLOAT_MAX is returned. */ - float Fit(); + float Fit() override; /** * Returns the distance from the point \a rcPoint to the fitted sphere. If Fit() has not been * called FLOAT_MAX is returned. diff --git a/src/Mod/Mesh/App/Core/Tools.h b/src/Mod/Mesh/App/Core/Tools.h index 09ce35acec..241efb2351 100644 --- a/src/Mod/Mesh/App/Core/Tools.h +++ b/src/Mod/Mesh/App/Core/Tools.h @@ -43,7 +43,7 @@ namespace MeshCore { class MeshSearchNeighbours { public: - MeshSearchNeighbours ( const MeshKernel &rclM, float fSampleDistance = 1.0f); + explicit MeshSearchNeighbours ( const MeshKernel &rclM, float fSampleDistance = 1.0f); virtual ~MeshSearchNeighbours () {} /** Re-initilaizes internal structures. */ void Reinit (float fSampleDistance); @@ -69,7 +69,7 @@ protected: struct CDistRad { - CDistRad (const Base::Vector3f clCenter) : _clCenter(clCenter) {} + explicit CDistRad (const Base::Vector3f clCenter) : _clCenter(clCenter) {} bool operator()(const Base::Vector3f &rclPt1, const Base::Vector3f &rclPt2) { return Base::DistanceP2(_clCenter, rclPt1) < Base::DistanceP2(_clCenter, rclPt2); } Base::Vector3f _clCenter; }; @@ -144,7 +144,7 @@ inline bool MeshSearchNeighbours::TriangleCutsSphere (const MeshFacet &rclF) con class MeshFaceIterator { public: - MeshFaceIterator(const MeshKernel& mesh) + explicit MeshFaceIterator(const MeshKernel& mesh) : it(mesh) {} Base::Vector3f operator() (FacetIndex index) { @@ -159,7 +159,7 @@ private: class MeshVertexIterator { public: - MeshVertexIterator(const MeshKernel& mesh) + explicit MeshVertexIterator(const MeshKernel& mesh) : it(mesh) {} Base::Vector3f operator() (PointIndex index) { diff --git a/src/Mod/Mesh/App/Core/TopoAlgorithm.h b/src/Mod/Mesh/App/Core/TopoAlgorithm.h index 778db23a21..153dca1ecf 100644 --- a/src/Mod/Mesh/App/Core/TopoAlgorithm.h +++ b/src/Mod/Mesh/App/Core/TopoAlgorithm.h @@ -52,7 +52,7 @@ class MeshExport MeshTopoAlgorithm { public: // construction/destruction - MeshTopoAlgorithm (MeshKernel &rclM); + explicit MeshTopoAlgorithm (MeshKernel &rclM); virtual ~MeshTopoAlgorithm (); public: @@ -336,7 +336,7 @@ class MeshExport MeshComponents public: enum TMode {OverEdge, OverPoint}; - MeshComponents( const MeshKernel& rclMesh ); + explicit MeshComponents( const MeshKernel& rclMesh ); ~MeshComponents(); /** diff --git a/src/Mod/Mesh/App/Core/Triangulation.cpp b/src/Mod/Mesh/App/Core/Triangulation.cpp index 8adfc38c2c..e51787b94f 100644 --- a/src/Mod/Mesh/App/Core/Triangulation.cpp +++ b/src/Mod/Mesh/App/Core/Triangulation.cpp @@ -102,7 +102,7 @@ void AbstractPolygonTriangulator::SetVerifier(TriangulationVerifier* v) void AbstractPolygonTriangulator::SetPolygon(const std::vector& raclPoints) { this->_points = raclPoints; - if (this->_points.size() > 0) { + if (!this->_points.empty()) { if (this->_points.front() == this->_points.back()) this->_points.pop_back(); } diff --git a/src/Mod/Mesh/App/Core/Triangulation.h b/src/Mod/Mesh/App/Core/Triangulation.h index 805a835823..0c8fc4c1fa 100644 --- a/src/Mod/Mesh/App/Core/Triangulation.h +++ b/src/Mod/Mesh/App/Core/Triangulation.h @@ -47,12 +47,12 @@ public: class MeshExport TriangulationVerifierV2 : public TriangulationVerifier { public: - virtual bool Accept(const Base::Vector3f& n, + bool Accept(const Base::Vector3f& n, const Base::Vector3f& p1, const Base::Vector3f& p2, - const Base::Vector3f& p3) const; - virtual bool MustFlip(const Base::Vector3f& n1, - const Base::Vector3f& n2) const; + const Base::Vector3f& p3) const override; + bool MustFlip(const Base::Vector3f& n1, + const Base::Vector3f& n2) const override; }; class MeshExport AbstractPolygonTriangulator @@ -149,10 +149,10 @@ class MeshExport EarClippingTriangulator : public AbstractPolygonTriangulator { public: EarClippingTriangulator(); - ~EarClippingTriangulator(); + ~EarClippingTriangulator() override; protected: - bool Triangulate(); + bool Triangulate() override; private: /** @@ -191,42 +191,42 @@ class MeshExport QuasiDelaunayTriangulator : public EarClippingTriangulator { public: QuasiDelaunayTriangulator(); - ~QuasiDelaunayTriangulator(); + ~QuasiDelaunayTriangulator() override; protected: - bool Triangulate(); + bool Triangulate() override; }; class MeshExport DelaunayTriangulator : public AbstractPolygonTriangulator { public: DelaunayTriangulator(); - ~DelaunayTriangulator(); + ~DelaunayTriangulator() override; protected: - bool Triangulate(); + bool Triangulate() override; }; class MeshExport FlatTriangulator : public AbstractPolygonTriangulator { public: FlatTriangulator(); - ~FlatTriangulator(); + ~FlatTriangulator() override; - void PostProcessing(const std::vector&); + void PostProcessing(const std::vector&) override; protected: - bool Triangulate(); + bool Triangulate() override; }; class MeshExport ConstraintDelaunayTriangulator : public AbstractPolygonTriangulator { public: - ConstraintDelaunayTriangulator(float area); - ~ConstraintDelaunayTriangulator(); + explicit ConstraintDelaunayTriangulator(float area); + ~ConstraintDelaunayTriangulator() override; protected: - bool Triangulate(); + bool Triangulate() override; private: float fMaxArea; diff --git a/src/Mod/Mesh/App/Core/Trim.cpp b/src/Mod/Mesh/App/Core/Trim.cpp index 3f3722dd88..08331fb9a8 100644 --- a/src/Mod/Mesh/App/Core/Trim.cpp +++ b/src/Mod/Mesh/App/Core/Trim.cpp @@ -342,7 +342,7 @@ bool MeshTrimming::CreateFacets(FacetIndex ulFacetPos, int iSide, const std::vec return false; // no intersection point found => triangle is only touched at a corner point - if (raclPoints.size() == 0) { + if (raclPoints.empty()) { MeshFacet& facet = myMesh._aclFacetArray[ulFacetPos]; int iCtPtsIn=0; int iCtPtsOn=0; diff --git a/src/Mod/Mesh/App/Core/TrimByPlane.h b/src/Mod/Mesh/App/Core/TrimByPlane.h index 6192365e5a..642336de7e 100644 --- a/src/Mod/Mesh/App/Core/TrimByPlane.h +++ b/src/Mod/Mesh/App/Core/TrimByPlane.h @@ -29,13 +29,13 @@ namespace MeshCore { /** - * Trim the the facets in 3D with a plane + * Trim the facets in 3D with a plane * \author Werner Mayer */ class MeshExport MeshTrimByPlane { public: - MeshTrimByPlane(MeshKernel& mesh); + explicit MeshTrimByPlane(MeshKernel& mesh); ~MeshTrimByPlane(); public: diff --git a/src/Mod/Mesh/App/Core/Utilities.h b/src/Mod/Mesh/App/Core/Utilities.h index 0ed6f838d1..84804b2208 100644 --- a/src/Mod/Mesh/App/Core/Utilities.h +++ b/src/Mod/Mesh/App/Core/Utilities.h @@ -33,7 +33,7 @@ template <> struct vec_traits { typedef Wm4::Vector3d vec_type; typedef double float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.X(), v.Y(), v.Z()); } @@ -45,7 +45,7 @@ template <> struct vec_traits { typedef Wm4::Vector3f vec_type; typedef float float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.X(), v.Y(), v.Z()); } diff --git a/src/Mod/Mesh/App/Core/Visitor.cpp b/src/Mod/Mesh/App/Core/Visitor.cpp index d5da1438bc..6346ca7ce5 100644 --- a/src/Mod/Mesh/App/Core/Visitor.cpp +++ b/src/Mod/Mesh/App/Core/Visitor.cpp @@ -44,7 +44,7 @@ unsigned long MeshKernel::VisitNeighbourFacets (MeshFacetVisitor &rclFVisitor, F _aclFacetArray[ulStartFacet].SetFlag(MeshFacet::VISIT); // as long as free neighbours - while (clCurrentLevel.size() > 0) { + while (!clCurrentLevel.empty()) { // visit all neighbours of the current level for (clCurrIter = clCurrentLevel.begin(); clCurrIter < clCurrentLevel.end(); ++clCurrIter) { clCurrFacet = _aclFacetArray.begin() + *clCurrIter; @@ -94,7 +94,7 @@ unsigned long MeshKernel::VisitNeighbourFacetsOverCorners (MeshFacetVisitor &rcl aclCurrentLevel.push_back(ulStartFacet); raclFAry[ulStartFacet].SetFlag(MeshFacet::VISIT); - while (aclCurrentLevel.size() > 0) { + while (!aclCurrentLevel.empty()) { // visit all neighbours of the current level for (std::vector::iterator pCurrFacet = aclCurrentLevel.begin(); pCurrFacet < aclCurrentLevel.end(); ++pCurrFacet) { for (int i = 0; i < 3; i++) { @@ -132,7 +132,7 @@ unsigned long MeshKernel::VisitNeighbourPoints (MeshPointVisitor &rclPVisitor, P aclCurrentLevel.push_back(ulStartPoint); (pPBegin + ulStartPoint)->SetFlag(MeshPoint::VISIT); - while (aclCurrentLevel.size() > 0) { + while (!aclCurrentLevel.empty()) { // visit all neighbours of the current level for (clCurrIter = aclCurrentLevel.begin(); clCurrIter < aclCurrentLevel.end(); ++clCurrIter) { const std::set& raclNB = clNPs[*clCurrIter]; diff --git a/src/Mod/Mesh/App/Core/Visitor.h b/src/Mod/Mesh/App/Core/Visitor.h index ea06184496..2305c79f34 100644 --- a/src/Mod/Mesh/App/Core/Visitor.h +++ b/src/Mod/Mesh/App/Core/Visitor.h @@ -80,9 +80,9 @@ class MeshExport MeshSearchNeighbourFacetsVisitor : public MeshFacetVisitor { public: MeshSearchNeighbourFacetsVisitor (const MeshKernel &rclMesh, float fRadius, FacetIndex ulStartFacetIdx); - virtual ~MeshSearchNeighbourFacetsVisitor () {} + ~MeshSearchNeighbourFacetsVisitor () override {} /** Checks the facet if it lies inside the search radius. */ - inline bool Visit (const MeshFacet &rclFacet, const MeshFacet &rclFrom, FacetIndex ulFInd, unsigned long ulLevel); + inline bool Visit (const MeshFacet &rclFacet, const MeshFacet &rclFrom, FacetIndex ulFInd, unsigned long ulLevel) override; /** Resets the VISIT flag of already visited facets. */ inline std::vector GetAndReset (); @@ -124,10 +124,10 @@ class MeshExport MeshTopFacetVisitor : public MeshFacetVisitor { public: MeshTopFacetVisitor (std::vector &raulNB) : _raulNeighbours(raulNB) {} - virtual ~MeshTopFacetVisitor () {} + ~MeshTopFacetVisitor () override {} /** Collects the facet indices. */ virtual bool Visit (const MeshFacet &rclFacet, const MeshFacet &rclFrom, - FacetIndex ulFInd, unsigned long) + FacetIndex ulFInd, unsigned long) override { (void)rclFacet; (void)rclFrom; @@ -152,11 +152,11 @@ public: FacetIndex index, float deviation, std::vector &indices); - virtual ~MeshPlaneVisitor (); + ~MeshPlaneVisitor () override; bool AllowVisit (const MeshFacet& face, const MeshFacet&, - FacetIndex, unsigned long, unsigned short neighbourIndex); + FacetIndex, unsigned long, unsigned short neighbourIndex) override; bool Visit (const MeshFacet & face, const MeshFacet &, - FacetIndex ulFInd, unsigned long); + FacetIndex ulFInd, unsigned long) override; protected: const MeshKernel& mesh; diff --git a/src/Mod/Mesh/App/Exporter.h b/src/Mod/Mesh/App/Exporter.h index 9ed7f7243c..96e8000f61 100644 --- a/src/Mod/Mesh/App/Exporter.h +++ b/src/Mod/Mesh/App/Exporter.h @@ -77,7 +77,7 @@ class MergeExporter : public Exporter { public: MergeExporter(std::string fileName, MeshCore::MeshIO::Format fmt); - ~MergeExporter(); + ~MergeExporter() override; bool addMesh(const char *name, const MeshObject & mesh) override; @@ -103,7 +103,7 @@ class AmfExporter : public Exporter bool compress = true); /// Writes AMF footer - ~AmfExporter(); + ~AmfExporter() override; bool addMesh(const char *name, const MeshObject & mesh) override; diff --git a/src/Mod/Mesh/App/Facet.h b/src/Mod/Mesh/App/Facet.h index e21dcb1d01..5873530119 100644 --- a/src/Mod/Mesh/App/Facet.h +++ b/src/Mod/Mesh/App/Facet.h @@ -43,7 +43,7 @@ class MeshObject; class MeshExport Facet : public MeshCore::MeshGeomFacet { public: - Facet(const MeshCore::MeshFacet& face = MeshCore::MeshFacet(), const MeshObject* obj = nullptr, MeshCore::FacetIndex index = MeshCore::FACET_INDEX_MAX); + explicit Facet(const MeshCore::MeshFacet& face = MeshCore::MeshFacet(), const MeshObject* obj = nullptr, MeshCore::FacetIndex index = MeshCore::FACET_INDEX_MAX); Facet(const Facet& f); ~Facet(); diff --git a/src/Mod/Mesh/App/FeatureMeshCurvature.h b/src/Mod/Mesh/App/FeatureMeshCurvature.h index bef9907d63..16b155f479 100644 --- a/src/Mod/Mesh/App/FeatureMeshCurvature.h +++ b/src/Mod/Mesh/App/FeatureMeshCurvature.h @@ -40,7 +40,7 @@ namespace Mesh */ class MeshExport Curvature : public App::DocumentObject { - PROPERTY_HEADER(Mesh::Curvature); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Curvature); public: Curvature(); @@ -51,10 +51,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "MeshGui::ViewProviderMeshCurvature"; } //@} diff --git a/src/Mod/Mesh/App/FeatureMeshDefects.h b/src/Mod/Mesh/App/FeatureMeshDefects.h index 0c336127c9..e584dd1d88 100644 --- a/src/Mod/Mesh/App/FeatureMeshDefects.h +++ b/src/Mod/Mesh/App/FeatureMeshDefects.h @@ -37,12 +37,12 @@ namespace Mesh */ class MeshExport FixDefects : public Mesh::Feature { - PROPERTY_HEADER(Mesh::FixDefects); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixDefects); public: /// Constructor FixDefects(); - virtual ~FixDefects(); + ~FixDefects() override; /** @name Properties */ //@{ @@ -53,8 +53,8 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider @@ -67,17 +67,17 @@ public: */ class MeshExport HarmonizeNormals : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::HarmonizeNormals); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::HarmonizeNormals); public: /// Constructor HarmonizeNormals(); - virtual ~HarmonizeNormals(); + ~HarmonizeNormals() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -87,17 +87,17 @@ public: */ class MeshExport FlipNormals : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FlipNormals); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FlipNormals); public: /// Constructor FlipNormals(); - virtual ~FlipNormals(); + ~FlipNormals() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -107,17 +107,17 @@ public: */ class MeshExport FixNonManifolds : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FixNonManifolds); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixNonManifolds); public: /// Constructor FixNonManifolds(); - virtual ~FixNonManifolds(); + ~FixNonManifolds() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -127,17 +127,17 @@ public: */ class MeshExport FixDuplicatedFaces : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FixDuplicatedFaces); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixDuplicatedFaces); public: /// Constructor FixDuplicatedFaces(); - virtual ~FixDuplicatedFaces(); + ~FixDuplicatedFaces() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -147,17 +147,17 @@ public: */ class MeshExport FixDuplicatedPoints : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FixDuplicatedPoints); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixDuplicatedPoints); public: /// Constructor FixDuplicatedPoints(); - virtual ~FixDuplicatedPoints(); + ~FixDuplicatedPoints() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -167,17 +167,17 @@ public: */ class MeshExport FixDegenerations : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FixDegenerations); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixDegenerations); public: /// Constructor FixDegenerations(); - virtual ~FixDegenerations(); + ~FixDegenerations() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -187,12 +187,12 @@ public: */ class MeshExport FixDeformations : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FixDeformations); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixDeformations); public: /// Constructor FixDeformations(); - virtual ~FixDeformations(); + ~FixDeformations() override; /** @name Properties */ //@{ @@ -201,7 +201,7 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -211,17 +211,17 @@ public: */ class MeshExport FixIndices : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FixIndices); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FixIndices); public: /// Constructor FixIndices(); - virtual ~FixIndices(); + ~FixIndices() override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -231,19 +231,19 @@ public: */ class MeshExport FillHoles : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::FillHoles); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::FillHoles); public: /// Constructor FillHoles(); - virtual ~FillHoles(); + ~FillHoles() override; App::PropertyInteger FillupHolesOfLength; App::PropertyFloat MaxArea; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; @@ -253,18 +253,18 @@ public: */ class MeshExport RemoveComponents : public Mesh::FixDefects { - PROPERTY_HEADER(Mesh::RemoveComponents); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::RemoveComponents); public: /// Constructor RemoveComponents(); - virtual ~RemoveComponents(); + ~RemoveComponents() override; App::PropertyInteger RemoveCompOfSize; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; //@} }; diff --git a/src/Mod/Mesh/App/FeatureMeshExport.h b/src/Mod/Mesh/App/FeatureMeshExport.h index d18211d38b..7aeef97ce5 100644 --- a/src/Mod/Mesh/App/FeatureMeshExport.h +++ b/src/Mod/Mesh/App/FeatureMeshExport.h @@ -40,7 +40,7 @@ namespace Mesh */ class MeshExport Export : public App::DocumentObject { - PROPERTY_HEADER(Mesh::Export); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Export); public: Export(); @@ -48,15 +48,15 @@ public: App::PropertyLink Source; App::PropertyString FileName; App::PropertyString Format; - const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "MeshGui::ViewProviderExport"; } /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} }; diff --git a/src/Mod/Mesh/App/FeatureMeshImport.h b/src/Mod/Mesh/App/FeatureMeshImport.h index 4632ac4167..69e6b42d6e 100644 --- a/src/Mod/Mesh/App/FeatureMeshImport.h +++ b/src/Mod/Mesh/App/FeatureMeshImport.h @@ -39,7 +39,7 @@ namespace Mesh */ class Import : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Import); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Import); public: Import(); @@ -49,8 +49,8 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} }; diff --git a/src/Mod/Mesh/App/FeatureMeshSegmentByMesh.h b/src/Mod/Mesh/App/FeatureMeshSegmentByMesh.h index 29295b9f8e..b872b70531 100644 --- a/src/Mod/Mesh/App/FeatureMeshSegmentByMesh.h +++ b/src/Mod/Mesh/App/FeatureMeshSegmentByMesh.h @@ -42,7 +42,7 @@ namespace Mesh */ class SegmentByMesh : public Mesh::Feature { - PROPERTY_HEADER(Mesh::SegmentByMesh); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::SegmentByMesh); public: SegmentByMesh(); @@ -56,8 +56,8 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} }; diff --git a/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp b/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp index b1879beaa9..1798aaf378 100644 --- a/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp +++ b/src/Mod/Mesh/App/FeatureMeshSetOperations.cpp @@ -72,7 +72,7 @@ App::DocumentObjectExecReturn *SetOperations::execute() Mesh::Feature *mesh1 = dynamic_cast(Source1.getValue()); Mesh::Feature *mesh2 = dynamic_cast(Source2.getValue()); - if ((mesh1 != nullptr) && (mesh2 != nullptr)) { + if (mesh1 && mesh2) { const MeshObject& meshKernel1 = mesh1->Mesh.getValue(); const MeshObject& meshKernel2 = mesh2->Mesh.getValue(); diff --git a/src/Mod/Mesh/App/FeatureMeshSetOperations.h b/src/Mod/Mesh/App/FeatureMeshSetOperations.h index 2e0baa8042..37f28d65ca 100644 --- a/src/Mod/Mesh/App/FeatureMeshSetOperations.h +++ b/src/Mod/Mesh/App/FeatureMeshSetOperations.h @@ -42,7 +42,7 @@ namespace Mesh */ class SetOperations : public Mesh::Feature { - PROPERTY_HEADER(Mesh::SetOperations); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::SetOperations); public: SetOperations(); @@ -54,8 +54,8 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} }; diff --git a/src/Mod/Mesh/App/FeatureMeshSolid.h b/src/Mod/Mesh/App/FeatureMeshSolid.h index d1ed0b3847..2895f5baff 100644 --- a/src/Mod/Mesh/App/FeatureMeshSolid.h +++ b/src/Mod/Mesh/App/FeatureMeshSolid.h @@ -37,7 +37,7 @@ namespace Mesh */ class Sphere : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Sphere); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Sphere); public: Sphere(); @@ -48,9 +48,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; //@} }; @@ -58,7 +58,7 @@ public: class Ellipsoid : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Ellipsoid); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Ellipsoid); public: Ellipsoid(); @@ -70,9 +70,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; //@} }; @@ -80,7 +80,7 @@ public: class Cylinder : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Cylinder); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Cylinder); public: Cylinder(); @@ -94,9 +94,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; //@} }; @@ -104,7 +104,7 @@ public: class Cone : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Cone); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Cone); public: Cone(); @@ -119,9 +119,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; //@} }; @@ -129,7 +129,7 @@ public: class Torus : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Torus); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Torus); public: Torus(); @@ -141,9 +141,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; //@} }; @@ -151,7 +151,7 @@ public: class Cube : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Cube); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Cube); public: Cube(); @@ -163,9 +163,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(); - short mustExecute() const; - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; //@} }; diff --git a/src/Mod/Mesh/App/FeatureMeshTransform.h b/src/Mod/Mesh/App/FeatureMeshTransform.h index b619244f24..6c51ceb084 100644 --- a/src/Mod/Mesh/App/FeatureMeshTransform.h +++ b/src/Mod/Mesh/App/FeatureMeshTransform.h @@ -40,7 +40,7 @@ namespace Mesh */ class Transform : public Mesh::Feature { - PROPERTY_HEADER(Mesh::Transform); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Transform); public: Transform(); @@ -52,9 +52,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "MeshGui::ViewProviderMeshTransform"; } //@} diff --git a/src/Mod/Mesh/App/FeatureMeshTransformDemolding.h b/src/Mod/Mesh/App/FeatureMeshTransformDemolding.h index c56f83e1ef..eafd295e86 100644 --- a/src/Mod/Mesh/App/FeatureMeshTransformDemolding.h +++ b/src/Mod/Mesh/App/FeatureMeshTransformDemolding.h @@ -39,7 +39,7 @@ namespace Mesh */ class TransformDemolding : public Transform { - PROPERTY_HEADER(Mesh::TransformDemolding); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::TransformDemolding); public: TransformDemolding(); @@ -51,9 +51,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "MeshGui::ViewProviderMeshTransformDemolding"; } //@} diff --git a/src/Mod/Mesh/App/Importer.h b/src/Mod/Mesh/App/Importer.h index e40afd79c9..6b3c5f1d6f 100644 --- a/src/Mod/Mesh/App/Importer.h +++ b/src/Mod/Mesh/App/Importer.h @@ -42,7 +42,7 @@ class Feature; class Importer { public: - Importer(App::Document*); + explicit Importer(App::Document*); ~Importer() = default; void load(const std::string& fileName); diff --git a/src/Mod/Mesh/App/Mesh.cpp b/src/Mod/Mesh/App/Mesh.cpp index 4436902f74..8b47ea49aa 100644 --- a/src/Mod/Mesh/App/Mesh.cpp +++ b/src/Mod/Mesh/App/Mesh.cpp @@ -174,7 +174,7 @@ Base::BoundBox3d MeshObject::getBoundBox()const Base::BoundBox3d Bnd2; if (Bnd.IsValid()) { for (int i =0 ;i<=7;i++) - Bnd2.Add(transformToOutside(Bnd.CalcPoint(i))); + Bnd2.Add(transformPointToOutside(Bnd.CalcPoint(i))); } return Bnd2; @@ -184,7 +184,7 @@ bool MeshObject::getCenterOfGravity(Base::Vector3d& center) const { MeshCore::MeshAlgorithm alg(_kernel); Base::Vector3f pnt = alg.GetGravityPoint(); - center = transformToOutside(pnt); + center = transformPointToOutside(pnt); return true; } @@ -311,26 +311,9 @@ void MeshObject::getPoints(std::vector &Points, std::vector &Normals, float /*Accuracy*/, uint16_t /*flags*/) const { - Base::Matrix4D mat = _Mtrx; - - unsigned long ctpoints = _kernel.CountPoints(); - Points.reserve(ctpoints); - for (unsigned long i=0; i coords; + coords.reserve(point.size()); + std::copy(point.begin(), point.end(), std::back_inserter(coords)); + + std::vector indices; + indices.reserve(4 * faces.size()); + for (const auto& it : faces) { + indices.push_back(it._aulPoints[0]); + indices.push_back(it._aulPoints[1]); + indices.push_back(it._aulPoints[2]); + indices.push_back(-1); + } + + Base::InventorBuilder builder(str); + builder.beginSeparator(); + builder.addTransformation(getTransform()); + builder.addShapeHints(creaseangle); + builder.beginPoints(); + builder.addPoints(coords); + builder.endPoints(); + builder.addIndexedFaceSet(indices); + builder.endSeparator(); + builder.close(); +} + void MeshObject::addFacet(const MeshCore::MeshGeomFacet& facet) { _kernel.AddFacet(facet); @@ -802,6 +815,63 @@ std::vector MeshObject::getPointsFromFacets(const std::vector(ray.first); + Base::Vector3f dir = Base::toVector(ray.second); + + Base::Placement plm = getPlacement(); + Base::Placement inv = plm.inverse(); + + // transform the ray relative to the mesh kernel + inv.multVec(pnt, pnt); + inv.getRotation().multVec(dir, dir); + + FacetIndex index = 0; + Base::Vector3f res; + MeshCore::MeshAlgorithm alg(getKernel()); + + if (alg.NearestFacetOnRay(pnt, dir, static_cast(maxAngle), res, index)) { + plm.multVec(res, res); + output.first = index; + output.second = Base::toVector(res); + return true; + } + + return false; +} + +std::vector MeshObject::foraminate(const TRay& ray, double maxAngle) const +{ + Base::Vector3f pnt = Base::toVector(ray.first); + Base::Vector3f dir = Base::toVector(ray.second); + + Base::Placement plm = getPlacement(); + Base::Placement inv = plm.inverse(); + + // transform the ray relative to the mesh kernel + inv.multVec(pnt, pnt); + inv.getRotation().multVec(dir, dir); + + Base::Vector3f res; + MeshCore::MeshFacetIterator f_it(getKernel()); + int index = 0; + + std::vector output; + for (f_it.Begin(); f_it.More(); f_it.Next(), index++) { + if (f_it->Foraminate(pnt, dir, res, static_cast(maxAngle))) { + plm.multVec(res, res); + + MeshObject::TFaceSection section; + section.first = index; + section.second = Base::toVector(res); + output.push_back(section); + } + } + + return output; +} + void MeshObject::updateMesh(const std::vector& facets) const { std::vector points; @@ -934,7 +1004,7 @@ void MeshObject::offsetSpecial2(float fSize) // if there are no flipped triangles -> stop //int f =fliped.size(); - if (fliped.size() == 0) + if (fliped.empty()) break; for( std::set::iterator It= fliped.begin();It!=fliped.end();++It) @@ -1001,12 +1071,12 @@ void MeshObject::movePoint(PointIndex index, const Base::Vector3d& v) vec.x += _Mtrx[0][3]; vec.y += _Mtrx[1][3]; vec.z += _Mtrx[2][3]; - _kernel.MovePoint(index,transformToInside(vec)); + _kernel.MovePoint(index, transformPointToInside(vec)); } void MeshObject::setPoint(PointIndex index, const Base::Vector3d& p) { - _kernel.SetPoint(index,transformToInside(p)); + _kernel.SetPoint(index, transformPointToInside(p)); } void MeshObject::smooth(int iterations, float d_max) @@ -1029,13 +1099,7 @@ void MeshObject::decimate(int targetSize) Base::Vector3d MeshObject::getPointNormal(PointIndex index) const { std::vector temp = _kernel.CalcVertexNormals(); - Base::Vector3d normal = transformToOutside(temp[index]); - - // the normal is a vector, hence we must not apply the translation part - // of the transformation to the vector - normal.x -= _Mtrx[0][3]; - normal.y -= _Mtrx[1][3]; - normal.z -= _Mtrx[2][3]; + Base::Vector3d normal = transformVectorToOutside(temp[index]); normal.Normalize(); return normal; } @@ -1044,19 +1108,10 @@ std::vector MeshObject::getPointNormals() const { std::vector temp = _kernel.CalcVertexNormals(); - std::vector normals; - normals.reserve(temp.size()); - for (std::vector::iterator it = temp.begin(); it != temp.end(); ++it) { - Base::Vector3d normal = transformToOutside(*it); - // the normal is a vector, hence we must not apply the translation part - // of the transformation to the vector - normal.x -= _Mtrx[0][3]; - normal.y -= _Mtrx[1][3]; - normal.z -= _Mtrx[2][3]; - normal.Normalize(); - normals.push_back(normal); + std::vector normals = transformVectorsToOutside(temp); + for (auto& n : normals) { + n.Normalize(); } - return normals; } @@ -1078,7 +1133,10 @@ void MeshObject::crossSections(const std::vector& planes, st void MeshObject::cut(const Base::Polygon2d& polygon2d, const Base::ViewProjMethod& proj, MeshObject::CutType type) { - MeshCore::MeshAlgorithm meshAlg(this->_kernel); + MeshCore::MeshKernel kernel(this->_kernel); + kernel.Transform(getTransform()); + + MeshCore::MeshAlgorithm meshAlg(kernel); std::vector check; bool inner; @@ -1094,7 +1152,7 @@ void MeshObject::cut(const Base::Polygon2d& polygon2d, break; } - MeshCore::MeshFacetGrid meshGrid(this->_kernel); + MeshCore::MeshFacetGrid meshGrid(kernel); meshAlg.CheckFacets(meshGrid, &proj, polygon2d, inner, check); if (!check.empty()) this->deleteFacets(check); @@ -1103,7 +1161,10 @@ void MeshObject::cut(const Base::Polygon2d& polygon2d, void MeshObject::trim(const Base::Polygon2d& polygon2d, const Base::ViewProjMethod& proj, MeshObject::CutType type) { - MeshCore::MeshTrimming trim(this->_kernel, &proj, polygon2d); + MeshCore::MeshKernel kernel(this->_kernel); + kernel.Transform(getTransform()); + + MeshCore::MeshTrimming trim(kernel, &proj, polygon2d); std::vector check; std::vector triangle; @@ -1116,13 +1177,20 @@ void MeshObject::trim(const Base::Polygon2d& polygon2d, break; } - MeshCore::MeshFacetGrid meshGrid(this->_kernel); + MeshCore::MeshFacetGrid meshGrid(kernel); trim.CheckFacets(meshGrid, check); trim.TrimFacets(check, triangle); if (!check.empty()) this->deleteFacets(check); - if (!triangle.empty()) + + // Re-add some triangles + if (!triangle.empty()) { + Base::Matrix4D mat(getTransform()); + mat.inverse(); + for (auto& it : triangle) + it.Transform(mat); this->_kernel.AddFacets(triangle); + } } void MeshObject::trimByPlane(const Base::Vector3f& base, const Base::Vector3f& normal) @@ -1131,9 +1199,17 @@ void MeshObject::trimByPlane(const Base::Vector3f& base, const Base::Vector3f& n std::vector trimFacets, removeFacets; std::vector triangle; + // Apply the inverted mesh placement to the plane because the trimming is done + // on the untransformed mesh data + Base::Vector3f baseL, normalL; + Base::Placement meshPlacement = getPlacement(); + meshPlacement.invert(); + meshPlacement.multVec(base, baseL); + meshPlacement.getRotation().multVec(normal, normalL); + MeshCore::MeshFacetGrid meshGrid(this->_kernel); - trim.CheckFacets(meshGrid, base, normal, trimFacets, removeFacets); - trim.TrimFacets(trimFacets, base, normal, triangle); + trim.CheckFacets(meshGrid, baseL, normalL, trimFacets, removeFacets); + trim.TrimFacets(trimFacets, baseL, normalL, triangle); if (!removeFacets.empty()) this->deleteFacets(removeFacets); if (!triangle.empty()) @@ -1438,6 +1514,32 @@ bool MeshObject::hasSelfIntersections() const return !cMeshEval.Evaluate(); } +MeshObject::TFacePairs MeshObject::getSelfIntersections() const +{ + MeshCore::MeshEvalSelfIntersection eval(getKernel()); + MeshObject::TFacePairs pairs; + eval.GetIntersections(pairs); + return pairs; +} + +std::vector MeshObject::getSelfIntersections(const MeshObject::TFacePairs& facets) const +{ + MeshCore::MeshEvalSelfIntersection eval(getKernel()); + using Section = std::pair; + std::vector
selfPoints; + eval.GetIntersections(facets, selfPoints); + + std::vector lines; + lines.reserve(selfPoints.size()); + + Base::Matrix4D mat(getTransform()); + std::transform(selfPoints.begin(), selfPoints.end(), std::back_inserter(lines), [&mat](const Section& l){ + return Base::Line3d(mat * Base::convertTo(l.first), + mat * Base::convertTo(l.second)); + }); + return lines; +} + void MeshObject::removeSelfIntersections() { std::vector > selfIntersections; diff --git a/src/Mod/Mesh/App/Mesh.h b/src/Mod/Mesh/App/Mesh.h index 922fffbe98..9f72e2f540 100644 --- a/src/Mod/Mesh/App/Mesh.h +++ b/src/Mod/Mesh/App/Mesh.h @@ -31,7 +31,7 @@ #include #include -#include +#include #include #include @@ -63,10 +63,10 @@ namespace Mesh class MeshObject; class MeshExport MeshSegment : public Data::Segment { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual std::string getName() const { + std::string getName() const override { return "MeshSegment"; } @@ -82,21 +82,26 @@ public: */ class MeshExport MeshObject : public Data::ComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: enum GeometryType {PLANE, CYLINDER, SPHERE}; enum CutType {INNER, OUTER}; + using TFacePair = std::pair; + using TFacePairs = std::vector; + // typedef needed for cross-section - typedef std::pair TPlane; - typedef std::list > TPolylines; + using TPlane = std::pair; + using TPolylines = std::list>; + using TRay = std::pair; + using TFaceSection = std::pair; MeshObject(); explicit MeshObject(const MeshCore::MeshKernel& Kernel); explicit MeshObject(const MeshCore::MeshKernel& Kernel, const Base::Matrix4D &Mtrx); MeshObject(const MeshObject&); - virtual ~MeshObject(); + ~MeshObject() override; void operator = (const MeshObject&); @@ -106,21 +111,21 @@ public: * List of different subelement types * its NOT a list of the subelements itself */ - virtual std::vector getElementTypes() const; - virtual unsigned long countSubElements(const char* Type) const; + std::vector getElementTypes() const override; + unsigned long countSubElements(const char* Type) const override; /// get the subelement by type and number - virtual Data::Segment* getSubElement(const char* Type, unsigned long) const; + Data::Segment* getSubElement(const char* Type, unsigned long) const override; /** Get faces from segment */ - virtual void getFacesFromSubElement( + void getFacesFromSubElement( const Data::Segment*, std::vector &Points, std::vector &PointNormals, - std::vector &faces) const; + std::vector &faces) const override; //@} - void setTransform(const Base::Matrix4D& rclTrf); - Base::Matrix4D getTransform() const; - void transformGeometry(const Base::Matrix4D &rclMat); + void setTransform(const Base::Matrix4D& rclTrf) override; + Base::Matrix4D getTransform() const override; + void transformGeometry(const Base::Matrix4D &rclMat) override; /** * Swaps the content of \a Kernel and the internal mesh kernel. @@ -143,12 +148,14 @@ public: double getSurface() const; double getVolume() const; /** Get points from object with given accuracy */ - virtual void getPoints(std::vector &Points, + void getPoints(std::vector &Points, std::vector &Normals, - float Accuracy, uint16_t flags=0) const; - virtual void getFaces(std::vector &Points,std::vector &Topo, - float Accuracy, uint16_t flags=0) const; + float Accuracy, uint16_t flags=0) const override; + void getFaces(std::vector &Points,std::vector &Topo, + float Accuracy, uint16_t flags=0) const override; std::vector getPointsFromFacets(const std::vector& facets) const; + bool nearestFacetOnRay(const TRay& ray, double maxAngle, TFaceSection& output) const; + std::vector foraminate(const TRay& ray, double maxAngle) const; //@} void setKernel(const MeshCore::MeshKernel& m); @@ -157,17 +164,17 @@ public: const MeshCore::MeshKernel& getKernel() const { return _kernel; } - virtual Base::BoundBox3d getBoundBox() const; - virtual bool getCenterOfGravity(Base::Vector3d& center) const; + Base::BoundBox3d getBoundBox() const override; + bool getCenterOfGravity(Base::Vector3d& center) const override; /** @name I/O */ //@{ // Implemented from Persistence - unsigned int getMemSize () const; - void Save (Base::Writer &writer) const; - void SaveDocFile (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); - void RestoreDocFile(Base::Reader &reader); + unsigned int getMemSize () const override; + void Save (Base::Writer &writer) const override; + void SaveDocFile (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; + void RestoreDocFile(Base::Reader &reader) override; void save(const char* file,MeshCore::MeshIO::Format f=MeshCore::MeshIO::Undefined, const MeshCore::Material* mat = nullptr, const char* objectname = nullptr) const; @@ -179,6 +186,7 @@ public: // Save and load in internal format void save(std::ostream&) const; void load(std::istream&); + void writeInventor(std::ostream& str, float creaseangle=0.0f) const; //@} /** @name Manipulation */ @@ -307,6 +315,8 @@ public: void removeNonManifolds(); void removeNonManifoldPoints(); bool hasSelfIntersections() const; + TFacePairs getSelfIntersections() const; + std::vector getSelfIntersections(const TFacePairs&) const; void removeSelfIntersections(); void removeSelfIntersections(const std::vector&); void removeFoldsOnSurface(); diff --git a/src/Mod/Mesh/App/MeshFeature.h b/src/Mod/Mesh/App/MeshFeature.h index d9b2438dcd..e3c02a0ce1 100644 --- a/src/Mod/Mesh/App/MeshFeature.h +++ b/src/Mod/Mesh/App/MeshFeature.h @@ -53,12 +53,12 @@ class MeshFeaturePy; */ class MeshExport Feature : public App::GeoFeature { - PROPERTY_HEADER(Mesh::Feature); + PROPERTY_HEADER_WITH_OVERRIDE(Mesh::Feature); public: /// Constructor Feature(); - virtual ~Feature(); + ~Feature() override; /** @name Properties */ //@{ @@ -69,20 +69,20 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); - virtual void onChanged(const App::Property* prop); + App::DocumentObjectExecReturn *execute() override; + void onChanged(const App::Property* prop) override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "MeshGui::ViewProviderMeshFaceSet"; } - virtual const App::PropertyComplexGeoData* getPropertyOfGeometry() const { + const App::PropertyComplexGeoData* getPropertyOfGeometry() const override { return &Mesh; } /// handles the MeshPy object - virtual PyObject* getPyObject(); + PyObject* getPyObject() override; }; typedef App::FeatureCustomT FeatureCustom; diff --git a/src/Mod/Mesh/App/MeshPoint.h b/src/Mod/Mesh/App/MeshPoint.h index e576f5cbc6..5cf418431d 100644 --- a/src/Mod/Mesh/App/MeshPoint.h +++ b/src/Mod/Mesh/App/MeshPoint.h @@ -49,7 +49,7 @@ class MeshExport MeshPoint : public Vector3d public: /// simple constructor - MeshPoint(const Vector3d& vec = Vector3d(), const MeshObject* obj = nullptr, unsigned int index = UINT_MAX) + explicit MeshPoint(const Vector3d& vec = Vector3d(), const MeshObject* obj = nullptr, unsigned int index = UINT_MAX) :Vector3d(vec),Index(index),Mesh(obj) {} diff --git a/src/Mod/Mesh/App/MeshProperties.h b/src/Mod/Mesh/App/MeshProperties.h index ea007cf8ca..46f9e997ad 100644 --- a/src/Mod/Mesh/App/MeshProperties.h +++ b/src/Mod/Mesh/App/MeshProperties.h @@ -52,14 +52,14 @@ class MeshPy; */ class MeshExport PropertyNormalList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyNormalList(); - ~PropertyNormalList(); + ~PropertyNormalList() override; - virtual void setSize(int newSize); - virtual int getSize() const; + void setSize(int newSize) override; + int getSize() const override; void setValue(const Base::Vector3f&); void setValue(float x, float y, float z); @@ -78,19 +78,19 @@ public: return _lValueList; } - virtual PyObject *getPyObject(); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual App::Property *Copy() const; - virtual void Paste(const App::Property &from); + App::Property *Copy() const override; + void Paste(const App::Property &from) override; - virtual unsigned int getMemSize () const; + unsigned int getMemSize () const override; void transformGeometry(const Base::Matrix4D &rclMat); @@ -110,7 +110,7 @@ struct MeshExport CurvatureInfo */ class MeshExport PropertyCurvatureList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: enum { @@ -123,10 +123,10 @@ public: public: PropertyCurvatureList(); - ~PropertyCurvatureList(); + ~PropertyCurvatureList() override; - void setSize(int newSize){_lValueList.resize(newSize);} - int getSize() const {return _lValueList.size();} + void setSize(int newSize) override{_lValueList.resize(newSize);} + int getSize() const override {return _lValueList.size();} std::vector getCurvature( int tMode) const; void setValue(const CurvatureInfo&); void setValues(const std::vector&); @@ -143,22 +143,22 @@ public: } void transformGeometry(const Base::Matrix4D &rclMat); - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; /** @name Python interface */ //@{ - PyObject* getPyObject(); - void setPyObject(PyObject *value); + PyObject* getPyObject() override; + void setPyObject(PyObject *value) override; //@} - App::Property *Copy() const; - void Paste(const App::Property &from); + App::Property *Copy() const override; + void Paste(const App::Property &from) override; - virtual unsigned int getMemSize () const{return _lValueList.size() * sizeof(CurvatureInfo);} + unsigned int getMemSize () const override{return _lValueList.size() * sizeof(CurvatureInfo);} private: std::vector _lValueList; @@ -169,11 +169,11 @@ private: */ class MeshExport PropertyMeshKernel : public App::PropertyComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyMeshKernel(); - ~PropertyMeshKernel(); + ~PropertyMeshKernel() override; /** @name Getter/setter */ //@{ @@ -199,14 +199,14 @@ public: */ const MeshObject &getValue() const; const MeshObject *getValuePtr() const; - virtual unsigned int getMemSize () const; + unsigned int getMemSize () const override; //@} /** @name Getting basic geometric entities */ //@{ - const Data::ComplexGeoData* getComplexData() const; + const Data::ComplexGeoData* getComplexData() const override; /** Returns the bounding box around the underlying mesh kernel */ - Base::BoundBox3d getBoundingBox() const; + Base::BoundBox3d getBoundingBox() const override; //@} /** @name Modification */ @@ -214,10 +214,10 @@ public: MeshObject* startEditing(); void finishEditing(); /// Transform the real mesh data - void transformGeometry(const Base::Matrix4D &rclMat); + void transformGeometry(const Base::Matrix4D &rclMat) override; void setPointIndices( const std::vector >& ); - void setTransform(const Base::Matrix4D& rclTrf); - Base::Matrix4D getTransform() const; + void setTransform(const Base::Matrix4D& rclTrf) override; + Base::Matrix4D getTransform() const override; //@} /** @name Python interface */ @@ -226,29 +226,29 @@ public: * create a copy. However, the Python wrapper is marked as \a immutable so * that the mesh object cannot be modified from outside. */ - PyObject* getPyObject(); + PyObject* getPyObject() override; /** This method copies the content, hence creates an new mesh object * to copy the data. The passed argument can be an instance of the Python * wrapper for the mesh object or simply a list of triangles, i.e. a list * of lists of three floats. */ - void setPyObject(PyObject *value); + void setPyObject(PyObject *value) override; //@} - const char* getEditorName() const { + const char* getEditorName() const override { return "MeshGui::PropertyMeshKernelItem"; } /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - App::Property *Copy() const; - void Paste(const App::Property &from); + App::Property *Copy() const override; + void Paste(const App::Property &from) override; //@} private: diff --git a/src/Mod/Mesh/App/MeshPyImp.cpp b/src/Mod/Mesh/App/MeshPyImp.cpp index e24949b7fd..cc62c3d08b 100644 --- a/src/Mod/Mesh/App/MeshPyImp.cpp +++ b/src/Mod/Mesh/App/MeshPyImp.cpp @@ -25,7 +25,6 @@ #include #include -#include #include #include #include @@ -55,7 +54,7 @@ using namespace Mesh; struct MeshPropertyLock { - MeshPropertyLock(PropertyMeshKernel* p) : prop(p) + explicit MeshPropertyLock(PropertyMeshKernel* p) : prop(p) { if (prop) prop->startEditing(); } ~MeshPropertyLock() { if (prop) prop->finishEditing(); } @@ -79,14 +78,14 @@ int MeshPy::PyInit(PyObject* args, PyObject*) } else if (PyList_Check(pcObj)) { PyObject* ret = addFacets(args); - bool ok = (ret!=nullptr); + bool ok = (ret != nullptr); Py_XDECREF(ret); if (!ok) return -1; } else if (PyTuple_Check(pcObj)) { PyObject* ret = addFacets(args); - bool ok = (ret!=nullptr); + bool ok = (ret != nullptr); Py_XDECREF(ret); if (!ok) return -1; @@ -311,32 +310,9 @@ PyObject* MeshPy::writeInventor(PyObject *args) if (!PyArg_ParseTuple(args, "|f",&creaseangle)) return nullptr; - MeshObject* mesh = getMeshObjectPtr(); - const MeshCore::MeshFacetArray& faces = mesh->getKernel().GetFacets(); - std::vector indices; - std::vector coords; - coords.reserve(mesh->countPoints()); - for (MeshObject::const_point_iterator it = mesh->points_begin(); it != mesh->points_end(); ++it) - coords.emplace_back((float)it->x,(float)it->y,(float)it->z); - indices.reserve(4*faces.size()); - for (MeshCore::MeshFacetArray::_TConstIterator it = faces.begin(); it != faces.end(); ++it) { - indices.push_back(it->_aulPoints[0]); - indices.push_back(it->_aulPoints[1]); - indices.push_back(it->_aulPoints[2]); - indices.push_back(-1); - } - std::stringstream result; - Base::InventorBuilder builder(result); - builder.beginSeparator(); - builder.addShapeHints(creaseangle); - builder.beginPoints(); - builder.addPoints(coords); - builder.endPoints(); - builder.addIndexedFaceSet(indices); - builder.endSeparator(); - builder.close(); - + MeshObject* mesh = getMeshObjectPtr(); + mesh->writeInventor(result, creaseangle); return Py::new_reference_to(Py::String(result.str())); } @@ -1067,19 +1043,19 @@ PyObject* MeshPy::getSelfIntersections(PyObject *args) return nullptr; std::vector > selfIndices; - std::vector > selfPoints; - MeshCore::MeshEvalSelfIntersection eval(getMeshObjectPtr()->getKernel()); - eval.GetIntersections(selfIndices); - eval.GetIntersections(selfIndices, selfPoints); + std::vector selfLines; + + selfIndices = getMeshObjectPtr()->getSelfIntersections(); + selfLines = getMeshObjectPtr()->getSelfIntersections(selfIndices); Py::Tuple tuple(selfIndices.size()); - if (selfIndices.size() == selfPoints.size()) { + if (selfIndices.size() == selfLines.size()) { for (std::size_t i=0; igetKernel()); - int index = 0; + MeshObject::TRay ray = std::make_pair(pnt_t.toVector(), + dir_t.toVector()); + auto output = getMeshObjectPtr()->foraminate(ray, maxAngle); Py::Dict dict; - for (f_it.Begin(); f_it.More(); f_it.Next(), index++) { - if (f_it->Foraminate(pnt, dir, res, static_cast(maxAngle))) { - Py::Tuple tuple(3); - tuple.setItem(0, Py::Float(res.x)); - tuple.setItem(1, Py::Float(res.y)); - tuple.setItem(2, Py::Float(res.z)); - dict.setItem(Py::Long(index), tuple); - } + for (const auto& it : output) { + Py::Tuple tuple(3); + tuple.setItem(0, Py::Float(it.second.x)); + tuple.setItem(1, Py::Float(it.second.y)); + tuple.setItem(2, Py::Float(it.second.z)); + dict.setItem(Py::Long(it.first), tuple); } return Py::new_reference_to(dict); @@ -1783,15 +1751,17 @@ PyObject* MeshPy::trimByPlane(PyObject *args) Py_Return; } -PyObject* MeshPy::smooth(PyObject *args, PyObject *kwds) +PyObject* MeshPy::smooth(PyObject *args, PyObject *kwds) { char* method = "Laplace"; int iter=1; double lambda = 0; double micro = 0; - static char* keywords_smooth[] = {"Method","Iteration","Lambda","Micro",nullptr}; - if (!PyArg_ParseTupleAndKeywords(args, kwds, "|sidd",keywords_smooth, - &method, &iter, &lambda, µ)) + double maximum = 1000; + int weight = 1; + static char* keywords_smooth[] = {"Method", "Iteration", "Lambda", "Micro", "Maximum", "Weight", nullptr}; + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|sidddi",keywords_smooth, + &method, &iter, &lambda, µ, &maximum, &weight)) return nullptr; PY_TRY { @@ -1813,6 +1783,12 @@ PyObject* MeshPy::smooth(PyObject *args, PyObject *kwds) } else if (strcmp(method, "PlaneFit") == 0) { MeshCore::PlaneFitSmoothing smooth(kernel); + smooth.SetMaximum(maximum); + smooth.Smooth(iter); + } + else if (strcmp(method, "MedianFilter") == 0) { + MeshCore::MedianFilterSmoothing smooth(kernel); + smooth.SetWeight(weight); smooth.Smooth(iter); } else { @@ -1857,54 +1833,21 @@ PyObject* MeshPy::nearestFacetOnRay(PyObject *args) return nullptr; try { - Py::Tuple pnt_t(pnt_p); - Py::Tuple dir_t(dir_p); + Py::Vector pnt_t(pnt_p, false); + Py::Vector dir_t(dir_p, false); Py::Dict dict; - Base::Vector3f pnt((float)Py::Float(pnt_t.getItem(0)), - (float)Py::Float(pnt_t.getItem(1)), - (float)Py::Float(pnt_t.getItem(2))); - Base::Vector3f dir((float)Py::Float(dir_t.getItem(0)), - (float)Py::Float(dir_t.getItem(1)), - (float)Py::Float(dir_t.getItem(2))); - FacetIndex index = 0; - Base::Vector3f res; - MeshCore::MeshAlgorithm alg(getMeshObjectPtr()->getKernel()); - -#if 0 // for testing only - MeshCore::MeshFacetGrid grid(getMeshObjectPtr()->getKernel(),10); - // With grids we might search in the opposite direction, too - if (alg.NearestFacetOnRay(pnt, dir, grid, res, index) || - alg.NearestFacetOnRay(pnt, -dir, grid, res, index)) { -#else - if (alg.NearestFacetOnRay(pnt, dir, static_cast(maxAngle), res, index)) { -#endif + MeshObject::TRay ray = std::make_pair(pnt_t.toVector(), + dir_t.toVector()); + MeshObject::TFaceSection output; + if (getMeshObjectPtr()->nearestFacetOnRay(ray, maxAngle, output)) { Py::Tuple tuple(3); - tuple.setItem(0, Py::Float(res.x)); - tuple.setItem(1, Py::Float(res.y)); - tuple.setItem(2, Py::Float(res.z)); - dict.setItem(Py::Long((int)index), tuple); + tuple.setItem(0, Py::Float(output.second.x)); + tuple.setItem(1, Py::Float(output.second.y)); + tuple.setItem(2, Py::Float(output.second.z)); + dict.setItem(Py::Long(static_cast(output.first)), tuple); } -#if 0 // for testing only - char szBuf[200]; - std::ofstream str("grid_test.iv"); - Base::InventorBuilder builder(str); - MeshCore::MeshGridIterator g_it(grid); - for (g_it.Init(); g_it.More(); g_it.Next()) { - Base::BoundBox3f box = g_it.GetBoundBox(); - unsigned long uX,uY,uZ; - g_it.GetGridPos(uX,uY,uZ); - builder.addBoundingBox(Base::Vector3f(box.MinX,box.MinY, box.MinZ), - Base::Vector3f(box.MaxX,box.MaxY, box.MaxZ)); - sprintf(szBuf, "(%lu,%lu,%lu)", uX, uY, uZ); - builder.addText(box.GetCenter(), szBuf); - } - builder.addSingleArrow(pnt-20.0f*dir, pnt+10.0f*dir); - builder.close(); - str.close(); -#endif - return Py::new_reference_to(dict); } catch (const Py::Exception&) { @@ -2022,26 +1965,25 @@ PyObject* MeshPy::getCurvaturePerVertex(PyObject* args) return nullptr; const MeshCore::MeshKernel& kernel = getMeshObjectPtr()->getKernel(); - MeshCore::MeshSegmentAlgorithm finder(kernel); MeshCore::MeshCurvature meshCurv(kernel); meshCurv.ComputePerVertex(); const std::vector& curv = meshCurv.GetCurvature(); + Base::Placement plm = getMeshObjectPtr()->getPlacement(); + plm.setPosition(Base::Vector3d()); + Py::List list; for (const auto& it : curv) { + Base::Vector3d maxCurve = Base::convertTo(it.cMaxCurvDir); + Base::Vector3d minCurve = Base::convertTo(it.cMinCurvDir); + plm.multVec(maxCurve, maxCurve); + plm.multVec(minCurve, minCurve); + Py::Tuple tuple(4); tuple.setItem(0, Py::Float(it.fMaxCurvature)); tuple.setItem(1, Py::Float(it.fMinCurvature)); - Py::Tuple maxDir(3); - maxDir.setItem(0, Py::Float(it.cMaxCurvDir.x)); - maxDir.setItem(1, Py::Float(it.cMaxCurvDir.y)); - maxDir.setItem(2, Py::Float(it.cMaxCurvDir.z)); - tuple.setItem(2, maxDir); - Py::Tuple minDir(3); - minDir.setItem(0, Py::Float(it.cMinCurvDir.x)); - minDir.setItem(1, Py::Float(it.cMinCurvDir.y)); - minDir.setItem(2, Py::Float(it.cMinCurvDir.z)); - tuple.setItem(3, minDir); + tuple.setItem(2, Py::Vector(maxCurve)); + tuple.setItem(3, Py::Vector(minCurve)); list.append(tuple); } diff --git a/src/Mod/Mesh/App/MeshTestsApp.py b/src/Mod/Mesh/App/MeshTestsApp.py index 77ba1c8f0c..23e286a993 100644 --- a/src/Mod/Mesh/App/MeshTestsApp.py +++ b/src/Mod/Mesh/App/MeshTestsApp.py @@ -200,6 +200,18 @@ class MeshSplitTestCases(unittest.TestCase): len(self.mesh.nearestFacetOnRay((0.2,0.1,0.2),(0,0,-1)))) self.assertEqual(len(self.mesh.nearestFacetOnRay((0.2,0.1,0.2),(0,0, 1), math.pi/2)), len(self.mesh.nearestFacetOnRay((0.2,0.1,0.2),(0,0,-1), math.pi/2))) + # Apply placement to mesh + plm = Base.Placement(Base.Vector(1,2,3), Base.Rotation(1,1,1,1)) + pnt = Base.Vector(0.5, 0.5, 0.5) + vec = Base.Vector(0.0, 0.0, 1.0) + + self.mesh.Placement = plm + self.assertEqual(len(self.mesh.nearestFacetOnRay(pnt,vec)), 0) + + # Apply the placement on the ray as well + pnt = plm.multVec(pnt) + vec = plm.Rotation.multVec(vec) + self.assertEqual(len(self.mesh.nearestFacetOnRay(pnt,vec)), 1) def testForaminate(self): class FilterAngle: @@ -217,6 +229,24 @@ class MeshSplitTestCases(unittest.TestCase): self.assertEqual(filtered_result, list(self.mesh.foraminate((0.0, 0.0, 0.0), (0,1,1), math.pi/2).keys())) + def testForaminatePlacement(self): + pnt = Base.Vector(0.0, 0.0, 0.0) + vec = Base.Vector(0.0, 1.0, 1.0) + results = self.mesh.foraminate(pnt, vec) + self.assertEqual(len(results), 4) + + # Apply placement to mesh + plm = Base.Placement(Base.Vector(1,2,3), Base.Rotation(1,1,1,1)) + self.mesh.Placement = plm + self.assertEqual(len(self.mesh.foraminate(pnt, vec)), 0) + + # Apply the placement on the ray as well + pnt = plm.multVec(pnt) + vec = plm.Rotation.multVec(vec) + results2 = self.mesh.foraminate(pnt, vec) + self.assertEqual(len(results2), 4) + self.assertEqual(list(results.keys()), list(results2.keys())) + class MeshGeoTestCases(unittest.TestCase): def setUp(self): # set up a planar face with 2 triangles @@ -457,7 +487,7 @@ class PivyTestCases(unittest.TestCase): rp.setRay(coin.SbVec3f(-16.05,16.0,16.0),coin.SbVec3f(0,-1,0)) rp.apply(view.getSoRenderManager().getSceneGraph()) pp=rp.getPickedPoint() - self.assertTrue(pp != None) + self.assertTrue(pp is not None) det=pp.getDetail() self.assertTrue(det.getTypeId() == coin.SoFaceDetail.getClassTypeId()) det=coin.cast(det, det.getTypeId().getName().getString()) diff --git a/src/Mod/Mesh/App/WildMagic4/Wm4DelTriangle.cpp b/src/Mod/Mesh/App/WildMagic4/Wm4DelTriangle.cpp index 23ad6b15c0..5ab4431ed1 100644 --- a/src/Mod/Mesh/App/WildMagic4/Wm4DelTriangle.cpp +++ b/src/Mod/Mesh/App/WildMagic4/Wm4DelTriangle.cpp @@ -84,7 +84,7 @@ bool DelTriangle::IsInsertionComponent (int i, DelTriangle* pkAdj, { for (j = 0; j < 3; j++) { - if (A[j] != nullptr && A[j] != pkAdj) + if (A[j] && A[j] != pkAdj) { break; } diff --git a/src/Mod/Mesh/App/WildMagic4/Wm4System.cpp b/src/Mod/Mesh/App/WildMagic4/Wm4System.cpp index 00e821e8fb..dc625384b6 100644 --- a/src/Mod/Mesh/App/WildMagic4/Wm4System.cpp +++ b/src/Mod/Mesh/App/WildMagic4/Wm4System.cpp @@ -632,7 +632,7 @@ const char* System::GetPath (const char* acDirectory, const char* acFilename) //---------------------------------------------------------------------------- void System::Initialize () { - assert(ms_pkDirectories == nullptr); + assert(!ms_pkDirectories); ms_pkDirectories = WM4_NEW std::vector; const char* acWm4Path = GetEnv("WM4_PATH"); @@ -839,7 +839,7 @@ const char* System::GetEnv (const char* acEnvVarName) getenv_s(&uiRequiredSize,ms_acEnvVar,SYSTEM_MAX_ENVVAR,acEnvVarName); #else char* acEnvVar = getenv(acEnvVarName); - if (acEnvVar == nullptr) + if (!acEnvVar) { return nullptr; } diff --git a/src/Mod/Mesh/Gui/AppMeshGui.cpp b/src/Mod/Mesh/Gui/AppMeshGui.cpp index 9f8ab0a3be..ccacd9eb86 100644 --- a/src/Mod/Mesh/Gui/AppMeshGui.cpp +++ b/src/Mod/Mesh/Gui/AppMeshGui.cpp @@ -84,7 +84,7 @@ public: initialize("This module is the MeshGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object convertToSTL(const Py::Tuple& args) diff --git a/src/Mod/Mesh/Gui/CMakeLists.txt b/src/Mod/Mesh/Gui/CMakeLists.txt index 92f4cc60af..33ba8cd1c8 100644 --- a/src/Mod/Mesh/Gui/CMakeLists.txt +++ b/src/Mod/Mesh/Gui/CMakeLists.txt @@ -5,6 +5,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS}/Inventor/annex ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) if(MSVC) diff --git a/src/Mod/Mesh/Gui/DlgDecimating.h b/src/Mod/Mesh/Gui/DlgDecimating.h index d988296969..0e1133cec0 100644 --- a/src/Mod/Mesh/Gui/DlgDecimating.h +++ b/src/Mod/Mesh/Gui/DlgDecimating.h @@ -36,8 +36,8 @@ class DlgDecimating : public QWidget Q_OBJECT public: - DlgDecimating(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgDecimating(); + explicit DlgDecimating(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgDecimating() override; void setNumberOfTriangles(int); double tolerance() const; double reduction() const; @@ -61,14 +61,14 @@ class TaskDecimating : public Gui::TaskView::TaskDialog public: TaskDecimating(); - ~TaskDecimating(); + ~TaskDecimating() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return true; } private: diff --git a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp index 184f6a7f2c..4c155732ab 100644 --- a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp +++ b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.cpp @@ -1255,7 +1255,7 @@ DockEvaluateMeshImp* DockEvaluateMeshImp::instance() void DockEvaluateMeshImp::destruct () { - if (_instance != nullptr) { + if (_instance) { DockEvaluateMeshImp *pTmp = _instance; _instance = nullptr; delete pTmp; diff --git a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.h b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.h index b25547a1d9..eac2b12a1d 100644 --- a/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.h +++ b/src/Mod/Mesh/Gui/DlgEvaluateMeshImp.h @@ -70,20 +70,20 @@ class DlgEvaluateMeshImp : public QDialog, public App::DocumentObserver Q_OBJECT public: - DlgEvaluateMeshImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgEvaluateMeshImp(); + explicit DlgEvaluateMeshImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgEvaluateMeshImp() override; void setMesh(Mesh::Feature*); private: /** Checks if the given document is about to be closed */ - void slotDeletedDocument(const App::Document& Doc); + void slotDeletedDocument(const App::Document& Doc) override; /** Checks if a new object was added. */ - void slotCreatedObject(const App::DocumentObject& Obj); + void slotCreatedObject(const App::DocumentObject& Obj) override; /** Checks if the given object is about to be removed. */ - void slotDeletedObject(const App::DocumentObject& Obj); + void slotDeletedObject(const App::DocumentObject& Obj) override; /** The property of an observed object has changed */ - void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); + void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) override; protected Q_SLOTS: void on_checkOrientationButton_clicked(); @@ -132,7 +132,7 @@ protected: void addViewProvider(const char* vp, const std::vector& indices); void removeViewProvider(const char* vp); void removeViewProviders(); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: class Private; @@ -148,16 +148,16 @@ class DockEvaluateMeshImp : public DlgEvaluateMeshImp Q_OBJECT protected: - DockEvaluateMeshImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DockEvaluateMeshImp(); - void closeEvent(QCloseEvent* e); + explicit DockEvaluateMeshImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + ~DockEvaluateMeshImp() override; + void closeEvent(QCloseEvent* e) override; public: static DockEvaluateMeshImp* instance(); static void destruct(); static bool hasInstance(); - QSize sizeHint () const; + QSize sizeHint () const override; private: QScrollArea* scrollArea; diff --git a/src/Mod/Mesh/Gui/DlgEvaluateSettings.h b/src/Mod/Mesh/Gui/DlgEvaluateSettings.h index 639c1c5447..18685c4a54 100644 --- a/src/Mod/Mesh/Gui/DlgEvaluateSettings.h +++ b/src/Mod/Mesh/Gui/DlgEvaluateSettings.h @@ -38,8 +38,8 @@ class DlgEvaluateSettings : public QDialog Q_OBJECT public: - DlgEvaluateSettings(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgEvaluateSettings(); + explicit DlgEvaluateSettings(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgEvaluateSettings() override; void setNonmanifoldPointsChecked(bool); bool isNonmanifoldPointsChecked() const; diff --git a/src/Mod/Mesh/Gui/DlgRegularSolidImp.cpp b/src/Mod/Mesh/Gui/DlgRegularSolidImp.cpp index 78dc4593b5..a5c909e6f9 100644 --- a/src/Mod/Mesh/Gui/DlgRegularSolidImp.cpp +++ b/src/Mod/Mesh/Gui/DlgRegularSolidImp.cpp @@ -135,10 +135,10 @@ void DlgRegularSolidImp::on_createSolidButton_clicked() "App.ActiveDocument.%1.Length=%2\n" "App.ActiveDocument.%1.Width=%3\n" "App.ActiveDocument.%1.Height=%4\n")) - .arg(QLatin1String(name.c_str())) - .arg(Base::UnitsApi::toNumber(ui->boxLength->value())) - .arg(Base::UnitsApi::toNumber(ui->boxWidth->value())) - .arg(Base::UnitsApi::toNumber(ui->boxHeight->value())); + .arg(QLatin1String(name.c_str()), + Base::UnitsApi::toNumber(ui->boxLength->value()), + Base::UnitsApi::toNumber(ui->boxWidth->value()), + Base::UnitsApi::toNumber(ui->boxHeight->value())); } else if (ui->comboBox1->currentIndex() == 1) { // cylinder name = doc->getUniqueObjectName("Cylinder"); @@ -149,11 +149,11 @@ void DlgRegularSolidImp::on_createSolidButton_clicked() "App.ActiveDocument.%1.EdgeLength=%4\n" "App.ActiveDocument.%1.Closed=%5\n" "App.ActiveDocument.%1.Sampling=%6\n")) - .arg(QLatin1String(name.c_str())) - .arg(Base::UnitsApi::toNumber(ui->cylinderRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderLength->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderEdgeLength->value())) - .arg(QLatin1String((ui->cylinderClosed->isChecked()?"True":"False"))) + .arg(QLatin1String(name.c_str()), + Base::UnitsApi::toNumber(ui->cylinderRadius->value()), + Base::UnitsApi::toNumber(ui->cylinderLength->value()), + Base::UnitsApi::toNumber(ui->cylinderEdgeLength->value()), + QLatin1String((ui->cylinderClosed->isChecked()?"True":"False"))) .arg(ui->cylinderCount->value()); } else if (ui->comboBox1->currentIndex() == 2) { // cone @@ -166,12 +166,12 @@ void DlgRegularSolidImp::on_createSolidButton_clicked() "App.ActiveDocument.%1.EdgeLength=%5\n" "App.ActiveDocument.%1.Closed=%6\n" "App.ActiveDocument.%1.Sampling=%7\n")) - .arg(QLatin1String(name.c_str())) - .arg(Base::UnitsApi::toNumber(ui->coneRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->coneRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->coneLength->value())) - .arg(Base::UnitsApi::toNumber(ui->coneEdgeLength->value())) - .arg(QLatin1String((ui->coneClosed->isChecked()?"True":"False"))) + .arg(QLatin1String(name.c_str()), + Base::UnitsApi::toNumber(ui->coneRadius1->value()), + Base::UnitsApi::toNumber(ui->coneRadius2->value()), + Base::UnitsApi::toNumber(ui->coneLength->value()), + Base::UnitsApi::toNumber(ui->coneEdgeLength->value()), + QLatin1String((ui->coneClosed->isChecked()?"True":"False"))) .arg(ui->coneCount->value()); } else if (ui->comboBox1->currentIndex() == 3) { // sphere @@ -180,8 +180,8 @@ void DlgRegularSolidImp::on_createSolidButton_clicked() "App.ActiveDocument.addObject(\"Mesh::Sphere\",\"%1\")\n" "App.ActiveDocument.%1.Radius=%2\n" "App.ActiveDocument.%1.Sampling=%3\n")) - .arg(QLatin1String(name.c_str())) - .arg(Base::UnitsApi::toNumber(ui->sphereRadius->value())) + .arg(QLatin1String(name.c_str()), + Base::UnitsApi::toNumber(ui->sphereRadius->value())) .arg(ui->sphereCount->value()); } else if (ui->comboBox1->currentIndex() == 4) { // ellipsoid @@ -191,9 +191,9 @@ void DlgRegularSolidImp::on_createSolidButton_clicked() "App.ActiveDocument.%1.Radius1=%2\n" "App.ActiveDocument.%1.Radius2=%3\n" "App.ActiveDocument.%1.Sampling=%4\n")) - .arg(QLatin1String(name.c_str())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value())) + .arg(QLatin1String(name.c_str()), + Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value()), + Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value())) .arg(ui->ellipsoidCount->value()); } else if (ui->comboBox1->currentIndex() == 5) { // toroid @@ -203,9 +203,9 @@ void DlgRegularSolidImp::on_createSolidButton_clicked() "App.ActiveDocument.%1.Radius1=%2\n" "App.ActiveDocument.%1.Radius2=%3\n" "App.ActiveDocument.%1.Sampling=%4\n")) - .arg(QLatin1String(name.c_str())) - .arg(Base::UnitsApi::toNumber(ui->toroidRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->toroidRadius2->value())) + .arg(QLatin1String(name.c_str()), + Base::UnitsApi::toNumber(ui->toroidRadius1->value()), + Base::UnitsApi::toNumber(ui->toroidRadius2->value())) .arg(ui->toroidCount->value()); } diff --git a/src/Mod/Mesh/Gui/DlgRegularSolidImp.h b/src/Mod/Mesh/Gui/DlgRegularSolidImp.h index b5afea5685..2212f1c4d0 100644 --- a/src/Mod/Mesh/Gui/DlgRegularSolidImp.h +++ b/src/Mod/Mesh/Gui/DlgRegularSolidImp.h @@ -34,14 +34,14 @@ class DlgRegularSolidImp : public QDialog Q_OBJECT public: - DlgRegularSolidImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgRegularSolidImp(); + explicit DlgRegularSolidImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgRegularSolidImp() override; public Q_SLOTS: void on_createSolidButton_clicked(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h b/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h index b27e0077bc..b835f32bd4 100644 --- a/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h +++ b/src/Mod/Mesh/Gui/DlgSettingsImportExportImp.h @@ -41,13 +41,13 @@ class DlgSettingsImportExport : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsImportExport(QWidget* parent = nullptr); - ~DlgSettingsImportExport(); + explicit DlgSettingsImportExport(QWidget* parent = nullptr); + ~DlgSettingsImportExport() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: Ui_DlgSettingsImportExport* ui; diff --git a/src/Mod/Mesh/Gui/DlgSettingsMeshView.h b/src/Mod/Mesh/Gui/DlgSettingsMeshView.h index 2e567094a2..68f209f178 100644 --- a/src/Mod/Mesh/Gui/DlgSettingsMeshView.h +++ b/src/Mod/Mesh/Gui/DlgSettingsMeshView.h @@ -42,13 +42,13 @@ class DlgSettingsMeshView : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsMeshView(QWidget* parent = nullptr); - ~DlgSettingsMeshView(); + explicit DlgSettingsMeshView(QWidget* parent = nullptr); + ~DlgSettingsMeshView() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Mesh/Gui/DlgSmoothing.cpp b/src/Mod/Mesh/Gui/DlgSmoothing.cpp index ee89b4db3c..afcd142420 100644 --- a/src/Mod/Mesh/Gui/DlgSmoothing.cpp +++ b/src/Mod/Mesh/Gui/DlgSmoothing.cpp @@ -212,6 +212,16 @@ bool TaskSmoothing::accept() s.Smooth(widget->iterations()); } } break; + case MeshGui::DlgSmoothing::MedianFilter: + { + MeshCore::MedianFilterSmoothing s(mm->getKernel()); + if (widget->smoothSelection()) { + s.SmoothPoints(widget->iterations(), selection); + } + else { + s.Smooth(widget->iterations()); + } + } break; default: break; } diff --git a/src/Mod/Mesh/Gui/DlgSmoothing.h b/src/Mod/Mesh/Gui/DlgSmoothing.h index 2b64d6e88e..4172794427 100644 --- a/src/Mod/Mesh/Gui/DlgSmoothing.h +++ b/src/Mod/Mesh/Gui/DlgSmoothing.h @@ -45,11 +45,12 @@ public: enum Smooth { None, Taubin, - Laplace + Laplace, + MedianFilter }; - DlgSmoothing(QWidget* parent = nullptr); - ~DlgSmoothing(); + explicit DlgSmoothing(QWidget* parent = nullptr); + ~DlgSmoothing() override; int iterations() const; double lambdaStep() const; double microStep() const; @@ -76,8 +77,8 @@ class MeshGuiExport SmoothingDialog : public QDialog Q_OBJECT public: - SmoothingDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~SmoothingDialog(); + explicit SmoothingDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~SmoothingDialog() override; int iterations() const { return widget->iterations(); } @@ -103,14 +104,14 @@ class TaskSmoothing : public Gui::TaskView::TaskDialog public: TaskSmoothing(); - ~TaskSmoothing(); + ~TaskSmoothing() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } - virtual bool isAllowedAlterDocument() const + bool isAllowedAlterDocument() const override { return true; } private: diff --git a/src/Mod/Mesh/Gui/MeshEditor.cpp b/src/Mod/Mesh/Gui/MeshEditor.cpp index 69ebebb297..47507f1232 100644 --- a/src/Mod/Mesh/Gui/MeshEditor.cpp +++ b/src/Mod/Mesh/Gui/MeshEditor.cpp @@ -153,8 +153,8 @@ const char* ViewProviderFace::getDefaultDisplayMode() const std::vector ViewProviderFace::getDisplayModes() const { std::vector modes; - modes.push_back("Marker"); - modes.push_back("Face"); + modes.emplace_back("Marker"); + modes.emplace_back("Face"); return modes; } diff --git a/src/Mod/Mesh/Gui/MeshEditor.h b/src/Mod/Mesh/Gui/MeshEditor.h index 225c40ab9a..f102014b8b 100644 --- a/src/Mod/Mesh/Gui/MeshEditor.h +++ b/src/Mod/Mesh/Gui/MeshEditor.h @@ -48,17 +48,17 @@ class SoFCMeshPickNode; */ class MeshGuiExport ViewProviderFace : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(MeshGui::ViewProviderFace); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderFace); public: ViewProviderFace(); - virtual ~ViewProviderFace(); + ~ViewProviderFace() override; // Build up the initial Inventor node - void attach(App::DocumentObject* obj); - void setDisplayMode(const char* ModeName); - const char* getDefaultDisplayMode() const; - std::vector getDisplayModes() const; + void attach(App::DocumentObject* obj) override; + void setDisplayMode(const char* ModeName) override; + const char* getDefaultDisplayMode() const override; + std::vector getDisplayModes() const override; SoPickedPoint* getPickedPoint(const SbVec2s& pos, const Gui::View3DInventorViewer* viewer) const; ViewProviderMesh* mesh; @@ -79,8 +79,8 @@ class MeshGuiExport MeshFaceAddition : public QObject Q_OBJECT public: - MeshFaceAddition(Gui::View3DInventor* parent); - ~MeshFaceAddition(); + explicit MeshFaceAddition(Gui::View3DInventor* parent); + ~MeshFaceAddition() override; void startEditing(ViewProviderMesh*); @@ -127,7 +127,7 @@ class MeshGuiExport MeshFillHole : public QObject public: MeshFillHole(MeshHoleFiller& hf, Gui::View3DInventor* parent); - virtual ~MeshFillHole(); + ~MeshFillHole() override; void startEditing(ViewProviderMesh*); diff --git a/src/Mod/Mesh/Gui/MeshSelection.cpp b/src/Mod/Mesh/Gui/MeshSelection.cpp index a6225086ee..3110521901 100644 --- a/src/Mod/Mesh/Gui/MeshSelection.cpp +++ b/src/Mod/Mesh/Gui/MeshSelection.cpp @@ -540,7 +540,7 @@ void MeshSelection::pickFaceCallback(void * ud, SoEventCallback * n) n->getAction()->setHandled(); if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No facet picked.\n"); return; } diff --git a/src/Mod/Mesh/Gui/PropertyEditorMesh.h b/src/Mod/Mesh/Gui/PropertyEditorMesh.h index c08228a580..2887de68ea 100644 --- a/src/Mod/Mesh/Gui/PropertyEditorMesh.h +++ b/src/Mod/Mesh/Gui/PropertyEditorMesh.h @@ -37,27 +37,27 @@ namespace MeshGui { class MeshGuiExport PropertyMeshKernelItem : public Gui::PropertyEditor::PropertyItem { Q_OBJECT - Q_PROPERTY(int Points READ countPoints) - Q_PROPERTY(int Edges READ countEdges) - Q_PROPERTY(int Faces READ countFaces) + Q_PROPERTY(int Points READ countPoints CONSTANT) + Q_PROPERTY(int Edges READ countEdges CONSTANT) + Q_PROPERTY(int Faces READ countFaces CONSTANT) PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget *editor, const QVariant& data) const; - virtual QVariant editorData(QWidget *editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget *editor, const QVariant& data) const override; + QVariant editorData(QWidget *editor) const override; int countPoints() const; int countEdges() const; int countFaces() const; protected: - virtual QVariant toolTip(const App::Property*) const; - virtual QVariant value(const App::Property*) const; - virtual void setValue(const QVariant&); + QVariant toolTip(const App::Property*) const override; + QVariant value(const App::Property*) const override; + void setValue(const QVariant&) override; protected: PropertyMeshKernelItem(); - void initialize(); + void initialize() override; private: Gui::PropertyEditor::PropertyIntegerItem* m_p; diff --git a/src/Mod/Mesh/Gui/RemeshGmsh.cpp b/src/Mod/Mesh/Gui/RemeshGmsh.cpp index 2ef375aba1..2d571dcf09 100644 --- a/src/Mod/Mesh/Gui/RemeshGmsh.cpp +++ b/src/Mod/Mesh/Gui/RemeshGmsh.cpp @@ -50,7 +50,7 @@ using namespace MeshGui; class GmshWidget::Private { public: - Private(QWidget* parent) + explicit Private(QWidget* parent) : gmsh(parent) { /* coverity[uninit_ctor] Members of ui are set in setupUI() */ @@ -270,7 +270,7 @@ void GmshWidget::reject() class RemeshGmsh::Private { public: - Private(Mesh::Feature* mesh) + explicit Private(Mesh::Feature* mesh) : mesh(mesh) { } diff --git a/src/Mod/Mesh/Gui/RemeshGmsh.h b/src/Mod/Mesh/Gui/RemeshGmsh.h index c485c14df2..ef9f125fc1 100644 --- a/src/Mod/Mesh/Gui/RemeshGmsh.h +++ b/src/Mod/Mesh/Gui/RemeshGmsh.h @@ -52,13 +52,13 @@ class MeshGuiExport GmshWidget : public QWidget Q_OBJECT public: - GmshWidget(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~GmshWidget(); + explicit GmshWidget(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~GmshWidget() override; void accept(); void reject(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; int meshingAlgorithm() const; double getAngle() const; double getMaxSize() const; @@ -90,12 +90,12 @@ class MeshGuiExport RemeshGmsh : public GmshWidget Q_OBJECT public: - RemeshGmsh(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~RemeshGmsh(); + explicit RemeshGmsh(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~RemeshGmsh() override; protected: - virtual bool writeProject(QString& inpFile, QString& outFile); - virtual bool loadOutput(); + bool writeProject(QString& inpFile, QString& outFile) override; + bool loadOutput() override; private: class Private; @@ -110,15 +110,15 @@ class TaskRemeshGmsh : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskRemeshGmsh(Mesh::Feature* mesh); - ~TaskRemeshGmsh(); + explicit TaskRemeshGmsh(Mesh::Feature* mesh); + ~TaskRemeshGmsh() override; public: - void clicked(int); + void clicked(int) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Apply | QDialogButtonBox::Close; } - virtual bool isAllowedAlterDocument() const + bool isAllowedAlterDocument() const override { return true; } private: diff --git a/src/Mod/Mesh/Gui/RemoveComponents.h b/src/Mod/Mesh/Gui/RemoveComponents.h index 113caac297..bc470af224 100644 --- a/src/Mod/Mesh/Gui/RemoveComponents.h +++ b/src/Mod/Mesh/Gui/RemoveComponents.h @@ -42,8 +42,8 @@ class MeshGuiExport RemoveComponents : public QWidget Q_OBJECT public: - RemoveComponents(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~RemoveComponents(); + explicit RemoveComponents(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~RemoveComponents() override; void reject(); void deleteSelection(); void invertSelection(); @@ -63,7 +63,7 @@ public Q_SLOTS: void on_cbDeselectComp_toggled(bool); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: Ui_RemoveComponents* ui; @@ -78,9 +78,9 @@ class MeshGuiExport RemoveComponentsDialog : public QDialog Q_OBJECT public: - RemoveComponentsDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~RemoveComponentsDialog(); - void reject(); + explicit RemoveComponentsDialog(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~RemoveComponentsDialog() override; + void reject() override; private Q_SLOTS: void clicked(QAbstractButton* btn); @@ -98,17 +98,17 @@ class TaskRemoveComponents : public Gui::TaskView::TaskDialog public: TaskRemoveComponents(); - ~TaskRemoveComponents(); + ~TaskRemoveComponents() override; public: - bool accept(); - void clicked(int); + bool accept() override; + void clicked(int) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Close; } - virtual bool isAllowedAlterDocument() const + bool isAllowedAlterDocument() const override { return true; } - virtual void modifyStandardButtons(QDialogButtonBox*); + void modifyStandardButtons(QDialogButtonBox*) override; private: RemoveComponents* widget; diff --git a/src/Mod/Mesh/Gui/Segmentation.h b/src/Mod/Mesh/Gui/Segmentation.h index 8e4a8f0c45..2686f8f270 100644 --- a/src/Mod/Mesh/Gui/Segmentation.h +++ b/src/Mod/Mesh/Gui/Segmentation.h @@ -40,12 +40,12 @@ class Ui_Segmentation; class MeshGuiExport Segmentation : public QWidget { public: - Segmentation(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~Segmentation(); + explicit Segmentation(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~Segmentation() override; void accept(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: Ui_Segmentation* ui; @@ -58,13 +58,13 @@ private: class TaskSegmentation : public Gui::TaskView::TaskDialog { public: - TaskSegmentation(Mesh::Feature* mesh); - ~TaskSegmentation(); + explicit TaskSegmentation(Mesh::Feature* mesh); + ~TaskSegmentation() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Mesh/Gui/SegmentationBestFit.cpp b/src/Mod/Mesh/Gui/SegmentationBestFit.cpp index 324cbd7743..11299a564b 100644 --- a/src/Mod/Mesh/Gui/SegmentationBestFit.cpp +++ b/src/Mod/Mesh/Gui/SegmentationBestFit.cpp @@ -51,8 +51,8 @@ class PlaneFitParameter : public FitParameter { public: PlaneFitParameter() {} - virtual ~PlaneFitParameter() {} - virtual std::vector getParameter(FitParameter::Points pts) const { + ~PlaneFitParameter() override {} + std::vector getParameter(FitParameter::Points pts) const override { std::vector values; MeshCore::PlaneFit fit; fit.AddPoints(pts.points); @@ -74,8 +74,8 @@ class CylinderFitParameter : public FitParameter { public: CylinderFitParameter() {} - virtual ~CylinderFitParameter() {} - virtual std::vector getParameter(FitParameter::Points pts) const { + ~CylinderFitParameter() override {} + std::vector getParameter(FitParameter::Points pts) const override { std::vector values; MeshCore::CylinderFit fit; fit.AddPoints(pts.points); @@ -129,8 +129,8 @@ class SphereFitParameter : public FitParameter { public: SphereFitParameter() {} - virtual ~SphereFitParameter() {} - virtual std::vector getParameter(FitParameter::Points pts) const { + ~SphereFitParameter() override {} + std::vector getParameter(FitParameter::Points pts) const override { std::vector values; MeshCore::SphereFit fit; fit.AddPoints(pts.points); diff --git a/src/Mod/Mesh/Gui/SegmentationBestFit.h b/src/Mod/Mesh/Gui/SegmentationBestFit.h index 471dc12b74..9a09fcbe04 100644 --- a/src/Mod/Mesh/Gui/SegmentationBestFit.h +++ b/src/Mod/Mesh/Gui/SegmentationBestFit.h @@ -58,9 +58,9 @@ public: ParametersDialog(std::vector&, FitParameter*, ParameterList, Mesh::Feature* mesh, QWidget* parent=nullptr); - ~ParametersDialog(); - void accept(); - void reject(); + ~ParametersDialog() override; + void accept() override; + void reject() override; private Q_SLOTS: void on_region_clicked(); @@ -82,12 +82,12 @@ class MeshGuiExport SegmentationBestFit : public QWidget Q_OBJECT public: - SegmentationBestFit(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~SegmentationBestFit(); + explicit SegmentationBestFit(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~SegmentationBestFit() override; void accept(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private Q_SLOTS: void on_planeParameters_clicked(); @@ -109,13 +109,13 @@ private: class TaskSegmentationBestFit : public Gui::TaskView::TaskDialog { public: - TaskSegmentationBestFit(Mesh::Feature* mesh); - ~TaskSegmentationBestFit(); + explicit TaskSegmentationBestFit(Mesh::Feature* mesh); + ~TaskSegmentationBestFit() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Mesh/Gui/Selection.h b/src/Mod/Mesh/Gui/Selection.h index 060bddc3e0..3ef79fb70a 100644 --- a/src/Mod/Mesh/Gui/Selection.h +++ b/src/Mod/Mesh/Gui/Selection.h @@ -40,11 +40,11 @@ class Selection : public QWidget Q_OBJECT public: - Selection(QWidget* parent = nullptr); - ~Selection(); + explicit Selection(QWidget* parent = nullptr); + ~Selection() override; void setObjects(const std::vector&); std::vector getObjects() const; - bool eventFilter(QObject*, QEvent*); + bool eventFilter(QObject*, QEvent*) override; private Q_SLOTS: void on_addSelection_clicked(); diff --git a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp index dc0d90027f..43c00033f4 100644 --- a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp +++ b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.cpp @@ -971,8 +971,8 @@ void SoFCIndexedFaceSet::startSelection(SoAction * action) int bufSize = 5*(this->coordIndex.getNum()/4); // make the buffer big enough this->selectBuf = new GLuint[bufSize]; - SbMatrix view = SoViewingMatrixElement::get(action->getState()); - SbMatrix proj = SoProjectionMatrixElement::get(action->getState()); + SbMatrix view = SoViewingMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft + SbMatrix proj = SoProjectionMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft glSelectBuffer(bufSize, selectBuf); glRenderMode(GL_SELECT); @@ -1054,8 +1054,8 @@ void SoFCIndexedFaceSet::renderSelectionGeometry(const SbVec3f * coords3d) void SoFCIndexedFaceSet::startVisibility(SoAction * action) { - SbMatrix view = SoViewingMatrixElement::get(action->getState()); - SbMatrix proj = SoProjectionMatrixElement::get(action->getState()); + SbMatrix view = SoViewingMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft + SbMatrix proj = SoProjectionMatrixElement::get(action->getState()); // clazy:exclude=rule-of-two-soft glMatrixMode(GL_PROJECTION); glPushMatrix(); diff --git a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h index cbd54ef8b4..2164a865c7 100644 --- a/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h +++ b/src/Mod/Mesh/Gui/SoFCIndexedFaceSet.h @@ -80,9 +80,9 @@ public: SoEngineOutput trigger; private: - virtual ~SoFCMaterialEngine(); - virtual void evaluate(); - virtual void inputChanged(SoField *); + ~SoFCMaterialEngine() override; + void evaluate() override; + void inputChanged(SoField *) override; }; /** @@ -108,8 +108,8 @@ public: protected: // Force using the reference count mechanism. - virtual ~SoFCIndexedFaceSet() {} - virtual void GLRender(SoGLRenderAction *action); + ~SoFCIndexedFaceSet() override {} + void GLRender(SoGLRenderAction *action) override; void drawFaces(SoGLRenderAction *action); void drawCoords(const SoGLCoordinateElement * const vertexlist, const int32_t *vertexindices, @@ -122,7 +122,7 @@ protected: const SoTextureCoordinateBundle * const texcoords, const int32_t *texindices); - void doAction(SoAction * action); + void doAction(SoAction * action) override; private: void startSelection(SoAction * action); diff --git a/src/Mod/Mesh/Gui/SoFCMeshObject.cpp b/src/Mod/Mesh/Gui/SoFCMeshObject.cpp index c656bbc302..b5ca99e379 100644 --- a/src/Mod/Mesh/Gui/SoFCMeshObject.cpp +++ b/src/Mod/Mesh/Gui/SoFCMeshObject.cpp @@ -71,11 +71,11 @@ using namespace MeshGui; class SoOutputStreambuf : public std::streambuf { public: - SoOutputStreambuf(SoOutput* o) : out(o) + explicit SoOutputStreambuf(SoOutput* o) : out(o) { } protected: - int overflow(int c = EOF) + int overflow(int c = EOF) override { if (c != EOF) { char z = static_cast(c); @@ -83,7 +83,7 @@ protected: } return c; } - std::streamsize xsputn (const char* s, std::streamsize num) + std::streamsize xsputn (const char* s, std::streamsize num) override { out->write(s); return num; @@ -96,7 +96,7 @@ private: class SoOutputStream : public std::ostream { public: - SoOutputStream(SoOutput* o) : std::ostream(nullptr), buf(o) + explicit SoOutputStream(SoOutput* o) : std::ostream(nullptr), buf(o) { this->rdbuf(&buf); } @@ -107,14 +107,14 @@ private: class SoInputStreambuf : public std::streambuf { public: - SoInputStreambuf(SoInput* o) : inp(o) + explicit SoInputStreambuf(SoInput* o) : inp(o) { setg (buffer+pbSize, buffer+pbSize, buffer+pbSize); } protected: - int underflow() + int underflow() override { if (gptr() < egptr()) { return *gptr(); @@ -160,11 +160,11 @@ private: class SoInputStream : public std::istream { public: - SoInputStream(SoInput* o) : std::istream(nullptr), buf(o) + explicit SoInputStream(SoInput* o) : std::istream(nullptr), buf(o) { this->rdbuf(&buf); } - ~SoInputStream() + ~SoInputStream() override { } @@ -1132,7 +1132,7 @@ void SoFCMeshObjectShape::generatePrimitives(SoAction* action) const MeshCore::MeshFacetArray & rFacets = mesh->getKernel().GetFacets(); if (rPoints.size() < 3) return; - if (rFacets.size() < 1) + if (rFacets.empty()) return; // get material binding @@ -1544,7 +1544,7 @@ void SoFCMeshSegmentShape::generatePrimitives(SoAction* action) const MeshCore::MeshFacetArray & rFacets = mesh->getKernel().GetFacets(); if (rPoints.size() < 3) return; - if (rFacets.size() < 1) + if (rFacets.empty()) return; if (mesh->countSegments() <= this->index.getValue()) return; @@ -1788,7 +1788,7 @@ void SoFCMeshObjectBoundary::computeBBox(SoAction *action, SbBox3f &box, SbVec3f if (!mesh) return; const MeshCore::MeshPointArray & rPoints = mesh->getKernel().GetPoints(); - if (rPoints.size() > 0) { + if (!rPoints.empty()) { Base::BoundBox3f cBox; for (MeshCore::MeshPointArray::_TConstIterator it = rPoints.begin(); it != rPoints.end(); ++it) cBox.Add(*it); diff --git a/src/Mod/Mesh/Gui/SoFCMeshObject.h b/src/Mod/Mesh/Gui/SoFCMeshObject.h index 791cc1ed98..a6e64594ab 100644 --- a/src/Mod/Mesh/Gui/SoFCMeshObject.h +++ b/src/Mod/Mesh/Gui/SoFCMeshObject.h @@ -64,14 +64,14 @@ class MeshGuiExport SoFCMeshObjectElement : public SoReplacedElement { public: static void initClass(); - virtual void init(SoState * state); + void init(SoState * state) override; static void set(SoState * const state, SoNode * const node, const Mesh::MeshObject * const mesh); static const Mesh::MeshObject * get(SoState * const state); static const SoFCMeshObjectElement * getInstance(SoState * state); - virtual void print(FILE * file) const; + void print(FILE * file) const override; protected: - virtual ~SoFCMeshObjectElement(); + ~SoFCMeshObjectElement() override; const Mesh::MeshObject *mesh; }; @@ -85,15 +85,15 @@ class MeshGuiExport SoFCMeshPickNode : public SoNode { public: static void initClass(); SoFCMeshPickNode(); - void notify(SoNotList *); + void notify(SoNotList *) override; SoSFMeshObject mesh; - virtual void rayPick(SoRayPickAction * action); - virtual void pick(SoPickAction * action); + void rayPick(SoRayPickAction * action) override; + void pick(SoPickAction * action) override; protected: - virtual ~SoFCMeshPickNode(); + ~SoFCMeshPickNode() override; private: MeshCore::MeshFacetGrid* meshGrid; @@ -109,14 +109,14 @@ class MeshGuiExport SoFCMeshGridNode : public SoNode { public: static void initClass(); SoFCMeshGridNode(); - void GLRender(SoGLRenderAction * action); + void GLRender(SoGLRenderAction * action) override; SoSFVec3f minGrid; SoSFVec3f maxGrid; SoSFVec3s lenGrid; protected: - virtual ~SoFCMeshGridNode(); + ~SoFCMeshGridNode() override; }; // ------------------------------------------------------- @@ -132,15 +132,15 @@ public: SoSFMeshObject mesh; - virtual void doAction(SoAction * action); - virtual void GLRender(SoGLRenderAction * action); - virtual void callback(SoCallbackAction * action); - virtual void getBoundingBox(SoGetBoundingBoxAction * action); - virtual void pick(SoPickAction * action); - virtual void getPrimitiveCount(SoGetPrimitiveCountAction * action); + void doAction(SoAction * action) override; + void GLRender(SoGLRenderAction * action) override; + void callback(SoCallbackAction * action) override; + void getBoundingBox(SoGetBoundingBoxAction * action) override; + void pick(SoPickAction * action) override; + void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; protected: - virtual ~SoFCMeshObjectNode(); + ~SoFCMeshObjectNode() override; }; /** @@ -175,17 +175,17 @@ public: unsigned int renderTriangleLimit; protected: - virtual void doAction(SoAction * action); - virtual void GLRender(SoGLRenderAction *action); - virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er); - virtual void getPrimitiveCount(SoGetPrimitiveCountAction * action); - virtual void rayPick (SoRayPickAction *action); - virtual void generatePrimitives(SoAction *action); - virtual SoDetail * createTriangleDetail(SoRayPickAction * action, + void doAction(SoAction * action) override; + void GLRender(SoGLRenderAction *action) override; + void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er) override; + void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; + void rayPick (SoRayPickAction *action) override; + void generatePrimitives(SoAction *action) override; + SoDetail * createTriangleDetail(SoRayPickAction * action, const SoPrimitiveVertex * v1, const SoPrimitiveVertex * v2, const SoPrimitiveVertex * v3, - SoPickedPoint * pp); + SoPickedPoint * pp) override; private: enum Binding { @@ -197,8 +197,8 @@ private: private: // Force using the reference count mechanism. - virtual ~SoFCMeshObjectShape(); - virtual void notify(SoNotList * list); + ~SoFCMeshObjectShape() override; + void notify(SoNotList * list) override; Binding findMaterialBinding(SoState * const state) const; // Draw faces void drawFaces(const Mesh::MeshObject *, SoMaterialBundle* mb, Binding bind, @@ -237,10 +237,10 @@ public: unsigned int renderTriangleLimit; protected: - virtual void GLRender(SoGLRenderAction *action); - virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er); - virtual void getPrimitiveCount(SoGetPrimitiveCountAction * action); - virtual void generatePrimitives(SoAction *action); + void GLRender(SoGLRenderAction *action) override; + void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er) override; + void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; + void generatePrimitives(SoAction *action) override; private: enum Binding { @@ -252,7 +252,7 @@ private: private: // Force using the reference count mechanism. - virtual ~SoFCMeshSegmentShape() {}; + ~SoFCMeshSegmentShape() override {}; Binding findMaterialBinding(SoState * const state) const; // Draw faces void drawFaces(const Mesh::MeshObject *, SoMaterialBundle* mb, Binding bind, @@ -270,13 +270,13 @@ public: SoFCMeshObjectBoundary(); protected: - virtual void GLRender(SoGLRenderAction *action); - virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er); - virtual void getPrimitiveCount(SoGetPrimitiveCountAction * action); - virtual void generatePrimitives(SoAction *action); + void GLRender(SoGLRenderAction *action) override; + void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er) override; + void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; + void generatePrimitives(SoAction *action) override; private: // Force using the reference count mechanism. - virtual ~SoFCMeshObjectBoundary() {}; + ~SoFCMeshObjectBoundary() override {}; void drawLines(const Mesh::MeshObject *) const ; }; diff --git a/src/Mod/Mesh/Gui/SoPolygon.h b/src/Mod/Mesh/Gui/SoPolygon.h index 265d17242a..ecde6b3919 100644 --- a/src/Mod/Mesh/Gui/SoPolygon.h +++ b/src/Mod/Mesh/Gui/SoPolygon.h @@ -51,11 +51,11 @@ public: SoSFBool render; protected: - virtual ~SoPolygon() {} - virtual void GLRender(SoGLRenderAction *action); - virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er); - virtual void rayPick (SoRayPickAction *action); - virtual void generatePrimitives(SoAction *action); + ~SoPolygon() override {} + void GLRender(SoGLRenderAction *action) override; + void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er) override; + void rayPick (SoRayPickAction *action) override; + void generatePrimitives(SoAction *action) override; private: void drawPolygon(const SbVec3f *,int32_t) const; diff --git a/src/Mod/Mesh/Gui/ViewProvider.cpp b/src/Mod/Mesh/Gui/ViewProvider.cpp index 503a7aa736..4d719115e5 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.cpp +++ b/src/Mod/Mesh/Gui/ViewProvider.cpp @@ -180,7 +180,7 @@ ViewProviderExport::~ViewProviderExport() std::vector ViewProviderExport::getDisplayModes() const { std::vector mode; - mode.push_back(""); + mode.emplace_back(""); return mode; } @@ -630,10 +630,10 @@ std::vector ViewProviderMesh::getDisplayModes() const std::vector StrList; // add your own modes - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Flat Lines"); - StrList.push_back("Points"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Points"); return StrList; } @@ -1265,7 +1265,7 @@ std::vector ViewProviderMesh::getFacetsOfRegion(const SbViewpo void ViewProviderMesh::panCamera(SoCamera * cam, float aspectratio, const SbPlane & panplane, const SbVec2f & currpos, const SbVec2f & prevpos) { - if (cam == nullptr) // can happen for empty scenegraph + if (!cam) // can happen for empty scenegraph return; if (currpos == prevpos) // useless invocation return; @@ -1589,7 +1589,7 @@ void ViewProviderMesh::faceInfoCallback(void * ud, SoEventCallback * n) } else if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No facet picked.\n"); return; } @@ -1663,7 +1663,7 @@ void ViewProviderMesh::fillHoleCallback(void * ud, SoEventCallback * n) } else if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No facet picked.\n"); return; } @@ -1730,7 +1730,7 @@ void ViewProviderMesh::markPartCallback(void * ud, SoEventCallback * n) } else if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::DOWN) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No facet picked.\n"); return; } diff --git a/src/Mod/Mesh/Gui/ViewProvider.h b/src/Mod/Mesh/Gui/ViewProvider.h index 934122e5a4..3be414fa11 100644 --- a/src/Mod/Mesh/Gui/ViewProvider.h +++ b/src/Mod/Mesh/Gui/ViewProvider.h @@ -79,8 +79,8 @@ class MeshGuiExport ViewProviderMeshBuilder : public Gui::ViewProviderBuilder { public: ViewProviderMeshBuilder(){} - ~ViewProviderMeshBuilder(){} - virtual void buildNodes(const App::Property*, std::vector&) const; + ~ViewProviderMeshBuilder() override{} + void buildNodes(const App::Property*, std::vector&) const override; void createMesh(const App::Property*, SoCoordinate3*, SoIndexedFaceSet*) const; }; @@ -90,16 +90,16 @@ public: */ class MeshGuiExport ViewProviderExport : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(MeshGui::ViewProviderExport); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderExport); public: ViewProviderExport(); - virtual ~ViewProviderExport(); + ~ViewProviderExport() override; - virtual QIcon getIcon() const; - SoSeparator* getRoot() const {return nullptr;} - std::vector getDisplayModes() const; - const char* getDefaultDisplayMode() const; + QIcon getIcon() const override; + SoSeparator* getRoot() const override {return nullptr;} + std::vector getDisplayModes() const override; + const char* getDefaultDisplayMode() const override; }; /** @@ -109,11 +109,11 @@ public: */ class MeshGuiExport ViewProviderMesh : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(MeshGui::ViewProviderMesh); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMesh); public: ViewProviderMesh(); - virtual ~ViewProviderMesh(); + ~ViewProviderMesh() override; // Display properties App::PropertyPercent LineTransparency; @@ -125,24 +125,24 @@ public: App::PropertyEnumeration Lighting; App::PropertyColor LineColor; - virtual void attach(App::DocumentObject *); - virtual void updateData(const App::Property*); - virtual bool useNewSelectionModel() const {return false;} + void attach(App::DocumentObject *) override; + void updateData(const App::Property*) override; + bool useNewSelectionModel() const override {return false;} Gui::SoFCSelection* getHighlightNode() const { return pcHighlight; } - virtual QIcon getIcon() const; + QIcon getIcon() const override; /// Sets the correct display mode - virtual void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes - virtual std::vector getDisplayModes() const; + std::vector getDisplayModes() const override; bool exportToVrml(const char* filename, const MeshCore::Material&, bool binary=false) const; void exportMesh(const char* filename, const char* fmt=nullptr) const; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; /// Get the python wrapper for that ViewProvider - PyObject* getPyObject(); + PyObject* getPyObject() override; /** @name Editing */ //@{ - bool doubleClicked(){ return false; } + bool doubleClicked() override{ return false; } bool isFacetSelected(Mesh::FacetIndex facet); void selectComponent(Mesh::FacetIndex facet); void deselectComponent(Mesh::FacetIndex facet); @@ -173,11 +173,11 @@ public: protected: /// Sets the edit mode - bool setEdit(int ModNum); + bool setEdit(int ModNum) override; /// Unsets the edit mode - void unsetEdit(int ModNum); + void unsetEdit(int ModNum) override; /// get called by the container whenever a property has been changed - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; virtual void showOpenEdges(bool); void setOpenEdgeColorFrom(const App::Color& col); virtual void splitMesh(const MeshCore::MeshKernel& toolMesh, const Base::Vector3f& normal, SbBool inner); @@ -252,20 +252,20 @@ private: */ class MeshGuiExport ViewProviderIndexedFaceSet : public ViewProviderMesh { - PROPERTY_HEADER(MeshGui::ViewProviderIndexedFaceSet); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderIndexedFaceSet); public: ViewProviderIndexedFaceSet(); - virtual ~ViewProviderIndexedFaceSet(); + ~ViewProviderIndexedFaceSet() override; - virtual void attach(App::DocumentObject *); + void attach(App::DocumentObject *) override; /// Update the Mesh representation - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - void showOpenEdges(bool); - SoShape* getShapeNode() const; - SoNode* getCoordNode() const; + void showOpenEdges(bool) override; + SoShape* getShapeNode() const override; + SoNode* getCoordNode() const override; private: SoCoordinate3 * pcMeshCoord; @@ -279,19 +279,19 @@ private: */ class MeshGuiExport ViewProviderMeshObject : public ViewProviderMesh { - PROPERTY_HEADER(MeshGui::ViewProviderMeshObject); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshObject); public: ViewProviderMeshObject(); - virtual ~ViewProviderMeshObject(); + ~ViewProviderMeshObject() override; - void attach(App::DocumentObject *pcFeat); - virtual void updateData(const App::Property*); + void attach(App::DocumentObject *pcFeat) override; + void updateData(const App::Property*) override; protected: - SoShape* getShapeNode() const; - SoNode* getCoordNode() const; - void showOpenEdges(bool); + SoShape* getShapeNode() const override; + SoNode* getCoordNode() const override; + void showOpenEdges(bool) override; private: SoFCMeshObjectNode * pcMeshNode; diff --git a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp index 294a71a010..0038050f33 100644 --- a/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderCurvature.cpp @@ -417,11 +417,11 @@ std::vector ViewProviderMeshCurvature::getDisplayModes() const std::vector StrList = inherited::getDisplayModes(); // add modes - StrList.push_back("Absolute curvature"); - StrList.push_back("Mean curvature"); - StrList.push_back("Gaussian curvature"); - StrList.push_back("Maximum curvature"); - StrList.push_back("Minimum curvature"); + StrList.emplace_back("Absolute curvature"); + StrList.emplace_back("Mean curvature"); + StrList.emplace_back("Gaussian curvature"); + StrList.emplace_back("Maximum curvature"); + StrList.emplace_back("Minimum curvature"); return StrList; } @@ -477,7 +477,7 @@ public: QStringList lines = s.split(QLatin1String("\n")); std::vector text; for (QStringList::Iterator it = lines.begin(); it != lines.end(); ++it) - text.push_back((const char*)it->toLatin1()); + text.emplace_back((const char*)it->toLatin1()); anno->LabelText.setValues(text); std::stringstream str; str << "Curvature info (" << group->Group.getSize() << ")"; @@ -526,7 +526,7 @@ void ViewProviderMeshCurvature::curvatureInfoCallback(void * ud, SoEventCallback } else if (mbe->getButton() == SoMouseButtonEvent::BUTTON1 && mbe->getState() == SoButtonEvent::UP) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) { + if (!point) { Base::Console().Message("No facet picked.\n"); return; } @@ -564,7 +564,7 @@ void ViewProviderMeshCurvature::curvatureInfoCallback(void * ud, SoEventCallback } else if (ev->getTypeId().isDerivedFrom(SoLocation2Event::getClassTypeId())) { const SoPickedPoint * point = n->getPickedPoint(); - if (point == nullptr) + if (!point) return; n->setHandled(); diff --git a/src/Mod/Mesh/Gui/ViewProviderCurvature.h b/src/Mod/Mesh/Gui/ViewProviderCurvature.h index 04fc759d1c..1e1112fc2d 100644 --- a/src/Mod/Mesh/Gui/ViewProviderCurvature.h +++ b/src/Mod/Mesh/Gui/ViewProviderCurvature.h @@ -60,41 +60,41 @@ class MeshGuiExport ViewProviderMeshCurvature : public Gui::ViewProviderDocument public Base::Observer { typedef Gui::ViewProviderDocumentObject inherited; - PROPERTY_HEADER(MeshGui::ViewProviderMeshCurvature); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshCurvature); public: ViewProviderMeshCurvature(); - virtual ~ViewProviderMeshCurvature(); + ~ViewProviderMeshCurvature() override; App::PropertyMaterial TextureMaterial; /// Extracts the mesh data from the feature \a pcFeature and creates an Inventor node \a SoNode with these data. - void attach(App::DocumentObject* pcFeature); - virtual bool useNewSelectionModel() const {return false;} + void attach(App::DocumentObject* pcFeature) override; + bool useNewSelectionModel() const override {return false;} /// Sets the viewing mode - void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; /// get the default display mode - virtual const char* getDefaultDisplayMode() const; + const char* getDefaultDisplayMode() const override; /// Returns a list of all possible modes - std::vector getDisplayModes() const; + std::vector getDisplayModes() const override; /// Updates the mesh feature representation - void updateData(const App::Property*); + void updateData(const App::Property*) override; /// Returns a pixmap for the associated feature type - QIcon getIcon() const; + QIcon getIcon() const override; /// Once the color bar settinhs has been changed this method gets called to update the feature's representation - void OnChange(Base::Subject &rCaller,int rcReason); + void OnChange(Base::Subject &rCaller,int rcReason) override; /// Returns a color bar - SoSeparator* getFrontRoot() const; + SoSeparator* getFrontRoot() const override; /// Hide the object in the view - virtual void hide(); + void hide() override; /// Show the object in the view - virtual void show(); + void show() override; public: static void curvatureInfoCallback(void * ud, SoEventCallback * n); protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; void setVertexCurvatureMode(int mode); std::string curvatureInfo(bool detail, int index1, int index2, int index3) const; void touchShapeNode(); @@ -102,7 +102,7 @@ protected: private: void init(const Mesh::PropertyCurvatureList *prop); - void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); + void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) override; protected: SoMaterial * pcColorMat; diff --git a/src/Mod/Mesh/Gui/ViewProviderDefects.cpp b/src/Mod/Mesh/Gui/ViewProviderDefects.cpp index d086511e70..f5d2418deb 100644 --- a/src/Mod/Mesh/Gui/ViewProviderDefects.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderDefects.cpp @@ -651,7 +651,7 @@ void ViewProviderMeshSelfIntersections::showDefects(const std::vector > lines; diff --git a/src/Mod/Mesh/Gui/ViewProviderDefects.h b/src/Mod/Mesh/Gui/ViewProviderDefects.h index 223585558f..57bb64cca4 100644 --- a/src/Mod/Mesh/Gui/ViewProviderDefects.h +++ b/src/Mod/Mesh/Gui/ViewProviderDefects.h @@ -38,23 +38,23 @@ namespace MeshGui { */ class MeshGuiExport ViewProviderMeshDefects : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(MeshGui::ViewProviderMeshDefects); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshDefects); public: ViewProviderMeshDefects(); - virtual ~ViewProviderMeshDefects(); + ~ViewProviderMeshDefects() override; // Display properties App::PropertyFloat LineWidth; // Build up the initial Inventor node - virtual void attach(App::DocumentObject* pcFeature) = 0; + void attach(App::DocumentObject* pcFeature) override = 0; /// Fill up the Inventor node with data virtual void showDefects(const std::vector&) = 0; protected: /// get called by the container whenever a property has been changed - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; SoCoordinate3 * pcCoords; SoDrawStyle * pcDrawStyle; @@ -65,14 +65,14 @@ protected: */ class MeshGuiExport ViewProviderMeshOrientation : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshOrientation); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshOrientation); public: ViewProviderMeshOrientation(); - virtual ~ViewProviderMeshOrientation(); + ~ViewProviderMeshOrientation() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoFaceSet* pcFaces; @@ -83,14 +83,14 @@ protected: */ class MeshGuiExport ViewProviderMeshNonManifolds : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshNonManifolds); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshNonManifolds); public: ViewProviderMeshNonManifolds(); - virtual ~ViewProviderMeshNonManifolds(); + ~ViewProviderMeshNonManifolds() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoLineSet* pcLines; @@ -101,14 +101,14 @@ protected: */ class MeshGuiExport ViewProviderMeshNonManifoldPoints : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshNonManifoldPoints); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshNonManifoldPoints); public: ViewProviderMeshNonManifoldPoints(); - virtual ~ViewProviderMeshNonManifoldPoints(); + ~ViewProviderMeshNonManifoldPoints() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoPointSet* pcPoints; @@ -119,14 +119,14 @@ protected: */ class MeshGuiExport ViewProviderMeshDuplicatedFaces : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshDuplicatedFaces); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshDuplicatedFaces); public: ViewProviderMeshDuplicatedFaces(); - virtual ~ViewProviderMeshDuplicatedFaces(); + ~ViewProviderMeshDuplicatedFaces() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoFaceSet* pcFaces; @@ -137,14 +137,14 @@ protected: */ class MeshGuiExport ViewProviderMeshDegenerations : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshDegenerations); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshDegenerations); public: ViewProviderMeshDegenerations(); - virtual ~ViewProviderMeshDegenerations(); + ~ViewProviderMeshDegenerations() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoLineSet* pcLines; @@ -152,14 +152,14 @@ protected: class MeshGuiExport ViewProviderMeshDuplicatedPoints : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshDuplicatedPoints); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshDuplicatedPoints); public: ViewProviderMeshDuplicatedPoints(); - virtual ~ViewProviderMeshDuplicatedPoints(); + ~ViewProviderMeshDuplicatedPoints() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoPointSet* pcPoints; @@ -167,14 +167,14 @@ protected: class MeshGuiExport ViewProviderMeshIndices : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshIndices); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshIndices); public: ViewProviderMeshIndices(); - virtual ~ViewProviderMeshIndices(); + ~ViewProviderMeshIndices() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoFaceSet* pcFaces; @@ -185,14 +185,14 @@ protected: */ class MeshGuiExport ViewProviderMeshSelfIntersections : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshSelfIntersections); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshSelfIntersections); public: ViewProviderMeshSelfIntersections(); - virtual ~ViewProviderMeshSelfIntersections(); + ~ViewProviderMeshSelfIntersections() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoLineSet* pcLines; @@ -200,14 +200,14 @@ protected: class MeshGuiExport ViewProviderMeshFolds : public ViewProviderMeshDefects { - PROPERTY_HEADER(MeshGui::ViewProviderMeshFolds); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshFolds); public: ViewProviderMeshFolds(); - virtual ~ViewProviderMeshFolds(); + ~ViewProviderMeshFolds() override; - void attach(App::DocumentObject* pcFeature); - void showDefects(const std::vector&); + void attach(App::DocumentObject* pcFeature) override; + void showDefects(const std::vector&) override; protected: SoFaceSet* pcFaces; diff --git a/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.h b/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.h index dd07001703..9bc233f949 100644 --- a/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.h +++ b/src/Mod/Mesh/Gui/ViewProviderMeshFaceSet.h @@ -48,19 +48,19 @@ class SoFCIndexedFaceSet; */ class MeshGuiExport ViewProviderMeshFaceSet : public ViewProviderMesh { - PROPERTY_HEADER(MeshGui::ViewProviderMeshFaceSet); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshFaceSet); public: ViewProviderMeshFaceSet(); - virtual ~ViewProviderMeshFaceSet(); + ~ViewProviderMeshFaceSet() override; - void attach(App::DocumentObject *pcFeat); - virtual void updateData(const App::Property*); + void attach(App::DocumentObject *pcFeat) override; + void updateData(const App::Property*) override; protected: - void showOpenEdges(bool); - SoShape* getShapeNode() const; - SoNode* getCoordNode() const; + void showOpenEdges(bool) override; + SoShape* getShapeNode() const override; + SoNode* getCoordNode() const override; private: bool directRendering; diff --git a/src/Mod/Mesh/Gui/ViewProviderTransform.cpp b/src/Mod/Mesh/Gui/ViewProviderTransform.cpp index eb40fab8ea..92871cdadf 100644 --- a/src/Mod/Mesh/Gui/ViewProviderTransform.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderTransform.cpp @@ -109,7 +109,7 @@ const char* ViewProviderMeshTransform::getDefaultDisplayMode() const std::vector ViewProviderMeshTransform::getDisplayModes() const { std::vector StrList = ViewProviderMesh::getDisplayModes(); - StrList.push_back("Transform"); + StrList.emplace_back("Transform"); return StrList; } diff --git a/src/Mod/Mesh/Gui/ViewProviderTransform.h b/src/Mod/Mesh/Gui/ViewProviderTransform.h index 13a6f0ddf6..46808eaf70 100644 --- a/src/Mod/Mesh/Gui/ViewProviderTransform.h +++ b/src/Mod/Mesh/Gui/ViewProviderTransform.h @@ -47,27 +47,27 @@ namespace MeshGui { */ class ViewProviderMeshTransform : public ViewProviderMesh { - PROPERTY_HEADER(MeshGui::ViewProviderMeshTransform); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshTransform); public: ViewProviderMeshTransform(); - virtual ~ViewProviderMeshTransform(); + ~ViewProviderMeshTransform() override; /** * Extracts the mesh data from the feature \a pcFeature and creates * an Inventor node \a SoNode with these data. */ - virtual void attach(App::DocumentObject *); + void attach(App::DocumentObject *) override; /// set the viewing mode - virtual void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; /// get the default display mode - virtual const char* getDefaultDisplayMode() const; + const char* getDefaultDisplayMode() const override; /// returns a list of all possible modes - virtual std::vector getDisplayModes() const; + std::vector getDisplayModes() const override; /// Update the Mesh representation - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: diff --git a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp index bba5b7bde0..3befe614e9 100644 --- a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp +++ b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.cpp @@ -220,6 +220,6 @@ const char* ViewProviderMeshTransformDemolding::getDefaultDisplayMode() const std::vector ViewProviderMeshTransformDemolding::getDisplayModes() const { std::vector StrList = ViewProviderMesh::getDisplayModes(); - StrList.push_back("Demold"); + StrList.emplace_back("Demold"); return StrList; } diff --git a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.h b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.h index f18be3b769..a33799f226 100644 --- a/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.h +++ b/src/Mod/Mesh/Gui/ViewProviderTransformDemolding.h @@ -52,25 +52,25 @@ namespace MeshGui { */ class ViewProviderMeshTransformDemolding : public ViewProviderMesh { - PROPERTY_HEADER(MeshGui::ViewProviderMeshTransformDemolding); + PROPERTY_HEADER_WITH_OVERRIDE(MeshGui::ViewProviderMeshTransformDemolding); public: ViewProviderMeshTransformDemolding(); - virtual ~ViewProviderMeshTransformDemolding(); + ~ViewProviderMeshTransformDemolding() override; /** * Extracts the mesh data from the feature \a pcFeature and creates * an Inventor node \a SoNode with these data. */ - virtual void attach(App::DocumentObject *); + void attach(App::DocumentObject *) override; /// set the viewing mode - virtual void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; /// get the default display mode - virtual const char* getDefaultDisplayMode() const; + const char* getDefaultDisplayMode() const override; /// returns a list of all possible modes - virtual std::vector getDisplayModes() const; + std::vector getDisplayModes() const override; protected: void calcMaterialIndex(const SbRotation &rot); diff --git a/src/Mod/Mesh/Gui/Workbench.cpp b/src/Mod/Mesh/Gui/Workbench.cpp index 1f2e19bc80..63ccdc29ae 100644 --- a/src/Mod/Mesh/Gui/Workbench.cpp +++ b/src/Mod/Mesh/Gui/Workbench.cpp @@ -107,11 +107,11 @@ public: taskbox->groupLayout()->addWidget(box); Content.push_back(taskbox); } - bool shouldShow(void) + bool shouldShow(void) override { return true; } - void onSelectionChanged(const Gui::SelectionChanges&) + void onSelectionChanged(const Gui::SelectionChanges&) override { Base::BoundBox3d bbox; unsigned long countPoints=0, countFacets=0; diff --git a/src/Mod/Mesh/Gui/Workbench.h b/src/Mod/Mesh/Gui/Workbench.h index ce10c46dc3..69aed2b132 100644 --- a/src/Mod/Mesh/Gui/Workbench.h +++ b/src/Mod/Mesh/Gui/Workbench.h @@ -36,20 +36,20 @@ namespace MeshGui { */ class MeshGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; - void activated(); - void deactivated(); - void setupContextMenu(const char* recipient, Gui::MenuItem*) const; + void activated() override; + void deactivated() override; + void setupContextMenu(const char* recipient, Gui::MenuItem*) const override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace MeshGui diff --git a/src/Mod/MeshPart/App/AppMeshPartPy.cpp b/src/Mod/MeshPart/App/AppMeshPartPy.cpp index c221a93073..4fa7c6edf6 100644 --- a/src/Mod/MeshPart/App/AppMeshPartPy.cpp +++ b/src/Mod/MeshPart/App/AppMeshPartPy.cpp @@ -144,10 +144,10 @@ public: initialize("This module is the MeshPart module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) + Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); @@ -272,7 +272,7 @@ private: proj.projectToMesh(shape, maxDist, polylines); Py::List list; - for (auto it : polylines) { + for (const auto& it : polylines) { Py::List poly; for (auto jt : it.points) { Py::Vector v(jt); @@ -304,7 +304,7 @@ private: std::vector polylines; proj.projectParallelToMesh(shape, dir, polylines); Py::List list; - for (auto it : polylines) { + for (const auto& it : polylines) { Py::List poly; for (auto jt : it.points) { Py::Vector v(jt); @@ -354,7 +354,7 @@ private: proj.projectParallelToMesh(polylinesIn, dir, polylines); Py::List list; - for (auto it : polylines) { + for (const auto& it : polylines) { Py::List poly; for (auto jt : it.points) { Py::Vector v(jt); diff --git a/src/Mod/MeshPart/App/CurveProjector.cpp b/src/Mod/MeshPart/App/CurveProjector.cpp index 5731521aa3..c295d92ced 100644 --- a/src/Mod/MeshPart/App/CurveProjector.cpp +++ b/src/Mod/MeshPart/App/CurveProjector.cpp @@ -59,7 +59,9 @@ #include #include +#include #include +#include using namespace MeshPart; @@ -78,7 +80,8 @@ CurveProjector::CurveProjector(const TopoDS_Shape &aShape, const MeshKernel &pMe void CurveProjector::writeIntersectionPointsToFile(const char *name) { // export points - std::ofstream str(name, std::ios::out | std::ios::binary); + Base::FileInfo fi(name); + Base::ofstream str(fi, std::ios::out | std::ios::binary); str.precision(4); str.setf(std::ios::fixed | std::ios::showpoint); for (result_type::const_iterator it1 = mvEdgeSplitPoints.begin();it1!=mvEdgeSplitPoints.end();++it1) { @@ -101,20 +104,15 @@ CurveProjectorShape::CurveProjectorShape(const TopoDS_Shape &aShape, const MeshK Do(); } -void CurveProjectorShape::Do(void) +void CurveProjectorShape::Do() { TopExp_Explorer Ex; - TopoDS_Shape Edge; - - for (Ex.Init(_Shape, TopAbs_EDGE); Ex.More(); Ex.Next()) - { - const TopoDS_Edge& aEdge = TopoDS::Edge(Ex.Current()); + for (Ex.Init(_Shape, TopAbs_EDGE); Ex.More(); Ex.Next()) { + const TopoDS_Edge& aEdge = TopoDS::Edge(Ex.Current()); //std::vector vSplitEdges; projectCurve(aEdge, mvEdgeSplitPoints[aEdge]); - } - } @@ -269,26 +267,22 @@ CurveProjectorSimple::CurveProjectorSimple(const TopoDS_Shape &aShape, const Mes } -void CurveProjectorSimple::Do(void) +void CurveProjectorSimple::Do() { TopExp_Explorer Ex; - TopoDS_Shape Edge; std::vector vEdgePolygon; for (Ex.Init(_Shape, TopAbs_EDGE); Ex.More(); Ex.Next()) { - const TopoDS_Edge& aEdge = TopoDS::Edge(Ex.Current()); + const TopoDS_Edge& aEdge = TopoDS::Edge(Ex.Current()); // GetSampledCurves(aEdge,vEdgePolygon,2000); //std::vector vSplitEdges; projectCurve(aEdge,vEdgePolygon, mvEdgeSplitPoints[aEdge]); - } - } - void CurveProjectorSimple::GetSampledCurves( const TopoDS_Edge& aEdge, std::vector& rclPoints, unsigned long ulNbOfPoints) { rclPoints.clear(); @@ -328,7 +322,8 @@ void CurveProjectorSimple::projectCurve( const TopoDS_Edge& aEdge, MeshFacetIterator It(_Mesh); Base::SequencerLauncher seq("Building up projection map...", ulNbOfPoints+1); - std::ofstream str("projected.asc", std::ios::out | std::ios::binary); + Base::FileInfo fi("projected.asc"); + Base::ofstream str(fi, std::ios::out | std::ios::binary); str.precision(4); str.setf(std::ios::fixed | std::ios::showpoint); @@ -583,27 +578,20 @@ CurveProjectorWithToolMesh::CurveProjectorWithToolMesh(const TopoDS_Shape &aShap } -void CurveProjectorWithToolMesh::Do(void) +void CurveProjectorWithToolMesh::Do() { TopExp_Explorer Ex; - TopoDS_Shape Edge; std::vector cVAry; - std::vector vEdgePolygon; - for (Ex.Init(_Shape, TopAbs_EDGE); Ex.More(); Ex.Next()) { - const TopoDS_Edge& aEdge = TopoDS::Edge(Ex.Current()); - + const TopoDS_Edge& aEdge = TopoDS::Edge(Ex.Current()); makeToolMesh(aEdge,cVAry); - } ToolMesh.AddFacets(cVAry); - } - //projectToNeighbours(Handle(Geom_Curve) hCurve,float pos void CurveProjectorWithToolMesh::makeToolMesh( const TopoDS_Edge& aEdge,std::vector &cVAry ) @@ -727,7 +715,8 @@ void MeshProjection::splitMeshByShape ( const TopoDS_Shape &aShape, float fMaxDi std::vector rPolyLines; projectToMesh( aShape, fMaxDist, rPolyLines ); - std::ofstream str("output.asc", std::ios::out | std::ios::binary); + Base::FileInfo fi("output.asc"); + Base::ofstream str(fi, std::ios::out | std::ios::binary); str.precision(4); str.setf(std::ios::fixed | std::ios::showpoint); for (std::vector::const_iterator it = rPolyLines.begin();it!=rPolyLines.end();++it) { @@ -785,7 +774,7 @@ void MeshProjection::findSectionParameters(const TopoDS_Edge& edge, const Base:: const MeshCore::MeshPointArray& points = _rcMesh.GetPoints(); Base::Vector3f res; - for (auto it : facets) { + for (const auto& it : facets) { for (int i=0; i<3; i++) { Base::Vector3f pt1 = points[it._aulPoints[i]]; Base::Vector3f pt2 = points[it._aulPoints[(i+1)%3]]; @@ -860,7 +849,7 @@ void MeshProjection::projectOnMesh(const std::vector& pointsIn, const MeshCore::MeshFacetArray& facets = _rcMesh.GetFacets(); const MeshCore::MeshPointArray& points = _rcMesh.GetPoints(); - for (auto it : facets) { + for (const auto& it : facets) { for (int i=0; i<3; i++) { if (!it.HasNeighbour(i)) { boundaryPoints.push_back(points[it._aulPoints[i]]); @@ -985,7 +974,7 @@ void MeshProjection::projectParallelToMesh (const std::vector &aEdges, Base::SequencerLauncher seq( "Project curve on mesh", aEdges.size() ); - for (auto it : aEdges) { + for (const auto& it : aEdges) { std::vector points = it.points; typedef std::pair HitPoint; diff --git a/src/Mod/MeshPart/App/CurveProjector.h b/src/Mod/MeshPart/App/CurveProjector.h index e74ee014b9..d460bd904a 100644 --- a/src/Mod/MeshPart/App/CurveProjector.h +++ b/src/Mod/MeshPart/App/CurveProjector.h @@ -72,7 +72,7 @@ public: typedef std::map,TopoDSLess > result_type; - result_type &result(void) {return mvEdgeSplitPoints;} + result_type &result() {return mvEdgeSplitPoints;} void writeIntersectionPointsToFile(const char *name="export_pts.asc"); @@ -91,7 +91,7 @@ class MeshPartExport CurveProjectorShape: public CurveProjector { public: CurveProjectorShape(const TopoDS_Shape &aShape, const MeshKernel &pMesh); - virtual ~CurveProjectorShape() {} + ~CurveProjectorShape() override {} void projectCurve(const TopoDS_Edge& aEdge, std::vector &vSplitEdges); @@ -101,7 +101,7 @@ public: protected: - virtual void Do(); + void Do() override; }; @@ -112,7 +112,7 @@ class MeshPartExport CurveProjectorSimple: public CurveProjector { public: CurveProjectorSimple(const TopoDS_Shape &aShape, const MeshKernel &pMesh); - virtual ~CurveProjectorSimple() {} + ~CurveProjectorSimple() override {} /// helper to discredicice a Edge... void GetSampledCurves( const TopoDS_Edge& aEdge, std::vector& rclPoints, unsigned long ulNbOfPoints = 30); @@ -127,7 +127,7 @@ public: protected: - virtual void Do(); + void Do() override; }; /** Project by projecting a sampled curve to the mesh @@ -141,7 +141,7 @@ public: }; CurveProjectorWithToolMesh(const TopoDS_Shape &aShape, const MeshKernel &pMesh,MeshKernel &rToolMesh); - virtual ~CurveProjectorWithToolMesh() {} + ~CurveProjectorWithToolMesh() override {} void makeToolMesh(const TopoDS_Edge& aEdge,std::vector &cVAry ); @@ -150,7 +150,7 @@ public: MeshKernel &ToolMesh; protected: - virtual void Do(); + void Do() override; }; /** @@ -177,7 +177,7 @@ public: }; /// Construction - MeshProjection(const MeshKernel& rMesh); + explicit MeshProjection(const MeshKernel& rMesh); /// Destruction ~MeshProjection(); diff --git a/src/Mod/MeshPart/App/MeshAlgos.cpp b/src/Mod/MeshPart/App/MeshAlgos.cpp index 3551766207..6035eb6cf7 100644 --- a/src/Mod/MeshPart/App/MeshAlgos.cpp +++ b/src/Mod/MeshPart/App/MeshAlgos.cpp @@ -24,7 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ # ifdef FC_OS_LINUX -# include +# include # endif #endif @@ -100,7 +100,7 @@ void MeshAlgos::offsetSpecial2(MeshCore::MeshKernel* Mesh, float fSize) // if there are no flipped triangles -> stop //int f =fliped.size(); - if(fliped.size() == 0) + if(fliped.empty()) break; for(std::set::iterator It= fliped.begin();It!=fliped.end();++It) @@ -206,7 +206,7 @@ MeshCore::MeshKernel* MeshAlgos::boolean(MeshCore::MeshKernel* pMesh1, self_intersects = gts_surface_is_self_intersecting (s1); if (self_intersects != NULL) { // if (verbose) -// gts_surface_print_stats (self_intersects, stderr); +// gts_surface_print_stats (self_intersects, stderr); // gts_surface_write (self_intersects, stdout); gts_object_destroy (GTS_OBJECT (self_intersects)); gts_object_destroy (GTS_OBJECT (s1)); @@ -216,7 +216,7 @@ MeshCore::MeshKernel* MeshAlgos::boolean(MeshCore::MeshKernel* pMesh1, self_intersects = gts_surface_is_self_intersecting (s2); if (self_intersects != NULL) { // if (verbose) -// gts_surface_print_stats (self_intersects, stderr); +// gts_surface_print_stats (self_intersects, stderr); // gts_surface_write (self_intersects, stdout); gts_object_destroy (GTS_OBJECT (self_intersects)); gts_object_destroy (GTS_OBJECT (s1)); @@ -234,7 +234,7 @@ MeshCore::MeshKernel* MeshAlgos::boolean(MeshCore::MeshKernel* pMesh1, is_open2 = gts_surface_volume (s2) < 0. ? true : false; si = gts_surface_inter_new (gts_surface_inter_class (), - s1, s2, tree1, tree2, is_open1, is_open2); + s1, s2, tree1, tree2, is_open1, is_open2); g_assert (gts_surface_inter_check (si, &closed)); if (!closed) { gts_object_destroy (GTS_OBJECT (s1)); @@ -245,9 +245,9 @@ MeshCore::MeshKernel* MeshAlgos::boolean(MeshCore::MeshKernel* pMesh1, } s3 = gts_surface_new (gts_surface_class (), - gts_face_class (), - gts_edge_class (), - gts_vertex_class ()); + gts_face_class (), + gts_edge_class (), + gts_vertex_class ()); if (Type==0) { // union gts_surface_inter_boolean (si, s3, GTS_1_OUT_2); gts_surface_inter_boolean (si, s3, GTS_2_OUT_1); @@ -478,7 +478,7 @@ class _VertexCompare return clP1.X() < clP2.X(); } - _VertexCompare (void) : dE(1.0e-5) {} + _VertexCompare () : dE(1.0e-5) {} double dE; }; diff --git a/src/Mod/MeshPart/App/Mesher.cpp b/src/Mod/MeshPart/App/Mesher.cpp index bc86eecfbd..7f3615a971 100644 --- a/src/Mod/MeshPart/App/Mesher.cpp +++ b/src/Mod/MeshPart/App/Mesher.cpp @@ -177,7 +177,7 @@ public: MeshCore::MeshFacetArray faces; std::size_t numTriangles = 0; - for (auto it : domains) + for (const auto& it : domains) numTriangles += it.facets.size(); faces.reserve(numTriangles); @@ -265,7 +265,7 @@ public: MeshCore::MeshPointArray verts; verts.resize(vertices.size()); - for (auto it : vertices) + for (const auto& it : vertices) verts[it.i] = it.toPoint(); MeshCore::MeshKernel kernel; @@ -275,7 +275,7 @@ public: meshdata->swap(kernel); if (createSegm) { int index = 0; - for (auto it : colorMap) { + for (const auto& it : colorMap) { Mesh::Segment segm(meshdata, false); for (auto jt : it.second) { segm.addIndices(meshSegments[jt]); @@ -291,7 +291,7 @@ public: } } else { - for (auto it : meshSegments) { + for (const auto& it : meshSegments) { meshdata->addSegment(it); } } diff --git a/src/Mod/MeshPart/App/Mesher.h b/src/Mod/MeshPart/App/Mesher.h index cc515e2b6c..43bc6929d7 100644 --- a/src/Mod/MeshPart/App/Mesher.h +++ b/src/Mod/MeshPart/App/Mesher.h @@ -48,7 +48,7 @@ public: Standard = 3 }; - Mesher(const TopoDS_Shape&); + explicit Mesher(const TopoDS_Shape&); ~Mesher(); void setMethod(Method m) @@ -170,8 +170,8 @@ public: MeshingOutput(); protected: - int overflow(int c = EOF); - int sync(); + int overflow(int c = EOF) override; + int sync() override; private: std::string buffer; diff --git a/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp b/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp index fc838d3194..3d1af7f5bc 100644 --- a/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp +++ b/src/Mod/MeshPart/Gui/AppMeshPartGui.cpp @@ -34,7 +34,7 @@ #include "Workbench.h" // use a different name to CreateCommand() -void CreateMeshPartCommands(void); +void CreateMeshPartCommands(); void loadMeshPartResource() { @@ -52,7 +52,7 @@ public: initialize("This module is the MeshPartGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/MeshPart/Gui/Command.cpp b/src/Mod/MeshPart/Gui/Command.cpp index f91ff09030..445397411d 100644 --- a/src/Mod/MeshPart/Gui/Command.cpp +++ b/src/Mod/MeshPart/Gui/Command.cpp @@ -68,7 +68,7 @@ void CmdMeshPartMesher::activated(int) Gui::Control().showDialog(new MeshPartGui::TaskTessellation()); } -bool CmdMeshPartMesher::isActive(void) +bool CmdMeshPartMesher::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -135,13 +135,6 @@ void CmdMeshPartTrimByPlane::activated(int) Mesh::MeshObject* mesh = static_cast(*it)->Mesh.startEditing(); - // Apply the inverted mesh placement to the plane because the trimming is done - // on the untransformed mesh data - Base::Placement meshPlacement = mesh->getPlacement(); - meshPlacement.invert(); - meshPlacement.multVec(base, base); - meshPlacement.getRotation().multVec(normal, normal); - Base::Vector3f plnBase = Base::convertTo(base); Base::Vector3f plnNormal = Base::convertTo(normal); @@ -171,7 +164,7 @@ void CmdMeshPartTrimByPlane::activated(int) commitCommand(); } -bool CmdMeshPartTrimByPlane::isActive(void) +bool CmdMeshPartTrimByPlane::isActive() { // Check for the selected mesh feature (all Mesh types) if (getSelection().countObjectsOfType(Mesh::Feature::getClassTypeId()) != 1) @@ -229,8 +222,8 @@ void CmdMeshPartSection::activated(int) std::vector polylines; mesh->crossSections(sections, polylines); - for (auto it2 : polylines) { - for (auto it3 : it2) { + for (const auto& it2 : polylines) { + for (const auto& it3 : it2) { Py::Tuple arg(1); Py::List list; for (auto it4 : it3) { @@ -255,7 +248,7 @@ void CmdMeshPartSection::activated(int) commitCommand(); } -bool CmdMeshPartSection::isActive(void) +bool CmdMeshPartSection::isActive() { // Check for the selected mesh feature (all Mesh types) if (getSelection().countObjectsOfType(Mesh::Feature::getClassTypeId()) != 1) @@ -297,7 +290,7 @@ void CmdMeshPartCrossSections::activated(int iMsg) Gui::Control().showDialog(dlg); } -bool CmdMeshPartCrossSections::isActive(void) +bool CmdMeshPartCrossSections::isActive() { return (Gui::Selection().countObjectsOfType(Mesh::Feature::getClassTypeId()) > 0 && !Gui::Control().activeDialog()); @@ -329,7 +322,7 @@ void CmdMeshPartCurveOnMesh::activated(int) Gui::Control().showDialog(new MeshPartGui::TaskCurveOnMesh(static_cast(mdis.front()))); } -bool CmdMeshPartCurveOnMesh::isActive(void) +bool CmdMeshPartCurveOnMesh::isActive() { if (Gui::Control().activeDialog()) return false; @@ -343,7 +336,7 @@ bool CmdMeshPartCurveOnMesh::isActive(void) } -void CreateMeshPartCommands(void) +void CreateMeshPartCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdMeshPartMesher()); diff --git a/src/Mod/MeshPart/Gui/CrossSections.cpp b/src/Mod/MeshPart/Gui/CrossSections.cpp index d05495878b..4e1e7ca24a 100644 --- a/src/Mod/MeshPart/Gui/CrossSections.cpp +++ b/src/Mod/MeshPart/Gui/CrossSections.cpp @@ -83,19 +83,19 @@ public: this->pcRoot->addChild(coords); this->pcRoot->addChild(planes); } - ~ViewProviderCrossSections() + ~ViewProviderCrossSections() override { coords->unref(); planes->unref(); } - void updateData(const App::Property*) + void updateData(const App::Property*) override { } - const char* getDefaultDisplayMode() const + const char* getDefaultDisplayMode() const override { return ""; } - std::vector getDisplayModes(void) const + std::vector getDisplayModes(void) const override { return std::vector(); } diff --git a/src/Mod/MeshPart/Gui/CrossSections.h b/src/Mod/MeshPart/Gui/CrossSections.h index 97a4fa5f34..d089e6ac57 100644 --- a/src/Mod/MeshPart/Gui/CrossSections.h +++ b/src/Mod/MeshPart/Gui/CrossSections.h @@ -44,14 +44,14 @@ class CrossSections : public QDialog enum Plane { XY, XZ, YZ }; public: - CrossSections(const Base::BoundBox3d& bb, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~CrossSections(); - void accept(); + explicit CrossSections(const Base::BoundBox3d& bb, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~CrossSections() override; + void accept() override; void apply(); protected: - void changeEvent(QEvent *e); - void keyPressEvent(QKeyEvent*); + void changeEvent(QEvent *e) override; + void keyPressEvent(QKeyEvent*) override; private Q_SLOTS: void on_xyPlane_clicked(); @@ -82,14 +82,14 @@ class TaskCrossSections : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskCrossSections(const Base::BoundBox3d& bb); - ~TaskCrossSections(); + explicit TaskCrossSections(const Base::BoundBox3d& bb); + ~TaskCrossSections() override; public: - bool accept(); - void clicked(int id); + bool accept() override; + void clicked(int id) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/MeshPart/Gui/CurveOnMesh.h b/src/Mod/MeshPart/Gui/CurveOnMesh.h index 7886ab524a..d98bbe1faa 100644 --- a/src/Mod/MeshPart/Gui/CurveOnMesh.h +++ b/src/Mod/MeshPart/Gui/CurveOnMesh.h @@ -45,16 +45,16 @@ namespace MeshPartGui class ViewProviderCurveOnMesh : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(MeshPartGui::ViewProviderCurveOnMesh); + PROPERTY_HEADER_WITH_OVERRIDE(MeshPartGui::ViewProviderCurveOnMesh); public: ViewProviderCurveOnMesh(); - virtual ~ViewProviderCurveOnMesh(); + ~ViewProviderCurveOnMesh() override; void addVertex(const SbVec3f&); void clearVertex(); void setPoints(const std::vector&); void clearPoints(); - void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; private: SoCoordinate3 * pcCoords; @@ -68,8 +68,8 @@ class CurveOnMeshHandler : public QObject Q_OBJECT public: - CurveOnMeshHandler(QObject* parent = nullptr); - ~CurveOnMeshHandler(); + explicit CurveOnMeshHandler(QObject* parent = nullptr); + ~CurveOnMeshHandler() override; void enableApproximation(bool); void setParameters(int maxDegree, GeomAbs_Shape cont, double tol3d, double angle); void enableCallback(Gui::View3DInventor* viewer); diff --git a/src/Mod/MeshPart/Gui/TaskCurveOnMesh.h b/src/Mod/MeshPart/Gui/TaskCurveOnMesh.h index dc54612c3f..d82869f315 100644 --- a/src/Mod/MeshPart/Gui/TaskCurveOnMesh.h +++ b/src/Mod/MeshPart/Gui/TaskCurveOnMesh.h @@ -42,13 +42,13 @@ class CurveOnMeshWidget : public QWidget Q_OBJECT public: - CurveOnMeshWidget(Gui::View3DInventor* view, QWidget* parent=nullptr); - ~CurveOnMeshWidget(); + explicit CurveOnMeshWidget(Gui::View3DInventor* view, QWidget* parent=nullptr); + ~CurveOnMeshWidget() override; void reject(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void setup(); private Q_SLOTS: @@ -65,13 +65,13 @@ class TaskCurveOnMesh : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskCurveOnMesh(Gui::View3DInventor* view); - ~TaskCurveOnMesh(); + explicit TaskCurveOnMesh(Gui::View3DInventor* view); + ~TaskCurveOnMesh() override; public: - bool reject(); + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Close; } private: diff --git a/src/Mod/MeshPart/Gui/Tessellation.cpp b/src/Mod/MeshPart/Gui/Tessellation.cpp index a0f5ac1bc1..8b8d8d6cf2 100644 --- a/src/Mod/MeshPart/Gui/Tessellation.cpp +++ b/src/Mod/MeshPart/Gui/Tessellation.cpp @@ -307,11 +307,11 @@ void Tessellation::process(int method, App::Document* doc, const std::listdocument) - .arg(objname) - .arg(subname) - .arg(param) - .arg(label); + .arg(this->document, + objname, + subname, + param, + label); Gui::Command::runCommand(Gui::Command::Doc, cmd.toUtf8()); @@ -370,7 +370,7 @@ std::vector Tessellation::getUniqueColors(const std::vector unique; for (const auto& it : col_set) - unique.push_back(App::Color(it)); + unique.emplace_back(it); return unique; } diff --git a/src/Mod/MeshPart/Gui/Tessellation.h b/src/Mod/MeshPart/Gui/Tessellation.h index 82fb69c119..bee0b1f1eb 100644 --- a/src/Mod/MeshPart/Gui/Tessellation.h +++ b/src/Mod/MeshPart/Gui/Tessellation.h @@ -47,8 +47,8 @@ class Mesh2ShapeGmsh : public MeshGui::GmshWidget Q_OBJECT public: - Mesh2ShapeGmsh(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~Mesh2ShapeGmsh(); + explicit Mesh2ShapeGmsh(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~Mesh2ShapeGmsh() override; void process(App::Document* doc, const std::list&); @@ -56,8 +56,8 @@ Q_SIGNALS: void processed(); protected: - virtual bool writeProject(QString& inpFile, QString& outFile); - virtual bool loadOutput(); + bool writeProject(QString& inpFile, QString& outFile) override; + bool loadOutput() override; private: class Private; @@ -77,12 +77,12 @@ class Tessellation : public QWidget }; public: - Tessellation(QWidget* parent = nullptr); - ~Tessellation(); + explicit Tessellation(QWidget* parent = nullptr); + ~Tessellation() override; bool accept(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void process(int method, App::Document* doc, const std::list&); void saveParameters(int method); void setFaceColors(int method, App::Document* doc, App::DocumentObject* obj); @@ -112,15 +112,15 @@ class TaskTessellation : public Gui::TaskView::TaskDialog public: TaskTessellation(); - ~TaskTessellation(); + ~TaskTessellation() override; public: - virtual void open(); - virtual void clicked(int); - virtual bool accept(); - virtual bool reject(); + void open() override; + void clicked(int) override; + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/MeshPart/Gui/Workbench.h b/src/Mod/MeshPart/Gui/Workbench.h index d25e095740..95687f59ef 100644 --- a/src/Mod/MeshPart/Gui/Workbench.h +++ b/src/Mod/MeshPart/Gui/Workbench.h @@ -33,15 +33,15 @@ namespace MeshPartGui { */ class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace MeshPartGui diff --git a/src/Mod/OpenSCAD/OpenSCADCommands.py b/src/Mod/OpenSCAD/OpenSCADCommands.py index 8c33634195..eedc7df637 100644 --- a/src/Mod/OpenSCAD/OpenSCADCommands.py +++ b/src/Mod/OpenSCAD/OpenSCADCommands.py @@ -93,7 +93,7 @@ class ExplodeGroup: import FreeCADGui oo.ViewObject.show() if color and isdefault(oo.ViewObject.DiffuseColor): - if color == True: + if color: oo.ViewObject.DiffuseColor=randomcolor() else: oo.ViewObject.DiffuseColor=color diff --git a/src/Mod/OpenSCAD/OpenSCADUtils.py b/src/Mod/OpenSCAD/OpenSCADUtils.py index 5ed6710f56..9cdbfa80dc 100644 --- a/src/Mod/OpenSCAD/OpenSCADUtils.py +++ b/src/Mod/OpenSCAD/OpenSCADUtils.py @@ -106,8 +106,7 @@ def searchforopenscadexe(): p1 = subprocess.Popen(['which','openscad'], stdout=subprocess.PIPE) if p1.wait() == 0: output = p1.stdout.read() - if sys.version_info.major >= 3: - output = output.decode("utf-8") + output = output.decode("utf-8") opath = output.split('\n')[0] return opath diff --git a/src/Mod/OpenSCAD/importCSG.py b/src/Mod/OpenSCAD/importCSG.py index 3d35ed5b37..13c2a79987 100644 --- a/src/Mod/OpenSCAD/importCSG.py +++ b/src/Mod/OpenSCAD/importCSG.py @@ -484,9 +484,9 @@ def p_offset_action(p): # newobj.ViewObject.Proxy = 0 p[0] = [newobj] -def checkObjShape(obj) : +def checkObjShape(obj): if printverbose: print('Check Object Shape') - if obj.Shape.isNull() == True : + if obj.Shape.isNull(): if printverbose: print('Shape is Null - recompute') obj.recompute() @@ -832,7 +832,7 @@ def p_linear_extrude_with_transform(p): newobj = process_linear_extrude_with_transform(obj,h,t,s) else: newobj = process_linear_extrude(obj,h) - if p[3]['center']=='true' : + if p[3].get('center','false')=='true' : center(newobj,0,0,h) p[0] = [newobj] if gui: @@ -851,7 +851,7 @@ def p_surface_action(p): if printverbose: print("Surface") obj = doc.addObject("Part::Feature",'surface') obj.Shape,xoff,yoff=makeSurfaceVolume(p[3]['file']) - if p[3]['center']=='true' : + if p[3].get('center','false')=='true' : center(obj,xoff,yoff,0.0) p[0] = [obj] if printverbose: print("End surface") @@ -1075,7 +1075,7 @@ def myPolygon(n,r1): def p_cylinder_action(p): 'cylinder_action : cylinder LPAREN keywordargument_list RPAREN SEMICOL' if printverbose: print("Cylinder") - tocenter = p[3]['center'] + tocenter = p[3].get('center','false') h = float(p[3]['h']) r1 = float(p[3]['r1']) r2 = float(p[3]['r2']) @@ -1178,7 +1178,7 @@ def p_cube_action(p): FreeCAD.Console.PrintWarning('cube with radius zero\n') mycube=doc.addObject("Part::Feature","emptycube") mycube.Shape = Part.Compound([]) - if p[3]['center']=='true' : + if p[3].get('center','false')=='true' : center(mycube,l,w,h); p[0] = [mycube] if printverbose: print("End Cube") @@ -1227,7 +1227,7 @@ def p_square_action(p) : mysquare = doc.addObject('Part::Plane',p[1]) mysquare.Length=x mysquare.Width=y - if p[3]['center']=='true' : + if p[3].get('center','false')=='true' : center(mysquare,x,y,0) p[0] = [mysquare] diff --git a/src/Mod/Part/App/AppPart.cpp b/src/Mod/Part/App/AppPart.cpp index b351e5fd00..874e344167 100644 --- a/src/Mod/Part/App/AppPart.cpp +++ b/src/Mod/Part/App/AppPart.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include "ArcOfCirclePy.h" #include "ArcOfConicPy.h" @@ -94,6 +95,7 @@ #include "GeometryMigrationExtension.h" #include "GeometryStringExtensionPy.h" #include "HyperbolaPy.h" +#include "ImportStep.h" #include "LinePy.h" #include "LineSegmentPy.h" #include "OffsetCurvePy.h" @@ -106,7 +108,6 @@ #include "PlanePy.h" #include "PlateSurfacePy.h" #include "PointPy.h" -#include "PrecisionPy.h" #include "PrimitiveFeature.h" #include "RectangularTrimmedSurfacePy.h" #include "SpherePy.h" @@ -314,7 +315,7 @@ PyMOD_INIT_FUNC(Part) Base::Interpreter().addType(&Part::GeometryStringExtensionPy ::Type,partModule,"GeometryStringExtension"); Base::Interpreter().addType(&Part::GeometryBoolExtensionPy ::Type,partModule,"GeometryBoolExtension"); Base::Interpreter().addType(&Part::GeometryDoubleExtensionPy ::Type,partModule,"GeometryDoubleExtension"); - Base::Interpreter().addType(&Part::PrecisionPy ::Type,partModule,"Precision"); + Base::Interpreter().addType(&Base::PrecisionPy ::Type,partModule,"Precision"); // BRepFeat package PyObject* brepfeatModule(module.getAttr("BRepFeat").ptr()); @@ -537,78 +538,8 @@ PyMOD_INIT_FUNC(Part) IGESControl_Controller::Init(); STEPControl_Controller::Init(); - // set the user-defined settings - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part"); - // General - Base::Reference hGenGrp = hGrp->GetGroup("General"); - // http://www.opencascade.org/org/forum/thread_20801/ - // read.surfacecurve.mode: - // A preference for the computation of curves in an entity which has both 2D and 3D representation. - // Each TopoDS_Edge in TopoDS_Face must have a 3D and 2D curve that references the surface. - // If both 2D and 3D representation of the entity are present, the computation of these curves depends on - // the following values of parameter: - // 0: "Default" - no preference, both curves are taken - // 3: "3DUse_Preferred" - 3D curves are used to rebuild 2D ones - // Additional modes for IGES - // 2: "2DUse_Preferred" - the 2D is used to rebuild the 3D in case of their inconsistency - // -2: "2DUse_Forced" - the 2D is always used to rebuild the 3D (even if 2D is present in the file) - // -3: "3DUse_Forced" - the 3D is always used to rebuild the 2D (even if 2D is present in the file) - int readsurfacecurve = hGenGrp->GetInt("ReadSurfaceCurveMode", 0); - Interface_Static::SetIVal("read.surfacecurve.mode", readsurfacecurve); - - // write.surfacecurve.mode (STEP-only): - // This parameter indicates whether parametric curves (curves in parametric space of surface) should be - // written into the STEP file. This parameter can be set to Off in order to minimize the size of the resulting - // STEP file. - // Off (0) : writes STEP files without pcurves. This mode decreases the size of the resulting file. - // On (1) : (default) writes pcurves to STEP file - int writesurfacecurve = hGenGrp->GetInt("WriteSurfaceCurveMode", 1); - Interface_Static::SetIVal("write.surfacecurve.mode", writesurfacecurve); - - //IGES handling - Base::Reference hIgesGrp = hGrp->GetGroup("IGES"); - int value = Interface_Static::IVal("write.iges.brep.mode"); - bool brep = hIgesGrp->GetBool("BrepMode", value > 0); - Interface_Static::SetIVal("write.iges.brep.mode",brep ? 1 : 0); - Interface_Static::SetCVal("write.iges.header.company", hIgesGrp->GetASCII("Company").c_str()); - Interface_Static::SetCVal("write.iges.header.author", hIgesGrp->GetASCII("Author").c_str()); - Interface_Static::SetCVal("write.iges.header.product", hIgesGrp->GetASCII("Product", - Interface_Static::CVal("write.iges.header.product")).c_str()); - - int unitIges = hIgesGrp->GetInt("Unit", 0); - switch (unitIges) { - case 1: - Interface_Static::SetCVal("write.iges.unit","M"); - break; - case 2: - Interface_Static::SetCVal("write.iges.unit","INCH"); - break; - default: - Interface_Static::SetCVal("write.iges.unit","MM"); - break; - } - - //STEP handling - Base::Reference hStepGrp = hGrp->GetGroup("STEP"); - int unitStep = hStepGrp->GetInt("Unit", 0); - switch (unitStep) { - case 1: - Interface_Static::SetCVal("write.step.unit","M"); - break; - case 2: - Interface_Static::SetCVal("write.step.unit","INCH"); - break; - default: - Interface_Static::SetCVal("write.step.unit","MM"); - break; - } - - std::string ap = hStepGrp->GetASCII("Scheme", Interface_Static::CVal("write.step.schema")); - Interface_Static::SetCVal("write.step.schema", ap.c_str()); - Interface_Static::SetCVal("write.step.product.name", hStepGrp->GetASCII("Product", - Interface_Static::CVal("write.step.product.name")).c_str()); + ImportExportSettings::initialize(); PyMOD_Return(partModule); } diff --git a/src/Mod/Part/App/AppPartPy.cpp b/src/Mod/Part/App/AppPartPy.cpp index 5c5bffd538..c8db1b0b07 100644 --- a/src/Mod/Part/App/AppPartPy.cpp +++ b/src/Mod/Part/App/AppPartPy.cpp @@ -50,6 +50,7 @@ # include # include # include +# include # include # include # include @@ -246,7 +247,7 @@ public: initialize("This is a module working with the BRepFeat package."); // register with Python } - virtual ~BRepFeatModule() {} + ~BRepFeatModule() override {} }; class BRepOffsetAPIModule : public Py::ExtensionModule @@ -257,7 +258,7 @@ public: initialize("This is a module working with the BRepOffsetAPI package."); // register with Python } - virtual ~BRepOffsetAPIModule() {} + ~BRepOffsetAPIModule() override {} }; class Geom2dModule : public Py::ExtensionModule @@ -268,7 +269,7 @@ public: initialize("This is a module working with 2d geometries."); // register with Python } - virtual ~Geom2dModule() {} + ~Geom2dModule() override {} }; class GeomPlateModule : public Py::ExtensionModule @@ -279,7 +280,7 @@ public: initialize("This is a module working with the GeomPlate framework."); // register with Python } - virtual ~GeomPlateModule() {} + ~GeomPlateModule() override {} }; class HLRBRepModule : public Py::ExtensionModule @@ -290,7 +291,7 @@ public: initialize("This is a module working with the HLRBRep framework."); // register with Python } - virtual ~HLRBRepModule() {} + ~HLRBRepModule() override {} }; class ShapeFixModule : public Py::ExtensionModule @@ -319,7 +320,7 @@ public: initialize("This is a module working with the ShapeFix framework."); // register with Python } - virtual ~ShapeFixModule() {} + ~ShapeFixModule() override {} private: Py::Object sameParameter(const Py::Tuple& args) @@ -389,7 +390,7 @@ public: initialize("This is a module working with the ShapeUpgrade framework."); // register with Python } - virtual ~ShapeUpgradeModule() {} + ~ShapeUpgradeModule() override {} }; class ChFi2dModule : public Py::ExtensionModule @@ -400,7 +401,7 @@ public: initialize("This is a module working with the ChFi2d framework."); // register with Python } - virtual ~ChFi2dModule() {} + ~ChFi2dModule() override {} }; class Module : public Py::ExtensionModule @@ -444,6 +445,9 @@ public: "makeFace(list_of_shapes_or_compound, maker_class_name) -- Create a face (faces) using facemaker class.\n" "maker_class_name is a string like 'Part::FaceMakerSimple'." ); + add_varargs_method("makeFilledSurface",&Module::makeFilledSurface, + "makeFilledSurface(list of curves, tolerance) -- Create a surface out of a list of curves." + ); add_varargs_method("makeFilledFace",&Module::makeFilledFace, "makeFilledFace(list) -- Create a face out of a list of edges." ); @@ -608,7 +612,7 @@ public: ); add_keyword_method("getShape",&Module::getShape, "getShape(obj,subname=None,mat=None,needSubElement=False,transform=True,retType=0):\n" - "Obtain the the TopoShape of a given object with SubName reference\n\n" + "Obtain the TopoShape of a given object with SubName reference\n\n" "* obj: the input object\n" "* subname: dot separated sub-object reference\n" "* mat: the current transformation matrix\n" @@ -643,10 +647,10 @@ public: PyModule_AddObject(m_module, "ChFi2d", chFi2d.module().ptr()); } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_keyword( void *method_def, + Py::Object invoke_method_keyword( void *method_def, const Py::Tuple &args, const Py::Dict &keywords ) override { try { @@ -680,7 +684,7 @@ private: } } - virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override + Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); @@ -1012,6 +1016,38 @@ private: throw Py::Exception(); } } + Py::Object makeFilledSurface(const Py::Tuple &args) + { + PyObject *obj; + double tolerance; + if (!PyArg_ParseTuple(args.ptr(), "Od", &obj, &tolerance)) + throw Py::Exception(); + + try { + GeomFill_Generator generator; + Py::Sequence list(obj); + for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { + if (PyObject_TypeCheck((*it).ptr(), &(Part::GeometryCurvePy::Type))) { + Handle(Geom_Curve) hCurve = Handle(Geom_Curve)::DownCast(static_cast((*it).ptr())->getGeomCurvePtr()->handle()); + if (!hCurve.IsNull()) { + generator.AddCurve(hCurve); + } + } + } + + generator.Perform(tolerance); + Handle(Geom_Surface) hSurface = generator.Surface(); + if (!hSurface.IsNull()) { + return Py::asObject(makeFromSurface(hSurface)->getPyObject()); + } + else { + throw Py::Exception(PartExceptionOCCError, "Failed to created surface by filling curves"); + } + } + catch (Standard_Failure& e) { + throw Py::Exception(PartExceptionOCCError, e.GetMessageString()); + } + } Py::Object makeFilledFace(const Py::Tuple& args) { // TODO: BRepFeat_SplitShape @@ -1988,11 +2024,8 @@ private: if (!p) { throw Py::TypeError("** makeWireString can't convert PyString."); } -#if PY_VERSION_HEX >= 0x03030000 + pysize = PyUnicode_GetLength(p); -#else - pysize = PyUnicode_GetSize(p); -#endif #if PY_VERSION_HEX < 0x03090000 unichars = PyUnicode_AS_UNICODE(p); #else @@ -2000,11 +2033,8 @@ private: #endif } else if (PyUnicode_Check(intext)) { -#if PY_VERSION_HEX >= 0x03030000 pysize = PyUnicode_GetLength(intext); -#else - pysize = PyUnicode_GetSize(intext); -#endif + #if PY_VERSION_HEX < 0x03090000 unichars = PyUnicode_AS_UNICODE(intext); #else @@ -2214,7 +2244,7 @@ private: } Py::List root_list; - while(edges.size()) { + while(!edges.empty()) { std::list sorted = sort_Edges(Precision::Confusion(), edges); Py::List sorted_list; for (std::list::iterator it = sorted.begin(); it != sorted.end(); ++it) { @@ -2338,7 +2368,7 @@ private: if (!PyArg_ParseTuple(args.ptr(), "sss",&sub,&mapped,&element)) throw Py::Exception(); std::string subname(sub); - if (subname.size() && subname[subname.size()-1]!='.') + if (!subname.empty() && subname[subname.size()-1]!='.') subname += '.'; if (mapped && mapped[0]) { if (!Data::ComplexGeoData::isMappedElement(mapped)) @@ -2346,7 +2376,7 @@ private: subname += mapped; } if (element && element[0]) { - if (subname.size() && subname[subname.size()-1]!='.') + if (!subname.empty() && subname[subname.size()-1]!='.') subname += '.'; subname += element; } diff --git a/src/Mod/Part/App/ArcOfCirclePyImp.cpp b/src/Mod/Part/App/ArcOfCirclePyImp.cpp index 05c17f0a18..d48d76f122 100644 --- a/src/Mod/Part/App/ArcOfCirclePyImp.cpp +++ b/src/Mod/Part/App/ArcOfCirclePyImp.cpp @@ -40,7 +40,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfCirclePy::representation(void) const +std::string ArcOfCirclePy::representation() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfCirclePtr()->handle()); @@ -126,7 +126,7 @@ int ArcOfCirclePy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfCirclePy::getRadius(void) const +Py::Float ArcOfCirclePy::getRadius() const { return Py::Float(getGeomArcOfCirclePtr()->getRadius()); } @@ -136,7 +136,7 @@ void ArcOfCirclePy::setRadius(Py::Float arg) getGeomArcOfCirclePtr()->setRadius((double)arg); } -Py::Object ArcOfCirclePy::getCircle(void) const +Py::Object ArcOfCirclePy::getCircle() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfCirclePtr()->handle()); diff --git a/src/Mod/Part/App/ArcOfConicPyImp.cpp b/src/Mod/Part/App/ArcOfConicPyImp.cpp index b3768b921d..b795c0e220 100644 --- a/src/Mod/Part/App/ArcOfConicPyImp.cpp +++ b/src/Mod/Part/App/ArcOfConicPyImp.cpp @@ -36,7 +36,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string ArcOfConicPy::representation(void) const +std::string ArcOfConicPy::representation() const { return ""; } @@ -55,12 +55,12 @@ int ArcOfConicPy::PyInit(PyObject* /*args*/, PyObject* /*kwds*/) return -1; } -Py::Object ArcOfConicPy::getLocation(void) const +Py::Object ArcOfConicPy::getLocation() const { return Py::Vector(getGeomArcOfConicPtr()->getLocation()); } -Py::Object ArcOfConicPy::getCenter(void) const +Py::Object ArcOfConicPy::getCenter() const { return Py::Vector(getGeomArcOfConicPtr()->getCenter()); } @@ -101,7 +101,7 @@ void ArcOfConicPy::setCenter(Py::Object arg) } } -Py::Float ArcOfConicPy::getAngleXU(void) const +Py::Float ArcOfConicPy::getAngleXU() const { return Py::Float(getGeomArcOfConicPtr()->getAngleXU()); } @@ -111,7 +111,7 @@ void ArcOfConicPy::setAngleXU(Py::Float arg) getGeomArcOfConicPtr()->setAngleXU((double)arg); } -Py::Object ArcOfConicPy::getAxis(void) const +Py::Object ArcOfConicPy::getAxis() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfConicPtr()->handle()); @@ -151,7 +151,7 @@ void ArcOfConicPy::setAxis(Py::Object arg) } } -Py::Object ArcOfConicPy::getXAxis(void) const +Py::Object ArcOfConicPy::getXAxis() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfConicPtr()->handle()); @@ -191,7 +191,7 @@ void ArcOfConicPy::setXAxis(Py::Object arg) } } -Py::Object ArcOfConicPy::getYAxis(void) const +Py::Object ArcOfConicPy::getYAxis() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfConicPtr()->handle()); diff --git a/src/Mod/Part/App/ArcOfEllipsePyImp.cpp b/src/Mod/Part/App/ArcOfEllipsePyImp.cpp index cf592b4463..8275935a4b 100644 --- a/src/Mod/Part/App/ArcOfEllipsePyImp.cpp +++ b/src/Mod/Part/App/ArcOfEllipsePyImp.cpp @@ -38,7 +38,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfEllipsePy::representation(void) const +std::string ArcOfEllipsePy::representation() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfEllipsePtr()->handle()); @@ -114,7 +114,7 @@ int ArcOfEllipsePy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfEllipsePy::getMajorRadius(void) const +Py::Float ArcOfEllipsePy::getMajorRadius() const { return Py::Float(getGeomArcOfEllipsePtr()->getMajorRadius()); } @@ -124,7 +124,7 @@ void ArcOfEllipsePy::setMajorRadius(Py::Float arg) getGeomArcOfEllipsePtr()->setMajorRadius((double)arg); } -Py::Float ArcOfEllipsePy::getMinorRadius(void) const +Py::Float ArcOfEllipsePy::getMinorRadius() const { return Py::Float(getGeomArcOfEllipsePtr()->getMinorRadius()); } @@ -134,7 +134,7 @@ void ArcOfEllipsePy::setMinorRadius(Py::Float arg) getGeomArcOfEllipsePtr()->setMinorRadius((double)arg); } -Py::Object ArcOfEllipsePy::getEllipse(void) const +Py::Object ArcOfEllipsePy::getEllipse() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfEllipsePtr()->handle()); diff --git a/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp b/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp index 437557339a..5276b7cdfa 100644 --- a/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp +++ b/src/Mod/Part/App/ArcOfHyperbolaPyImp.cpp @@ -38,7 +38,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfHyperbolaPy::representation(void) const +std::string ArcOfHyperbolaPy::representation() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfHyperbolaPtr()->handle()); @@ -114,7 +114,7 @@ int ArcOfHyperbolaPy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfHyperbolaPy::getMajorRadius(void) const +Py::Float ArcOfHyperbolaPy::getMajorRadius() const { return Py::Float(getGeomArcOfHyperbolaPtr()->getMajorRadius()); } @@ -124,7 +124,7 @@ void ArcOfHyperbolaPy::setMajorRadius(Py::Float arg) getGeomArcOfHyperbolaPtr()->setMajorRadius((double)arg); } -Py::Float ArcOfHyperbolaPy::getMinorRadius(void) const +Py::Float ArcOfHyperbolaPy::getMinorRadius() const { return Py::Float(getGeomArcOfHyperbolaPtr()->getMinorRadius()); } @@ -134,7 +134,7 @@ void ArcOfHyperbolaPy::setMinorRadius(Py::Float arg) getGeomArcOfHyperbolaPtr()->setMinorRadius((double)arg); } -Py::Object ArcOfHyperbolaPy::getHyperbola(void) const +Py::Object ArcOfHyperbolaPy::getHyperbola() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfHyperbolaPtr()->handle()); diff --git a/src/Mod/Part/App/ArcOfParabolaPyImp.cpp b/src/Mod/Part/App/ArcOfParabolaPyImp.cpp index beeaac9e63..98b0fc3d84 100644 --- a/src/Mod/Part/App/ArcOfParabolaPyImp.cpp +++ b/src/Mod/Part/App/ArcOfParabolaPyImp.cpp @@ -38,7 +38,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfParabolaPy::representation(void) const +std::string ArcOfParabolaPy::representation() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfParabolaPtr()->handle()); @@ -112,7 +112,7 @@ int ArcOfParabolaPy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfParabolaPy::getFocal(void) const +Py::Float ArcOfParabolaPy::getFocal() const { return Py::Float(getGeomArcOfParabolaPtr()->getFocal()); } @@ -122,7 +122,7 @@ void ArcOfParabolaPy::setFocal(Py::Float arg) getGeomArcOfParabolaPtr()->setFocal((double)arg); } -Py::Object ArcOfParabolaPy::getParabola(void) const +Py::Object ArcOfParabolaPy::getParabola() const { Handle(Geom_TrimmedCurve) trim = Handle(Geom_TrimmedCurve)::DownCast (getGeomArcOfParabolaPtr()->handle()); diff --git a/src/Mod/Part/App/ArcPyImp.cpp b/src/Mod/Part/App/ArcPyImp.cpp index a3e5908e6b..8ccf6627ab 100644 --- a/src/Mod/Part/App/ArcPyImp.cpp +++ b/src/Mod/Part/App/ArcPyImp.cpp @@ -48,7 +48,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcPy::representation(void) const +std::string ArcPy::representation() const { return ""; } diff --git a/src/Mod/Part/App/AttachEnginePyImp.cpp b/src/Mod/Part/App/AttachEnginePyImp.cpp index adee423c4f..f160a0b8f5 100644 --- a/src/Mod/Part/App/AttachEnginePyImp.cpp +++ b/src/Mod/Part/App/AttachEnginePyImp.cpp @@ -38,7 +38,7 @@ using namespace Attacher; // returns a string which represents the object e.g. when printed in python -std::string AttachEnginePy::representation(void) const +std::string AttachEnginePy::representation() const { return std::string(""); } @@ -92,7 +92,7 @@ int AttachEnginePy::PyInit(PyObject* args, PyObject* /*kwd*/) } -Py::String AttachEnginePy::getAttacherType(void) const +Py::String AttachEnginePy::getAttacherType() const { return Py::String(std::string(this->getAttachEnginePtr()->getTypeId().getName())); } @@ -110,7 +110,7 @@ Py::String AttachEnginePy::getAttacherType(void) const throw Py::Exception();\ } -Py::String AttachEnginePy::getMode(void) const +Py::String AttachEnginePy::getMode() const { try { AttachEngine &attacher = *(this->getAttachEnginePtr()); @@ -127,7 +127,7 @@ void AttachEnginePy::setMode(Py::String arg) } ATTACHERPY_STDCATCH_ATTR; } -Py::Object AttachEnginePy::getReferences(void) const +Py::Object AttachEnginePy::getReferences() const { try { AttachEngine &attacher = *(this->getAttachEnginePtr()); @@ -144,7 +144,7 @@ void AttachEnginePy::setReferences(Py::Object arg) } ATTACHERPY_STDCATCH_ATTR; } -Py::Object AttachEnginePy::getAttachmentOffset(void) const +Py::Object AttachEnginePy::getAttachmentOffset() const { try { AttachEngine &attacher = *(this->getAttachEnginePtr()); @@ -167,7 +167,7 @@ void AttachEnginePy::setAttachmentOffset(Py::Object arg) } ATTACHERPY_STDCATCH_ATTR; } -Py::Boolean AttachEnginePy::getReverse(void) const +Py::Boolean AttachEnginePy::getReverse() const { try { AttachEngine &attacher = *(this->getAttachEnginePtr()); @@ -183,7 +183,7 @@ void AttachEnginePy::setReverse(Py::Boolean arg) } ATTACHERPY_STDCATCH_ATTR; } -Py::Float AttachEnginePy::getParameter(void) const +Py::Float AttachEnginePy::getParameter() const { try { AttachEngine &attacher = *(this->getAttachEnginePtr()); @@ -200,7 +200,7 @@ void AttachEnginePy::setParameter(Py::Float arg) } -Py::List AttachEnginePy::getCompleteModeList(void) const +Py::List AttachEnginePy::getCompleteModeList() const { try { Py::List ret; @@ -212,7 +212,7 @@ Py::List AttachEnginePy::getCompleteModeList(void) const } ATTACHERPY_STDCATCH_ATTR; } -Py::List AttachEnginePy::getCompleteRefTypeList(void) const +Py::List AttachEnginePy::getCompleteRefTypeList() const { try { Py::List ret; @@ -224,13 +224,13 @@ Py::List AttachEnginePy::getCompleteRefTypeList(void) const } ATTACHERPY_STDCATCH_ATTR; } -Py::List AttachEnginePy::getImplementedModes(void) const +Py::List AttachEnginePy::getImplementedModes() const { try { Py::List ret; AttachEngine &attacher = *(this->getAttachEnginePtr()); for(int imode = 0 ; imode < mmDummy_NumberOfModes ; imode++){ - if(attacher.modeRefTypes[imode].size() > 0){ + if(!attacher.modeRefTypes[imode].empty()){ ret.append(Py::String(attacher.getModeName(eMapMode(imode)))); } } diff --git a/src/Mod/Part/App/AttachExtension.cpp b/src/Mod/Part/App/AttachExtension.cpp index ab2e2eedd8..fae069f712 100644 --- a/src/Mod/Part/App/AttachExtension.cpp +++ b/src/Mod/Part/App/AttachExtension.cpp @@ -141,7 +141,7 @@ bool AttachExtension::isAttacherActive() const { return _active!=0; } -short int AttachExtension::extensionMustExecute(void) { +short int AttachExtension::extensionMustExecute() { return DocumentObjectExtension::extensionMustExecute(); } @@ -274,7 +274,7 @@ App::PropertyPlacement& AttachExtension::getPlacement() const { return *pla; } -PyObject* AttachExtension::getExtensionPyObject(void) { +PyObject* AttachExtension::getExtensionPyObject() { if (ExtensionPythonObject.is(Py::_None())){ // ref counter is set to 1 diff --git a/src/Mod/Part/App/AttachExtension.h b/src/Mod/Part/App/AttachExtension.h index e2d61012cf..c93521363d 100644 --- a/src/Mod/Part/App/AttachExtension.h +++ b/src/Mod/Part/App/AttachExtension.h @@ -46,10 +46,10 @@ class PartExport AttachEngineException : public Base::Exception public: /// Construction AttachEngineException(); - AttachEngineException(const char * sMessage); - AttachEngineException(const std::string& sMessage); + explicit AttachEngineException(const char * sMessage); + explicit AttachEngineException(const std::string& sMessage); /// Destruction - virtual ~AttachEngineException() throw() {} + ~AttachEngineException() throw() override {} }; /** @@ -59,10 +59,10 @@ public: */ class PartExport AttachExtension : public App::DocumentObjectExtension { - EXTENSION_PROPERTY_HEADER(Part::AttachableObject); + EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Part::AttachableObject); public: AttachExtension(); - virtual ~AttachExtension(); + ~AttachExtension() override; /** * @brief setAttacher sets the AttachEngine object. The class takes the @@ -81,7 +81,7 @@ public: */ bool changeAttacherType(const char* typeName); - Attacher::AttachEngine &attacher(void) const {if(!_attacher) throw AttachEngineException("AttachableObject: no attacher is set."); return *_attacher;} + Attacher::AttachEngine &attacher() const {if(!_attacher) throw AttachEngineException("AttachableObject: no attacher is set."); return *_attacher;} App::PropertyString AttacherType; @@ -101,7 +101,7 @@ public: * mode. Can throw FreeCAD and OCC exceptions. Returns true if attached, * false if not, throws if attachment failed. */ - virtual bool positionBySupport(void); + virtual bool positionBySupport(); /** Return whether this attacher is active */ @@ -110,13 +110,13 @@ public: virtual bool isTouched_Mapping() {return true; /*support.isTouched isn't true when linked objects are changed... why?..*/} - virtual short int extensionMustExecute(void); - virtual App::DocumentObjectExecReturn *extensionExecute(void); - virtual PyObject* getExtensionPyObject(void); - virtual void onExtendedDocumentRestored(); + short int extensionMustExecute() override; + App::DocumentObjectExecReturn *extensionExecute() override; + PyObject* getExtensionPyObject() override; + void onExtendedDocumentRestored() override; protected: - virtual void extensionOnChanged(const App::Property* /*prop*/); + void extensionOnChanged(const App::Property* /*prop*/) override; virtual void extHandleChangedPropertyName(Base::XMLReader &reader, const char* TypeName, const char* PropName); App::PropertyPlacement& getPlacement() const; diff --git a/src/Mod/Part/App/AttachExtensionPyImp.cpp b/src/Mod/Part/App/AttachExtensionPyImp.cpp index 57f7522fa2..d9fd263565 100644 --- a/src/Mod/Part/App/AttachExtensionPyImp.cpp +++ b/src/Mod/Part/App/AttachExtensionPyImp.cpp @@ -31,7 +31,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string AttachExtensionPy::representation(void) const +std::string AttachExtensionPy::representation() const { return std::string(""); } @@ -71,7 +71,7 @@ PyObject* AttachExtensionPy::changeAttacherType(PyObject *args) return Py::new_reference_to(Py::Boolean(ret)); } -Py::Object AttachExtensionPy::getAttacher(void) const +Py::Object AttachExtensionPy::getAttacher() const { try { this->getAttachExtensionPtr()->attacher(); //throws if attacher is not set diff --git a/src/Mod/Part/App/Attacher.cpp b/src/Mod/Part/App/Attacher.cpp index 888864207d..5f3289575b 100644 --- a/src/Mod/Part/App/Attacher.cpp +++ b/src/Mod/Part/App/Attacher.cpp @@ -398,7 +398,7 @@ void AttachEngine::suggestMapModes(SuggestResult &result) const } } if (score > 0){ - if(mlist.size() == 0) + if(mlist.empty()) mlist.push_back(eMapMode(iMode)); else if (mlist.back() != eMapMode(iMode)) mlist.push_back(eMapMode(iMode)); @@ -413,7 +413,7 @@ void AttachEngine::EnableAllSupportedModes() this->modeEnabled.resize(mmDummy_NumberOfModes,false); assert(modeRefTypes.size() > 0); for (std::size_t i = 0; i < this->modeEnabled.size(); i++) { - modeEnabled[i] = modeRefTypes[i].size() > 0; + modeEnabled[i] = !modeRefTypes[i].empty(); } } @@ -988,7 +988,7 @@ Base::Placement AttachEngine3D::calculateAttachedPlacement(const Base::Placement std::vector types; readLinks(this->references, parts, shapes, copiedShapeStorage, types); - if (parts.size() == 0) + if (parts.empty()) throw ExceptionCancel(); @@ -1010,7 +1010,7 @@ Base::Placement AttachEngine3D::calculateAttachedPlacement(const Base::Placement //should have been filtered out already! break; case mmTranslate:{ - if (shapes.size() < 1) + if (shapes.empty()) throw Base::ValueError("AttachEngine3D::calculateAttachedPlacement: no subobjects specified (need one vertex)."); const TopoDS_Shape &sh = *shapes[0]; if (sh.IsNull()) @@ -1116,7 +1116,7 @@ Base::Placement AttachEngine3D::calculateAttachedPlacement(const Base::Placement SketchBasePoint = gpr.CentreOfMass(); }break; case mmFlatFace:{ - if (shapes.size() < 1) + if (shapes.empty()) throw Base::ValueError("AttachEngine3D::calculateAttachedPlacement: no subobjects specified (needed one planar face)."); const TopoDS_Face &face = TopoDS::Face(*(shapes[0])); @@ -1222,7 +1222,7 @@ Base::Placement AttachEngine3D::calculateAttachedPlacement(const Base::Placement case mmFrenetTB: case mmRevolutionSection: case mmConcentric: {//all alignments to point on curve - if (shapes.size() < 1) + if (shapes.empty()) throw Base::ValueError("AttachEngine3D::calculateAttachedPlacement: no subshapes specified (need one edge, and an optional vertex)."); bool bThruVertex = false; @@ -1756,7 +1756,7 @@ Base::Placement AttachEngineLine::calculateAttachedPlacement(const Base::Placeme std::vector types; readLinks(this->references, parts, shapes, copiedShapeStorage, types); - if (parts.size() == 0) + if (parts.empty()) throw ExceptionCancel(); diff --git a/src/Mod/Part/App/Attacher.h b/src/Mod/Part/App/Attacher.h index cc72fdcbd9..dd62bb7ead 100644 --- a/src/Mod/Part/App/Attacher.h +++ b/src/Mod/Part/App/Attacher.h @@ -212,7 +212,7 @@ struct SuggestResult{ */ class PartExport AttachEngine : public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: //methods AttachEngine(); virtual void setUp(const App::PropertyLinkSubList &references, @@ -284,9 +284,9 @@ public: //methods /** * @brief EnableAllModes enables all modes that have shape type lists filled. The function acts on modeEnabled array. */ - void EnableAllSupportedModes(void); + void EnableAllSupportedModes(); - virtual ~AttachEngine(){}; + ~AttachEngine() override{}; public://helper functions that may be useful outside of the class /** @@ -417,11 +417,11 @@ protected: class PartExport AttachEngine3D : public AttachEngine { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: AttachEngine3D(); - virtual AttachEngine3D* copy() const; - virtual Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const; + AttachEngine3D* copy() const override; + Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const override; private: double calculateFoldAngle(gp_Vec axA, gp_Vec axB, gp_Vec edA, gp_Vec edB) const; }; @@ -429,31 +429,31 @@ private: //attacher specialized for datum planes class PartExport AttachEnginePlane : public AttachEngine { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: AttachEnginePlane(); - virtual AttachEnginePlane* copy() const; - virtual Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const; + AttachEnginePlane* copy() const override; + Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const override; }; //attacher specialized for datum lines class PartExport AttachEngineLine : public AttachEngine { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: AttachEngineLine(); - virtual AttachEngineLine* copy() const; - virtual Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const; + AttachEngineLine* copy() const override; + Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const override; }; //attacher specialized for datum points class PartExport AttachEnginePoint : public AttachEngine { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: AttachEnginePoint(); - virtual AttachEnginePoint* copy() const; - virtual Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const; + AttachEnginePoint* copy() const override; + Base::Placement calculateAttachedPlacement(const Base::Placement& origPlacement) const override; private: gp_Pnt getProximityPoint(eMapMode mode, const TopoDS_Shape& s1, const TopoDS_Shape& s2) const; @@ -465,8 +465,8 @@ class ExceptionCancel : public Base::Exception { public: ExceptionCancel(){} - ExceptionCancel(char* msg){this->setMessage(msg);} - virtual ~ExceptionCancel() throw() {} + explicit ExceptionCancel(char* msg){this->setMessage(msg);} + ~ExceptionCancel() throw() override {} }; } // namespace Attacher diff --git a/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp b/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp index 99f5f29729..e2cb79d59e 100644 --- a/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp +++ b/src/Mod/Part/App/BRepFeat/MakePrismPyImp.cpp @@ -97,7 +97,7 @@ int MakePrismPy::PyInit(PyObject* args, PyObject* kwds) } // returns a string which represents the object e.g. when printed in python -std::string MakePrismPy::representation(void) const +std::string MakePrismPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp b/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp index a07d38e8be..2693221009 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeFillingPyImp.cpp @@ -114,7 +114,7 @@ int BRepOffsetAPI_MakeFillingPy::PyInit(PyObject* args, PyObject* kwds) } // returns a string which represents the object e.g. when printed in python -std::string BRepOffsetAPI_MakeFillingPy::representation(void) const +std::string BRepOffsetAPI_MakeFillingPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp index 85273198ba..7ffd399233 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.cpp @@ -103,7 +103,11 @@ void BRepOffsetAPI_MakeOffsetFix::Perform (const Standard_Real Offset, const Sta mkOffset.Perform(Offset, Alt); } +#if OCC_VERSION_HEX >= 0x070600 +void BRepOffsetAPI_MakeOffsetFix::Build(const Message_ProgressRange&) +#else void BRepOffsetAPI_MakeOffsetFix::Build() +#endif { mkOffset.Build(); } @@ -136,7 +140,7 @@ void BRepOffsetAPI_MakeOffsetFix::MakeWire(TopoDS_Shape& wire) } std::list edgeList; - for (auto itLoc : myLocations) { + for (const auto& itLoc : myLocations) { TopTools_ListOfShape newShapes = mkOffset.Generated(itLoc.first); // Check generated shapes for the vertexes, too TopExp_Explorer xpv(itLoc.first, TopAbs_VERTEX); @@ -252,7 +256,7 @@ TopoDS_Shape BRepOffsetAPI_MakeOffsetFix::Replace(GeomAbs_CurveType type, const xp.Next(); } - return comp; + return TopoDS_Compound(std::move(comp)); } else if (S.ShapeType() == TopAbs_WIRE) { return ReplaceEdges(type, TopoDS::Wire(S)); diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h index 2f6af6f189..a675a3c1a3 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h +++ b/src/Mod/Part/App/BRepOffsetAPI_MakeOffsetFix.h @@ -30,6 +30,7 @@ #include #include +#include namespace Part { @@ -44,7 +45,7 @@ class PartExport BRepOffsetAPI_MakeOffsetFix : public BRepBuilderAPI_MakeShape public: BRepOffsetAPI_MakeOffsetFix(); BRepOffsetAPI_MakeOffsetFix(const GeomAbs_JoinType Join, const Standard_Boolean IsOpenResult); - virtual ~BRepOffsetAPI_MakeOffsetFix(); + ~BRepOffsetAPI_MakeOffsetFix() override; //! Initializes the algorithm to construct parallels to the wire Spine. void AddWire (const TopoDS_Wire& Spine); @@ -56,7 +57,11 @@ public: void Perform (const Standard_Real Offset, const Standard_Real Alt = 0.0); //! Builds the resulting shape (redefined from MakeShape). - void Build(); +#if OCC_VERSION_HEX >= 0x070600 + void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) override; +#else + void Build() override; +#endif //! Initializes the algorithm to construct parallels to the spine Spine. //! Join defines the type of parallel generated by the @@ -71,22 +76,22 @@ public: //! Initialize the evaluation of Offsetting. void Init(const GeomAbs_JoinType Join = GeomAbs_Arc, const Standard_Boolean IsOpenResult = Standard_False); - virtual Standard_Boolean IsDone() const; + Standard_Boolean IsDone() const override; //! Returns a shape built by the shape construction algorithm. //! Raises exception StdFail_NotDone if the shape was not built. - virtual const TopoDS_Shape& Shape(); + const TopoDS_Shape& Shape() override; //! returns a list of the created shapes //! from the shape . - virtual const TopTools_ListOfShape& Generated (const TopoDS_Shape& S); + const TopTools_ListOfShape& Generated (const TopoDS_Shape& S) override; //! Returns the list of shapes modified from the shape //! . - virtual const TopTools_ListOfShape& Modified (const TopoDS_Shape& S); + const TopTools_ListOfShape& Modified (const TopoDS_Shape& S) override; //! Returns true if the shape S has been deleted. - virtual Standard_Boolean IsDeleted (const TopoDS_Shape& S); + Standard_Boolean IsDeleted (const TopoDS_Shape& S) override; //! Replaces the given curve type with a B-Spline. Input shape //! must be a wire or a compound of wires diff --git a/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp b/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp index 592d2cd387..d43f4b4ed7 100644 --- a/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp +++ b/src/Mod/Part/App/BRepOffsetAPI_MakePipeShellPyImp.cpp @@ -66,7 +66,7 @@ int BRepOffsetAPI_MakePipeShellPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) } // returns a string which represents the object e.g. when printed in python -std::string BRepOffsetAPI_MakePipeShellPy::representation(void) const +std::string BRepOffsetAPI_MakePipeShellPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/BSplineCurvePy.xml b/src/Mod/Part/App/BSplineCurvePy.xml index 32529fdff5..a37377a614 100644 --- a/src/Mod/Part/App/BSplineCurvePy.xml +++ b/src/Mod/Part/App/BSplineCurvePy.xml @@ -1,20 +1,20 @@ - - - - Describes a B-Spline curve in 3D space - + FatherNamespace="Part" + Constructor="true"> + + + Describes a B-Spline curve in 3D space + __reduce__() @@ -23,446 +23,456 @@ Serialization of Part.BSplineCurve objects - - Returns the polynomial degree of this B-Spline curve. - - - - - - Returns the value of the maximum polynomial degree of any + + Returns the polynomial degree of this B-Spline curve. + + + + + + Returns the value of the maximum polynomial degree of any B-Spline curve curve. This value is 25. - - - - - - Returns the number of poles of this B-Spline curve. - - - - - - - - Returns the number of knots of this B-Spline curve. - - - - - - - Returns the start point of this B-Spline curve. - - - - - - Returns the end point of this B-Spline curve. - - - - - - Returns the index in the knot array of the knot + + + + + + Returns the number of poles of this B-Spline curve. + + + + + + + + Returns the number of knots of this B-Spline curve. + + + + + + + Returns the start point of this B-Spline curve. + + + + + + Returns the end point of this B-Spline curve. + + + + + + Returns the index in the knot array of the knot corresponding to the first or last parameter of this B-Spline curve. - - - - - - Returns the index in the knot array of the knot + + + + + + Returns the index in the knot array of the knot corresponding to the first or last parameter of this B-Spline curve. - - - - - - Returns the knots sequence of this B-Spline curve. - - - + + + + + + Returns the knots sequence of this B-Spline curve. + + + - - - Returns true if this B-Spline curve is rational. - A B-Spline curve is rational if, at the time of construction, - the weight table has been initialized. - - - + + + Returns true if this B-Spline curve is rational. + A B-Spline curve is rational if, at the time of construction, + the weight table has been initialized. + + + - - Returns true if this BSpline curve is periodic. - - + + Returns true if this BSpline curve is periodic. + + - - - Returns true if the distance between the start point and end point of - this B-Spline curve is less than or equal to gp::Resolution(). - - - - - - increase(Int=Degree) + + + Returns true if the distance between the start point and end point of + this B-Spline curve is less than or equal to gp::Resolution(). + + + + + + increase(Int=Degree) Increases the degree of this B-Spline curve to Degree. As a result, the poles, weights and multiplicities tables are modified; the knots table is not changed. Nothing is done if Degree is less than or equal to the current degree. - - - - - - increaseMultiplicity(int index, int mult) - increaseMultiplicity(int start, int end, int mult) - Increases multiplicity of knots up to mult. + + + + + + increaseMultiplicity(int index, int mult) + increaseMultiplicity(int start, int end, int mult) + Increases multiplicity of knots up to mult. - index: the index of a knot to modify (1-based) - start, end: index range of knots to modify. - If mult is lower or equal to the current multiplicity nothing is done. If mult is higher than the degree the degree is used. - - - - - - - incrementMultiplicity(int start, int end, int mult) - Raises multiplicity of knots by mult. + index: the index of a knot to modify (1-based) + start, end: index range of knots to modify. + If mult is lower or equal to the current multiplicity nothing is done. If mult is higher than the degree the degree is used. + + + + + + + incrementMultiplicity(int start, int end, int mult) + Raises multiplicity of knots by mult. - start, end: index range of knots to modify. - - - - - - - insertKnot(u, mult = 1, tol = 0.0) - Inserts a knot value in the sequence of knots. If u is an existing knot the - multiplicity is increased by mult. - - - - - - insertKnots(list_of_floats, list_of_ints, tol = 0.0, bool_add = True) - Inserts a set of knots values in the sequence of knots. + start, end: index range of knots to modify. + + + + + + + insertKnot(u, mult = 1, tol = 0.0) + Inserts a knot value in the sequence of knots. If u is an existing knot the + multiplicity is increased by mult. + + + + + + insertKnots(list_of_floats, list_of_ints, tol = 0.0, bool_add = True) + Inserts a set of knots values in the sequence of knots. - For each u = list_of_floats[i], mult = list_of_ints[i] + For each u = list_of_floats[i], mult = list_of_ints[i] - If u is an existing knot the multiplicity is increased by mult if bool_add is - True, otherwise increased to mult. + If u is an existing knot the multiplicity is increased by mult if bool_add is + True, otherwise increased to mult. - If u is not on the parameter range nothing is done. + If u is not on the parameter range nothing is done. - If the multiplicity is negative or null nothing is done. The new multiplicity - is limited to the degree. + If the multiplicity is negative or null nothing is done. The new multiplicity + is limited to the degree. - The tolerance criterion for knots equality is the max of Epsilon(U) and ParametricTolerance. - - - - - - - removeKnot(Index, M, tol) + The tolerance criterion for knots equality is the max of Epsilon(U) and ParametricTolerance. + + + + + + + removeKnot(Index, M, tol) - Reduces the multiplicity of the knot of index Index to M. - If M is equal to 0, the knot is removed. - With a modification of this type, the array of poles is also modified. - Two different algorithms are systematically used to compute the new - poles of the curve. If, for each pole, the distance between the pole - calculated using the first algorithm and the same pole calculated using - the second algorithm, is less than Tolerance, this ensures that the curve - is not modified by more than Tolerance. Under these conditions, true is - returned; otherwise, false is returned. + Reduces the multiplicity of the knot of index Index to M. + If M is equal to 0, the knot is removed. + With a modification of this type, the array of poles is also modified. + Two different algorithms are systematically used to compute the new + poles of the curve. If, for each pole, the distance between the pole + calculated using the first algorithm and the same pole calculated using + the second algorithm, is less than Tolerance, this ensures that the curve + is not modified by more than Tolerance. Under these conditions, true is + returned; otherwise, false is returned. - A low tolerance is used to prevent modification of the curve. - A high tolerance is used to 'smooth' the curve. - - - - - - - segment(u1,u2) - Modifies this B-Spline curve by segmenting it. - - - - - Set a knot of the B-Spline curve. - - + A low tolerance is used to prevent modification of the curve. + A high tolerance is used to 'smooth' the curve. + + + + + + + segment(u1,u2) + Modifies this B-Spline curve by segmenting it. + + + + + Set a knot of the B-Spline curve. + + - - Get a knot of the B-Spline curve. - - - - - Set knots of the B-Spline curve. - - + + Get a knot of the B-Spline curve. + + + + + Set knots of the B-Spline curve. + + - - Get all knots of the B-Spline curve. - - - - - Modifies this B-Spline curve by assigning P + + Get all knots of the B-Spline curve. + + + + + Modifies this B-Spline curve by assigning P to the pole of index Index in the poles table. - - + + - - Get a pole of the B-Spline curve. - - + + Get a pole of the B-Spline curve. + + - - Get all poles of the B-Spline curve. - - - - - Set a weight of the B-Spline curve. - - + + Get all poles of the B-Spline curve. + + + + + Set a weight of the B-Spline curve. + + - - Get a weight of the B-Spline curve. - - + + Get a weight of the B-Spline curve. + + - - Get all weights of the B-Spline curve. - - + + Get all weights of the B-Spline curve. + + - - Returns the table of poles and weights in homogeneous coordinates. - - - - - Computes for this B-Spline curve the parametric tolerance (UTolerance) + + Returns the table of poles and weights in homogeneous coordinates. + + + + + Computes for this B-Spline curve the parametric tolerance (UTolerance) for a given 3D tolerance (Tolerance3D). If f(t) is the equation of this B-Spline curve, the parametric tolerance ensures that: |t1-t0| < UTolerance =""==> |f(t1)-f(t0)| < Tolerance3D - - - - - - movePoint(U, P, Index1, Index2) - Moves the point of parameter U of this B-Spline curve to P. + + + + + + movePoint(U, P, Index1, Index2) + Moves the point of parameter U of this B-Spline curve to P. Index1 and Index2 are the indexes in the table of poles of this B-Spline curve of the first and last poles designated to be moved. Returns: (FirstModifiedPole, LastModifiedPole). They are the indexes of the first and last poles which are effectively modified. - - - - - Changes this B-Spline curve into a non-periodic curve. + + + + + Changes this B-Spline curve into a non-periodic curve. If this curve is already non-periodic, it is not modified. - - - - - Changes this B-Spline curve into a periodic curve. - - - - - Assigns the knot of index Index in the knots table + + + + + Changes this B-Spline curve into a periodic curve. + + + + + Assigns the knot of index Index in the knots table as the origin of this periodic B-Spline curve. As a consequence, the knots and poles tables are modified. - - + + - - Returns the multiplicity of the knot of index + + Returns the multiplicity of the knot of index from the knots table of this B-Spline curve. - - + + - - - Returns the multiplicities table M of the knots of this B-Spline curve. - - - - - - - Replaces this B-Spline curve by approximating a set of points. - The function accepts keywords as arguments. + + + Returns the multiplicities table M of the knots of this B-Spline curve. + + + + + + + Replaces this B-Spline curve by approximating a set of points. + The function accepts keywords as arguments. - approximate(Points = list_of_points) + approximate(Points = list_of_points) - Optional arguments : + Optional arguments : - DegMin = integer (3) : Minimum degree of the curve. - DegMax = integer (8) : Maximum degree of the curve. - Tolerance = float (1e-3) : approximating tolerance. - Continuity = string ('C2') : Desired continuity of the curve. - Possible values : 'C0','G1','C1','G2','C2','C3','CN' + DegMin = integer (3) : Minimum degree of the curve. + DegMax = integer (8) : Maximum degree of the curve. + Tolerance = float (1e-3) : approximating tolerance. + Continuity = string ('C2') : Desired continuity of the curve. + Possible values : 'C0','G1','C1','G2','C2','C3','CN' - LengthWeight = float, CurvatureWeight = float, TorsionWeight = float - If one of these arguments is not null, the functions approximates the - points using variational smoothing algorithm, which tries to minimize - additional criterium: - LengthWeight*CurveLength + CurvatureWeight*Curvature + TorsionWeight*Torsion + LengthWeight = float, CurvatureWeight = float, TorsionWeight = float + If one of these arguments is not null, the functions approximates the + points using variational smoothing algorithm, which tries to minimize + additional criterium: + LengthWeight*CurveLength + CurvatureWeight*Curvature + TorsionWeight*Torsion Continuity must be C0, C1(with DegMax >= 3) or C2(with DegMax >= 5). - Parameters = list of floats : knot sequence of the approximated points. - This argument is only used if the weights above are all null. + Parameters = list of floats : knot sequence of the approximated points. + This argument is only used if the weights above are all null. - ParamType = string ('Uniform','Centripetal' or 'ChordLength') - Parameterization type. Only used if weights and Parameters above aren't specified. + ParamType = string ('Uniform','Centripetal' or 'ChordLength') + Parameterization type. Only used if weights and Parameters above aren't specified. - Note : Continuity of the spline defaults to C2. However, it may not be applied if - it conflicts with other parameters ( especially DegMax ). - - - + Note : Continuity of the spline defaults to C2. However, it may not be applied if + it conflicts with other parameters ( especially DegMax ). + + + Compute the tangents for a Cardinal spline - - - Replaces this B-Spline curve by interpolating a set of points. - The function accepts keywords as arguments. + + + Replaces this B-Spline curve by interpolating a set of points. + The function accepts keywords as arguments. - interpolate(Points = list_of_points) + interpolate(Points = list_of_points) - Optional arguments : + Optional arguments : - PeriodicFlag = bool (False) : Sets the curve closed or opened. - Tolerance = float (1e-6) : interpolating tolerance + PeriodicFlag = bool (False) : Sets the curve closed or opened. + Tolerance = float (1e-6) : interpolating tolerance - Parameters : knot sequence of the interpolated points. - If not supplied, the function defaults to chord-length parameterization. - If PeriodicFlag == True, one extra parameter must be appended. + Parameters : knot sequence of the interpolated points. + If not supplied, the function defaults to chord-length parameterization. + If PeriodicFlag == True, one extra parameter must be appended. - EndPoint Tangent constraints : + EndPoint Tangent constraints : - InitialTangent = vector, FinalTangent = vector - specify tangent vectors for starting and ending points - of the BSpline. Either none, or both must be specified. + InitialTangent = vector, FinalTangent = vector + specify tangent vectors for starting and ending points + of the BSpline. Either none, or both must be specified. - Full Tangent constraints : + Full Tangent constraints : - Tangents = list_of_vectors, TangentFlags = list_of_bools - Both lists must have the same length as Points list. - Tangents specifies the tangent vector of each point in Points list. - TangentFlags (bool) activates or deactivates the corresponding tangent. - These arguments will be ignored if EndPoint Tangents (above) are also defined. + Tangents = list_of_vectors, TangentFlags = list_of_bools + Both lists must have the same length as Points list. + Tangents specifies the tangent vector of each point in Points list. + TangentFlags (bool) activates or deactivates the corresponding tangent. + These arguments will be ignored if EndPoint Tangents (above) are also defined. - Note : Continuity of the spline defaults to C2. However, if periodic, or tangents - are supplied, the continuity will drop to C1. - - - - - - - Builds a B-Spline by a list of poles. - arguments: poles (sequence of Base.Vector), [periodic (default is False), degree (default is 3), interpolate (default is False)] + Note : Continuity of the spline defaults to C2. However, if periodic, or tangents + are supplied, the continuity will drop to C1. + + + + + + + Builds a B-Spline by a list of poles. + arguments: poles (sequence of Base.Vector), [periodic (default is False), degree (default is 3), interpolate (default is False)] - Examples: - from FreeCAD import Base - import Part - V = Base.Vector - poles = [V(-2, 2, 0),V(0, 2, 1),V(2, 2, 0),V(2, -2, 0),V(0, -2, 1),V(-2, -2, 0)] + Examples: + from FreeCAD import Base + import Part + V = Base.Vector + poles = [V(-2, 2, 0),V(0, 2, 1),V(2, 2, 0),V(2, -2, 0),V(0, -2, 1),V(-2, -2, 0)] - # non-periodic spline - n=Part.BSplineCurve() - n.buildFromPoles(poles) - Part.show(n.toShape()) + # non-periodic spline + n=Part.BSplineCurve() + n.buildFromPoles(poles) + Part.show(n.toShape()) - # periodic spline - n=Part.BSplineCurve() - n.buildFromPoles(poles, True) - Part.show(n.toShape()) - - - - - - - Builds a B-Spline by a lists of Poles, Mults, Knots. - arguments: poles (sequence of Base.Vector), [mults , knots, periodic, degree, weights (sequence of float), CheckRational] + # periodic spline + n=Part.BSplineCurve() + n.buildFromPoles(poles, True) + Part.show(n.toShape()) + + + + + + + Builds a B-Spline by a lists of Poles, Mults, Knots. + arguments: poles (sequence of Base.Vector), [mults , knots, periodic, degree, weights (sequence of float), CheckRational] - Examples: - from FreeCAD import Base - import Part - V=Base.Vector - poles=[V(-10,-10),V(10,-10),V(10,10),V(-10,10)] + Examples: + from FreeCAD import Base + import Part + V=Base.Vector + poles=[V(-10,-10),V(10,-10),V(10,10),V(-10,10)] - # non-periodic spline - n=Part.BSplineCurve() - n.buildFromPolesMultsKnots(poles,(3,1,3),(0,0.5,1),False,2) - Part.show(n.toShape()) + # non-periodic spline + n=Part.BSplineCurve() + n.buildFromPolesMultsKnots(poles,(3,1,3),(0,0.5,1),False,2) + Part.show(n.toShape()) - # periodic spline - p=Part.BSplineCurve() - p.buildFromPolesMultsKnots(poles,(1,1,1,1,1),(0,0.25,0.5,0.75,1),True,2) - Part.show(p.toShape()) + # periodic spline + p=Part.BSplineCurve() + p.buildFromPolesMultsKnots(poles,(1,1,1,1,1),(0,0.25,0.5,0.75,1),True,2) + Part.show(p.toShape()) - # periodic and rational spline - r=Part.BSplineCurve() - r.buildFromPolesMultsKnots(poles,(1,1,1,1,1),(0,0.25,0.5,0.75,1),True,2,(1,0.8,0.7,0.2)) - Part.show(r.toShape()) - - - + # periodic and rational spline + r=Part.BSplineCurve() + r.buildFromPolesMultsKnots(poles,(1,1,1,1,1),(0,0.25,0.5,0.75,1),True,2,(1,0.8,0.7,0.2)) + Part.show(r.toShape()) + + + - - - Build a list of Bezier splines. - - - + + + Build a list of Bezier splines. + + + - - - Build a list of arcs and lines to approximate the B-spline. - toBiArcs(tolerance) -> list. - - - - - - - Build a new spline by joining this and a second spline. - - - - - - - makeC1Continuous(tol = 1e-6, ang_tol = 1e-7) - Reduces as far as possible the multiplicities of the knots of this BSpline - (keeping the geometry). It returns a new BSpline, which could still be C0. - tol is a geometrical tolerance. - The tol_ang is angular tolerance, in radians. It sets tolerable angle mismatch - of the tangents on the left and on the right to decide if the curve is G1 or - not at a given point. - - - - + + + Build a list of arcs and lines to approximate the B-spline. + toBiArcs(tolerance) -> list. + + + + + + + Build a new spline by joining this and a second spline. + + + + + + + makeC1Continuous(tol = 1e-6, ang_tol = 1e-7) + Reduces as far as possible the multiplicities of the knots of this BSpline + (keeping the geometry). It returns a new BSpline, which could still be C0. + tol is a geometrical tolerance. + The tol_ang is angular tolerance, in radians. It sets tolerable angle mismatch + of the tangents on the left and on the right to decide if the curve is G1 or + not at a given point. + + + + + + + Scales the knots list to fit the specified bounds. + The shape of the curve is not modified. + bspline_curve.scaleKnotsToBounds(u0, u1) + Default arguments are (0.0, 1.0) + + + + diff --git a/src/Mod/Part/App/BSplineCurvePyImp.cpp b/src/Mod/Part/App/BSplineCurvePyImp.cpp index 14932d2c14..5bedfa679c 100644 --- a/src/Mod/Part/App/BSplineCurvePyImp.cpp +++ b/src/Mod/Part/App/BSplineCurvePyImp.cpp @@ -50,7 +50,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BSplineCurvePy::representation(void) const +std::string BSplineCurvePy::representation() const { return ""; } @@ -72,7 +72,7 @@ int BSplineCurvePy::PyInit(PyObject* args, PyObject* kwd) PyObject* obj; // poles, [ periodic, degree, interpolate ] // {"poles", "mults", "knots", "periodic", "degree", "weights", "CheckRational", NULL}; - obj = buildFromPolesMultsKnots(args,kwd); + obj = buildFromPolesMultsKnots(args, kwd); if (obj) { Py_DECREF(obj); @@ -154,7 +154,7 @@ PyObject* BSplineCurvePy::increaseDegree(PyObject * args) (getGeometryPtr()->handle()); curve->IncreaseDegree(degree); Py_Return; - } PY_CATCH_OCC ; + } PY_CATCH_OCC; } PyObject* BSplineCurvePy::increaseMultiplicity(PyObject * args) @@ -236,14 +236,14 @@ PyObject* BSplineCurvePy::insertKnots(PyObject * args) try { Py::Sequence knots(obj1); - TColStd_Array1OfReal k(1,knots.size()); + TColStd_Array1OfReal k(1, knots.size()); int index=1; for (Py::Sequence::iterator it = knots.begin(); it != knots.end(); ++it) { Py::Float val(*it); k(index++) = (double)val; } Py::Sequence mults(obj2); - TColStd_Array1OfInteger m(1,mults.size()); + TColStd_Array1OfInteger m(1, mults.size()); index=1; for (Py::Sequence::iterator it = mults.begin(); it != mults.end(); ++it) { Py::Long val(*it); @@ -266,14 +266,14 @@ PyObject* BSplineCurvePy::insertKnots(PyObject * args) PyObject* BSplineCurvePy::removeKnot(PyObject * args) { double tol; - int Index,M; + int Index, M; if (!PyArg_ParseTuple(args, "iid", &Index, &M, &tol)) return nullptr; try { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); - Standard_Boolean ok = curve->RemoveKnot(Index,M,tol); + Standard_Boolean ok = curve->RemoveKnot(Index, M, tol); return PyBool_FromLong(ok ? 1 : 0); } catch (Standard_Failure& e) { @@ -284,22 +284,22 @@ PyObject* BSplineCurvePy::removeKnot(PyObject * args) PyObject* BSplineCurvePy::segment(PyObject * args) { - double u1,u2; - if (!PyArg_ParseTuple(args, "dd", &u1,&u2)) + double u1, u2; + if (!PyArg_ParseTuple(args, "dd", &u1, &u2)) return nullptr; try { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); Handle(Geom_BSplineCurve) tempCurve = Handle(Geom_BSplineCurve)::DownCast (curve->Copy()); - tempCurve->Segment(u1,u2); + tempCurve->Segment(u1, u2); if (std::abs(tempCurve->FirstParameter()-u1) > Precision::Approximation() || std::abs(tempCurve->LastParameter()-u2) > Precision::Approximation()) { Standard_Failure::Raise("Failed to segment BSpline curve"); return nullptr; } else { - curve->Segment(u1,u2); + curve->Segment(u1, u2); } Py_Return; } @@ -682,35 +682,35 @@ PyObject* BSplineCurvePy::getMultiplicities(PyObject * args) return nullptr; } } -Py::Long BSplineCurvePy::getDegree(void) const +Py::Long BSplineCurvePy::getDegree() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->Degree()); } -Py::Long BSplineCurvePy::getMaxDegree(void) const +Py::Long BSplineCurvePy::getMaxDegree() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->MaxDegree()); } -Py::Long BSplineCurvePy::getNbPoles(void) const +Py::Long BSplineCurvePy::getNbPoles() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->NbPoles()); } -Py::Long BSplineCurvePy::getNbKnots(void) const +Py::Long BSplineCurvePy::getNbKnots() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->NbKnots()); } -Py::Object BSplineCurvePy::getStartPoint(void) const +Py::Object BSplineCurvePy::getStartPoint() const { Handle(Geom_BSplineCurve) c = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); @@ -718,7 +718,7 @@ Py::Object BSplineCurvePy::getStartPoint(void) const return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } -Py::Object BSplineCurvePy::getEndPoint(void) const +Py::Object BSplineCurvePy::getEndPoint() const { Handle(Geom_BSplineCurve) c = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); @@ -726,21 +726,21 @@ Py::Object BSplineCurvePy::getEndPoint(void) const return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } -Py::Object BSplineCurvePy::getFirstUKnotIndex(void) const +Py::Object BSplineCurvePy::getFirstUKnotIndex() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->FirstUKnotIndex()); } -Py::Object BSplineCurvePy::getLastUKnotIndex(void) const +Py::Object BSplineCurvePy::getLastUKnotIndex() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->LastUKnotIndex()); } -Py::List BSplineCurvePy::getKnotSequence(void) const +Py::List BSplineCurvePy::getKnotSequence() const { Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast (getGeometryPtr()->handle()); @@ -1392,6 +1392,29 @@ PyObject* BSplineCurvePy::makeC1Continuous(PyObject *args) } } +PyObject* BSplineCurvePy::scaleKnotsToBounds(PyObject *args) +{ + double u0=0.0; + double u1=1.0; + if (!PyArg_ParseTuple(args, "|dd", &u0, &u1)) + return nullptr; + try { + if (u0 >= u1) { + Standard_Failure::Raise("Bad parameter range"); + return nullptr; + } + GeomBSplineCurve* curve = getGeomBSplineCurvePtr(); + curve->scaleKnotsToBounds(u0, u1); + Py_Return; + } + catch (Standard_Failure& e) { + std::string err = e.GetMessageString(); + if (err.empty()) err = e.DynamicType()->Name(); + PyErr_SetString(PartExceptionOCCError, err.c_str()); + return nullptr; + } +} + PyObject* BSplineCurvePy::getCustomAttributes(const char* /*attr*/) const { return nullptr; diff --git a/src/Mod/Part/App/BSplineSurfacePy.xml b/src/Mod/Part/App/BSplineSurfacePy.xml index b53cbecb4c..421beb54b1 100644 --- a/src/Mod/Part/App/BSplineSurfacePy.xml +++ b/src/Mod/Part/App/BSplineSurfacePy.xml @@ -1,733 +1,743 @@ - - - - Describes a B-Spline surface in 3D space - - - - - Returns the degree of this B-Spline surface in the u parametric direction. - - - - - - - - Returns the degree of this B-Spline surface in the v parametric direction. - - - - - - - - Returns the value of the maximum polynomial degree of any - B-Spline surface surface in either parametric directions. - This value is 25. - - - - - - - - Returns the number of poles of this B-Spline surface in the u parametric direction. - - - - - - - - Returns the number of poles of this B-Spline surface in the v parametric direction. - - - - - - - - Returns the number of knots of this B-Spline surface in the u parametric direction. - - - - - - - - Returns the number of knots of this B-Spline surface in the v parametric direction. - - - - - - - - Returns the index in the knot array associated with the u parametric direction, - which corresponds to the first parameter of this B-Spline surface in the specified - parametric direction. + Twin="GeomBSplineSurface" + TwinPointer="GeomBSplineSurface" + Include="Mod/Part/App/Geometry.h" + Namespace="Part" + FatherInclude="Mod/Part/App/GeometrySurfacePy.h" + FatherNamespace="Part" + Constructor="true"> + + + Describes a B-Spline surface in 3D space + + + + + Returns the degree of this B-Spline surface in the u parametric direction. + + + + + + + + Returns the degree of this B-Spline surface in the v parametric direction. + + + + + + + + Returns the value of the maximum polynomial degree of any + B-Spline surface surface in either parametric directions. + This value is 25. + + + + + + + + Returns the number of poles of this B-Spline surface in the u parametric direction. + + + + + + + + Returns the number of poles of this B-Spline surface in the v parametric direction. + + + + + + + + Returns the number of knots of this B-Spline surface in the u parametric direction. + + + + + + + + Returns the number of knots of this B-Spline surface in the v parametric direction. + + + + + + + + Returns the index in the knot array associated with the u parametric direction, + which corresponds to the first parameter of this B-Spline surface in the specified + parametric direction. - The isoparametric curves corresponding to these values are the boundary curves of - this surface. + The isoparametric curves corresponding to these values are the boundary curves of + this surface. - Note: The index does not correspond to the first knot of the surface in the specified - parametric direction unless the multiplicity of the first knot is equal to Degree + 1, - where Degree is the degree of this surface in the corresponding parametric direction. - - - - - - - - Returns the index in the knot array associated with the u parametric direction, - which corresponds to the last parameter of this B-Spline surface in the specified - parametric direction. + Note: The index does not correspond to the first knot of the surface in the specified + parametric direction unless the multiplicity of the first knot is equal to Degree + 1, + where Degree is the degree of this surface in the corresponding parametric direction. + + + + + + + + Returns the index in the knot array associated with the u parametric direction, + which corresponds to the last parameter of this B-Spline surface in the specified + parametric direction. - The isoparametric curves corresponding to these values are the boundary curves of - this surface. + The isoparametric curves corresponding to these values are the boundary curves of + this surface. - Note: The index does not correspond to the first knot of the surface in the specified - parametric direction unless the multiplicity of the last knot is equal to Degree + 1, - where Degree is the degree of this surface in the corresponding parametric direction. - - - - - - - - Returns the index in the knot array associated with the v parametric direction, - which corresponds to the first parameter of this B-Spline surface in the specified - parametric direction. + Note: The index does not correspond to the first knot of the surface in the specified + parametric direction unless the multiplicity of the last knot is equal to Degree + 1, + where Degree is the degree of this surface in the corresponding parametric direction. + + + + + + + + Returns the index in the knot array associated with the v parametric direction, + which corresponds to the first parameter of this B-Spline surface in the specified + parametric direction. - The isoparametric curves corresponding to these values are the boundary curves of - this surface. + The isoparametric curves corresponding to these values are the boundary curves of + this surface. - Note: The index does not correspond to the first knot of the surface in the specified - parametric direction unless the multiplicity of the first knot is equal to Degree + 1, - where Degree is the degree of this surface in the corresponding parametric direction. - - - - - - - - Returns the index in the knot array associated with the v parametric direction, - which corresponds to the last parameter of this B-Spline surface in the specified - parametric direction. + Note: The index does not correspond to the first knot of the surface in the specified + parametric direction unless the multiplicity of the first knot is equal to Degree + 1, + where Degree is the degree of this surface in the corresponding parametric direction. + + + + + + + + Returns the index in the knot array associated with the v parametric direction, + which corresponds to the last parameter of this B-Spline surface in the specified + parametric direction. - The isoparametric curves corresponding to these values are the boundary curves of - this surface. + The isoparametric curves corresponding to these values are the boundary curves of + this surface. - Note: The index does not correspond to the first knot of the surface in the specified - parametric direction unless the multiplicity of the last knot is equal to Degree + 1, - where Degree is the degree of this surface in the corresponding parametric direction. - - - - - - - - Returns the knots sequence of this B-Spline surface in - the u direction. - - - - - - - - Returns the knots sequence of this B-Spline surface in - the v direction. - - - - + Note: The index does not correspond to the first knot of the surface in the specified + parametric direction unless the multiplicity of the last knot is equal to Degree + 1, + where Degree is the degree of this surface in the corresponding parametric direction. + + + + + + + + Returns the knots sequence of this B-Spline surface in + the u direction. + + + + + + + + Returns the knots sequence of this B-Spline surface in + the v direction. + + + + - - - Returns the parametric bounds (U1, U2, V1, V2) of this B-Spline surface. - - - + + + Returns the parametric bounds (U1, U2, V1, V2) of this B-Spline surface. + + + - - - Returns false if the equation of this B-Spline surface is polynomial - (e.g. non-rational) in the u or v parametric direction. - In other words, returns false if for each row of poles, the associated - weights are identical - - - + + + Returns false if the equation of this B-Spline surface is polynomial + (e.g. non-rational) in the u or v parametric direction. + In other words, returns false if for each row of poles, the associated + weights are identical + + + - - - Returns false if the equation of this B-Spline surface is polynomial - (e.g. non-rational) in the u or v parametric direction. - In other words, returns false if for each column of poles, the associated - weights are identical - - - + + + Returns false if the equation of this B-Spline surface is polynomial + (e.g. non-rational) in the u or v parametric direction. + In other words, returns false if for each column of poles, the associated + weights are identical + + + - - Returns true if this surface is periodic in the u parametric direction. - - + + Returns true if this surface is periodic in the u parametric direction. + + - - Returns true if this surface is periodic in the v parametric direction. - - + + Returns true if this surface is periodic in the v parametric direction. + + - - - Checks if this surface is closed in the u parametric direction. - Returns true if, in the table of poles the first row and the last - row are identical. - - - + + + Checks if this surface is closed in the u parametric direction. + Returns true if, in the table of poles the first row and the last + row are identical. + + + - - - Checks if this surface is closed in the v parametric direction. - Returns true if, in the table of poles the first column and the - last column are identical. - - - - - - - increase(Int=UDegree, int=VDegree) - Increases the degrees of this B-Spline surface to UDegree and VDegree - in the u and v parametric directions respectively. - As a result, the tables of poles, weights and multiplicities are modified. - The tables of knots is not changed. + + + Checks if this surface is closed in the v parametric direction. + Returns true if, in the table of poles the first column and the + last column are identical. + + + + + + + increase(Int=UDegree, int=VDegree) + Increases the degrees of this B-Spline surface to UDegree and VDegree + in the u and v parametric directions respectively. + As a result, the tables of poles, weights and multiplicities are modified. + The tables of knots is not changed. - Note: Nothing is done if the given degree is less than or equal to the - current degree in the corresponding parametric direction. - - - - - - Increases the multiplicity in the u direction. - - - - - Increases the multiplicity in the v direction. - - - - - Increment the multiplicity in the u direction - - - - - Increment the multiplicity in the v direction - - - - - insertUKnote(float U, int Index, float Tolerance) - Insert or override a knot - - - - - insertUKnote(List of float U, List of float Mult, float Tolerance) - Inserts knots. - - - - - insertUKnote(float V, int Index, float Tolerance) - Insert or override a knot. - - - - - insertUKnote(List of float V, List of float Mult, float Tolerance) - Inserts knots. - - - - - - Reduces to M the multiplicity of the knot of index Index in the given - parametric direction. If M is 0, the knot is removed. - With a modification of this type, the table of poles is also modified. - Two different algorithms are used systematically to compute the new - poles of the surface. For each pole, the distance between the pole - calculated using the first algorithm and the same pole calculated using - the second algorithm, is checked. If this distance is less than Tolerance - it ensures that the surface is not modified by more than Tolerance. - Under these conditions, the function returns true; otherwise, it returns - false. + Note: Nothing is done if the given degree is less than or equal to the + current degree in the corresponding parametric direction. + + + + + + Increases the multiplicity in the u direction. + + + + + Increases the multiplicity in the v direction. + + + + + Increment the multiplicity in the u direction + + + + + Increment the multiplicity in the v direction + + + + + insertUKnote(float U, int Index, float Tolerance) - Insert or override a knot + + + + + insertUKnote(List of float U, List of float Mult, float Tolerance) - Inserts knots. + + + + + insertUKnote(float V, int Index, float Tolerance) - Insert or override a knot. + + + + + insertUKnote(List of float V, List of float Mult, float Tolerance) - Inserts knots. + + + + + + Reduces to M the multiplicity of the knot of index Index in the given + parametric direction. If M is 0, the knot is removed. + With a modification of this type, the table of poles is also modified. + Two different algorithms are used systematically to compute the new + poles of the surface. For each pole, the distance between the pole + calculated using the first algorithm and the same pole calculated using + the second algorithm, is checked. If this distance is less than Tolerance + it ensures that the surface is not modified by more than Tolerance. + Under these conditions, the function returns true; otherwise, it returns + false. - A low tolerance prevents modification of the surface. A high tolerance - 'smoothes' the surface. - - - - - - - Reduces to M the multiplicity of the knot of index Index in the given - parametric direction. If M is 0, the knot is removed. - With a modification of this type, the table of poles is also modified. - Two different algorithms are used systematically to compute the new - poles of the surface. For each pole, the distance between the pole - calculated using the first algorithm and the same pole calculated using - the second algorithm, is checked. If this distance is less than Tolerance - it ensures that the surface is not modified by more than Tolerance. - Under these conditions, the function returns true; otherwise, it returns - false. + A low tolerance prevents modification of the surface. A high tolerance + 'smoothes' the surface. + + + + + + + Reduces to M the multiplicity of the knot of index Index in the given + parametric direction. If M is 0, the knot is removed. + With a modification of this type, the table of poles is also modified. + Two different algorithms are used systematically to compute the new + poles of the surface. For each pole, the distance between the pole + calculated using the first algorithm and the same pole calculated using + the second algorithm, is checked. If this distance is less than Tolerance + it ensures that the surface is not modified by more than Tolerance. + Under these conditions, the function returns true; otherwise, it returns + false. - A low tolerance prevents modification of the surface. A high tolerance - 'smoothes' the surface. - - - - - - - Modifies this B-Spline surface by segmenting it between U1 and U2 in the - u parametric direction and between V1 and V2 in the v parametric direction. - Any of these values can be outside the bounds of this surface, but U2 must - be greater than U1 and V2 must be greater than V1. + A low tolerance prevents modification of the surface. A high tolerance + 'smoothes' the surface. + + + + + + + Modifies this B-Spline surface by segmenting it between U1 and U2 in the + u parametric direction and between V1 and V2 in the v parametric direction. + Any of these values can be outside the bounds of this surface, but U2 must + be greater than U1 and V2 must be greater than V1. - All the data structure tables of this B-Spline surface are modified but the - knots located between U1 and U2 in the u parametric direction, and between - V1 and V2 in the v parametric direction are retained. - The degree of the surface in each parametric direction is not modified. - - - - - - - Modifies this B-Spline surface by assigning the value K to the knot of index - UIndex of the knots table corresponding to the u parametric direction. - This modification remains relatively local, since K must lie between the values - of the knots which frame the modified knot. + All the data structure tables of this B-Spline surface are modified but the + knots located between U1 and U2 in the u parametric direction, and between + V1 and V2 in the v parametric direction are retained. + The degree of the surface in each parametric direction is not modified. + + + + + + + Modifies this B-Spline surface by assigning the value K to the knot of index + UIndex of the knots table corresponding to the u parametric direction. + This modification remains relatively local, since K must lie between the values + of the knots which frame the modified knot. - You can also increase the multiplicity of the modified knot to M. Note however - that it is not possible to decrease the multiplicity of a knot with this function. - - - - - - - Modifies this B-Spline surface by assigning the value K to the knot of index - VIndex of the knots table corresponding to the v parametric direction. - This modification remains relatively local, since K must lie between the values - of the knots which frame the modified knot. + You can also increase the multiplicity of the modified knot to M. Note however + that it is not possible to decrease the multiplicity of a knot with this function. + + + + + + + Modifies this B-Spline surface by assigning the value K to the knot of index + VIndex of the knots table corresponding to the v parametric direction. + This modification remains relatively local, since K must lie between the values + of the knots which frame the modified knot. - You can also increase the multiplicity of the modified knot to M. Note however - that it is not possible to decrease the multiplicity of a knot with this function. - - - + You can also increase the multiplicity of the modified knot to M. Note however + that it is not possible to decrease the multiplicity of a knot with this function. + + + - - - Returns, for this B-Spline surface, in the u parametric direction - the knot of index UIndex of the knots table. - - - + + + Returns, for this B-Spline surface, in the u parametric direction + the knot of index UIndex of the knots table. + + + - - - Returns, for this B-Spline surface, in the v parametric direction - the knot of index VIndex of the knots table. - - - - - - - Changes all knots of this B-Spline surface in the u parametric - direction. The multiplicity of the knots is not modified. - - - - - - - Changes all knots of this B-Spline surface in the v parametric - direction. The multiplicity of the knots is not modified. - - - + + + Returns, for this B-Spline surface, in the v parametric direction + the knot of index VIndex of the knots table. + + + + + + + Changes all knots of this B-Spline surface in the u parametric + direction. The multiplicity of the knots is not modified. + + + + + + + Changes all knots of this B-Spline surface in the v parametric + direction. The multiplicity of the knots is not modified. + + + - - - Returns, for this B-Spline surface, the knots table - in the u parametric direction - - - + + + Returns, for this B-Spline surface, the knots table + in the u parametric direction + + + - - - Returns, for this B-Spline surface, the knots table - in the v parametric direction - - - - - - - Modifies this B-Spline surface by assigning P to the pole of - index (UIndex, VIndex) in the poles table. - The second syntax allows you also to change the weight of the - modified pole. The weight is set to Weight. This syntax must - only be used for rational surfaces. - Modifies this B-Spline curve by assigning P to the pole of - index Index in the poles table. - - - - - - - Modifies this B-Spline surface by assigning values to all or part - of the column of poles of index VIndex, of this B-Spline surface. - You can also change the weights of the modified poles. The weights - are set to the corresponding values of CPoleWeights. - These syntaxes must only be used for rational surfaces. - - - - - - - Modifies this B-Spline surface by assigning values to all or part - of the row of poles of index VIndex, of this B-Spline surface. - You can also change the weights of the modified poles. The weights - are set to the corresponding values of CPoleWeights. - These syntaxes must only be used for rational surfaces. - - - + + + Returns, for this B-Spline surface, the knots table + in the v parametric direction + + + + + + + Modifies this B-Spline surface by assigning P to the pole of + index (UIndex, VIndex) in the poles table. + The second syntax allows you also to change the weight of the + modified pole. The weight is set to Weight. This syntax must + only be used for rational surfaces. + Modifies this B-Spline curve by assigning P to the pole of + index Index in the poles table. + + + + + + + Modifies this B-Spline surface by assigning values to all or part + of the column of poles of index VIndex, of this B-Spline surface. + You can also change the weights of the modified poles. The weights + are set to the corresponding values of CPoleWeights. + These syntaxes must only be used for rational surfaces. + + + + + + + Modifies this B-Spline surface by assigning values to all or part + of the row of poles of index VIndex, of this B-Spline surface. + You can also change the weights of the modified poles. The weights + are set to the corresponding values of CPoleWeights. + These syntaxes must only be used for rational surfaces. + + + - - - Returns the pole of index (UIndex,VIndex) of this B-Spline surface. - - - + + + Returns the pole of index (UIndex,VIndex) of this B-Spline surface. + + + - - Returns the table of poles of this B-Spline surface. - - - - - - Modifies this B-Spline surface by assigning the value Weight to the weight - of the pole of index (UIndex, VIndex) in the poles tables of this B-Spline - surface. + + Returns the table of poles of this B-Spline surface. + + + + + + Modifies this B-Spline surface by assigning the value Weight to the weight + of the pole of index (UIndex, VIndex) in the poles tables of this B-Spline + surface. - This function must only be used for rational surfaces. - - - - - - - Modifies this B-Spline surface by assigning values to all or part of the - weights of the column of poles of index VIndex of this B-Spline surface. + This function must only be used for rational surfaces. + + + + + + + Modifies this B-Spline surface by assigning values to all or part of the + weights of the column of poles of index VIndex of this B-Spline surface. - The modified part of the column of weights is defined by the bounds - of the array CPoleWeights. + The modified part of the column of weights is defined by the bounds + of the array CPoleWeights. - This function must only be used for rational surfaces. - - - - - - - Modifies this B-Spline surface by assigning values to all or part of the - weights of the row of poles of index UIndex of this B-Spline surface. + This function must only be used for rational surfaces. + + + + + + + Modifies this B-Spline surface by assigning values to all or part of the + weights of the row of poles of index UIndex of this B-Spline surface. - The modified part of the row of weights is defined by the bounds of the - array CPoleWeights. + The modified part of the row of weights is defined by the bounds of the + array CPoleWeights. - This function must only be used for rational surfaces. - - - + This function must only be used for rational surfaces. + + + - - - Return the weight of the pole of index (UIndex,VIndex) - in the poles table for this B-Spline surface. - - - + + + Return the weight of the pole of index (UIndex,VIndex) + in the poles table for this B-Spline surface. + + + - - Returns the table of weights of the poles for this B-Spline surface. - - + + Returns the table of weights of the poles for this B-Spline surface. + + - - Returns the table of poles and weights in homogeneous coordinates. - - - - - - Computes two tolerance values for this B-Spline surface, based on the - given tolerance in 3D space Tolerance3D. The tolerances computed are: - -- UTolerance in the u parametric direction and - -- VTolerance in the v parametric direction. + + Returns the table of poles and weights in homogeneous coordinates. + + + + + + Computes two tolerance values for this B-Spline surface, based on the + given tolerance in 3D space Tolerance3D. The tolerances computed are: + -- UTolerance in the u parametric direction and + -- VTolerance in the v parametric direction. - If f(u,v) is the equation of this B-Spline surface, UTolerance and - VTolerance guarantee that: - |u1 - u0| < UTolerance - |v1 - v0| < VTolerance - ====> ||f(u1, v1) - f(u2, v2)|| < Tolerance3D - - - - - - - Moves the point of parameters (U, V) of this B-Spline surface to P. - UIndex1, UIndex2, VIndex1 and VIndex2 are the indexes in the poles - table of this B-Spline surface, of the first and last poles which - can be moved in each parametric direction. - The returned indexes UFirstIndex, ULastIndex, VFirstIndex and - VLastIndex are the indexes of the first and last poles effectively - modified in each parametric direction. - In the event of incompatibility between UIndex1, UIndex2, VIndex1, - VIndex2 and the values U and V: - -- no change is made to this B-Spline surface, and - -- UFirstIndex, ULastIndex, VFirstIndex and VLastIndex are set to - null. - - - - - - - Changes this B-Spline surface into a non-periodic one in the u parametric direction. - If this B-Spline surface is already non-periodic in the given parametric direction, - it is not modified. - If this B-Spline surface is periodic in the given parametric direction, the boundaries - of the surface are not given by the first and last rows (or columns) of poles (because - the multiplicity of the first knot and of the last knot in the given parametric direction - are not modified, nor are they equal to Degree+1, where Degree is the degree of this - B-Spline surface in the given parametric direction). Only the function Segment ensures - this property. + If f(u,v) is the equation of this B-Spline surface, UTolerance and + VTolerance guarantee that: + |u1 - u0| < UTolerance + |v1 - v0| < VTolerance + ====> ||f(u1, v1) - f(u2, v2)|| < Tolerance3D + + + + + + + Moves the point of parameters (U, V) of this B-Spline surface to P. + UIndex1, UIndex2, VIndex1 and VIndex2 are the indexes in the poles + table of this B-Spline surface, of the first and last poles which + can be moved in each parametric direction. + The returned indexes UFirstIndex, ULastIndex, VFirstIndex and + VLastIndex are the indexes of the first and last poles effectively + modified in each parametric direction. + In the event of incompatibility between UIndex1, UIndex2, VIndex1, + VIndex2 and the values U and V: + -- no change is made to this B-Spline surface, and + -- UFirstIndex, ULastIndex, VFirstIndex and VLastIndex are set to + null. + + + + + + + Changes this B-Spline surface into a non-periodic one in the u parametric direction. + If this B-Spline surface is already non-periodic in the given parametric direction, + it is not modified. + If this B-Spline surface is periodic in the given parametric direction, the boundaries + of the surface are not given by the first and last rows (or columns) of poles (because + the multiplicity of the first knot and of the last knot in the given parametric direction + are not modified, nor are they equal to Degree+1, where Degree is the degree of this + B-Spline surface in the given parametric direction). Only the function Segment ensures + this property. - Note: the poles and knots tables are modified. - - - - - - - Changes this B-Spline surface into a non-periodic one in the v parametric direction. - If this B-Spline surface is already non-periodic in the given parametric direction, - it is not modified. - If this B-Spline surface is periodic in the given parametric direction, the boundaries - of the surface are not given by the first and last rows (or columns) of poles (because - the multiplicity of the first knot and of the last knot in the given parametric direction - are not modified, nor are they equal to Degree+1, where Degree is the degree of this - B-Spline surface in the given parametric direction). Only the function Segment ensures - this property. + Note: the poles and knots tables are modified. + + + + + + + Changes this B-Spline surface into a non-periodic one in the v parametric direction. + If this B-Spline surface is already non-periodic in the given parametric direction, + it is not modified. + If this B-Spline surface is periodic in the given parametric direction, the boundaries + of the surface are not given by the first and last rows (or columns) of poles (because + the multiplicity of the first knot and of the last knot in the given parametric direction + are not modified, nor are they equal to Degree+1, where Degree is the degree of this + B-Spline surface in the given parametric direction). Only the function Segment ensures + this property. - Note: the poles and knots tables are modified. - - - - - - - Modifies this surface to be periodic in the u parametric direction. - To become periodic in a given parametric direction a surface must - be closed in that parametric direction, and the knot sequence relative - to that direction must be periodic. - To generate this periodic sequence of knots, the functions FirstUKnotIndex - and LastUKnotIndex are used to compute I1 and I2. These are the indexes, - in the knot array associated with the given parametric direction, of the - knots that correspond to the first and last parameters of this B-Spline - surface in the given parametric direction. Hence the period is: + Note: the poles and knots tables are modified. + + + + + + + Modifies this surface to be periodic in the u parametric direction. + To become periodic in a given parametric direction a surface must + be closed in that parametric direction, and the knot sequence relative + to that direction must be periodic. + To generate this periodic sequence of knots, the functions FirstUKnotIndex + and LastUKnotIndex are used to compute I1 and I2. These are the indexes, + in the knot array associated with the given parametric direction, of the + knots that correspond to the first and last parameters of this B-Spline + surface in the given parametric direction. Hence the period is: - Knots(I1) - Knots(I2) + Knots(I1) - Knots(I2) - As a result, the knots and poles tables are modified. - - - - - - - Modifies this surface to be periodic in the v parametric direction. - To become periodic in a given parametric direction a surface must - be closed in that parametric direction, and the knot sequence relative - to that direction must be periodic. - To generate this periodic sequence of knots, the functions FirstUKnotIndex - and LastUKnotIndex are used to compute I1 and I2. These are the indexes, - in the knot array associated with the given parametric direction, of the - knots that correspond to the first and last parameters of this B-Spline - surface in the given parametric direction. Hence the period is: + As a result, the knots and poles tables are modified. + + + + + + + Modifies this surface to be periodic in the v parametric direction. + To become periodic in a given parametric direction a surface must + be closed in that parametric direction, and the knot sequence relative + to that direction must be periodic. + To generate this periodic sequence of knots, the functions FirstUKnotIndex + and LastUKnotIndex are used to compute I1 and I2. These are the indexes, + in the knot array associated with the given parametric direction, of the + knots that correspond to the first and last parameters of this B-Spline + surface in the given parametric direction. Hence the period is: - Knots(I1) - Knots(I2) + Knots(I1) - Knots(I2) - As a result, the knots and poles tables are modified. - - - - - - - Assigns the knot of index Index in the knots table - in the u parametric direction to be the origin of - this periodic B-Spline surface. As a consequence, - the knots and poles tables are modified. - - - - - - - Assigns the knot of index Index in the knots table - in the v parametric direction to be the origin of - this periodic B-Spline surface. As a consequence, - the knots and poles tables are modified. - - - + As a result, the knots and poles tables are modified. + + + + + + + Assigns the knot of index Index in the knots table + in the u parametric direction to be the origin of + this periodic B-Spline surface. As a consequence, + the knots and poles tables are modified. + + + + + + + Assigns the knot of index Index in the knots table + in the v parametric direction to be the origin of + this periodic B-Spline surface. As a consequence, + the knots and poles tables are modified. + + + - - - Returns, for this B-Spline surface, the multiplicity of - the knot of index UIndex in the u parametric direction. - - - + + + Returns, for this B-Spline surface, the multiplicity of + the knot of index UIndex in the u parametric direction. + + + - - - Returns, for this B-Spline surface, the multiplicity of - the knot of index VIndex in the v parametric direction. - - - + + + Returns, for this B-Spline surface, the multiplicity of + the knot of index VIndex in the v parametric direction. + + + - - - Returns, for this B-Spline surface, the table of - multiplicities in the u parametric direction - - - + + + Returns, for this B-Spline surface, the table of + multiplicities in the u parametric direction + + + - - - Returns, for this B-Spline surface, the table of - multiplicities in the v parametric direction - - - - - - - Exchanges the u and v parametric directions on this B-Spline surface. - As a consequence: - -- the poles and weights tables are transposed, - -- the knots and multiplicities tables are exchanged, - -- degrees of continuity and rational, periodic and uniform - characteristics are exchanged and - -- the orientation of the surface is reversed. - - - - - - Returns a reparametrized copy of this surface - - - - - - Replaces this B-Spline surface by approximating a set of points. - This method uses keywords : - - Points = 2Darray of points (or floats, in combination with X0, dX, Y0, dY) - - DegMin (int), DegMax (int) - - Continuity = 0,1 or 2 (for C0, C1, C2) - - Tolerance (float) - - X0, dX, Y0, dY (floats) with Points = 2Darray of floats - - ParamType = 'Uniform','Centripetal' or 'ChordLength' - - LengthWeight, CurvatureWeight, TorsionWeight (floats) - (with this smoothing algorithm, continuity C1 requires DegMax >= 3 and C2, DegMax >=5) + + + Returns, for this B-Spline surface, the table of + multiplicities in the v parametric direction + + + + + + + Exchanges the u and v parametric directions on this B-Spline surface. + As a consequence: + -- the poles and weights tables are transposed, + -- the knots and multiplicities tables are exchanged, + -- degrees of continuity and rational, periodic and uniform + characteristics are exchanged and + -- the orientation of the surface is reversed. + + + + + + Returns a reparametrized copy of this surface + + + + + + Replaces this B-Spline surface by approximating a set of points. + This method uses keywords : + - Points = 2Darray of points (or floats, in combination with X0, dX, Y0, dY) + - DegMin (int), DegMax (int) + - Continuity = 0,1 or 2 (for C0, C1, C2) + - Tolerance (float) + - X0, dX, Y0, dY (floats) with Points = 2Darray of floats + - ParamType = 'Uniform','Centripetal' or 'ChordLength' + - LengthWeight, CurvatureWeight, TorsionWeight (floats) + (with this smoothing algorithm, continuity C1 requires DegMax >= 3 and C2, DegMax >=5) - Possible combinations : - - approximate(Points, DegMin, DegMax, Continuity, Tolerance) - - approximate(Points, DegMin, DegMax, Continuity, Tolerance, X0, dX, Y0, dY) - With explicit keywords : - - approximate(Points, DegMin, DegMax, Continuity, Tolerance, ParamType) - - approximate(Points, DegMax, Continuity, Tolerance, LengthWeight, CurvatureWeight, TorsionWeight) - - - - - - - interpolate(points) - interpolate(zpoints, X0, dX, Y0, dY) + Possible combinations : + - approximate(Points, DegMin, DegMax, Continuity, Tolerance) + - approximate(Points, DegMin, DegMax, Continuity, Tolerance, X0, dX, Y0, dY) + With explicit keywords : + - approximate(Points, DegMin, DegMax, Continuity, Tolerance, ParamType) + - approximate(Points, DegMax, Continuity, Tolerance, LengthWeight, CurvatureWeight, TorsionWeight) + + + + + + + interpolate(points) + interpolate(zpoints, X0, dX, Y0, dY) - Replaces this B-Spline surface by interpolating a set of points. - The resulting surface is of degree 3 and continuity C2. - Arguments: - a 2 dimensional array of vectors, that the surface passes through - or - a 2 dimensional array of floats with the z values, - the x starting point X0 (float), - the x increment dX (float), - the y starting point Y0 and increment dY - - - - - - - Builds a B-Spline by a lists of Poles, Mults and Knots - arguments: poles (sequence of sequence of Base.Vector), umults, vmults, [uknots, vknots, uperiodic, vperiodic, udegree, vdegree, weights (sequence of sequence of float)] - - - - - - - Builds a B-Spline from a list of control curves - - - - + Replaces this B-Spline surface by interpolating a set of points. + The resulting surface is of degree 3 and continuity C2. + Arguments: + a 2 dimensional array of vectors, that the surface passes through + or + a 2 dimensional array of floats with the z values, + the x starting point X0 (float), + the x increment dX (float), + the y starting point Y0 and increment dY + + + + + + + Builds a B-Spline by a lists of Poles, Mults and Knots + arguments: poles (sequence of sequence of Base.Vector), umults, vmults, [uknots, vknots, uperiodic, vperiodic, udegree, vdegree, weights (sequence of sequence of float)] + + + + + + + Builds a B-Spline from a list of control curves + + + + + + + Scales the U and V knots lists to fit the specified bounds. + The shape of the surface is not modified. + bspline_surf.scaleKnotsToBounds(u0, u1, v0, v1) + Default arguments are 0.0, 1.0, 0.0, 1.0 + + + + diff --git a/src/Mod/Part/App/BSplineSurfacePyImp.cpp b/src/Mod/Part/App/BSplineSurfacePyImp.cpp index 2f5eaf8b5f..ef02c34028 100644 --- a/src/Mod/Part/App/BSplineSurfacePyImp.cpp +++ b/src/Mod/Part/App/BSplineSurfacePyImp.cpp @@ -53,7 +53,7 @@ std::string BSplineSurfacePy::representation(void) const PyObject *BSplineSurfacePy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper { - // create a new instance of BSplineSurfacePy and the Twin object + // create a new instance of BSplineSurfacePy and the Twin object return new BSplineSurfacePy(new GeomBSplineSurface); } @@ -613,7 +613,7 @@ PyObject* BSplineSurfacePy::setPoleCol(PyObject *args) Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->SetPoleCol(vindex, poles); } else { @@ -653,7 +653,7 @@ PyObject* BSplineSurfacePy::setPoleRow(PyObject *args) Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->SetPoleRow(uindex, poles); } else { @@ -1167,7 +1167,7 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) Standard_Real dY=0; static char* kwds_interp[] = {"Points", "DegMin", "DegMax", "Continuity", "Tolerance", "X0", "dX", "Y0", "dY", "ParamType", "LengthWeight", "CurvatureWeight", "TorsionWeight", nullptr}; - + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|iiidddddsddd", kwds_interp, &obj, °Min, °Max, &continuity, &tol3d, &X0, &dX, &Y0, &dY, &parType, &weight1, &weight2, &weight3)) return nullptr; try { @@ -1220,7 +1220,7 @@ PyObject* BSplineSurfacePy::approximate(PyObject *args, PyObject *kwds) c = GeomAbs_C2; break; } - + Approx_ParametrizationType pt; std::string pstr = parType; Standard_Boolean useParam = Standard_True; @@ -1573,35 +1573,35 @@ Py::Long BSplineSurfacePy::getMaxDegree(void) const { Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - return Py::Long(surf->MaxDegree()); + return Py::Long(surf->MaxDegree()); } Py::Long BSplineSurfacePy::getNbUPoles(void) const { Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - return Py::Long(surf->NbUPoles()); + return Py::Long(surf->NbUPoles()); } Py::Long BSplineSurfacePy::getNbVPoles(void) const { Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - return Py::Long(surf->NbVPoles()); + return Py::Long(surf->NbVPoles()); } Py::Long BSplineSurfacePy::getNbUKnots(void) const { Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - return Py::Long(surf->NbUKnots()); + return Py::Long(surf->NbUKnots()); } Py::Long BSplineSurfacePy::getNbVKnots(void) const { Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); - return Py::Long(surf->NbVKnots()); + return Py::Long(surf->NbVKnots()); } Py::Object BSplineSurfacePy::getFirstUKnotIndex(void) const @@ -1641,8 +1641,14 @@ Py::List BSplineSurfacePy::getUKnotSequence(void) const Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); Standard_Integer m = 0; - for (int i=1; i<= surf->NbUKnots(); i++) - m += surf->UMultiplicity(i); + if (surf->IsUPeriodic()) { + // knots=poles+2*degree-mult(1)+2 + m = surf->NbUPoles() + 2*surf->UDegree() - surf->UMultiplicity(1) + 2; + } + else { + for (int i=1; i<= surf->NbUKnots(); i++) + m += surf->UMultiplicity(i); + } TColStd_Array1OfReal k(1,m); surf->UKnotSequence(k); Py::List list; @@ -1657,8 +1663,14 @@ Py::List BSplineSurfacePy::getVKnotSequence(void) const Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast (getGeometryPtr()->handle()); Standard_Integer m = 0; - for (int i=1; i<= surf->NbVKnots(); i++) - m += surf->VMultiplicity(i); + if (surf->IsVPeriodic()) { + // knots=poles+2*degree-mult(1)+2 + m = surf->NbVPoles() + 2*surf->VDegree() - surf->VMultiplicity(1) + 2; + } + else { + for (int i=1; i<= surf->NbVKnots(); i++) + m += surf->VMultiplicity(i); + } TColStd_Array1OfReal k(1,m); surf->VKnotSequence(k); Py::List list; @@ -1668,12 +1680,42 @@ Py::List BSplineSurfacePy::getVKnotSequence(void) const return list; } -PyObject *BSplineSurfacePy::getCustomAttributes(const char* /*attr*/) const +PyObject* BSplineSurfacePy::scaleKnotsToBounds(PyObject *args) { + double u0=0.0; + double u1=1.0; + double v0=0.0; + double v1=1.0; + + if (!PyArg_ParseTuple(args, "|dddd", &u0, &u1, &v0, &v1)) + return nullptr; + try { + if (u0 >= u1 || v0 >= v1) { + Standard_Failure::Raise("Bad parameter range"); + return nullptr;; + } + GeomBSplineSurface* surf = getGeomBSplineSurfacePtr(); + surf->scaleKnotsToBounds(u0, u1, v0, v1); + Py_Return; + } + catch (Standard_Failure& e) { + std::string err = e.GetMessageString(); + if (err.empty()) err = e.DynamicType()->Name(); + PyErr_SetString(PartExceptionOCCError, err.c_str()); + return nullptr; + } +} + +PyObject *BSplineSurfacePy::getCustomAttributes(const char* attr) const +{ + // for backward compatibility + if (strcmp(attr, "setBounds") == 0) { + return PyObject_GetAttrString(const_cast(this), "scaleKnotsToBounds"); + } return nullptr; } int BSplineSurfacePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) { - return 0; + return 0; } diff --git a/src/Mod/Part/App/BezierCurvePyImp.cpp b/src/Mod/Part/App/BezierCurvePyImp.cpp index 089e13ff8f..d0630b5882 100644 --- a/src/Mod/Part/App/BezierCurvePyImp.cpp +++ b/src/Mod/Part/App/BezierCurvePyImp.cpp @@ -42,7 +42,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BezierCurvePy::representation(void) const +std::string BezierCurvePy::representation() const { return ""; } @@ -345,28 +345,28 @@ PyObject* BezierCurvePy::getResolution(PyObject* args) return nullptr; } } -Py::Long BezierCurvePy::getDegree(void) const +Py::Long BezierCurvePy::getDegree() const { Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->Degree()); } -Py::Long BezierCurvePy::getMaxDegree(void) const +Py::Long BezierCurvePy::getMaxDegree() const { Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->MaxDegree()); } -Py::Long BezierCurvePy::getNbPoles(void) const +Py::Long BezierCurvePy::getNbPoles() const { Handle(Geom_BezierCurve) curve = Handle(Geom_BezierCurve)::DownCast (getGeometryPtr()->handle()); return Py::Long(curve->NbPoles()); } -Py::Object BezierCurvePy::getStartPoint(void) const +Py::Object BezierCurvePy::getStartPoint() const { Handle(Geom_BezierCurve) c = Handle(Geom_BezierCurve)::DownCast (getGeometryPtr()->handle()); @@ -374,7 +374,7 @@ Py::Object BezierCurvePy::getStartPoint(void) const return Py::Vector(Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z())); } -Py::Object BezierCurvePy::getEndPoint(void) const +Py::Object BezierCurvePy::getEndPoint() const { Handle(Geom_BezierCurve) c = Handle(Geom_BezierCurve)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/BezierSurfacePyImp.cpp b/src/Mod/Part/App/BezierSurfacePyImp.cpp index 0b8c570f51..2ff67c75c6 100644 --- a/src/Mod/Part/App/BezierSurfacePyImp.cpp +++ b/src/Mod/Part/App/BezierSurfacePyImp.cpp @@ -41,7 +41,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BezierSurfacePy::representation(void) const +std::string BezierSurfacePy::representation() const { return ""; } @@ -178,7 +178,7 @@ PyObject* BezierSurfacePy::insertPoleColAfter(PyObject *args) Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->InsertPoleColAfter(vindex, poles); } else { @@ -218,7 +218,7 @@ PyObject* BezierSurfacePy::insertPoleRowAfter(PyObject *args) Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->InsertPoleRowAfter(uindex, poles); } else { @@ -258,7 +258,7 @@ PyObject* BezierSurfacePy::insertPoleColBefore(PyObject *args) Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->InsertPoleColBefore(vindex, poles); } else { @@ -298,7 +298,7 @@ PyObject* BezierSurfacePy::insertPoleRowBefore(PyObject *args) Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->InsertPoleRowBefore(uindex, poles); } else { @@ -412,7 +412,7 @@ PyObject* BezierSurfacePy::setPoleCol(PyObject *args) Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->SetPoleCol(vindex, poles); } else { @@ -452,7 +452,7 @@ PyObject* BezierSurfacePy::setPoleRow(PyObject *args) Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); - if (obj2 == nullptr) { + if (!obj2) { surf->SetPoleRow(uindex, poles); } else { @@ -669,35 +669,35 @@ PyObject* BezierSurfacePy::exchangeUV(PyObject *args) } } -Py::Long BezierSurfacePy::getUDegree(void) const +Py::Long BezierSurfacePy::getUDegree() const { Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); return Py::Long(surf->UDegree()); } -Py::Long BezierSurfacePy::getVDegree(void) const +Py::Long BezierSurfacePy::getVDegree() const { Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); return Py::Long(surf->VDegree()); } -Py::Long BezierSurfacePy::getMaxDegree(void) const +Py::Long BezierSurfacePy::getMaxDegree() const { Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); return Py::Long(surf->MaxDegree()); } -Py::Long BezierSurfacePy::getNbUPoles(void) const +Py::Long BezierSurfacePy::getNbUPoles() const { Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); return Py::Long(surf->NbUPoles()); } -Py::Long BezierSurfacePy::getNbVPoles(void) const +Py::Long BezierSurfacePy::getNbVPoles() const { Handle(Geom_BezierSurface) surf = Handle(Geom_BezierSurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/BodyBase.cpp b/src/Mod/Part/App/BodyBase.cpp index 20d86a6ab1..62ae889d94 100644 --- a/src/Mod/Part/App/BodyBase.cpp +++ b/src/Mod/Part/App/BodyBase.cpp @@ -45,7 +45,7 @@ BodyBase::BodyBase() BodyBase* BodyBase::findBodyOf(const App::DocumentObject* f) { App::Document* doc = f->getDocument(); - if (doc != nullptr) { + if (doc) { std::vector bodies = doc->getObjectsOfType(BodyBase::getClassTypeId()); for (std::vector::const_iterator b = bodies.begin(); b != bodies.end(); b++) { BodyBase* body = static_cast(*b); diff --git a/src/Mod/Part/App/BodyBase.h b/src/Mod/Part/App/BodyBase.h index 829a4a8b1d..0ac0c9c056 100644 --- a/src/Mod/Part/App/BodyBase.h +++ b/src/Mod/Part/App/BodyBase.h @@ -78,14 +78,14 @@ public: * TODO introduce a findBodiesOf() if needed (2015-08-04, Fat-Zer) */ static BodyBase* findBodyOf(const App::DocumentObject* f); - virtual PyObject* getPyObject() override; + PyObject* getPyObject() override; protected: /// If BaseFeature is getting changed and Tip points to it reset the Tip - virtual void onBeforeChange (const App::Property* prop) override; + void onBeforeChange (const App::Property* prop) override; /// If BaseFeature is set and Tip is null set the Tip to it - virtual void onChanged (const App::Property* prop) override; - virtual void handleChangedPropertyName(Base::XMLReader &reader, + void onChanged (const App::Property* prop) override; + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; diff --git a/src/Mod/Part/App/BodyBasePyImp.cpp b/src/Mod/Part/App/BodyBasePyImp.cpp index 00b3db4670..97c0fbdfcc 100644 --- a/src/Mod/Part/App/BodyBasePyImp.cpp +++ b/src/Mod/Part/App/BodyBasePyImp.cpp @@ -31,7 +31,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BodyBasePy::representation(void) const +std::string BodyBasePy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/BoundedCurvePyImp.cpp b/src/Mod/Part/App/BoundedCurvePyImp.cpp index cfd4ddead4..f6e8adff2a 100644 --- a/src/Mod/Part/App/BoundedCurvePyImp.cpp +++ b/src/Mod/Part/App/BoundedCurvePyImp.cpp @@ -34,7 +34,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BoundedCurvePy::representation(void) const +std::string BoundedCurvePy::representation() const { return ""; } @@ -53,12 +53,12 @@ int BoundedCurvePy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -Py::Object BoundedCurvePy::getStartPoint(void) const +Py::Object BoundedCurvePy::getStartPoint() const { return Py::Vector(getGeomBoundedCurvePtr()->getStartPoint()); } -Py::Object BoundedCurvePy::getEndPoint(void) const +Py::Object BoundedCurvePy::getEndPoint() const { return Py::Vector(getGeomBoundedCurvePtr()->getEndPoint()); } diff --git a/src/Mod/Part/App/CMakeLists.txt b/src/Mod/Part/App/CMakeLists.txt index b496444af8..ecf13f8eba 100644 --- a/src/Mod/Part/App/CMakeLists.txt +++ b/src/Mod/Part/App/CMakeLists.txt @@ -17,20 +17,21 @@ include_directories( ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${FREETYPE_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) -set(Part_LIBS +set(Part_LIBS ${OCC_LIBRARIES} ${OCC_DEBUG_LIBRARIES} FreeCADApp ) if(FREETYPE_FOUND) - set(Part_LIBS + set(Part_LIBS ${Part_LIBS} ${FREETYPE_LIBRARIES} ) @@ -91,7 +92,6 @@ generate_from_xml(TopoShapeVertexPy) generate_from_xml(TopoShapeWirePy) generate_from_xml(BRepOffsetAPI_MakePipeShellPy) generate_from_xml(BRepOffsetAPI_MakeFillingPy) -generate_from_xml(PrecisionPy) # make sure to create the directory at configure time file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/BRepFeat) @@ -343,8 +343,6 @@ SET(Python_SRCS BRepOffsetAPI_MakePipeShellPyImp.cpp BRepOffsetAPI_MakeFillingPy.xml BRepOffsetAPI_MakeFillingPyImp.cpp - PrecisionPy.xml - PrecisionPyImp.cpp PartPyCXX.cpp PartPyCXX.h ) diff --git a/src/Mod/Part/App/CirclePyImp.cpp b/src/Mod/Part/App/CirclePyImp.cpp index 878b1c4df9..462e148028 100644 --- a/src/Mod/Part/App/CirclePyImp.cpp +++ b/src/Mod/Part/App/CirclePyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string CirclePy::representation(void) const +std::string CirclePy::representation() const { Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(getGeomCirclePtr()->handle()); gp_Ax1 axis = circle->Axis(); @@ -161,7 +161,7 @@ int CirclePy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Float CirclePy::getRadius(void) const +Py::Float CirclePy::getRadius() const { Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(getGeomCirclePtr()->handle()); return Py::Float(circle->Radius()); diff --git a/src/Mod/Part/App/ConePyImp.cpp b/src/Mod/Part/App/ConePyImp.cpp index b2f35de625..c9ed212f85 100644 --- a/src/Mod/Part/App/ConePyImp.cpp +++ b/src/Mod/Part/App/ConePyImp.cpp @@ -41,7 +41,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ConePy::representation(void) const +std::string ConePy::representation() const { return ""; } @@ -143,7 +143,7 @@ int ConePy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Object ConePy::getApex(void) const +Py::Object ConePy::getApex() const { Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast (getGeomConePtr()->handle()); @@ -151,7 +151,7 @@ Py::Object ConePy::getApex(void) const return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -Py::Float ConePy::getRadius(void) const +Py::Float ConePy::getRadius() const { Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast (getGeomConePtr()->handle()); @@ -165,7 +165,7 @@ void ConePy::setRadius(Py::Float arg) s->SetRadius((double)arg); } -Py::Float ConePy::getSemiAngle(void) const +Py::Float ConePy::getSemiAngle() const { Handle(Geom_ConicalSurface) s = Handle(Geom_ConicalSurface)::DownCast (getGeomConePtr()->handle()); @@ -179,7 +179,7 @@ void ConePy::setSemiAngle(Py::Float arg) s->SetSemiAngle((double)arg); } -Py::Object ConePy::getCenter(void) const +Py::Object ConePy::getCenter() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeomConePtr()->handle()); @@ -209,7 +209,7 @@ void ConePy::setCenter(Py::Object arg) } } -Py::Object ConePy::getAxis(void) const +Py::Object ConePy::getAxis() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/ConicPyImp.cpp b/src/Mod/Part/App/ConicPyImp.cpp index b8fbae5609..06d5d4456d 100644 --- a/src/Mod/Part/App/ConicPyImp.cpp +++ b/src/Mod/Part/App/ConicPyImp.cpp @@ -36,7 +36,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string ConicPy::representation(void) const +std::string ConicPy::representation() const { return ""; } @@ -55,14 +55,14 @@ int ConicPy::PyInit(PyObject* /*args*/, PyObject* /*kwds*/) return 0; } -Py::Object ConicPy::getCenter(void) const +Py::Object ConicPy::getCenter() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(getGeomConicPtr()->handle()); gp_Pnt loc = conic->Location(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -Py::Object ConicPy::getLocation(void) const +Py::Object ConicPy::getLocation() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(getGeomConicPtr()->handle()); gp_Pnt loc = conic->Location(); @@ -103,13 +103,13 @@ void ConicPy::setLocation(Py::Object arg) } } -Py::Float ConicPy::getEccentricity(void) const +Py::Float ConicPy::getEccentricity() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(getGeomConicPtr()->handle()); return Py::Float(conic->Eccentricity()); } -Py::Float ConicPy::getAngleXU(void) const +Py::Float ConicPy::getAngleXU() const { return Py::Float(getGeomConicPtr()->getAngleXU()); } @@ -119,7 +119,7 @@ void ConicPy::setAngleXU(Py::Float arg) getGeomConicPtr()->setAngleXU((double)arg); } -Py::Object ConicPy::getAxis(void) const +Py::Object ConicPy::getAxis() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(getGeomConicPtr()->handle()); gp_Ax1 axis = conic->Axis(); @@ -155,7 +155,7 @@ void ConicPy::setAxis(Py::Object arg) } } -Py::Object ConicPy::getXAxis(void) const +Py::Object ConicPy::getXAxis() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(getGeomConicPtr()->handle()); gp_Ax1 axis = conic->XAxis(); @@ -191,7 +191,7 @@ void ConicPy::setXAxis(Py::Object arg) } } -Py::Object ConicPy::getYAxis(void) const +Py::Object ConicPy::getYAxis() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(getGeomConicPtr()->handle()); gp_Ax1 axis = conic->YAxis(); diff --git a/src/Mod/Part/App/CrossSection.cpp b/src/Mod/Part/App/CrossSection.cpp index 0a8887823a..88d53dfeb7 100644 --- a/src/Mod/Part/App/CrossSection.cpp +++ b/src/Mod/Part/App/CrossSection.cpp @@ -138,7 +138,7 @@ void CrossSection::connectEdges (const std::list& edges, std::list< { // Hint: Use ShapeAnalysis_FreeBounds::ConnectEdgesToWires() as an alternative std::list edge_list = edges; - while (edge_list.size() > 0) { + while (!edge_list.empty()) { BRepBuilderAPI_MakeWire mkWire; // add and erase first edge mkWire.Add(edge_list.front()); diff --git a/src/Mod/Part/App/CustomFeature.cpp b/src/Mod/Part/App/CustomFeature.cpp index ed0f29b21f..fb79a4a20b 100644 --- a/src/Mod/Part/App/CustomFeature.cpp +++ b/src/Mod/Part/App/CustomFeature.cpp @@ -31,7 +31,7 @@ using namespace Part; PROPERTY_SOURCE(Part::CustomFeature, Part::Feature) -CustomFeature::CustomFeature(void) +CustomFeature::CustomFeature() { } @@ -39,12 +39,12 @@ CustomFeature::~CustomFeature() { } -short CustomFeature::mustExecute(void) const +short CustomFeature::mustExecute() const { return Part::Feature::mustExecute(); } -App::DocumentObjectExecReturn *CustomFeature::execute(void) +App::DocumentObjectExecReturn *CustomFeature::execute() { return App::DocumentObject::StdReturn; } @@ -54,7 +54,7 @@ App::DocumentObjectExecReturn *CustomFeature::execute(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Part::CustomFeaturePython, Part::CustomFeature) -template<> const char* Part::CustomFeaturePython::getViewProviderName(void) const { +template<> const char* Part::CustomFeaturePython::getViewProviderName() const { return "PartGui::ViewProviderCustomPython"; } /// @endcond diff --git a/src/Mod/Part/App/CustomFeature.h b/src/Mod/Part/App/CustomFeature.h index 09f2538a4d..389e208bc5 100644 --- a/src/Mod/Part/App/CustomFeature.h +++ b/src/Mod/Part/App/CustomFeature.h @@ -34,22 +34,22 @@ namespace Part */ class PartExport CustomFeature : public Part::Feature { - PROPERTY_HEADER(Part::UserFeature); + PROPERTY_HEADER_WITH_OVERRIDE(Part::UserFeature); public: /// Constructor - CustomFeature(void); - virtual ~CustomFeature(); + CustomFeature(); + ~CustomFeature() override; /** @name methods override feature */ //@{ /// recalculate the feature - virtual App::DocumentObjectExecReturn *execute(void); - virtual short mustExecute(void) const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderCustom"; } }; diff --git a/src/Mod/Part/App/CylinderPyImp.cpp b/src/Mod/Part/App/CylinderPyImp.cpp index 7881dda880..75559ce6a6 100644 --- a/src/Mod/Part/App/CylinderPyImp.cpp +++ b/src/Mod/Part/App/CylinderPyImp.cpp @@ -42,7 +42,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string CylinderPy::representation(void) const +std::string CylinderPy::representation() const { return ""; } @@ -150,7 +150,7 @@ int CylinderPy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Float CylinderPy::getRadius(void) const +Py::Float CylinderPy::getRadius() const { Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast (getGeomCylinderPtr()->handle()); @@ -164,7 +164,7 @@ void CylinderPy::setRadius(Py::Float arg) cyl->SetRadius((double)arg); } -Py::Object CylinderPy::getCenter(void) const +Py::Object CylinderPy::getCenter() const { Handle(Geom_CylindricalSurface) cyl = Handle(Geom_CylindricalSurface)::DownCast (getGeomCylinderPtr()->handle()); @@ -194,7 +194,7 @@ void CylinderPy::setCenter(Py::Object arg) } } -Py::Object CylinderPy::getAxis(void) const +Py::Object CylinderPy::getAxis() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/DatumFeature.cpp b/src/Mod/Part/App/DatumFeature.cpp index 3ddce9dafb..8cabfb5d5a 100644 --- a/src/Mod/Part/App/DatumFeature.cpp +++ b/src/Mod/Part/App/DatumFeature.cpp @@ -33,7 +33,7 @@ using namespace Attacher; PROPERTY_SOURCE_ABSTRACT_WITH_EXTENSIONS(Part::Datum, Part::Feature) -Datum::Datum(void) +Datum::Datum() { AttachExtension::initExtension(this); touch(); diff --git a/src/Mod/Part/App/DatumFeature.h b/src/Mod/Part/App/DatumFeature.h index e11da948e4..ef9b1f7fa4 100644 --- a/src/Mod/Part/App/DatumFeature.h +++ b/src/Mod/Part/App/DatumFeature.h @@ -39,11 +39,11 @@ class PartExport Datum : public Part::Feature, public Part::AttachExtension public: Datum(); - virtual ~Datum(); + ~Datum() override; //short mustExecute(); /// returns the type name of the view provider - virtual const char* getViewProviderName(void) const override = 0; + const char* getViewProviderName(void) const override = 0; /// Return a shape including Placement representing the datum feature virtual TopoDS_Shape getShape() const; @@ -51,7 +51,7 @@ public: /// Returns a point of the feature it counts as it's base virtual Base::Vector3d getBasePoint () const; - virtual App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, + App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const override; protected: void onDocumentRestored() override; diff --git a/src/Mod/Part/App/EllipsePyImp.cpp b/src/Mod/Part/App/EllipsePyImp.cpp index 91d55e8e06..3630a8defd 100644 --- a/src/Mod/Part/App/EllipsePyImp.cpp +++ b/src/Mod/Part/App/EllipsePyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string EllipsePy::representation(void) const +std::string EllipsePy::representation() const { return ""; } @@ -125,7 +125,7 @@ int EllipsePy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Float EllipsePy::getMajorRadius(void) const +Py::Float EllipsePy::getMajorRadius() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(getGeomEllipsePtr()->handle()); return Py::Float(ellipse->MajorRadius()); @@ -137,7 +137,7 @@ void EllipsePy::setMajorRadius(Py::Float arg) ellipse->SetMajorRadius((double)arg); } -Py::Float EllipsePy::getMinorRadius(void) const +Py::Float EllipsePy::getMinorRadius() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(getGeomEllipsePtr()->handle()); return Py::Float(ellipse->MinorRadius()); @@ -149,20 +149,20 @@ void EllipsePy::setMinorRadius(Py::Float arg) ellipse->SetMinorRadius((double)arg); } -Py::Float EllipsePy::getFocal(void) const +Py::Float EllipsePy::getFocal() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(getGeomEllipsePtr()->handle()); return Py::Float(ellipse->Focal()); } -Py::Object EllipsePy::getFocus1(void) const +Py::Object EllipsePy::getFocus1() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(getGeomEllipsePtr()->handle()); gp_Pnt loc = ellipse->Focus1(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -Py::Object EllipsePy::getFocus2(void) const +Py::Object EllipsePy::getFocus2() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(getGeomEllipsePtr()->handle()); gp_Pnt loc = ellipse->Focus2(); diff --git a/src/Mod/Part/App/ExtrusionHelper.cpp b/src/Mod/Part/App/ExtrusionHelper.cpp index d8987fd60b..27b6866bc1 100644 --- a/src/Mod/Part/App/ExtrusionHelper.cpp +++ b/src/Mod/Part/App/ExtrusionHelper.cpp @@ -69,7 +69,7 @@ void ExtrusionHelper::makeDraft(const TopoDS_Shape& shape, TopExp_Explorer ex; size_t i = 0; for (ex.Init(shape, TopAbs_WIRE); ex.More(); ex.Next(), ++i) { - wiresections.push_back(std::vector()); + wiresections.emplace_back(); wiresections[i].push_back(TopoDS::Wire(ex.Current())); } return i; diff --git a/src/Mod/Part/App/FT2FC.cpp b/src/Mod/Part/App/FT2FC.cpp index 3853b93056..b58d5085ef 100644 --- a/src/Mod/Part/App/FT2FC.cpp +++ b/src/Mod/Part/App/FT2FC.cpp @@ -224,7 +224,7 @@ static int move_cb(const FT_Vector* pt, void* p) { } dc->LastVert = *pt; if (dc->polyPoints.empty()) { - dc->polyPoints.push_back(Base::Vector3d(pt->x, pt->y, 0.0)); + dc->polyPoints.emplace_back(pt->x, pt->y, 0.0); } return 0; @@ -240,7 +240,7 @@ static int line_cb(const FT_Vector* pt, void* p) { TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(lseg , dc->surf); dc->Edges.push_back(edge); dc->LastVert = *pt; - dc->polyPoints.push_back(Base::Vector3d(pt->x, pt->y, 0.0)); + dc->polyPoints.emplace_back(pt->x, pt->y, 0.0); } return 0; } @@ -268,7 +268,7 @@ static int quad_cb(const FT_Vector* pt0, const FT_Vector* pt1, void* p) { TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf); dc->Edges.push_back(edge); dc->LastVert = *pt1; - dc->polyPoints.push_back(Base::Vector3d(pt1->x, pt1->y, 0.0)); + dc->polyPoints.emplace_back(pt1->x, pt1->y, 0.0); return 0; } @@ -297,7 +297,7 @@ static int cubic_cb(const FT_Vector* pt0, const FT_Vector* pt1, const FT_Vector* TopoDS_Edge edge = BRepBuilderAPI_MakeEdge(spline , dc->surf); dc->Edges.push_back(edge); dc->LastVert = *pt2; - dc->polyPoints.push_back(Base::Vector3d(pt2->x, pt2->y, 0.0)); + dc->polyPoints.emplace_back(pt2->x, pt2->y, 0.0); return 0; } diff --git a/src/Mod/Part/App/FaceMaker.cpp b/src/Mod/Part/App/FaceMaker.cpp index d01b65a270..d4e39c6388 100644 --- a/src/Mod/Part/App/FaceMaker.cpp +++ b/src/Mod/Part/App/FaceMaker.cpp @@ -83,7 +83,11 @@ const TopoDS_Face& Part::FaceMaker::Face() return TopoDS::Face(sh); } +#if OCC_VERSION_HEX >= 0x070600 +void Part::FaceMaker::Build(const Message_ProgressRange&) +#else void Part::FaceMaker::Build() +#endif { this->NotDone(); this->myShapesToReturn.clear(); diff --git a/src/Mod/Part/App/FaceMaker.h b/src/Mod/Part/App/FaceMaker.h index b9cd2be7f5..89c9a0ba67 100644 --- a/src/Mod/Part/App/FaceMaker.h +++ b/src/Mod/Part/App/FaceMaker.h @@ -24,6 +24,7 @@ #define PART_FACEMAKER_H #include +#include #include #include #include @@ -46,11 +47,11 @@ namespace Part */ class PartExport FaceMaker: public BRepBuilderAPI_MakeShape, public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: FaceMaker() {} - virtual ~FaceMaker() {} + ~FaceMaker() override {} virtual void addWire(const TopoDS_Wire& w); /** @@ -75,7 +76,11 @@ public: */ virtual const TopoDS_Face& Face(); - virtual void Build(); +#if OCC_VERSION_HEX >= 0x070600 + void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) override; +#else + void Build() override; +#endif //fails to compile, huh! //virtual const TopTools_ListOfShape& Generated(const TopoDS_Shape &S) override {throwNotImplemented();} @@ -110,7 +115,7 @@ protected: */ class PartExport FaceMakerPublic : public FaceMaker { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: virtual std::string getUserFriendlyName() const = 0; virtual std::string getBriefExplanation() const = 0; @@ -136,10 +141,10 @@ class PartExport FaceMakerSimple : public FaceMakerPublic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual std::string getUserFriendlyName() const override; - virtual std::string getBriefExplanation() const override; + std::string getUserFriendlyName() const override; + std::string getBriefExplanation() const override; protected: - virtual void Build_Essence() override; + void Build_Essence() override; }; diff --git a/src/Mod/Part/App/FaceMakerBullseye.h b/src/Mod/Part/App/FaceMakerBullseye.h index 003f0b4905..ac84bde6e7 100644 --- a/src/Mod/Part/App/FaceMakerBullseye.h +++ b/src/Mod/Part/App/FaceMakerBullseye.h @@ -55,11 +55,11 @@ public: */ void setPlane(const gp_Pln& plane); - virtual std::string getUserFriendlyName() const override; - virtual std::string getBriefExplanation() const override; + std::string getUserFriendlyName() const override; + std::string getBriefExplanation() const override; protected: - virtual void Build_Essence() override; + void Build_Essence() override; protected: gp_Pln myPlane; //externally supplied plane (if any) diff --git a/src/Mod/Part/App/FaceMakerCheese.h b/src/Mod/Part/App/FaceMakerCheese.h index 36430bcb09..db191889a4 100644 --- a/src/Mod/Part/App/FaceMakerCheese.h +++ b/src/Mod/Part/App/FaceMakerCheese.h @@ -42,8 +42,8 @@ class PartExport FaceMakerCheese: public FaceMakerPublic { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual std::string getUserFriendlyName() const override; - virtual std::string getBriefExplanation() const override; + std::string getUserFriendlyName() const override; + std::string getBriefExplanation() const override; public: //in Extrusion, they used to be private. but they are also used by PartDesign, so made public. /** @@ -63,7 +63,7 @@ private: static TopoDS_Shape makeFace(std::list&); // for internal use only protected: - virtual void Build_Essence() override; + void Build_Essence() override; }; diff --git a/src/Mod/Part/App/FeatureChamfer.h b/src/Mod/Part/App/FeatureChamfer.h index 9af5ee50a2..48212d1618 100644 --- a/src/Mod/Part/App/FeatureChamfer.h +++ b/src/Mod/Part/App/FeatureChamfer.h @@ -31,7 +31,7 @@ namespace Part class Chamfer : public Part::FilletBase { - PROPERTY_HEADER(Part::Chamfer); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Chamfer); public: Chamfer(); @@ -39,9 +39,9 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderChamfer"; } //@} diff --git a/src/Mod/Part/App/FeatureCompound.cpp b/src/Mod/Part/App/FeatureCompound.cpp index 8d8a9aeeb9..1e28fb3104 100644 --- a/src/Mod/Part/App/FeatureCompound.cpp +++ b/src/Mod/Part/App/FeatureCompound.cpp @@ -53,7 +53,7 @@ short Compound::mustExecute() const return 0; } -App::DocumentObjectExecReturn *Compound::execute(void) +App::DocumentObjectExecReturn *Compound::execute() { try { std::vector history; diff --git a/src/Mod/Part/App/FeatureCompound.h b/src/Mod/Part/App/FeatureCompound.h index 86c47e47bd..8e3f8ec4b0 100644 --- a/src/Mod/Part/App/FeatureCompound.h +++ b/src/Mod/Part/App/FeatureCompound.h @@ -32,21 +32,21 @@ namespace Part class Compound : public Part::Feature { - PROPERTY_HEADER(Part::Compound); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Compound); public: Compound(); - virtual ~Compound(); + ~Compound() override; App::PropertyLinkList Links; /** @name methods override feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderCompound"; } //@} @@ -57,7 +57,7 @@ class Compound2 : public Compound { PROPERTY_HEADER_WITH_OVERRIDE(Part::Compound2); public: Compound2(); - virtual void onDocumentRestored() override; + void onDocumentRestored() override; }; } //namespace Part diff --git a/src/Mod/Part/App/FeatureExtrusion.cpp b/src/Mod/Part/App/FeatureExtrusion.cpp index c516e5c509..c5264c04e2 100644 --- a/src/Mod/Part/App/FeatureExtrusion.cpp +++ b/src/Mod/Part/App/FeatureExtrusion.cpp @@ -97,7 +97,7 @@ bool Extrusion::fetchAxisLink(const App::PropertyLinkSub& axisLink, Base::Vector auto linked = axisLink.getValue(); TopoDS_Shape axEdge; - if (axisLink.getSubValues().size() > 0 && axisLink.getSubValues()[0].length() > 0) { + if (!axisLink.getSubValues().empty() && axisLink.getSubValues()[0].length() > 0) { axEdge = Feature::getTopoShape(linked, axisLink.getSubValues()[0].c_str(), true /*need element*/).getShape(); } else { @@ -311,7 +311,7 @@ TopoShape Extrusion::extrudeShape(const TopoShape& source, const Extrusion::Extr return TopoShape(result); } -App::DocumentObjectExecReturn* Extrusion::execute(void) +App::DocumentObjectExecReturn* Extrusion::execute() { App::DocumentObject* link = Base.getValue(); if (!link) @@ -342,7 +342,11 @@ std::string FaceMakerExtrusion::getBriefExplanation() const return std::string(QT_TRANSLATE_NOOP("Part_FaceMaker", "Supports making faces with holes, does not support nesting.")); } +#if OCC_VERSION_HEX >= 0x070600 +void FaceMakerExtrusion::Build(const Message_ProgressRange&) +#else void FaceMakerExtrusion::Build() +#endif { this->NotDone(); this->myGenerated.Clear(); diff --git a/src/Mod/Part/App/FeatureExtrusion.h b/src/Mod/Part/App/FeatureExtrusion.h index d9c346e1be..69158aae6a 100644 --- a/src/Mod/Part/App/FeatureExtrusion.h +++ b/src/Mod/Part/App/FeatureExtrusion.h @@ -121,7 +121,7 @@ public: //mode enumerations static const char* eDirModeStrings[]; protected: - virtual void setupObject() override; + void setupObject() override; }; /** @@ -133,12 +133,17 @@ class FaceMakerExtrusion: public FaceMakerCheese { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual std::string getUserFriendlyName() const override; - virtual std::string getBriefExplanation() const override; + std::string getUserFriendlyName() const override; + std::string getBriefExplanation() const override; + +#if OCC_VERSION_HEX >= 0x070600 + void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) override; +#else + void Build() override; +#endif - virtual void Build() override; protected: - virtual void Build_Essence() override {} + void Build_Essence() override {} }; } //namespace Part diff --git a/src/Mod/Part/App/FeatureFace.cpp b/src/Mod/Part/App/FeatureFace.cpp index c1ab98f76b..4b6cb26c20 100644 --- a/src/Mod/Part/App/FeatureFace.cpp +++ b/src/Mod/Part/App/FeatureFace.cpp @@ -57,7 +57,7 @@ void Face::setupObject() Feature::setupObject(); } -App::DocumentObjectExecReturn *Face::execute(void) +App::DocumentObjectExecReturn *Face::execute() { std::vector links = Sources.getValues(); if (links.empty()) diff --git a/src/Mod/Part/App/FeatureFace.h b/src/Mod/Part/App/FeatureFace.h index 912ad2a554..b0f3d2eb26 100644 --- a/src/Mod/Part/App/FeatureFace.h +++ b/src/Mod/Part/App/FeatureFace.h @@ -42,10 +42,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartGui::ViewProviderFace"; } void setupObject() override; diff --git a/src/Mod/Part/App/FeatureFillet.cpp b/src/Mod/Part/App/FeatureFillet.cpp index 17ea046085..3365962369 100644 --- a/src/Mod/Part/App/FeatureFillet.cpp +++ b/src/Mod/Part/App/FeatureFillet.cpp @@ -44,7 +44,7 @@ Fillet::Fillet() { } -App::DocumentObjectExecReturn *Fillet::execute(void) +App::DocumentObjectExecReturn *Fillet::execute() { App::DocumentObject* link = Base.getValue(); if (!link) diff --git a/src/Mod/Part/App/FeatureFillet.h b/src/Mod/Part/App/FeatureFillet.h index 86a07eebb0..bf3013aa85 100644 --- a/src/Mod/Part/App/FeatureFillet.h +++ b/src/Mod/Part/App/FeatureFillet.h @@ -31,7 +31,7 @@ namespace Part class Fillet : public Part::FilletBase { - PROPERTY_HEADER(Part::Fillet); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Fillet); public: Fillet(); @@ -39,9 +39,9 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderFillet"; } //@} diff --git a/src/Mod/Part/App/FeatureGeometrySet.cpp b/src/Mod/Part/App/FeatureGeometrySet.cpp index 2a2c0e1081..759c5df839 100644 --- a/src/Mod/Part/App/FeatureGeometrySet.cpp +++ b/src/Mod/Part/App/FeatureGeometrySet.cpp @@ -37,7 +37,7 @@ FeatureGeometrySet::FeatureGeometrySet() } -App::DocumentObjectExecReturn *FeatureGeometrySet::execute(void) +App::DocumentObjectExecReturn *FeatureGeometrySet::execute() { TopoShape result; diff --git a/src/Mod/Part/App/FeatureGeometrySet.h b/src/Mod/Part/App/FeatureGeometrySet.h index 79341c0003..7522e023ea 100644 --- a/src/Mod/Part/App/FeatureGeometrySet.h +++ b/src/Mod/Part/App/FeatureGeometrySet.h @@ -32,7 +32,7 @@ namespace Part class PartExport FeatureGeometrySet :public Part::Feature { - PROPERTY_HEADER(Part::FeatureGeometrySet); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FeatureGeometrySet); public: FeatureGeometrySet(); @@ -42,9 +42,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute(void) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "PartGui::ViewProviderGeometrySet"; } //@} diff --git a/src/Mod/Part/App/FeatureMirroring.cpp b/src/Mod/Part/App/FeatureMirroring.cpp index 4057881fe9..3449410dfc 100644 --- a/src/Mod/Part/App/FeatureMirroring.cpp +++ b/src/Mod/Part/App/FeatureMirroring.cpp @@ -90,7 +90,7 @@ void Mirroring::handleChangedPropertyType(Base::XMLReader &reader, const char *T } } -App::DocumentObjectExecReturn *Mirroring::execute(void) +App::DocumentObjectExecReturn *Mirroring::execute() { App::DocumentObject* link = Source.getValue(); if (!link) diff --git a/src/Mod/Part/App/FeatureMirroring.h b/src/Mod/Part/App/FeatureMirroring.h index 6dcdb836b5..d737acff7c 100644 --- a/src/Mod/Part/App/FeatureMirroring.h +++ b/src/Mod/Part/App/FeatureMirroring.h @@ -33,7 +33,7 @@ namespace Part class Mirroring : public Part::Feature { - PROPERTY_HEADER(Part::Mirroring); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Mirroring); public: Mirroring(); @@ -45,18 +45,18 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderMirror"; } //@} protected: - void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; - void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; }; diff --git a/src/Mod/Part/App/FeatureOffset.h b/src/Mod/Part/App/FeatureOffset.h index a46b55a1ab..ee3f6769a2 100644 --- a/src/Mod/Part/App/FeatureOffset.h +++ b/src/Mod/Part/App/FeatureOffset.h @@ -37,7 +37,7 @@ class PartExport Offset : public Part::Feature public: Offset(); - ~Offset(); + ~Offset() override; App::PropertyLink Source; App::PropertyFloat Value; @@ -50,9 +50,9 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual short mustExecute() const override; - virtual const char* getViewProviderName(void) const override { + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderOffset"; } //@} @@ -67,14 +67,14 @@ class PartExport Offset2D : public Offset PROPERTY_HEADER_WITH_OVERRIDE(Part::Offset2D); public: Offset2D(); - ~Offset2D(); + ~Offset2D() override; /** @name methods override feature */ //@{ /// recalculate the feature - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual short mustExecute() const override; - virtual const char* getViewProviderName(void) const override { + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderOffset2D"; } //@} diff --git a/src/Mod/Part/App/FeaturePartBoolean.cpp b/src/Mod/Part/App/FeaturePartBoolean.cpp index 91c6e2e519..4cf3d561f3 100644 --- a/src/Mod/Part/App/FeaturePartBoolean.cpp +++ b/src/Mod/Part/App/FeaturePartBoolean.cpp @@ -41,7 +41,7 @@ using namespace Part; PROPERTY_SOURCE_ABSTRACT(Part::Boolean, Part::Feature) -Boolean::Boolean(void) +Boolean::Boolean() { ADD_PROPERTY(Base,(nullptr)); ADD_PROPERTY(Tool,(nullptr)); @@ -68,7 +68,7 @@ short Boolean::mustExecute() const return 0; } -App::DocumentObjectExecReturn *Boolean::execute(void) +App::DocumentObjectExecReturn *Boolean::execute() { try { #if defined(__GNUC__) && defined (FC_OS_LINUX) diff --git a/src/Mod/Part/App/FeaturePartBoolean.h b/src/Mod/Part/App/FeaturePartBoolean.h index 72ec174178..0570fad18d 100644 --- a/src/Mod/Part/App/FeaturePartBoolean.h +++ b/src/Mod/Part/App/FeaturePartBoolean.h @@ -34,7 +34,7 @@ namespace Part class Boolean : public Part::Feature { - PROPERTY_HEADER(Part::Boolean); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Boolean); public: Boolean(); @@ -47,12 +47,12 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderBoolean"; } diff --git a/src/Mod/Part/App/FeaturePartBox.cpp b/src/Mod/Part/App/FeaturePartBox.cpp index eba2e89c0f..69b86d16e0 100644 --- a/src/Mod/Part/App/FeaturePartBox.cpp +++ b/src/Mod/Part/App/FeaturePartBox.cpp @@ -52,7 +52,7 @@ short Box::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Box::execute(void) +App::DocumentObjectExecReturn *Box::execute() { double L = Length.getValue(); double W = Width.getValue(); diff --git a/src/Mod/Part/App/FeaturePartBox.h b/src/Mod/Part/App/FeaturePartBox.h index f3cea7d1c3..bc3e7c4a05 100644 --- a/src/Mod/Part/App/FeaturePartBox.h +++ b/src/Mod/Part/App/FeaturePartBox.h @@ -33,7 +33,7 @@ namespace Part class PartExport Box :public Part::Primitive { - PROPERTY_HEADER(Part::Box); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Box); public: Box(); @@ -44,16 +44,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderBox"; } protected: - void Restore(Base::XMLReader &reader); + void Restore(Base::XMLReader &reader) override; /// get called by the container when a property has changed - virtual void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; //@} }; diff --git a/src/Mod/Part/App/FeaturePartCircle.cpp b/src/Mod/Part/App/FeaturePartCircle.cpp index db55127be5..b2f23dc648 100644 --- a/src/Mod/Part/App/FeaturePartCircle.cpp +++ b/src/Mod/Part/App/FeaturePartCircle.cpp @@ -58,7 +58,7 @@ short Circle::mustExecute() const Angle2.isTouched() || Radius.isTouched()) return 1; - return Part::Feature::mustExecute(); + return Part::Primitive::mustExecute(); } App::DocumentObjectExecReturn *Circle::execute(void) @@ -85,7 +85,7 @@ void Circle::onChanged(const App::Property* prop) } } } - Part::Feature::onChanged(prop); + Part::Feature::onChanged(prop); // clazy:exclude=skipped-base-method } void Circle::Restore(Base::XMLReader &reader) diff --git a/src/Mod/Part/App/FeaturePartCircle.h b/src/Mod/Part/App/FeaturePartCircle.h index d1a86403a6..f880f52099 100644 --- a/src/Mod/Part/App/FeaturePartCircle.h +++ b/src/Mod/Part/App/FeaturePartCircle.h @@ -32,11 +32,11 @@ namespace Part { class PartExport Circle : public Part::Primitive { - PROPERTY_HEADER(Part::Circle); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Circle); public: Circle(); - virtual ~Circle(); + ~Circle() override; App::PropertyLength Radius; App::PropertyAngle Angle1; @@ -45,17 +45,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - void onChanged(const App::Property*); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderCircleParametric"; } protected: - void Restore(Base::XMLReader &reader); - void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName); + void Restore(Base::XMLReader &reader) override; + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; private: static App::PropertyQuantityConstraint::Constraints angleRange; diff --git a/src/Mod/Part/App/FeaturePartCommon.cpp b/src/Mod/Part/App/FeaturePartCommon.cpp index 94fa3b443f..d849d5009b 100644 --- a/src/Mod/Part/App/FeaturePartCommon.cpp +++ b/src/Mod/Part/App/FeaturePartCommon.cpp @@ -42,7 +42,7 @@ using namespace Part; PROPERTY_SOURCE(Part::Common, Part::Boolean) -Common::Common(void) +Common::Common() { } @@ -57,7 +57,7 @@ BRepAlgoAPI_BooleanOperation* Common::makeOperation(const TopoDS_Shape& base, co PROPERTY_SOURCE(Part::MultiCommon, Part::Feature) -MultiCommon::MultiCommon(void) +MultiCommon::MultiCommon() { ADD_PROPERTY(Shapes,(nullptr)); Shapes.setSize(0); @@ -80,7 +80,7 @@ short MultiCommon::mustExecute() const return 0; } -App::DocumentObjectExecReturn *MultiCommon::execute(void) +App::DocumentObjectExecReturn *MultiCommon::execute() { std::vector s; std::vector obj = Shapes.getValues(); diff --git a/src/Mod/Part/App/FeaturePartCommon.h b/src/Mod/Part/App/FeaturePartCommon.h index 8bf4b3685e..37c1f8e1d7 100644 --- a/src/Mod/Part/App/FeaturePartCommon.h +++ b/src/Mod/Part/App/FeaturePartCommon.h @@ -31,7 +31,7 @@ namespace Part class Common : public Boolean { - PROPERTY_HEADER(Part::Common); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Common); public: Common(); @@ -40,13 +40,13 @@ public: //@{ /// recalculate the Feature protected: - BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const; + BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; //@} }; class MultiCommon : public Part::Feature { - PROPERTY_HEADER(Part::MultiCommon); + PROPERTY_HEADER_WITH_OVERRIDE(Part::MultiCommon); public: MultiCommon(); @@ -58,11 +58,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderMultiCommon"; } diff --git a/src/Mod/Part/App/FeaturePartCurveNet.cpp b/src/Mod/Part/App/FeaturePartCurveNet.cpp index 39dfcf6958..aafcf457ae 100644 --- a/src/Mod/Part/App/FeaturePartCurveNet.cpp +++ b/src/Mod/Part/App/FeaturePartCurveNet.cpp @@ -43,7 +43,7 @@ short CurveNet::mustExecute() const return 0; } -App::DocumentObjectExecReturn *CurveNet::execute(void) +App::DocumentObjectExecReturn *CurveNet::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { diff --git a/src/Mod/Part/App/FeaturePartCurveNet.h b/src/Mod/Part/App/FeaturePartCurveNet.h index 34f8d6c1e6..b1b84608fe 100644 --- a/src/Mod/Part/App/FeaturePartCurveNet.h +++ b/src/Mod/Part/App/FeaturePartCurveNet.h @@ -31,7 +31,7 @@ namespace Part class CurveNet :public Part::Feature { - PROPERTY_HEADER(Part::FeaturePartCurveNet); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FeaturePartCurveNet); public: CurveNet(); @@ -41,10 +41,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderCurveNet"; } //@} diff --git a/src/Mod/Part/App/FeaturePartCut.cpp b/src/Mod/Part/App/FeaturePartCut.cpp index 41e517dafa..d603618c83 100644 --- a/src/Mod/Part/App/FeaturePartCut.cpp +++ b/src/Mod/Part/App/FeaturePartCut.cpp @@ -33,7 +33,7 @@ using namespace Part; PROPERTY_SOURCE(Part::Cut, Part::Boolean) -Cut::Cut(void) +Cut::Cut() { } diff --git a/src/Mod/Part/App/FeaturePartCut.h b/src/Mod/Part/App/FeaturePartCut.h index 42891fba88..7b6c357cc2 100644 --- a/src/Mod/Part/App/FeaturePartCut.h +++ b/src/Mod/Part/App/FeaturePartCut.h @@ -31,7 +31,7 @@ namespace Part class Cut : public Boolean { - PROPERTY_HEADER(Part::Cut); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Cut); public: Cut(); @@ -40,7 +40,7 @@ public: //@{ /// recalculate the Feature protected: - BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const; + BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; //@} }; diff --git a/src/Mod/Part/App/FeaturePartFuse.cpp b/src/Mod/Part/App/FeaturePartFuse.cpp index f11ec9ad58..d72d08ddf8 100644 --- a/src/Mod/Part/App/FeaturePartFuse.cpp +++ b/src/Mod/Part/App/FeaturePartFuse.cpp @@ -42,7 +42,7 @@ using namespace Part; PROPERTY_SOURCE(Part::Fuse, Part::Boolean) -Fuse::Fuse(void) +Fuse::Fuse() { } @@ -57,7 +57,7 @@ BRepAlgoAPI_BooleanOperation* Fuse::makeOperation(const TopoDS_Shape& base, cons PROPERTY_SOURCE(Part::MultiFuse, Part::Feature) -MultiFuse::MultiFuse(void) +MultiFuse::MultiFuse() { ADD_PROPERTY(Shapes,(nullptr)); Shapes.setSize(0); @@ -81,7 +81,7 @@ short MultiFuse::mustExecute() const return 0; } -App::DocumentObjectExecReturn *MultiFuse::execute(void) +App::DocumentObjectExecReturn *MultiFuse::execute() { std::vector s; std::vector obj = Shapes.getValues(); diff --git a/src/Mod/Part/App/FeaturePartFuse.h b/src/Mod/Part/App/FeaturePartFuse.h index 5525374e33..fdee701b5c 100644 --- a/src/Mod/Part/App/FeaturePartFuse.h +++ b/src/Mod/Part/App/FeaturePartFuse.h @@ -31,7 +31,7 @@ namespace Part class Fuse : public Boolean { - PROPERTY_HEADER(Part::Fuse); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Fuse); public: Fuse(); @@ -40,13 +40,13 @@ public: //@{ /// recalculate the Feature protected: - BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const; + BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; //@} }; class MultiFuse : public Part::Feature { - PROPERTY_HEADER(Part::MultiFuse); + PROPERTY_HEADER_WITH_OVERRIDE(Part::MultiFuse); public: MultiFuse(); @@ -58,11 +58,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderMultiFuse"; } diff --git a/src/Mod/Part/App/FeaturePartImportBrep.cpp b/src/Mod/Part/App/FeaturePartImportBrep.cpp index be6cec3487..81c09ef1c2 100644 --- a/src/Mod/Part/App/FeaturePartImportBrep.cpp +++ b/src/Mod/Part/App/FeaturePartImportBrep.cpp @@ -36,7 +36,7 @@ using namespace Part; PROPERTY_SOURCE(Part::ImportBrep, Part::Feature) -ImportBrep::ImportBrep(void) +ImportBrep::ImportBrep() { ADD_PROPERTY(FileName,("")); } @@ -48,7 +48,7 @@ short ImportBrep::mustExecute() const return 0; } -App::DocumentObjectExecReturn *ImportBrep::execute(void) +App::DocumentObjectExecReturn *ImportBrep::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { diff --git a/src/Mod/Part/App/FeaturePartImportBrep.h b/src/Mod/Part/App/FeaturePartImportBrep.h index dfd2fdea39..341c0b3d16 100644 --- a/src/Mod/Part/App/FeaturePartImportBrep.h +++ b/src/Mod/Part/App/FeaturePartImportBrep.h @@ -31,7 +31,7 @@ namespace Part class ImportBrep :public Part::Feature { - PROPERTY_HEADER(Part::ImportBrep); + PROPERTY_HEADER_WITH_OVERRIDE(Part::ImportBrep); public: ImportBrep(); @@ -41,10 +41,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderImport"; } //@} diff --git a/src/Mod/Part/App/FeaturePartImportIges.cpp b/src/Mod/Part/App/FeaturePartImportIges.cpp index 837e9275ea..cc28d598a8 100644 --- a/src/Mod/Part/App/FeaturePartImportIges.cpp +++ b/src/Mod/Part/App/FeaturePartImportIges.cpp @@ -36,7 +36,7 @@ using namespace Part; PROPERTY_SOURCE(Part::ImportIges, Part::Feature) -ImportIges::ImportIges(void) +ImportIges::ImportIges() { ADD_PROPERTY(FileName,("")); } @@ -48,7 +48,7 @@ short ImportIges::mustExecute() const return 0; } -App::DocumentObjectExecReturn *ImportIges::execute(void) +App::DocumentObjectExecReturn *ImportIges::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { diff --git a/src/Mod/Part/App/FeaturePartImportIges.h b/src/Mod/Part/App/FeaturePartImportIges.h index 5593b8dbb5..695663104c 100644 --- a/src/Mod/Part/App/FeaturePartImportIges.h +++ b/src/Mod/Part/App/FeaturePartImportIges.h @@ -31,7 +31,7 @@ namespace Part class ImportIges :public Part::Feature { - PROPERTY_HEADER(Part::FeaturePartImportIges); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FeaturePartImportIges); public: ImportIges(); @@ -41,10 +41,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute(void) override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "PartGui::ViewProviderImport"; } //@} diff --git a/src/Mod/Part/App/FeaturePartImportStep.cpp b/src/Mod/Part/App/FeaturePartImportStep.cpp index 201980521a..435722b7cd 100644 --- a/src/Mod/Part/App/FeaturePartImportStep.cpp +++ b/src/Mod/Part/App/FeaturePartImportStep.cpp @@ -36,7 +36,7 @@ using namespace Part; PROPERTY_SOURCE(Part::ImportStep, Part::Feature) -ImportStep::ImportStep(void) +ImportStep::ImportStep() { ADD_PROPERTY(FileName,("")); } @@ -48,7 +48,7 @@ short ImportStep::mustExecute() const return 0; } -App::DocumentObjectExecReturn *ImportStep::execute(void) +App::DocumentObjectExecReturn *ImportStep::execute() { Base::FileInfo fi(FileName.getValue()); if (!fi.isReadable()) { diff --git a/src/Mod/Part/App/FeaturePartImportStep.h b/src/Mod/Part/App/FeaturePartImportStep.h index 1327905ae9..4b0475b5f4 100644 --- a/src/Mod/Part/App/FeaturePartImportStep.h +++ b/src/Mod/Part/App/FeaturePartImportStep.h @@ -33,7 +33,7 @@ namespace Part class ImportStep :public Part::Feature { - PROPERTY_HEADER(Part::FeaturePartImportStep); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FeaturePartImportStep); public: ImportStep(); @@ -43,10 +43,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderImport"; } //@} diff --git a/src/Mod/Part/App/FeaturePartPolygon.cpp b/src/Mod/Part/App/FeaturePartPolygon.cpp index ccc4c83197..1c52c98ecd 100644 --- a/src/Mod/Part/App/FeaturePartPolygon.cpp +++ b/src/Mod/Part/App/FeaturePartPolygon.cpp @@ -50,7 +50,7 @@ short Part::Polygon::mustExecute() const return 0; } -App::DocumentObjectExecReturn *Part::Polygon::execute(void) +App::DocumentObjectExecReturn *Part::Polygon::execute() { BRepBuilderAPI_MakePolygon poly; const std::vector nodes = Nodes.getValues(); diff --git a/src/Mod/Part/App/FeaturePartPolygon.h b/src/Mod/Part/App/FeaturePartPolygon.h index 64ce124558..65c8d334ab 100644 --- a/src/Mod/Part/App/FeaturePartPolygon.h +++ b/src/Mod/Part/App/FeaturePartPolygon.h @@ -33,11 +33,11 @@ namespace Part class Polygon : public Part::Feature { - PROPERTY_HEADER(Part::Polygon); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Polygon); public: Polygon(); - virtual ~Polygon(); + ~Polygon() override; App::PropertyVectorList Nodes; App::PropertyBool Close; @@ -45,8 +45,8 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} }; diff --git a/src/Mod/Part/App/FeaturePartSection.h b/src/Mod/Part/App/FeaturePartSection.h index 8f3d37a7d5..74c233e0ff 100644 --- a/src/Mod/Part/App/FeaturePartSection.h +++ b/src/Mod/Part/App/FeaturePartSection.h @@ -33,7 +33,7 @@ namespace Part class Section : public Boolean { - PROPERTY_HEADER(Part::Section); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Section); public: Section(); @@ -43,9 +43,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - short mustExecute() const; + short mustExecute() const override; protected: - BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const; + BRepAlgoAPI_BooleanOperation* makeOperation(const TopoDS_Shape&, const TopoDS_Shape&) const override; //@} }; diff --git a/src/Mod/Part/App/FeaturePartSpline.h b/src/Mod/Part/App/FeaturePartSpline.h index 921dcd0317..5bdc765dab 100644 --- a/src/Mod/Part/App/FeaturePartSpline.h +++ b/src/Mod/Part/App/FeaturePartSpline.h @@ -31,12 +31,12 @@ namespace Part class PartExport Spline :public Part::Feature { - PROPERTY_HEADER(Part::Spline); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Spline); public: Spline(); /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderSpline"; } }; diff --git a/src/Mod/Part/App/FeatureRevolution.cpp b/src/Mod/Part/App/FeatureRevolution.cpp index 5b887169b6..5667f263e7 100644 --- a/src/Mod/Part/App/FeatureRevolution.cpp +++ b/src/Mod/Part/App/FeatureRevolution.cpp @@ -89,7 +89,7 @@ bool Revolution::fetchAxisLink(const App::PropertyLinkSub &axisLink, auto linked = axisLink.getValue(); TopoDS_Shape axEdge; - if (axisLink.getSubValues().size() > 0 && axisLink.getSubValues()[0].length() > 0){ + if (!axisLink.getSubValues().empty() && axisLink.getSubValues()[0].length() > 0){ axEdge = Feature::getTopoShape(linked, axisLink.getSubValues()[0].c_str(), true /*need element*/).getShape(); } else { axEdge = Feature::getShape(linked); @@ -121,7 +121,7 @@ bool Revolution::fetchAxisLink(const App::PropertyLinkSub &axisLink, return true; } -App::DocumentObjectExecReturn *Revolution::execute(void) +App::DocumentObjectExecReturn *Revolution::execute() { App::DocumentObject* link = Source.getValue(); if (!link) diff --git a/src/Mod/Part/App/FeatureRevolution.h b/src/Mod/Part/App/FeatureRevolution.h index cf8dc28d00..27da2fb1e8 100644 --- a/src/Mod/Part/App/FeatureRevolution.h +++ b/src/Mod/Part/App/FeatureRevolution.h @@ -51,13 +51,13 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; void onChanged(const App::Property* prop) override; /// returns the type name of the view provider - const char* getViewProviderName(void) const override{ + const char* getViewProviderName() const override{ return "PartGui::ViewProviderRevolution"; } //@} @@ -83,7 +83,7 @@ private: static App::PropertyFloatConstraint::Constraints angleRangeU; protected: - virtual void setupObject() override; + void setupObject() override; }; } //namespace Part diff --git a/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp index 25ef756a10..37cf28cf92 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfCircle2dPyImp.cpp @@ -41,7 +41,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfCircle2dPy::representation(void) const +std::string ArcOfCircle2dPy::representation() const { return ""; } @@ -108,7 +108,7 @@ int ArcOfCircle2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfCircle2dPy::getRadius(void) const +Py::Float ArcOfCircle2dPy::getRadius() const { return Py::Float(getGeom2dArcOfCirclePtr()->getRadius()); } @@ -118,7 +118,7 @@ void ArcOfCircle2dPy::setRadius(Py::Float arg) getGeom2dArcOfCirclePtr()->setRadius((double)arg); } -Py::Object ArcOfCircle2dPy::getCircle(void) const +Py::Object ArcOfCircle2dPy::getCircle() const { Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(curve->BasisCurve()); diff --git a/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp index 0ad55faadb..20be65c3ec 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfConic2dPyImp.cpp @@ -36,7 +36,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string ArcOfConic2dPy::representation(void) const +std::string ArcOfConic2dPy::representation() const { return ""; } @@ -55,7 +55,7 @@ int ArcOfConic2dPy::PyInit(PyObject* /*args*/, PyObject* /*kwds*/) return -1; } -Py::Object ArcOfConic2dPy::getLocation(void) const +Py::Object ArcOfConic2dPy::getLocation() const { Base::Vector2d loc = getGeom2dArcOfConicPtr()->getLocation(); return Base::Vector2dPy::create(loc); @@ -67,14 +67,14 @@ void ArcOfConic2dPy::setLocation(Py::Object arg) getGeom2dArcOfConicPtr()->setLocation(loc); } -Py::Float ArcOfConic2dPy::getEccentricity(void) const +Py::Float ArcOfConic2dPy::getEccentricity() const { Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); return Py::Float(conic->Eccentricity()); } -Py::Object ArcOfConic2dPy::getXAxis(void) const +Py::Object ArcOfConic2dPy::getXAxis() const { Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); @@ -92,7 +92,7 @@ void ArcOfConic2dPy::setXAxis(Py::Object arg) conic->SetXAxis(xaxis); } -Py::Object ArcOfConic2dPy::getYAxis(void) const +Py::Object ArcOfConic2dPy::getYAxis() const { Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); diff --git a/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp index 5a0ecbe6ab..1cccf0b23f 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfEllipse2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfEllipse2dPy::representation(void) const +std::string ArcOfEllipse2dPy::representation() const { return ""; } @@ -86,7 +86,7 @@ int ArcOfEllipse2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfEllipse2dPy::getMajorRadius(void) const +Py::Float ArcOfEllipse2dPy::getMajorRadius() const { return Py::Float(getGeom2dArcOfEllipsePtr()->getMajorRadius()); } @@ -96,7 +96,7 @@ void ArcOfEllipse2dPy::setMajorRadius(Py::Float arg) getGeom2dArcOfEllipsePtr()->setMajorRadius((double)arg); } -Py::Float ArcOfEllipse2dPy::getMinorRadius(void) const +Py::Float ArcOfEllipse2dPy::getMinorRadius() const { return Py::Float(getGeom2dArcOfEllipsePtr()->getMinorRadius()); } @@ -106,7 +106,7 @@ void ArcOfEllipse2dPy::setMinorRadius(Py::Float arg) getGeom2dArcOfEllipsePtr()->setMinorRadius((double)arg); } -Py::Object ArcOfEllipse2dPy::getEllipse(void) const +Py::Object ArcOfEllipse2dPy::getEllipse() const { Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(getGeom2dArcOfConicPtr()->handle()); Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(curve->BasisCurve()); diff --git a/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp index f7cc422bb4..c31836e611 100644 --- a/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/ArcOfParabola2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ArcOfParabola2dPy::representation(void) const +std::string ArcOfParabola2dPy::representation() const { return ""; } @@ -86,7 +86,7 @@ int ArcOfParabola2dPy::PyInit(PyObject* args, PyObject* /*kwds*/) return -1; } -Py::Float ArcOfParabola2dPy::getFocal(void) const +Py::Float ArcOfParabola2dPy::getFocal() const { return Py::Float(getGeom2dArcOfParabolaPtr()->getFocal()); } @@ -96,7 +96,7 @@ void ArcOfParabola2dPy::setFocal(Py::Float arg) getGeom2dArcOfParabolaPtr()->setFocal((double)arg); } -Py::Object ArcOfParabola2dPy::getParabola(void) const +Py::Object ArcOfParabola2dPy::getParabola() const { Handle(Geom2d_TrimmedCurve) trim = Handle(Geom2d_TrimmedCurve)::DownCast (getGeom2dArcOfParabolaPtr()->handle()); diff --git a/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp index e1c843b911..f32ec4b3de 100644 --- a/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/BSplineCurve2dPyImp.cpp @@ -48,7 +48,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BSplineCurve2dPy::representation(void) const +std::string BSplineCurve2dPy::representation() const { return ""; } @@ -618,35 +618,35 @@ PyObject* BSplineCurve2dPy::getMultiplicities(PyObject * args) } } -Py::Long BSplineCurve2dPy::getDegree(void) const +Py::Long BSplineCurve2dPy::getDegree() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->Degree()); } -Py::Long BSplineCurve2dPy::getMaxDegree(void) const +Py::Long BSplineCurve2dPy::getMaxDegree() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->MaxDegree()); } -Py::Long BSplineCurve2dPy::getNbPoles(void) const +Py::Long BSplineCurve2dPy::getNbPoles() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->NbPoles()); } -Py::Long BSplineCurve2dPy::getNbKnots(void) const +Py::Long BSplineCurve2dPy::getNbKnots() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->NbKnots()); } -Py::Object BSplineCurve2dPy::getStartPoint(void) const +Py::Object BSplineCurve2dPy::getStartPoint() const { Handle(Geom2d_BSplineCurve) c = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); @@ -654,7 +654,7 @@ Py::Object BSplineCurve2dPy::getStartPoint(void) const return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } -Py::Object BSplineCurve2dPy::getEndPoint(void) const +Py::Object BSplineCurve2dPy::getEndPoint() const { Handle(Geom2d_BSplineCurve) c = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); @@ -662,21 +662,21 @@ Py::Object BSplineCurve2dPy::getEndPoint(void) const return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } -Py::Object BSplineCurve2dPy::getFirstUKnotIndex(void) const +Py::Object BSplineCurve2dPy::getFirstUKnotIndex() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->FirstUKnotIndex()); } -Py::Object BSplineCurve2dPy::getLastUKnotIndex(void) const +Py::Object BSplineCurve2dPy::getLastUKnotIndex() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->LastUKnotIndex()); } -Py::List BSplineCurve2dPy::getKnotSequence(void) const +Py::List BSplineCurve2dPy::getKnotSequence() const { Handle(Geom2d_BSplineCurve) curve = Handle(Geom2d_BSplineCurve)::DownCast (getGeometry2dPtr()->handle()); diff --git a/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp index 17e5baeb94..a56306bf40 100644 --- a/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/BezierCurve2dPyImp.cpp @@ -38,7 +38,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string BezierCurve2dPy::representation(void) const +std::string BezierCurve2dPy::representation() const { return ""; } @@ -337,28 +337,28 @@ PyObject* BezierCurve2dPy::getResolution(PyObject* args) return nullptr; } } -Py::Long BezierCurve2dPy::getDegree(void) const +Py::Long BezierCurve2dPy::getDegree() const { Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->Degree()); } -Py::Long BezierCurve2dPy::getMaxDegree(void) const +Py::Long BezierCurve2dPy::getMaxDegree() const { Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->MaxDegree()); } -Py::Long BezierCurve2dPy::getNbPoles(void) const +Py::Long BezierCurve2dPy::getNbPoles() const { Handle(Geom2d_BezierCurve) curve = Handle(Geom2d_BezierCurve)::DownCast (getGeometry2dPtr()->handle()); return Py::Long(curve->NbPoles()); } -Py::Object BezierCurve2dPy::getStartPoint(void) const +Py::Object BezierCurve2dPy::getStartPoint() const { Handle(Geom2d_BezierCurve) c = Handle(Geom2d_BezierCurve)::DownCast (getGeometry2dPtr()->handle()); @@ -366,7 +366,7 @@ Py::Object BezierCurve2dPy::getStartPoint(void) const return Base::Vector2dPy::create(pnt.X(), pnt.Y()); } -Py::Object BezierCurve2dPy::getEndPoint(void) const +Py::Object BezierCurve2dPy::getEndPoint() const { Handle(Geom2d_BezierCurve) c = Handle(Geom2d_BezierCurve)::DownCast (getGeometry2dPtr()->handle()); diff --git a/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp index 25941ab3b4..c1ca37908f 100644 --- a/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Circle2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string Circle2dPy::representation(void) const +std::string Circle2dPy::representation() const { return ""; } @@ -161,7 +161,7 @@ PyObject* Circle2dPy::getCircleCenter(PyObject *args) return Py::new_reference_to(Base::Vector2dPy::create(cnt)); } -Py::Float Circle2dPy::getRadius(void) const +Py::Float Circle2dPy::getRadius() const { Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(getGeom2dCirclePtr()->handle()); return Py::Float(circle->Radius()); diff --git a/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp index c8095c6e1a..7f070c5e5f 100644 --- a/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Conic2dPyImp.cpp @@ -35,7 +35,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string Conic2dPy::representation(void) const +std::string Conic2dPy::representation() const { return ""; } @@ -54,7 +54,7 @@ int Conic2dPy::PyInit(PyObject* /*args*/, PyObject* /*kwds*/) return 0; } -Py::Object Conic2dPy::getLocation(void) const +Py::Object Conic2dPy::getLocation() const { Base::Vector2d loc = getGeom2dConicPtr()->getLocation(); return Base::Vector2dPy::create(loc); @@ -66,13 +66,13 @@ void Conic2dPy::setLocation(Py::Object arg) getGeom2dConicPtr()->setLocation(loc); } -Py::Float Conic2dPy::getEccentricity(void) const +Py::Float Conic2dPy::getEccentricity() const { Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(getGeom2dConicPtr()->handle()); return Py::Float(conic->Eccentricity()); } -Py::Object Conic2dPy::getXAxis(void) const +Py::Object Conic2dPy::getXAxis() const { Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(getGeom2dConicPtr()->handle()); gp_Dir2d xdir = conic->XAxis().Direction(); @@ -88,7 +88,7 @@ void Conic2dPy::setXAxis(Py::Object arg) conic->SetXAxis(xaxis); } -Py::Object Conic2dPy::getYAxis(void) const +Py::Object Conic2dPy::getYAxis() const { Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(getGeom2dConicPtr()->handle()); gp_Dir2d ydir = conic->YAxis().Direction(); diff --git a/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp index 8cee685f0f..79fe755056 100644 --- a/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Curve2dPyImp.cpp @@ -68,7 +68,7 @@ extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string Curve2dPy::representation(void) const +std::string Curve2dPy::representation() const { return ""; } @@ -719,7 +719,7 @@ PyObject* Curve2dPy::approximateBSpline(PyObject *args) } } -Py::String Curve2dPy::getContinuity(void) const +Py::String Curve2dPy::getContinuity() const { GeomAbs_Shape c = Handle(Geom2d_Curve)::DownCast (getGeometry2dPtr()->handle())->Continuity(); @@ -753,25 +753,25 @@ Py::String Curve2dPy::getContinuity(void) const return Py::String(str); } -Py::Boolean Curve2dPy::getClosed(void) const +Py::Boolean Curve2dPy::getClosed() const { return Py::Boolean(Handle(Geom2d_Curve)::DownCast (getGeometry2dPtr()->handle())->IsClosed() ? true : false); } -Py::Boolean Curve2dPy::getPeriodic(void) const +Py::Boolean Curve2dPy::getPeriodic() const { return Py::Boolean(Handle(Geom2d_Curve)::DownCast (getGeometry2dPtr()->handle())->IsPeriodic() ? true : false); } -Py::Float Curve2dPy::getFirstParameter(void) const +Py::Float Curve2dPy::getFirstParameter() const { return Py::Float(Handle(Geom2d_Curve)::DownCast (getGeometry2dPtr()->handle())->FirstParameter()); } -Py::Float Curve2dPy::getLastParameter(void) const +Py::Float Curve2dPy::getLastParameter() const { return Py::Float(Handle(Geom2d_Curve)::DownCast (getGeometry2dPtr()->handle())->LastParameter()); diff --git a/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp index e422927105..9fd42a96d7 100644 --- a/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Ellipse2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string Ellipse2dPy::representation(void) const +std::string Ellipse2dPy::representation() const { return ""; } @@ -125,7 +125,7 @@ int Ellipse2dPy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Float Ellipse2dPy::getMajorRadius(void) const +Py::Float Ellipse2dPy::getMajorRadius() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); return Py::Float(ellipse->MajorRadius()); @@ -137,7 +137,7 @@ void Ellipse2dPy::setMajorRadius(Py::Float arg) ellipse->SetMajorRadius((double)arg); } -Py::Float Ellipse2dPy::getMinorRadius(void) const +Py::Float Ellipse2dPy::getMinorRadius() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); return Py::Float(ellipse->MinorRadius()); @@ -149,20 +149,20 @@ void Ellipse2dPy::setMinorRadius(Py::Float arg) ellipse->SetMinorRadius((double)arg); } -Py::Float Ellipse2dPy::getFocal(void) const +Py::Float Ellipse2dPy::getFocal() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); return Py::Float(ellipse->Focal()); } -Py::Object Ellipse2dPy::getFocus1(void) const +Py::Object Ellipse2dPy::getFocus1() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); gp_Pnt2d loc = ellipse->Focus1(); return Base::Vector2dPy::create(loc.X(), loc.Y()); } -Py::Object Ellipse2dPy::getFocus2(void) const +Py::Object Ellipse2dPy::getFocus2() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(getGeom2dEllipsePtr()->handle()); gp_Pnt2d loc = ellipse->Focus2(); diff --git a/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp index b5f9c360d3..e08976077c 100644 --- a/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Geometry2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string Geometry2dPy::representation(void) const +std::string Geometry2dPy::representation() const { return ""; } diff --git a/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp index 5a0e5c8855..a65160d3d0 100644 --- a/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Hyperbola2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string Hyperbola2dPy::representation(void) const +std::string Hyperbola2dPy::representation() const { return ""; } @@ -125,7 +125,7 @@ int Hyperbola2dPy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Float Hyperbola2dPy::getMajorRadius(void) const +Py::Float Hyperbola2dPy::getMajorRadius() const { Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); return Py::Float(hyperbola->MajorRadius()); @@ -137,7 +137,7 @@ void Hyperbola2dPy::setMajorRadius(Py::Float arg) hyperbola->SetMajorRadius((double)arg); } -Py::Float Hyperbola2dPy::getMinorRadius(void) const +Py::Float Hyperbola2dPy::getMinorRadius() const { Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); return Py::Float(hyperbola->MinorRadius()); @@ -149,20 +149,20 @@ void Hyperbola2dPy::setMinorRadius(Py::Float arg) hyperbola->SetMinorRadius((double)arg); } -Py::Float Hyperbola2dPy::getFocal(void) const +Py::Float Hyperbola2dPy::getFocal() const { Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); return Py::Float(hyperbola->Focal()); } -Py::Object Hyperbola2dPy::getFocus1(void) const +Py::Object Hyperbola2dPy::getFocus1() const { Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); gp_Pnt2d loc = hyperbola->Focus1(); return Base::Vector2dPy::create(loc.X(), loc.Y()); } -Py::Object Hyperbola2dPy::getFocus2(void) const +Py::Object Hyperbola2dPy::getFocus2() const { Handle(Geom2d_Hyperbola) hyperbola = Handle(Geom2d_Hyperbola)::DownCast(getGeom2dHyperbolaPtr()->handle()); gp_Pnt2d loc = hyperbola->Focus2(); diff --git a/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp index 822dc8dd72..7ef16eb806 100644 --- a/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Line2dPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string Line2dPy::representation(void) const +std::string Line2dPy::representation() const { return ""; } @@ -118,7 +118,7 @@ int Line2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Object Line2dPy::getLocation(void) const +Py::Object Line2dPy::getLocation() const { Handle(Geom2d_Line) this_curve = Handle(Geom2d_Line)::DownCast (this->getGeom2dLinePtr()->handle()); @@ -166,7 +166,7 @@ void Line2dPy::setLocation(Py::Object arg) } } -Py::Object Line2dPy::getDirection(void) const +Py::Object Line2dPy::getDirection() const { Handle(Geom2d_Line) this_curve = Handle(Geom2d_Line)::DownCast (this->getGeom2dLinePtr()->handle()); diff --git a/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp b/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp index f7904f068c..ebf37a6d4f 100644 --- a/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Line2dSegmentPyImp.cpp @@ -41,7 +41,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string Line2dSegmentPy::representation(void) const +std::string Line2dSegmentPy::representation() const { return ""; } @@ -192,7 +192,7 @@ PyObject* Line2dSegmentPy::setParameterRange(PyObject *args) Py_Return; } -Py::Object Line2dSegmentPy::getStartPoint(void) const +Py::Object Line2dSegmentPy::getStartPoint() const { Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast (this->getGeom2dLineSegmentPtr()->handle()); @@ -246,7 +246,7 @@ void Line2dSegmentPy::setStartPoint(Py::Object arg) } } -Py::Object Line2dSegmentPy::getEndPoint(void) const +Py::Object Line2dSegmentPy::getEndPoint() const { Handle(Geom2d_TrimmedCurve) this_curve = Handle(Geom2d_TrimmedCurve)::DownCast (this->getGeom2dLineSegmentPtr()->handle()); diff --git a/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp b/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp index 31333aebc7..c4f39e711a 100644 --- a/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/OffsetCurve2dPyImp.cpp @@ -33,7 +33,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string OffsetCurve2dPy::representation(void) const +std::string OffsetCurve2dPy::representation() const { return ""; } @@ -74,7 +74,7 @@ int OffsetCurve2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } -Py::Float OffsetCurve2dPy::getOffsetValue(void) const +Py::Float OffsetCurve2dPy::getOffsetValue() const { Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast(getGeometry2dPtr()->handle()); return Py::Float(curve->Offset()); @@ -86,7 +86,7 @@ void OffsetCurve2dPy::setOffsetValue(Py::Float arg) curve->SetOffsetValue((double)arg); } -Py::Object OffsetCurve2dPy::getBasisCurve(void) const +Py::Object OffsetCurve2dPy::getBasisCurve() const { Handle(Geom2d_OffsetCurve) curve = Handle(Geom2d_OffsetCurve)::DownCast(getGeometry2dPtr()->handle()); Handle(Geom2d_Curve) basis = curve->BasisCurve(); diff --git a/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp b/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp index 353eb1bdbd..9c79d43a01 100644 --- a/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp +++ b/src/Mod/Part/App/Geom2d/Parabola2dPyImp.cpp @@ -35,7 +35,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string Parabola2dPy::representation(void) const +std::string Parabola2dPy::representation() const { return ""; } @@ -59,7 +59,7 @@ int Parabola2dPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Float Parabola2dPy::getFocal(void) const +Py::Float Parabola2dPy::getFocal() const { Handle(Geom2d_Parabola) curve = Handle(Geom2d_Parabola)::DownCast(getGeometry2dPtr()->handle()); return Py::Float(curve->Focal()); @@ -71,14 +71,14 @@ void Parabola2dPy::setFocal(Py::Float arg) curve->SetFocal((double)arg); } -Py::Object Parabola2dPy::getFocus(void) const +Py::Object Parabola2dPy::getFocus() const { Handle(Geom2d_Parabola) curve = Handle(Geom2d_Parabola)::DownCast(getGeometry2dPtr()->handle()); gp_Pnt2d loc = curve->Focus(); return Base::Vector2dPy::create(loc.X(), loc.Y()); } -Py::Float Parabola2dPy::getParameter(void) const +Py::Float Parabola2dPy::getParameter() const { Handle(Geom2d_Parabola) curve = Handle(Geom2d_Parabola)::DownCast(getGeometry2dPtr()->handle()); return Py::Float(curve->Parameter()); diff --git a/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePy.xml b/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePy.xml index 56207b3910..acc63debfb 100644 --- a/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePy.xml +++ b/src/Mod/Part/App/GeomPlate/BuildPlateSurfacePy.xml @@ -58,7 +58,7 @@ - Returns the orientation of the curves in the the array returned by curves2d + Returns the orientation of the curves in the array returned by curves2d diff --git a/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp b/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp index 450a778554..aca3233ddb 100644 --- a/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp +++ b/src/Mod/Part/App/GeomPlate/CurveConstraintPyImp.cpp @@ -116,7 +116,7 @@ int CurveConstraintPy::PyInit(PyObject* args, PyObject* kwds) } // returns a string which represents the object e.g. when printed in python -std::string CurveConstraintPy::representation(void) const +std::string CurveConstraintPy::representation() const { return std::string(""); } @@ -353,7 +353,7 @@ PyObject* CurveConstraintPy::projectedCurve(PyObject *args) } } -Py::Long CurveConstraintPy::getNbPoints(void) const +Py::Long CurveConstraintPy::getNbPoints() const { try { Standard_Integer v = getGeomPlate_CurveConstraintPtr()->NbPoints(); @@ -374,7 +374,7 @@ void CurveConstraintPy::setNbPoints(Py::Long arg) } } -Py::Float CurveConstraintPy::getFirstParameter(void) const +Py::Float CurveConstraintPy::getFirstParameter() const { try { Standard_Real v = getGeomPlate_CurveConstraintPtr()->FirstParameter(); @@ -385,7 +385,7 @@ Py::Float CurveConstraintPy::getFirstParameter(void) const } } -Py::Float CurveConstraintPy::getLastParameter(void) const +Py::Float CurveConstraintPy::getLastParameter() const { try { Standard_Real v = getGeomPlate_CurveConstraintPtr()->LastParameter(); @@ -396,7 +396,7 @@ Py::Float CurveConstraintPy::getLastParameter(void) const } } -Py::Float CurveConstraintPy::getLength(void) const +Py::Float CurveConstraintPy::getLength() const { try { Standard_Real v = getGeomPlate_CurveConstraintPtr()->Length(); diff --git a/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp b/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp index 73e9284a5f..89713c5717 100644 --- a/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp +++ b/src/Mod/Part/App/GeomPlate/PointConstraintPyImp.cpp @@ -68,7 +68,7 @@ int PointConstraintPy::PyInit(PyObject* args, PyObject* kwds) } // returns a string which represents the object e.g. when printed in python -std::string PointConstraintPy::representation(void) const +std::string PointConstraintPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/Geometry.cpp b/src/Mod/Part/App/Geometry.cpp index b9728251dd..118f0bb16b 100644 --- a/src/Mod/Part/App/Geometry.cpp +++ b/src/Mod/Part/App/Geometry.cpp @@ -26,6 +26,7 @@ # include # include # include +# include # include # include # include @@ -37,10 +38,10 @@ # include # include # include -#include -#include -#include -#include +# include +# include +# include +# include # include # include # include @@ -197,7 +198,7 @@ Geometry::~Geometry() } // Persistence implementer -unsigned int Geometry::getMemSize (void) const +unsigned int Geometry::getMemSize () const { return 1; } @@ -208,7 +209,7 @@ void Geometry::Save(Base::Writer &writer) const // Get the number of persistent extensions int counter = 0; - for(auto att:extensions) { + for(const auto& att : extensions) { if(att->isDerivedFrom(Part::GeometryPersistenceExtension::getClassTypeId())) counter++; } @@ -217,7 +218,7 @@ void Geometry::Save(Base::Writer &writer) const writer.incInd(); - for(auto att:extensions) { + for(const auto& att : extensions) { if(att->isDerivedFrom(Part::GeometryPersistenceExtension::getClassTypeId())) std::static_pointer_cast(att)->Save(writer); } @@ -282,7 +283,7 @@ std::vector> Geometry::getExtensions() co bool Geometry::hasExtension(Base::Type type) const { - for( auto ext : extensions) { + for(const auto& ext : extensions) { if(ext->getTypeId() == type) return true; } @@ -292,7 +293,7 @@ bool Geometry::hasExtension(Base::Type type) const bool Geometry::hasExtension(const std::string & name) const { - for( auto ext : extensions) { + for(const auto& ext : extensions) { if(ext->getName() == name) return true; } @@ -302,7 +303,7 @@ bool Geometry::hasExtension(const std::string & name) const std::weak_ptr Geometry::getExtension(Base::Type type) { - for( auto ext : extensions) { + for(const auto& ext : extensions) { if(ext->getTypeId() == type) return ext; } @@ -312,7 +313,7 @@ std::weak_ptr Geometry::getExtension(Base::Type type) std::weak_ptr Geometry::getExtension(const std::string & name) { - for( auto ext : extensions) { + for(const auto& ext : extensions) { if(ext->getName() == name) return ext; } @@ -406,7 +407,7 @@ void Geometry::copyNonTag(const Part::Geometry * src) } } -Geometry *Geometry::clone(void) const +Geometry *Geometry::clone() const { Geometry* cpy = this->copy(); cpy->tag = this->tag; @@ -498,7 +499,7 @@ void GeomPoint::setHandle(const Handle(Geom_CartesianPoint)& p) myPoint = Handle(Geom_CartesianPoint)::DownCast(p->Copy()); } -Geometry *GeomPoint::copy(void) const +Geometry *GeomPoint::copy() const { GeomPoint *newPoint = new GeomPoint(myPoint); newPoint->copyNonTag(this); @@ -510,7 +511,7 @@ TopoDS_Shape GeomPoint::toShape() const return BRepBuilderAPI_MakeVertex(myPoint->Pnt()); } -Base::Vector3d GeomPoint::getPoint(void)const +Base::Vector3d GeomPoint::getPoint()const { return Base::Vector3d(myPoint->X(),myPoint->Y(),myPoint->Z()); } @@ -521,7 +522,7 @@ void GeomPoint::setPoint(const Base::Vector3d& p) } // Persistence implementer -unsigned int GeomPoint::getMemSize (void) const +unsigned int GeomPoint::getMemSize () const { return sizeof(Geom_CartesianPoint); } @@ -558,7 +559,7 @@ void GeomPoint::Restore(Base::XMLReader &reader) setPoint(Base::Vector3d(X,Y,Z) ); } -PyObject *GeomPoint::getPyObject(void) +PyObject *GeomPoint::getPyObject() { return new PointPy(new GeomPoint(getPoint())); } @@ -757,14 +758,14 @@ bool GeomCurve::intersect(const Handle(Geom_Curve) curve1, const Handle(Geom_Cur } catch (Standard_Failure& e) { // Yes Extrema finding failed, but if we got an intersection then go on with it - if(points.size()>0) - return points.size()>0?true:false; + if(!points.empty()) + return true; else THROWM(Base::CADKernelError,e.GetMessageString()) } - return points.size()>0?true:false; + return !points.empty()?true:false; } bool GeomCurve::closestParameter(const Base::Vector3d& point, double &u) const @@ -883,7 +884,7 @@ double GeomCurve::length(double u, double v) const } } -void GeomCurve::reverse(void) +void GeomCurve::reverse() { Handle(Geom_Curve) c = Handle(Geom_Curve)::DownCast(handle()); @@ -972,7 +973,7 @@ const Handle(Geom_Geometry)& GeomBezierCurve::handle() const return myCurve; } -Geometry *GeomBezierCurve::copy(void) const +Geometry *GeomBezierCurve::copy() const { GeomBezierCurve *newCurve = new GeomBezierCurve(myCurve); newCurve->copyNonTag(this); @@ -1008,7 +1009,7 @@ std::vector GeomBezierCurve::getWeights() const } // Persistence implementer -unsigned int GeomBezierCurve::getMemSize (void) const +unsigned int GeomBezierCurve::getMemSize () const { return sizeof(Geom_BezierCurve); } @@ -1085,7 +1086,7 @@ void GeomBezierCurve::Restore(Base::XMLReader& reader) } } -PyObject *GeomBezierCurve::getPyObject(void) +PyObject *GeomBezierCurve::getPyObject() { return new BezierCurvePy(static_cast(this->clone())); } @@ -1160,7 +1161,7 @@ const Handle(Geom_Geometry)& GeomBSplineCurve::handle() const return myCurve; } -Geometry *GeomBSplineCurve::copy(void) const +Geometry *GeomBSplineCurve::copy() const { try { GeomBSplineCurve *newCurve = new GeomBSplineCurve(myCurve); @@ -1615,8 +1616,27 @@ void GeomBSplineCurve::Trim(double u, double v) } } +void GeomBSplineCurve::scaleKnotsToBounds(double u0, double u1) +{ + try { + Handle(Geom_BSplineCurve) curve = Handle(Geom_BSplineCurve)::DownCast(myCurve->Copy()); + Standard_RangeError_Raise_if (u1 <= u0, " "); + TColStd_Array1OfReal k(1,curve->NbKnots()); + curve->Knots(k); + if ((abs(u0-k.First()) > Precision::Confusion()) || (abs(u1-k.Last()) > Precision::Confusion())) { + BSplCLib::Reparametrize(u0, u1, k); + curve->SetKnots(k); + } + myCurve = curve; + return; + } + catch (Standard_Failure& e) { + THROWM(Base::CADKernelError,e.GetMessageString()) + } +} + // Persistence implementer -unsigned int GeomBSplineCurve::getMemSize (void) const +unsigned int GeomBSplineCurve::getMemSize () const { return sizeof(Geom_BSplineCurve); } @@ -1732,7 +1752,7 @@ void GeomBSplineCurve::Restore(Base::XMLReader& reader) } -PyObject *GeomBSplineCurve::getPyObject(void) +PyObject *GeomBSplineCurve::getPyObject() { return new BSplineCurvePy(static_cast(this->clone())); } @@ -1749,7 +1769,7 @@ GeomConic::~GeomConic() { } -Base::Vector3d GeomConic::getLocation(void) const +Base::Vector3d GeomConic::getLocation() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); gp_Ax1 axis = conic->Axis(); @@ -1771,7 +1791,7 @@ void GeomConic::setLocation(const Base::Vector3d& Center) } } -Base::Vector3d GeomConic::getCenter(void) const +Base::Vector3d GeomConic::getCenter() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); gp_Ax1 axis = conic->Axis(); @@ -1793,7 +1813,7 @@ void GeomConic::setCenter(const Base::Vector3d& Center) } } -Base::Vector3d GeomConic::getAxisDirection(void) const +Base::Vector3d GeomConic::getAxisDirection() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); gp_Ax1 axis = conic->Axis(); @@ -1811,7 +1831,7 @@ Base::Vector3d GeomConic::getAxisDirection(void) const * system is reversed compared to the global X axis. This angle, in conjunction * with ellipse's axis, fully defines the orientation of the ellipse. */ -double GeomConic::getAngleXU(void) const +double GeomConic::getAngleXU() const { Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(handle()); @@ -1890,7 +1910,7 @@ const Handle(Geom_Geometry)& GeomTrimmedCurve::handle() const return myCurve; } -Geometry *GeomTrimmedCurve::copy(void) const +Geometry *GeomTrimmedCurve::copy() const { GeomTrimmedCurve *newCurve = new GeomTrimmedCurve(myCurve); newCurve->copyNonTag(this); @@ -1898,7 +1918,7 @@ Geometry *GeomTrimmedCurve::copy(void) const } // Persistence implementer -unsigned int GeomTrimmedCurve::getMemSize (void) const +unsigned int GeomTrimmedCurve::getMemSize () const { return sizeof(Geom_TrimmedCurve); } @@ -1913,7 +1933,7 @@ void GeomTrimmedCurve::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomTrimmedCurve::Restore"); } -PyObject *GeomTrimmedCurve::getPyObject(void) +PyObject *GeomTrimmedCurve::getPyObject() { return new TrimmedCurvePy(static_cast(this->clone())); } @@ -2002,7 +2022,7 @@ Base::Vector3d GeomArcOfConic::getEndPoint(bool emulateCCWXY) const return Base::Vector3d(pnt.X(), pnt.Y(), pnt.Z()); } -Base::Vector3d GeomArcOfConic::getCenter(void) const +Base::Vector3d GeomArcOfConic::getCenter() const { Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); @@ -2011,7 +2031,7 @@ Base::Vector3d GeomArcOfConic::getCenter(void) const return Base::Vector3d(loc.X(),loc.Y(),loc.Z()); } -Base::Vector3d GeomArcOfConic::getLocation(void) const +Base::Vector3d GeomArcOfConic::getLocation() const { Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); @@ -2050,7 +2070,7 @@ void GeomArcOfConic::setLocation(const Base::Vector3d& Center) } } -Base::Vector3d GeomArcOfConic::getAxisDirection(void) const +Base::Vector3d GeomArcOfConic::getAxisDirection() const { Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); @@ -2083,7 +2103,7 @@ bool GeomArcOfConic::isReversed() const * system is reversed compared to the global X axis. This angle, in conjunction * with ellipse's axis, fully defines the orientation of the ellipse. */ -double GeomArcOfConic::getAngleXU(void) const +double GeomArcOfConic::getAngleXU() const { Handle(Geom_TrimmedCurve) curve = Handle(Geom_TrimmedCurve)::DownCast(handle()); Handle(Geom_Conic) conic = Handle(Geom_Conic)::DownCast(curve->BasisCurve()); @@ -2194,7 +2214,7 @@ void GeomCircle::setHandle(const Handle(Geom_Circle)& c) myCurve = Handle(Geom_Circle)::DownCast(c->Copy()); } -Geometry *GeomCircle::copy(void) const +Geometry *GeomCircle::copy() const { GeomCircle *newCirc = new GeomCircle(myCurve); newCirc->copyNonTag(this); @@ -2248,7 +2268,7 @@ GeomBSplineCurve* GeomCircle::toNurbs(double first, double last) const return new GeomBSplineCurve(spline); } -double GeomCircle::getRadius(void) const +double GeomCircle::getRadius() const { Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(handle()); return circle->Radius(); @@ -2270,7 +2290,7 @@ void GeomCircle::setRadius(double Radius) } // Persistence implementer -unsigned int GeomCircle::getMemSize (void) const +unsigned int GeomCircle::getMemSize () const { return sizeof(Geom_Circle); } @@ -2342,7 +2362,7 @@ void GeomCircle::Restore(Base::XMLReader& reader) } } -PyObject *GeomCircle::getPyObject(void) +PyObject *GeomCircle::getPyObject() { return new CirclePy(static_cast(this->clone())); } @@ -2385,7 +2405,7 @@ const Handle(Geom_Geometry)& GeomArcOfCircle::handle() const return myCurve; } -Geometry *GeomArcOfCircle::copy(void) const +Geometry *GeomArcOfCircle::copy() const { GeomArcOfCircle* copy = new GeomArcOfCircle(); copy->setHandle(this->myCurve); @@ -2400,7 +2420,7 @@ GeomBSplineCurve* GeomArcOfCircle::toNurbs(double first, double last) const return GeomCircle(circle).toNurbs(first, last); } -double GeomArcOfCircle::getRadius(void) const +double GeomArcOfCircle::getRadius() const { Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast(myCurve->BasisCurve()); return circle->Radius(); @@ -2495,7 +2515,7 @@ void GeomArcOfCircle::setRange(double u, double v, bool emulateCCWXY) } // Persistence implementer -unsigned int GeomArcOfCircle::getMemSize (void) const +unsigned int GeomArcOfCircle::getMemSize () const { return sizeof(Geom_Circle) + 2 *sizeof(double); } @@ -2581,7 +2601,7 @@ void GeomArcOfCircle::Restore(Base::XMLReader &reader) } } -PyObject *GeomArcOfCircle::getPyObject(void) +PyObject *GeomArcOfCircle::getPyObject() { return new ArcOfCirclePy(static_cast(this->clone())); } @@ -2615,7 +2635,7 @@ void GeomEllipse::setHandle(const Handle(Geom_Ellipse) &e) this->myCurve = Handle(Geom_Ellipse)::DownCast(e->Copy()); } -Geometry *GeomEllipse::copy(void) const +Geometry *GeomEllipse::copy() const { GeomEllipse *newEllipse = new GeomEllipse(myCurve); newEllipse->copyNonTag(this); @@ -2670,7 +2690,7 @@ GeomBSplineCurve* GeomEllipse::toNurbs(double first, double last) const return new GeomBSplineCurve(spline); } -double GeomEllipse::getMajorRadius(void) const +double GeomEllipse::getMajorRadius() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(handle()); return ellipse->MajorRadius(); @@ -2689,7 +2709,7 @@ void GeomEllipse::setMajorRadius(double Radius) } } -double GeomEllipse::getMinorRadius(void) const +double GeomEllipse::getMinorRadius() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(handle()); return ellipse->MinorRadius(); @@ -2754,7 +2774,7 @@ void GeomEllipse::setMajorAxisDir(Base::Vector3d newdir) } // Persistence implementer -unsigned int GeomEllipse::getMemSize (void) const +unsigned int GeomEllipse::getMemSize () const { return sizeof(Geom_Ellipse); } @@ -2835,7 +2855,7 @@ void GeomEllipse::Restore(Base::XMLReader& reader) } } -PyObject *GeomEllipse::getPyObject(void) +PyObject *GeomEllipse::getPyObject() { return new EllipsePy(static_cast(this->clone())); } @@ -2877,7 +2897,7 @@ const Handle(Geom_Geometry)& GeomArcOfEllipse::handle() const return myCurve; } -Geometry *GeomArcOfEllipse::copy(void) const +Geometry *GeomArcOfEllipse::copy() const { GeomArcOfEllipse* copy = new GeomArcOfEllipse(); copy->setHandle(this->myCurve); @@ -2892,7 +2912,7 @@ GeomBSplineCurve* GeomArcOfEllipse::toNurbs(double first, double last) const return GeomEllipse(ellipse).toNurbs(first, last); } -double GeomArcOfEllipse::getMajorRadius(void) const +double GeomArcOfEllipse::getMajorRadius() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(myCurve->BasisCurve()); return ellipse->MajorRadius(); @@ -2911,7 +2931,7 @@ void GeomArcOfEllipse::setMajorRadius(double Radius) } } -double GeomArcOfEllipse::getMinorRadius(void) const +double GeomArcOfEllipse::getMinorRadius() const { Handle(Geom_Ellipse) ellipse = Handle(Geom_Ellipse)::DownCast(myCurve->BasisCurve()); return ellipse->MinorRadius(); @@ -3016,7 +3036,7 @@ void GeomArcOfEllipse::setRange(double u, double v, bool emulateCCWXY) } // Persistence implementer -unsigned int GeomArcOfEllipse::getMemSize (void) const +unsigned int GeomArcOfEllipse::getMemSize () const { return sizeof(Geom_Ellipse) + 2 *sizeof(double); } @@ -3108,7 +3128,7 @@ void GeomArcOfEllipse::Restore(Base::XMLReader &reader) } } -PyObject *GeomArcOfEllipse::getPyObject(void) +PyObject *GeomArcOfEllipse::getPyObject() { return new ArcOfEllipsePy(static_cast(this->clone())); } @@ -3143,7 +3163,7 @@ void GeomHyperbola::setHandle(const Handle(Geom_Hyperbola)& c) myCurve = Handle(Geom_Hyperbola)::DownCast(c->Copy()); } -Geometry *GeomHyperbola::copy(void) const +Geometry *GeomHyperbola::copy() const { GeomHyperbola *newHyp = new GeomHyperbola(myCurve); newHyp->copyNonTag(this); @@ -3155,7 +3175,7 @@ GeomBSplineCurve* GeomHyperbola::toNurbs(double first, double last) const return GeomCurve::toNurbs(first, last); } -double GeomHyperbola::getMajorRadius(void) const +double GeomHyperbola::getMajorRadius() const { Handle(Geom_Hyperbola) h = Handle(Geom_Hyperbola)::DownCast(handle()); return h->MajorRadius(); @@ -3174,7 +3194,7 @@ void GeomHyperbola::setMajorRadius(double Radius) } } -double GeomHyperbola::getMinorRadius(void) const +double GeomHyperbola::getMinorRadius() const { Handle(Geom_Hyperbola) h = Handle(Geom_Hyperbola)::DownCast(handle()); return h->MinorRadius(); @@ -3194,7 +3214,7 @@ void GeomHyperbola::setMinorRadius(double Radius) } // Persistence implementer -unsigned int GeomHyperbola::getMemSize (void) const +unsigned int GeomHyperbola::getMemSize () const { return sizeof(Geom_Hyperbola); } @@ -3269,7 +3289,7 @@ void GeomHyperbola::Restore(Base::XMLReader& reader) } } -PyObject *GeomHyperbola::getPyObject(void) +PyObject *GeomHyperbola::getPyObject() { return new HyperbolaPy(static_cast(this->clone())); } @@ -3311,7 +3331,7 @@ const Handle(Geom_Geometry)& GeomArcOfHyperbola::handle() const return myCurve; } -Geometry *GeomArcOfHyperbola::copy(void) const +Geometry *GeomArcOfHyperbola::copy() const { GeomArcOfHyperbola* copy = new GeomArcOfHyperbola(); copy->setHandle(this->myCurve); @@ -3326,7 +3346,7 @@ GeomBSplineCurve* GeomArcOfHyperbola::toNurbs(double first, double last) const return GeomHyperbola(hyperbola).toNurbs(first, last); } -double GeomArcOfHyperbola::getMajorRadius(void) const +double GeomArcOfHyperbola::getMajorRadius() const { Handle(Geom_Hyperbola) h = Handle(Geom_Hyperbola)::DownCast(myCurve->BasisCurve()); return h->MajorRadius(); @@ -3345,7 +3365,7 @@ void GeomArcOfHyperbola::setMajorRadius(double Radius) } } -double GeomArcOfHyperbola::getMinorRadius(void) const +double GeomArcOfHyperbola::getMinorRadius() const { Handle(Geom_Hyperbola) h = Handle(Geom_Hyperbola)::DownCast(myCurve->BasisCurve()); return h->MinorRadius(); @@ -3443,7 +3463,7 @@ void GeomArcOfHyperbola::setRange(double u, double v, bool emulateCCWXY) } // Persistence implementer -unsigned int GeomArcOfHyperbola::getMemSize (void) const +unsigned int GeomArcOfHyperbola::getMemSize () const { return sizeof(Geom_Hyperbola) + 2 *sizeof(double); } @@ -3534,7 +3554,7 @@ void GeomArcOfHyperbola::Restore(Base::XMLReader &reader) } } -PyObject *GeomArcOfHyperbola::getPyObject(void) +PyObject *GeomArcOfHyperbola::getPyObject() { return new ArcOfHyperbolaPy(static_cast(this->clone())); } @@ -3567,7 +3587,7 @@ void GeomParabola::setHandle(const Handle(Geom_Parabola)& c) myCurve = Handle(Geom_Parabola)::DownCast(c->Copy()); } -Geometry *GeomParabola::copy(void) const +Geometry *GeomParabola::copy() const { GeomParabola *newPar = new GeomParabola(myCurve); newPar->copyNonTag(this); @@ -3581,7 +3601,7 @@ GeomBSplineCurve* GeomParabola::toNurbs(double first, double last) const return GeomCurve::toNurbs(first, last); } -double GeomParabola::getFocal(void) const +double GeomParabola::getFocal() const { Handle(Geom_Parabola) p = Handle(Geom_Parabola)::DownCast(handle()); return p->Focal(); @@ -3601,7 +3621,7 @@ void GeomParabola::setFocal(double length) } // Persistence implementer -unsigned int GeomParabola::getMemSize (void) const +unsigned int GeomParabola::getMemSize () const { return sizeof(Geom_Parabola); } @@ -3674,7 +3694,7 @@ void GeomParabola::Restore(Base::XMLReader& reader) } } -PyObject *GeomParabola::getPyObject(void) +PyObject *GeomParabola::getPyObject() { return new ParabolaPy(static_cast(this->clone())); } @@ -3716,7 +3736,7 @@ const Handle(Geom_Geometry)& GeomArcOfParabola::handle() const return myCurve; } -Geometry *GeomArcOfParabola::copy(void) const +Geometry *GeomArcOfParabola::copy() const { GeomArcOfParabola* copy = new GeomArcOfParabola(); copy->setHandle(this->myCurve); @@ -3731,7 +3751,7 @@ GeomBSplineCurve* GeomArcOfParabola::toNurbs(double first, double last) const return GeomParabola(parabola).toNurbs(first, last); } -double GeomArcOfParabola::getFocal(void) const +double GeomArcOfParabola::getFocal() const { Handle(Geom_Parabola) p = Handle(Geom_Parabola)::DownCast(myCurve->BasisCurve()); return p->Focal(); @@ -3750,7 +3770,7 @@ void GeomArcOfParabola::setFocal(double length) } } -Base::Vector3d GeomArcOfParabola::getFocus(void) const +Base::Vector3d GeomArcOfParabola::getFocus() const { Handle(Geom_Parabola) p = Handle(Geom_Parabola)::DownCast(myCurve->BasisCurve()); gp_Pnt gp = p->Focus(); @@ -3797,7 +3817,7 @@ void GeomArcOfParabola::setRange(double u, double v, bool emulateCCWXY) } // Persistence implementer -unsigned int GeomArcOfParabola::getMemSize (void) const +unsigned int GeomArcOfParabola::getMemSize () const { return sizeof(Geom_Parabola) + 2 *sizeof(double); } @@ -3886,7 +3906,7 @@ void GeomArcOfParabola::Restore(Base::XMLReader &reader) } } -PyObject *GeomArcOfParabola::getPyObject(void) +PyObject *GeomArcOfParabola::getPyObject() { return new ArcOfParabolaPy(static_cast(this->clone())); } @@ -3922,13 +3942,13 @@ void GeomLine::setLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir) this->myCurve->SetDirection(gp_Dir(Dir.x,Dir.y,Dir.z)); } -Base::Vector3d GeomLine::getPos(void) const +Base::Vector3d GeomLine::getPos() const { gp_Pnt Pos = this->myCurve->Lin().Location(); return Base::Vector3d(Pos.X(),Pos.Y(),Pos.Z()); } -Base::Vector3d GeomLine::getDir(void) const +Base::Vector3d GeomLine::getDir() const { gp_Dir Dir = this->myCurve->Lin().Direction(); return Base::Vector3d(Dir.X(),Dir.Y(),Dir.Z()); @@ -3945,7 +3965,7 @@ void GeomLine::setHandle(const Handle(Geom_Line)& l) this->myCurve = Handle(Geom_Line)::DownCast(l->Copy()); } -Geometry *GeomLine::copy(void) const +Geometry *GeomLine::copy() const { GeomLine *newLine = new GeomLine(myCurve); newLine->copyNonTag(this); @@ -3953,7 +3973,7 @@ Geometry *GeomLine::copy(void) const } // Persistence implementer -unsigned int GeomLine::getMemSize (void) const +unsigned int GeomLine::getMemSize () const { return sizeof(Geom_Line); } @@ -3997,7 +4017,7 @@ void GeomLine::Restore(Base::XMLReader &reader) setLine(Base::Vector3d(PosX,PosY,PosZ),Base::Vector3d(DirX,DirY,DirZ) ); } -PyObject *GeomLine::getPyObject(void) +PyObject *GeomLine::getPyObject() { return new LinePy(static_cast(this->clone())); } @@ -4042,7 +4062,7 @@ const Handle(Geom_Geometry)& GeomLineSegment::handle() const return myCurve; } -Geometry *GeomLineSegment::copy(void)const +Geometry *GeomLineSegment::copy()const { GeomLineSegment *tempCurve = new GeomLineSegment(); tempCurve->myCurve = Handle(Geom_TrimmedCurve)::DownCast(myCurve->Copy()); @@ -4094,7 +4114,7 @@ void GeomLineSegment::setPoints(const Base::Vector3d& Start, const Base::Vector3 } // Persistence implementer -unsigned int GeomLineSegment::getMemSize (void) const +unsigned int GeomLineSegment::getMemSize () const { return sizeof(Geom_TrimmedCurve) + sizeof(Geom_Line); } @@ -4158,7 +4178,7 @@ void GeomLineSegment::Restore (Base::XMLReader &reader) } } -PyObject *GeomLineSegment::getPyObject(void) +PyObject *GeomLineSegment::getPyObject() { return new LineSegmentPy(static_cast(this->clone())); } @@ -4189,7 +4209,7 @@ GeomOffsetCurve::~GeomOffsetCurve() { } -Geometry *GeomOffsetCurve::copy(void) const +Geometry *GeomOffsetCurve::copy() const { GeomOffsetCurve *newCurve = new GeomOffsetCurve(myCurve); newCurve->copyNonTag(this); @@ -4207,7 +4227,7 @@ const Handle(Geom_Geometry)& GeomOffsetCurve::handle() const } // Persistence implementer -unsigned int GeomOffsetCurve::getMemSize (void) const +unsigned int GeomOffsetCurve::getMemSize () const { return sizeof(Geom_OffsetCurve); } @@ -4222,7 +4242,7 @@ void GeomOffsetCurve::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomOffsetCurve::Restore"); } -PyObject *GeomOffsetCurve::getPyObject(void) +PyObject *GeomOffsetCurve::getPyObject() { return new OffsetCurvePy(static_cast(this->clone())); } @@ -4374,7 +4394,7 @@ void GeomBezierSurface::setHandle(const Handle(Geom_BezierSurface)& b) this->mySurface = Handle(Geom_BezierSurface)::DownCast(b->Copy()); } -Geometry *GeomBezierSurface::copy(void) const +Geometry *GeomBezierSurface::copy() const { GeomBezierSurface *newSurf = new GeomBezierSurface(mySurface); newSurf->copyNonTag(this); @@ -4382,7 +4402,7 @@ Geometry *GeomBezierSurface::copy(void) const } // Persistence implementer -unsigned int GeomBezierSurface::getMemSize (void) const +unsigned int GeomBezierSurface::getMemSize () const { unsigned int size = sizeof(Geom_BezierSurface); if (!mySurface.IsNull()) { @@ -4404,7 +4424,7 @@ void GeomBezierSurface::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomBezierSurface::Restore"); } -PyObject *GeomBezierSurface::getPyObject(void) +PyObject *GeomBezierSurface::getPyObject() { return new BezierSurfacePy(static_cast(this->clone())); } @@ -4451,15 +4471,42 @@ const Handle(Geom_Geometry)& GeomBSplineSurface::handle() const return mySurface; } -Geometry *GeomBSplineSurface::copy(void) const +Geometry *GeomBSplineSurface::copy() const { GeomBSplineSurface *newSurf = new GeomBSplineSurface(mySurface); newSurf->copyNonTag(this); return newSurf; } +void GeomBSplineSurface::scaleKnotsToBounds(double u0, double u1, double v0, double v1) +{ + try { + Handle(Geom_BSplineSurface) surf = Handle(Geom_BSplineSurface)::DownCast(mySurface->Copy()); + Standard_RangeError_Raise_if (u1 <= u0 || v1 <= v0, " "); + Standard_Real bu0,bu1,bv0,bv1; + surf->Bounds(bu0,bu1,bv0,bv1); + if ((abs(u0-bu0) > Precision::Confusion()) || (abs(u1-bu1) > Precision::Confusion())) { + TColStd_Array1OfReal uk(1,surf->NbUKnots()); + surf->UKnots(uk); + BSplCLib::Reparametrize(u0, u1, uk); + surf->SetUKnots(uk); + } + if ((abs(v0-bv0) > Precision::Confusion()) || (abs(v1-bv1) > Precision::Confusion())) { + TColStd_Array1OfReal vk(1,surf->NbVKnots()); + surf->VKnots(vk); + BSplCLib::Reparametrize(v0, v1, vk); + surf->SetVKnots(vk); + } + mySurface = surf; + return; + } + catch (Standard_Failure& e) { + THROWM(Base::CADKernelError,e.GetMessageString()) + } +} + // Persistence implementer -unsigned int GeomBSplineSurface::getMemSize (void) const +unsigned int GeomBSplineSurface::getMemSize () const { unsigned int size = sizeof(Geom_BSplineSurface); if (!mySurface.IsNull()) { @@ -4485,7 +4532,7 @@ void GeomBSplineSurface::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomBSplineSurface::Restore"); } -PyObject *GeomBSplineSurface::getPyObject(void) +PyObject *GeomBSplineSurface::getPyObject() { return new BSplineSurfacePy(static_cast(this->clone())); } @@ -4519,7 +4566,7 @@ const Handle(Geom_Geometry)& GeomCylinder::handle() const return mySurface; } -Geometry *GeomCylinder::copy(void) const +Geometry *GeomCylinder::copy() const { GeomCylinder *tempCurve = new GeomCylinder(); tempCurve->mySurface = Handle(Geom_CylindricalSurface)::DownCast(mySurface->Copy()); @@ -4528,7 +4575,7 @@ Geometry *GeomCylinder::copy(void) const } // Persistence implementer -unsigned int GeomCylinder::getMemSize (void) const +unsigned int GeomCylinder::getMemSize () const { return sizeof(Geom_CylindricalSurface); } @@ -4543,7 +4590,7 @@ void GeomCylinder::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomCylinder::Restore"); } -PyObject *GeomCylinder::getPyObject(void) +PyObject *GeomCylinder::getPyObject() { return new CylinderPy(static_cast(this->clone())); } @@ -4577,7 +4624,7 @@ const Handle(Geom_Geometry)& GeomCone::handle() const return mySurface; } -Geometry *GeomCone::copy(void) const +Geometry *GeomCone::copy() const { GeomCone *tempCurve = new GeomCone(); tempCurve->mySurface = Handle(Geom_ConicalSurface)::DownCast(mySurface->Copy()); @@ -4586,7 +4633,7 @@ Geometry *GeomCone::copy(void) const } // Persistence implementer -unsigned int GeomCone::getMemSize (void) const +unsigned int GeomCone::getMemSize () const { return sizeof(Geom_ConicalSurface); } @@ -4601,7 +4648,7 @@ void GeomCone::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomCone::Restore"); } -PyObject *GeomCone::getPyObject(void) +PyObject *GeomCone::getPyObject() { return new ConePy(static_cast(this->clone())); } @@ -4683,7 +4730,7 @@ const Handle(Geom_Geometry)& GeomToroid::handle() const return mySurface; } -Geometry *GeomToroid::copy(void) const +Geometry *GeomToroid::copy() const { GeomToroid *tempCurve = new GeomToroid(); tempCurve->mySurface = Handle(Geom_ToroidalSurface)::DownCast(mySurface->Copy()); @@ -4692,7 +4739,7 @@ Geometry *GeomToroid::copy(void) const } // Persistence implementer -unsigned int GeomToroid::getMemSize (void) const +unsigned int GeomToroid::getMemSize () const { return sizeof(Geom_ToroidalSurface); } @@ -4707,7 +4754,7 @@ void GeomToroid::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomToroid::Restore"); } -PyObject *GeomToroid::getPyObject(void) +PyObject *GeomToroid::getPyObject() { return new ToroidPy(static_cast(this->clone())); } @@ -4741,7 +4788,7 @@ const Handle(Geom_Geometry)& GeomSphere::handle() const return mySurface; } -Geometry *GeomSphere::copy(void) const +Geometry *GeomSphere::copy() const { GeomSphere *tempCurve = new GeomSphere(); tempCurve->mySurface = Handle(Geom_SphericalSurface)::DownCast(mySurface->Copy()); @@ -4750,7 +4797,7 @@ Geometry *GeomSphere::copy(void) const } // Persistence implementer -unsigned int GeomSphere::getMemSize (void) const +unsigned int GeomSphere::getMemSize () const { return sizeof(Geom_SphericalSurface); } @@ -4765,7 +4812,7 @@ void GeomSphere::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomSphere::Restore"); } -PyObject *GeomSphere::getPyObject(void) +PyObject *GeomSphere::getPyObject() { return new SpherePy(static_cast(this->clone())); } @@ -4799,7 +4846,7 @@ const Handle(Geom_Geometry)& GeomPlane::handle() const return mySurface; } -Geometry *GeomPlane::copy(void) const +Geometry *GeomPlane::copy() const { GeomPlane *tempCurve = new GeomPlane(); tempCurve->mySurface = Handle(Geom_Plane)::DownCast(mySurface->Copy()); @@ -4808,7 +4855,7 @@ Geometry *GeomPlane::copy(void) const } // Persistence implementer -unsigned int GeomPlane::getMemSize (void) const +unsigned int GeomPlane::getMemSize () const { return sizeof(Geom_Plane); } @@ -4823,7 +4870,7 @@ void GeomPlane::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomPlane::Restore"); } -PyObject *GeomPlane::getPyObject(void) +PyObject *GeomPlane::getPyObject() { return new PlanePy(static_cast(this->clone())); } @@ -4860,7 +4907,7 @@ const Handle(Geom_Geometry)& GeomOffsetSurface::handle() const return mySurface; } -Geometry *GeomOffsetSurface::copy(void) const +Geometry *GeomOffsetSurface::copy() const { GeomOffsetSurface *newSurf = new GeomOffsetSurface(mySurface); newSurf->copyNonTag(this); @@ -4868,7 +4915,7 @@ Geometry *GeomOffsetSurface::copy(void) const } // Persistence implementer -unsigned int GeomOffsetSurface::getMemSize (void) const +unsigned int GeomOffsetSurface::getMemSize () const { return sizeof(Geom_OffsetSurface); } @@ -4883,7 +4930,7 @@ void GeomOffsetSurface::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomOffsetSurface::Restore"); } -PyObject *GeomOffsetSurface::getPyObject(void) +PyObject *GeomOffsetSurface::getPyObject() { return new OffsetSurfacePy(static_cast(this->clone())); } @@ -4926,7 +4973,7 @@ const Handle(Geom_Geometry)& GeomPlateSurface::handle() const return mySurface; } -Geometry *GeomPlateSurface::copy(void) const +Geometry *GeomPlateSurface::copy() const { GeomPlateSurface *newSurf = new GeomPlateSurface(mySurface); newSurf->copyNonTag(this); @@ -4934,7 +4981,7 @@ Geometry *GeomPlateSurface::copy(void) const } // Persistence implementer -unsigned int GeomPlateSurface::getMemSize (void) const +unsigned int GeomPlateSurface::getMemSize () const { throw Base::NotImplementedError("GeomPlateSurface::getMemSize"); } @@ -4949,7 +4996,7 @@ void GeomPlateSurface::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomPlateSurface::Restore"); } -PyObject *GeomPlateSurface::getPyObject(void) +PyObject *GeomPlateSurface::getPyObject() { return new PlateSurfacePy(static_cast(this->clone())); } @@ -4981,7 +5028,7 @@ const Handle(Geom_Geometry)& GeomTrimmedSurface::handle() const return mySurface; } -Geometry *GeomTrimmedSurface::copy(void) const +Geometry *GeomTrimmedSurface::copy() const { GeomTrimmedSurface *newSurf = new GeomTrimmedSurface(mySurface); newSurf->copyNonTag(this); @@ -4989,7 +5036,7 @@ Geometry *GeomTrimmedSurface::copy(void) const } // Persistence implementer -unsigned int GeomTrimmedSurface::getMemSize (void) const +unsigned int GeomTrimmedSurface::getMemSize () const { return sizeof(Geom_RectangularTrimmedSurface); } @@ -5004,7 +5051,7 @@ void GeomTrimmedSurface::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomTrimmedSurface::Restore"); } -PyObject *GeomTrimmedSurface::getPyObject(void) +PyObject *GeomTrimmedSurface::getPyObject() { return new RectangularTrimmedSurfacePy(static_cast(this->clone())); } @@ -5041,7 +5088,7 @@ const Handle(Geom_Geometry)& GeomSurfaceOfRevolution::handle() const return mySurface; } -Geometry *GeomSurfaceOfRevolution::copy(void) const +Geometry *GeomSurfaceOfRevolution::copy() const { GeomSurfaceOfRevolution *newSurf = new GeomSurfaceOfRevolution(mySurface); newSurf->copyNonTag(this); @@ -5049,7 +5096,7 @@ Geometry *GeomSurfaceOfRevolution::copy(void) const } // Persistence implementer -unsigned int GeomSurfaceOfRevolution::getMemSize (void) const +unsigned int GeomSurfaceOfRevolution::getMemSize () const { return sizeof(Geom_SurfaceOfRevolution); } @@ -5064,7 +5111,7 @@ void GeomSurfaceOfRevolution::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomSurfaceOfRevolution::Restore"); } -PyObject *GeomSurfaceOfRevolution::getPyObject(void) +PyObject *GeomSurfaceOfRevolution::getPyObject() { return new SurfaceOfRevolutionPy(static_cast(this->clone())); } @@ -5101,7 +5148,7 @@ const Handle(Geom_Geometry)& GeomSurfaceOfExtrusion::handle() const return mySurface; } -Geometry *GeomSurfaceOfExtrusion::copy(void) const +Geometry *GeomSurfaceOfExtrusion::copy() const { GeomSurfaceOfExtrusion *newSurf = new GeomSurfaceOfExtrusion(mySurface); newSurf->copyNonTag(this); @@ -5109,7 +5156,7 @@ Geometry *GeomSurfaceOfExtrusion::copy(void) const } // Persistence implementer -unsigned int GeomSurfaceOfExtrusion::getMemSize (void) const +unsigned int GeomSurfaceOfExtrusion::getMemSize () const { return sizeof(Geom_SurfaceOfLinearExtrusion); } @@ -5124,7 +5171,7 @@ void GeomSurfaceOfExtrusion::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("GeomSurfaceOfExtrusion::Restore"); } -PyObject *GeomSurfaceOfExtrusion::getPyObject(void) +PyObject *GeomSurfaceOfExtrusion::getPyObject() { return new SurfaceOfExtrusionPy(static_cast(this->clone())); } diff --git a/src/Mod/Part/App/Geometry.h b/src/Mod/Part/App/Geometry.h index b13626772f..31c81a515f 100644 --- a/src/Mod/Part/App/Geometry.h +++ b/src/Mod/Part/App/Geometry.h @@ -73,27 +73,27 @@ namespace Part { class PartExport Geometry: public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~Geometry(); + ~Geometry() override; virtual TopoDS_Shape toShape() const = 0; virtual const Handle(Geom_Geometry)& handle() const = 0; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; /// returns a copy of this object having a new randomly generated tag. If you also want to copy the tag, you may use clone() instead. /// For creation of geometry with other handles, with or without the same tag, you may use the constructors and the sethandle functions. /// The tag of a geometry can be copied to another geometry using the assignTag function. - virtual Geometry *copy(void) const = 0; + virtual Geometry *copy() const = 0; /// returns a cloned object. A cloned object has the same tag (see getTag) as the original object. /// if you want a copy not having the same tag, you can use copy() instead. /// If you want a clone with another geometry handle, it is possible to clone an object and then assign another handle or to create an object /// via constructor and use assignTag to assign the tag of the other geometry. /// If you do not desire to have the same tag, then a copy can be performed by using a constructor (which will generate another tag) /// and then, if necessary (e.g. if the constructor did not take a handle as a parameter), set a new handle. - Geometry *clone(void) const; + Geometry *clone() const; /// returns the tag of the geometry object boost::uuids::uuid getTag() const; @@ -138,26 +138,26 @@ private: class PartExport GeomPoint : public Geometry { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomPoint(); GeomPoint(const Handle(Geom_CartesianPoint)&); GeomPoint(const Base::Vector3d&); - virtual ~GeomPoint(); - virtual Geometry *copy(void) const; - virtual TopoDS_Shape toShape() const; + ~GeomPoint() override; + Geometry *copy() const override; + TopoDS_Shape toShape() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; void setHandle(const Handle(Geom_CartesianPoint)&); - Base::Vector3d getPoint(void)const; + Base::Vector3d getPoint()const; void setPoint(const Base::Vector3d&); private: @@ -167,12 +167,12 @@ private: class GeomBSplineCurve; class PartExport GeomCurve : public Geometry { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomCurve(); - virtual ~GeomCurve(); + ~GeomCurve() override; - TopoDS_Shape toShape() const; + TopoDS_Shape toShape() const override; /*! * \brief toBSpline Converts the curve to a B-spline * \param This is the start parameter of the curve @@ -203,7 +203,7 @@ public: std::vector>& points, double tol = Precision::Confusion()) const; - void reverse(void); + void reverse(); Base::Vector3d value(double u) const; @@ -215,10 +215,10 @@ protected: class PartExport GeomBoundedCurve : public GeomCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomBoundedCurve(); - virtual ~GeomBoundedCurve(); + ~GeomBoundedCurve() override; // Geometry helper virtual Base::Vector3d getStartPoint() const; @@ -227,25 +227,25 @@ public: class PartExport GeomBezierCurve : public GeomBoundedCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomBezierCurve(); GeomBezierCurve(const Handle(Geom_BezierCurve)&); GeomBezierCurve(const std::vector&, const std::vector&); - virtual ~GeomBezierCurve(); - virtual Geometry *copy(void) const; + ~GeomBezierCurve() override; + Geometry *copy() const override; std::vector getPoles() const; std::vector getWeights() const; // Persistence implementer --------------------- - virtual unsigned int getMemSize (void) const; - virtual void Save (Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize () const override; + void Save (Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_BezierCurve)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_BezierCurve) myCurve; @@ -253,7 +253,7 @@ private: class PartExport GeomBSplineCurve : public GeomBoundedCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomBSplineCurve(); GeomBSplineCurve(const Handle(Geom_BSplineCurve)&); @@ -262,8 +262,8 @@ public: const std::vector& knots, const std::vector& multiplicities, int degree, bool periodic=false, bool checkrational = true); - virtual ~GeomBSplineCurve(); - virtual Geometry *copy(void) const; + ~GeomBSplineCurve() override; + Geometry *copy() const override; /*! * Interpolate a spline passing through the given points without tangency. @@ -317,16 +317,17 @@ public: bool removeKnot(int index, int multiplicity, double tolerance = Precision::PConfusion()); void Trim(double u, double v); + void scaleKnotsToBounds(double u0, double u1); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_BSplineCurve)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: // If during assignment of weights (during the for loop iteratively setting the poles) all weights @@ -344,57 +345,57 @@ private: class PartExport GeomConic : public GeomCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); protected: GeomConic(); public: - virtual ~GeomConic(); - virtual Geometry *copy(void) const = 0; + ~GeomConic() override; + Geometry *copy() const override = 0; /*! * \deprecated use getLocation * \brief getCenter */ - Base::Vector3d getCenter(void) const; - Base::Vector3d getLocation(void) const; + Base::Vector3d getCenter() const; + Base::Vector3d getLocation() const; void setLocation(const Base::Vector3d& Center); /*! * \deprecated use setLocation * \brief setCenter */ void setCenter(const Base::Vector3d& Center); - double getAngleXU(void) const; + double getAngleXU() const; void setAngleXU(double angle); bool isReversed() const; - Base::Vector3d getAxisDirection(void) const; + Base::Vector3d getAxisDirection() const; - virtual unsigned int getMemSize(void) const = 0; - virtual PyObject *getPyObject(void) = 0; + unsigned int getMemSize() const override = 0; + PyObject *getPyObject() override = 0; - const Handle(Geom_Geometry)& handle() const = 0; + const Handle(Geom_Geometry)& handle() const override = 0; }; class PartExport GeomTrimmedCurve : public GeomBoundedCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomTrimmedCurve(); GeomTrimmedCurve(const Handle(Geom_TrimmedCurve)&); - virtual ~GeomTrimmedCurve(); - virtual Geometry *copy(void) const; + ~GeomTrimmedCurve() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_TrimmedCurve)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; bool intersectBasisCurves( const GeomTrimmedCurve * c, std::vector>& points, @@ -411,26 +412,26 @@ protected: class PartExport GeomArcOfConic : public GeomTrimmedCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); protected: GeomArcOfConic(); public: - virtual ~GeomArcOfConic(); - virtual Geometry *copy(void) const = 0; + ~GeomArcOfConic() override; + Geometry *copy() const override = 0; Base::Vector3d getStartPoint(bool emulateCCWXY) const; Base::Vector3d getEndPoint(bool emulateCCWXY) const; - inline virtual Base::Vector3d getStartPoint() const {return getStartPoint(false);} - inline virtual Base::Vector3d getEndPoint() const {return getEndPoint(false);} + inline Base::Vector3d getStartPoint() const override {return getStartPoint(false);} + inline Base::Vector3d getEndPoint() const override {return getEndPoint(false);} /*! * \deprecated use getLocation * \brief getCenter */ - Base::Vector3d getCenter(void) const; - Base::Vector3d getLocation(void) const; + Base::Vector3d getCenter() const; + Base::Vector3d getLocation() const; void setLocation(const Base::Vector3d& Center); /*! * \deprecated use setLocation @@ -438,48 +439,48 @@ public: */ void setCenter(const Base::Vector3d& Center); - Base::Vector3d getAxisDirection(void) const; + Base::Vector3d getAxisDirection() const; virtual void getRange(double& u, double& v, bool emulateCCWXY) const = 0; virtual void setRange(double u, double v, bool emulateCCWXY) = 0; - inline virtual void getRange(double& u, double& v) const { getRange(u,v,false);} - inline virtual void setRange(double u, double v) { setRange(u,v,false);} + inline void getRange(double& u, double& v) const override { getRange(u,v,false);} + inline void setRange(double u, double v) override { setRange(u,v,false);} bool isReversed() const; - double getAngleXU(void) const; + double getAngleXU() const; void setAngleXU(double angle); Base::Vector3d getXAxisDir() const; void setXAxisDir(const Base::Vector3d& newdir); - virtual unsigned int getMemSize(void) const = 0; - virtual PyObject *getPyObject(void) = 0; + unsigned int getMemSize() const override = 0; + PyObject *getPyObject() override = 0; - const Handle(Geom_Geometry)& handle() const = 0; + const Handle(Geom_Geometry)& handle() const override = 0; }; class PartExport GeomCircle : public GeomConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomCircle(); GeomCircle(const Handle(Geom_Circle)&); - virtual ~GeomCircle(); - virtual Geometry *copy(void) const; + ~GeomCircle() override; + Geometry *copy() const override; - double getRadius(void) const; + double getRadius() const; void setRadius(double Radius); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; void setHandle(const Handle(Geom_Circle)&); @@ -489,60 +490,60 @@ private: class PartExport GeomArcOfCircle : public GeomArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomArcOfCircle(); GeomArcOfCircle(const Handle(Geom_Circle)&); - virtual ~GeomArcOfCircle(); - virtual Geometry *copy(void) const; + ~GeomArcOfCircle() override; + Geometry *copy() const override; - double getRadius(void) const; + double getRadius() const; void setRadius(double Radius); - virtual void getRange(double& u, double& v, bool emulateCCWXY) const; - virtual void setRange(double u, double v, bool emulateCCWXY); + void getRange(double& u, double& v, bool emulateCCWXY) const override; + void setRange(double u, double v, bool emulateCCWXY) override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; void setHandle(const Handle(Geom_TrimmedCurve)&); void setHandle(const Handle(Geom_Circle)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; }; class PartExport GeomEllipse : public GeomConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomEllipse(); GeomEllipse(const Handle(Geom_Ellipse)&); - virtual ~GeomEllipse(); - virtual Geometry *copy(void) const; + ~GeomEllipse() override; + Geometry *copy() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); Base::Vector3d getMajorAxisDir() const; void setMajorAxisDir(Base::Vector3d newdir); Base::Vector3d getMinorAxisDir() const; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; void setHandle(const Handle(Geom_Ellipse) &e); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_Ellipse) myCurve; @@ -550,60 +551,60 @@ private: class PartExport GeomArcOfEllipse : public GeomArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomArcOfEllipse(); GeomArcOfEllipse(const Handle(Geom_Ellipse)&); - virtual ~GeomArcOfEllipse(); - virtual Geometry *copy(void) const; + ~GeomArcOfEllipse() override; + Geometry *copy() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); Base::Vector3d getMajorAxisDir() const; void setMajorAxisDir(Base::Vector3d newdir); - virtual void getRange(double& u, double& v, bool emulateCCWXY) const; - virtual void setRange(double u, double v, bool emulateCCWXY); + void getRange(double& u, double& v, bool emulateCCWXY) const override; + void setRange(double u, double v, bool emulateCCWXY) override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; void setHandle(const Handle(Geom_TrimmedCurve)&); void setHandle(const Handle(Geom_Ellipse)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; }; class PartExport GeomHyperbola : public GeomConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomHyperbola(); GeomHyperbola(const Handle(Geom_Hyperbola)&); - virtual ~GeomHyperbola(); - virtual Geometry *copy(void) const; + ~GeomHyperbola() override; + Geometry *copy() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; void setHandle(const Handle(Geom_Hyperbola)&); private: @@ -612,57 +613,57 @@ private: class PartExport GeomArcOfHyperbola : public GeomArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomArcOfHyperbola(); GeomArcOfHyperbola(const Handle(Geom_Hyperbola)&); - virtual ~GeomArcOfHyperbola(); - virtual Geometry *copy(void) const; + ~GeomArcOfHyperbola() override; + Geometry *copy() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); Base::Vector3d getMajorAxisDir() const; void setMajorAxisDir(Base::Vector3d newdir); - virtual void getRange(double& u, double& v, bool emulateCCWXY) const; - virtual void setRange(double u, double v, bool emulateCCWXY); + void getRange(double& u, double& v, bool emulateCCWXY) const override; + void setRange(double u, double v, bool emulateCCWXY) override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; void setHandle(const Handle(Geom_TrimmedCurve)&); void setHandle(const Handle(Geom_Hyperbola)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; }; class PartExport GeomParabola : public GeomConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomParabola(); GeomParabola(const Handle(Geom_Parabola)&); - virtual ~GeomParabola(); - virtual Geometry *copy(void) const; + ~GeomParabola() override; + Geometry *copy() const override; - double getFocal(void) const; + double getFocal() const; void setFocal(double length); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; void setHandle(const Handle(Geom_Parabola)&); private: @@ -671,56 +672,56 @@ private: class PartExport GeomArcOfParabola : public GeomArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomArcOfParabola(); GeomArcOfParabola(const Handle(Geom_Parabola)&); - virtual ~GeomArcOfParabola(); - virtual Geometry *copy(void) const; + ~GeomArcOfParabola() override; + Geometry *copy() const override; - double getFocal(void) const; + double getFocal() const; void setFocal(double length); - Base::Vector3d getFocus(void) const; + Base::Vector3d getFocus() const; - virtual void getRange(double& u, double& v, bool emulateCCWXY) const; - virtual void setRange(double u, double v, bool emulateCCWXY); + void getRange(double& u, double& v, bool emulateCCWXY) const override; + void setRange(double u, double v, bool emulateCCWXY) override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); - virtual GeomBSplineCurve* toNurbs(double first, double last) const; + PyObject *getPyObject() override; + GeomBSplineCurve* toNurbs(double first, double last) const override; void setHandle(const Handle(Geom_TrimmedCurve)&); void setHandle(const Handle(Geom_Parabola)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; }; class PartExport GeomLine : public GeomCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomLine(); GeomLine(const Handle(Geom_Line)&); GeomLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir); - virtual ~GeomLine(); - virtual Geometry *copy(void) const; + ~GeomLine() override; + Geometry *copy() const override; void setLine(const Base::Vector3d& Pos, const Base::Vector3d& Dir); - Base::Vector3d getPos(void) const; - Base::Vector3d getDir(void) const; + Base::Vector3d getPos() const; + Base::Vector3d getDir() const; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; void setHandle(const Handle(Geom_Line)&); private: @@ -729,52 +730,52 @@ private: class PartExport GeomLineSegment : public GeomTrimmedCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomLineSegment(); GeomLineSegment(const Handle(Geom_Line)& l); - virtual ~GeomLineSegment(); - virtual Geometry *copy(void) const; + ~GeomLineSegment() override; + Geometry *copy() const override; - Base::Vector3d getStartPoint() const; - Base::Vector3d getEndPoint() const; + Base::Vector3d getStartPoint() const override; + Base::Vector3d getEndPoint() const override; void setPoints(const Base::Vector3d& p1, const Base::Vector3d& p2); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_TrimmedCurve)&); void setHandle(const Handle(Geom_Line)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; }; class PartExport GeomOffsetCurve : public GeomCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomOffsetCurve(); GeomOffsetCurve(const Handle(Geom_Curve)&, double, const gp_Dir&); GeomOffsetCurve(const Handle(Geom_Curve)&, double, Base::Vector3d&); GeomOffsetCurve(const Handle(Geom_OffsetCurve)&); - virtual ~GeomOffsetCurve(); - virtual Geometry *copy(void) const; + ~GeomOffsetCurve() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_OffsetCurve)& c); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_OffsetCurve) myCurve; @@ -782,7 +783,7 @@ private: class PartExport GeomSurface : public Geometry { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: enum Curvature { Maximum, @@ -792,9 +793,9 @@ public: }; GeomSurface(); - virtual ~GeomSurface(); + ~GeomSurface() override; - TopoDS_Shape toShape() const; + TopoDS_Shape toShape() const override; bool tangentU(double u, double v, gp_Dir& dirU) const; bool tangentV(double u, double v, gp_Dir& dirV) const; bool normal(double u, double v, gp_Dir& dir) const; @@ -814,22 +815,22 @@ public: class PartExport GeomBezierSurface : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomBezierSurface(); GeomBezierSurface(const Handle(Geom_BezierSurface)&); - virtual ~GeomBezierSurface(); - virtual Geometry *copy(void) const; + ~GeomBezierSurface() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_BezierSurface)& b); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_BezierSurface) mySurface; @@ -837,22 +838,23 @@ private: class PartExport GeomBSplineSurface : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomBSplineSurface(); GeomBSplineSurface(const Handle(Geom_BSplineSurface)&); - virtual ~GeomBSplineSurface(); - virtual Geometry *copy(void) const; + ~GeomBSplineSurface() override; + Geometry *copy() const override; + void scaleKnotsToBounds(double u0, double u1, double v0, double v1); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_BSplineSurface)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_BSplineSurface) mySurface; @@ -860,22 +862,22 @@ private: class PartExport GeomCylinder : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomCylinder(); GeomCylinder(const Handle(Geom_CylindricalSurface)&); - virtual ~GeomCylinder(); - virtual Geometry *copy(void) const; + ~GeomCylinder() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_CylindricalSurface)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_CylindricalSurface) mySurface; @@ -883,25 +885,25 @@ private: class PartExport GeomCone : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomCone(); GeomCone(const Handle(Geom_ConicalSurface)&); - virtual ~GeomCone(); - virtual Geometry *copy(void) const; + ~GeomCone() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_ConicalSurface)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; // Overloaded for Geom_ConicalSurface because of an OCC bug - virtual gp_Vec getDN(double u, double v, int Nu, int Nv) const; + gp_Vec getDN(double u, double v, int Nu, int Nv) const override; private: Handle(Geom_ConicalSurface) mySurface; @@ -909,22 +911,22 @@ private: class PartExport GeomSphere : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomSphere(); GeomSphere(const Handle(Geom_SphericalSurface)&); - virtual ~GeomSphere(); - virtual Geometry *copy(void) const; + ~GeomSphere() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_SphericalSurface)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_SphericalSurface) mySurface; @@ -932,22 +934,22 @@ private: class PartExport GeomToroid : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomToroid(); GeomToroid(const Handle(Geom_ToroidalSurface)&); - virtual ~GeomToroid(); - virtual Geometry *copy(void) const; + ~GeomToroid() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_ToroidalSurface)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_ToroidalSurface) mySurface; @@ -955,22 +957,22 @@ private: class PartExport GeomPlane : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomPlane(); GeomPlane(const Handle(Geom_Plane)&); - virtual ~GeomPlane(); - virtual Geometry *copy(void) const; + ~GeomPlane() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_Plane)&); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_Plane) mySurface; @@ -978,23 +980,23 @@ private: class PartExport GeomOffsetSurface : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomOffsetSurface(); GeomOffsetSurface(const Handle(Geom_Surface)&, double); GeomOffsetSurface(const Handle(Geom_OffsetSurface)&); - virtual ~GeomOffsetSurface(); - virtual Geometry *copy(void) const; + ~GeomOffsetSurface() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_OffsetSurface)& s); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_OffsetSurface) mySurface; @@ -1002,24 +1004,24 @@ private: class PartExport GeomPlateSurface : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomPlateSurface(); GeomPlateSurface(const Handle(Geom_Surface)&, const Plate_Plate&); GeomPlateSurface(const GeomPlate_BuildPlateSurface&); GeomPlateSurface(const Handle(GeomPlate_Surface)&); - virtual ~GeomPlateSurface(); - virtual Geometry *copy(void) const; + ~GeomPlateSurface() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(GeomPlate_Surface)& s); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(GeomPlate_Surface) mySurface; @@ -1027,22 +1029,22 @@ private: class PartExport GeomTrimmedSurface : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomTrimmedSurface(); GeomTrimmedSurface(const Handle(Geom_RectangularTrimmedSurface)&); - virtual ~GeomTrimmedSurface(); - virtual Geometry *copy(void) const; + ~GeomTrimmedSurface() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_RectangularTrimmedSurface)& s); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_RectangularTrimmedSurface) mySurface; @@ -1050,23 +1052,23 @@ private: class PartExport GeomSurfaceOfRevolution : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomSurfaceOfRevolution(); GeomSurfaceOfRevolution(const Handle(Geom_Curve)&, const gp_Ax1&); GeomSurfaceOfRevolution(const Handle(Geom_SurfaceOfRevolution)&); - virtual ~GeomSurfaceOfRevolution(); - virtual Geometry *copy(void) const; + ~GeomSurfaceOfRevolution() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_SurfaceOfRevolution)& c); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_SurfaceOfRevolution) mySurface; @@ -1074,23 +1076,23 @@ private: class PartExport GeomSurfaceOfExtrusion : public GeomSurface { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomSurfaceOfExtrusion(); GeomSurfaceOfExtrusion(const Handle(Geom_Curve)&, const gp_Dir&); - GeomSurfaceOfExtrusion(const Handle(Geom_SurfaceOfLinearExtrusion)&); - virtual ~GeomSurfaceOfExtrusion(); - virtual Geometry *copy(void) const; + explicit GeomSurfaceOfExtrusion(const Handle(Geom_SurfaceOfLinearExtrusion)&); + ~GeomSurfaceOfExtrusion() override; + Geometry *copy() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom_SurfaceOfLinearExtrusion)& c); - const Handle(Geom_Geometry)& handle() const; + const Handle(Geom_Geometry)& handle() const override; private: Handle(Geom_SurfaceOfLinearExtrusion) mySurface; diff --git a/src/Mod/Part/App/Geometry2d.cpp b/src/Mod/Part/App/Geometry2d.cpp index 247beca2d4..9d362598a2 100644 --- a/src/Mod/Part/App/Geometry2d.cpp +++ b/src/Mod/Part/App/Geometry2d.cpp @@ -94,7 +94,7 @@ Geometry2d::~Geometry2d() { } -unsigned int Geometry2d::getMemSize (void) const +unsigned int Geometry2d::getMemSize () const { return sizeof(Geometry2d); } @@ -148,13 +148,13 @@ const Handle(Geom2d_Geometry)& Geom2dPoint::handle() const return myPoint; } -Geometry2d *Geom2dPoint::clone(void) const +Geometry2d *Geom2dPoint::clone() const { Geom2dPoint *newPoint = new Geom2dPoint(myPoint); return newPoint; } -Base::Vector2d Geom2dPoint::getPoint(void)const +Base::Vector2d Geom2dPoint::getPoint()const { return Base::Vector2d(myPoint->X(),myPoint->Y()); } @@ -164,7 +164,7 @@ void Geom2dPoint::setPoint(const Base::Vector2d& p) this->myPoint->SetCoord(p.x,p.y); } -unsigned int Geom2dPoint::getMemSize (void) const +unsigned int Geom2dPoint::getMemSize () const { return sizeof(Geom2d_CartesianPoint); } @@ -199,7 +199,7 @@ void Geom2dPoint::Restore(Base::XMLReader &reader) setPoint(Base::Vector2d(X,Y)); } -PyObject *Geom2dPoint::getPyObject(void) +PyObject *Geom2dPoint::getPyObject() { Handle(Geom2d_CartesianPoint) c = Handle(Geom2d_CartesianPoint)::DownCast(handle()); gp_Pnt2d xy = c->Pnt2d(); @@ -361,13 +361,13 @@ const Handle(Geom2d_Geometry)& Geom2dBezierCurve::handle() const return myCurve; } -Geometry2d *Geom2dBezierCurve::clone(void) const +Geometry2d *Geom2dBezierCurve::clone() const { Geom2dBezierCurve *newCurve = new Geom2dBezierCurve(myCurve); return newCurve; } -unsigned int Geom2dBezierCurve::getMemSize (void) const +unsigned int Geom2dBezierCurve::getMemSize () const { throw Base::NotImplementedError("Geom2dBezierCurve::getMemSize"); } @@ -382,7 +382,7 @@ void Geom2dBezierCurve::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("Geom2dBezierCurve::Restore"); } -PyObject *Geom2dBezierCurve::getPyObject(void) +PyObject *Geom2dBezierCurve::getPyObject() { return new BezierCurve2dPy(static_cast(this->clone())); } @@ -427,7 +427,7 @@ const Handle(Geom2d_Geometry)& Geom2dBSplineCurve::handle() const return myCurve; } -Geometry2d *Geom2dBSplineCurve::clone(void) const +Geometry2d *Geom2dBSplineCurve::clone() const { Geom2dBSplineCurve *newCurve = new Geom2dBSplineCurve(myCurve); return newCurve; @@ -571,7 +571,7 @@ std::list Geom2dBSplineCurve::toBiArcs(double /*tolerance*/) const return std::list(); } -unsigned int Geom2dBSplineCurve::getMemSize(void) const +unsigned int Geom2dBSplineCurve::getMemSize() const { throw Base::NotImplementedError("Geom2dBSplineCurve::getMemSize"); } @@ -586,7 +586,7 @@ void Geom2dBSplineCurve::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("Geom2dBSplineCurve::Restore"); } -PyObject *Geom2dBSplineCurve::getPyObject(void) +PyObject *Geom2dBSplineCurve::getPyObject() { return new BSplineCurve2dPy(static_cast(this->clone())); } @@ -603,7 +603,7 @@ Geom2dConic::~Geom2dConic() { } -Base::Vector2d Geom2dConic::getLocation(void) const +Base::Vector2d Geom2dConic::getLocation() const { Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(handle()); const gp_Pnt2d& loc = conic->Location(); @@ -680,7 +680,7 @@ Geom2dArcOfConic::~Geom2dArcOfConic() { } -Base::Vector2d Geom2dArcOfConic::getLocation(void) const +Base::Vector2d Geom2dArcOfConic::getLocation() const { Handle(Geom2d_TrimmedCurve) curve = Handle(Geom2d_TrimmedCurve)::DownCast(handle()); Handle(Geom2d_Conic) conic = Handle(Geom2d_Conic)::DownCast(curve->BasisCurve()); @@ -826,13 +826,13 @@ const Handle(Geom2d_Geometry)& Geom2dCircle::handle() const return myCurve; } -Geometry2d *Geom2dCircle::clone(void) const +Geometry2d *Geom2dCircle::clone() const { Geom2dCircle *newCirc = new Geom2dCircle(myCurve); return newCirc; } -double Geom2dCircle::getRadius(void) const +double Geom2dCircle::getRadius() const { Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(handle()); return circle->Radius(); @@ -852,7 +852,7 @@ void Geom2dCircle::setRadius(double Radius) } } -unsigned int Geom2dCircle::getMemSize (void) const +unsigned int Geom2dCircle::getMemSize () const { return sizeof(Geom2d_Circle); } @@ -900,7 +900,7 @@ void Geom2dCircle::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dCircle::getPyObject(void) +PyObject *Geom2dCircle::getPyObject() { return new Circle2dPy(static_cast(this->clone())); } @@ -983,14 +983,14 @@ const Handle(Geom2d_Geometry)& Geom2dArcOfCircle::handle() const return myCurve; } -Geometry2d *Geom2dArcOfCircle::clone(void) const +Geometry2d *Geom2dArcOfCircle::clone() const { Geom2dArcOfCircle* copy = new Geom2dArcOfCircle(); copy->setHandle(this->myCurve); return copy; } -double Geom2dArcOfCircle::getRadius(void) const +double Geom2dArcOfCircle::getRadius() const { Handle(Geom2d_Circle) circle = Handle(Geom2d_Circle)::DownCast(myCurve->BasisCurve()); return circle->Radius(); @@ -1010,7 +1010,7 @@ void Geom2dArcOfCircle::setRadius(double Radius) } } -unsigned int Geom2dArcOfCircle::getMemSize (void) const +unsigned int Geom2dArcOfCircle::getMemSize () const { return sizeof(Geom2d_Circle) + 2 *sizeof(double); } @@ -1069,7 +1069,7 @@ void Geom2dArcOfCircle::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfCircle::getPyObject(void) +PyObject *Geom2dArcOfCircle::getPyObject() { return new ArcOfCircle2dPy(static_cast(this->clone())); } @@ -1098,13 +1098,13 @@ const Handle(Geom2d_Geometry)& Geom2dEllipse::handle() const return myCurve; } -Geometry2d *Geom2dEllipse::clone(void) const +Geometry2d *Geom2dEllipse::clone() const { Geom2dEllipse *newEllipse = new Geom2dEllipse(myCurve); return newEllipse; } -double Geom2dEllipse::getMajorRadius(void) const +double Geom2dEllipse::getMajorRadius() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(handle()); return ellipse->MajorRadius(); @@ -1122,7 +1122,7 @@ void Geom2dEllipse::setMajorRadius(double Radius) } } -double Geom2dEllipse::getMinorRadius(void) const +double Geom2dEllipse::getMinorRadius() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(handle()); return ellipse->MinorRadius(); @@ -1175,7 +1175,7 @@ void Geom2dEllipse::setMajorAxisDir(Base::Vector2d newdir) } } -unsigned int Geom2dEllipse::getMemSize (void) const +unsigned int Geom2dEllipse::getMemSize () const { return sizeof(Geom2d_Ellipse); } @@ -1224,7 +1224,7 @@ void Geom2dEllipse::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dEllipse::getPyObject(void) +PyObject *Geom2dEllipse::getPyObject() { return new Ellipse2dPy(static_cast(this->clone())); } @@ -1266,14 +1266,14 @@ const Handle(Geom2d_Geometry)& Geom2dArcOfEllipse::handle() const return myCurve; } -Geometry2d *Geom2dArcOfEllipse::clone(void) const +Geometry2d *Geom2dArcOfEllipse::clone() const { Geom2dArcOfEllipse* copy = new Geom2dArcOfEllipse(); copy->setHandle(this->myCurve); return copy; } -double Geom2dArcOfEllipse::getMajorRadius(void) const +double Geom2dArcOfEllipse::getMajorRadius() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(myCurve->BasisCurve()); return ellipse->MajorRadius(); @@ -1291,7 +1291,7 @@ void Geom2dArcOfEllipse::setMajorRadius(double Radius) } } -double Geom2dArcOfEllipse::getMinorRadius(void) const +double Geom2dArcOfEllipse::getMinorRadius() const { Handle(Geom2d_Ellipse) ellipse = Handle(Geom2d_Ellipse)::DownCast(myCurve->BasisCurve()); return ellipse->MinorRadius(); @@ -1348,7 +1348,7 @@ void Geom2dArcOfEllipse::setMajorAxisDir(Base::Vector2d newdir) } } -unsigned int Geom2dArcOfEllipse::getMemSize (void) const +unsigned int Geom2dArcOfEllipse::getMemSize () const { return sizeof(Geom2d_Ellipse) + 2 *sizeof(double); } @@ -1410,7 +1410,7 @@ void Geom2dArcOfEllipse::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfEllipse::getPyObject(void) +PyObject *Geom2dArcOfEllipse::getPyObject() { return new ArcOfEllipse2dPy(static_cast(this->clone())); } @@ -1439,13 +1439,13 @@ const Handle(Geom2d_Geometry)& Geom2dHyperbola::handle() const return myCurve; } -Geometry2d *Geom2dHyperbola::clone(void) const +Geometry2d *Geom2dHyperbola::clone() const { Geom2dHyperbola *newHyp = new Geom2dHyperbola(myCurve); return newHyp; } -double Geom2dHyperbola::getMajorRadius(void) const +double Geom2dHyperbola::getMajorRadius() const { Handle(Geom2d_Hyperbola) h = Handle(Geom2d_Hyperbola)::DownCast(handle()); return h->MajorRadius(); @@ -1463,7 +1463,7 @@ void Geom2dHyperbola::setMajorRadius(double Radius) } } -double Geom2dHyperbola::getMinorRadius(void) const +double Geom2dHyperbola::getMinorRadius() const { Handle(Geom2d_Hyperbola) h = Handle(Geom2d_Hyperbola)::DownCast(handle()); return h->MinorRadius(); @@ -1481,7 +1481,7 @@ void Geom2dHyperbola::setMinorRadius(double Radius) } } -unsigned int Geom2dHyperbola::getMemSize (void) const +unsigned int Geom2dHyperbola::getMemSize () const { return sizeof(Geom2d_Hyperbola); } @@ -1530,7 +1530,7 @@ void Geom2dHyperbola::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dHyperbola::getPyObject(void) +PyObject *Geom2dHyperbola::getPyObject() { return new Hyperbola2dPy(static_cast(this->clone())); } @@ -1567,14 +1567,14 @@ const Handle(Geom2d_Geometry)& Geom2dArcOfHyperbola::handle() const return myCurve; } -Geometry2d *Geom2dArcOfHyperbola::clone(void) const +Geometry2d *Geom2dArcOfHyperbola::clone() const { Geom2dArcOfHyperbola* copy = new Geom2dArcOfHyperbola(); copy->setHandle(this->myCurve); return copy; } -double Geom2dArcOfHyperbola::getMajorRadius(void) const +double Geom2dArcOfHyperbola::getMajorRadius() const { Handle(Geom2d_Hyperbola) h = Handle(Geom2d_Hyperbola)::DownCast(myCurve->BasisCurve()); return h->MajorRadius(); @@ -1592,7 +1592,7 @@ void Geom2dArcOfHyperbola::setMajorRadius(double Radius) } } -double Geom2dArcOfHyperbola::getMinorRadius(void) const +double Geom2dArcOfHyperbola::getMinorRadius() const { Handle(Geom2d_Hyperbola) h = Handle(Geom2d_Hyperbola)::DownCast(myCurve->BasisCurve()); return h->MinorRadius(); @@ -1610,7 +1610,7 @@ void Geom2dArcOfHyperbola::setMinorRadius(double Radius) } } -unsigned int Geom2dArcOfHyperbola::getMemSize (void) const +unsigned int Geom2dArcOfHyperbola::getMemSize () const { return sizeof(Geom2d_Hyperbola) + 2 *sizeof(double); } @@ -1672,7 +1672,7 @@ void Geom2dArcOfHyperbola::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfHyperbola::getPyObject(void) +PyObject *Geom2dArcOfHyperbola::getPyObject() { return new ArcOfHyperbola2dPy(static_cast(this->clone())); } @@ -1701,13 +1701,13 @@ const Handle(Geom2d_Geometry)& Geom2dParabola::handle() const return myCurve; } -Geometry2d *Geom2dParabola::clone(void) const +Geometry2d *Geom2dParabola::clone() const { Geom2dParabola *newPar = new Geom2dParabola(myCurve); return newPar; } -double Geom2dParabola::getFocal(void) const +double Geom2dParabola::getFocal() const { Handle(Geom2d_Parabola) p = Handle(Geom2d_Parabola)::DownCast(handle()); return p->Focal(); @@ -1725,7 +1725,7 @@ void Geom2dParabola::setFocal(double length) } } -unsigned int Geom2dParabola::getMemSize (void) const +unsigned int Geom2dParabola::getMemSize () const { return sizeof(Geom2d_Parabola); } @@ -1773,7 +1773,7 @@ void Geom2dParabola::Restore(Base::XMLReader& reader) } } -PyObject *Geom2dParabola::getPyObject(void) +PyObject *Geom2dParabola::getPyObject() { return new Parabola2dPy(static_cast(this->clone())); } @@ -1810,14 +1810,14 @@ const Handle(Geom2d_Geometry)& Geom2dArcOfParabola::handle() const return myCurve; } -Geometry2d *Geom2dArcOfParabola::clone(void) const +Geometry2d *Geom2dArcOfParabola::clone() const { Geom2dArcOfParabola* copy = new Geom2dArcOfParabola(); copy->setHandle(this->myCurve); return copy; } -double Geom2dArcOfParabola::getFocal(void) const +double Geom2dArcOfParabola::getFocal() const { Handle(Geom2d_Parabola) p = Handle(Geom2d_Parabola)::DownCast(myCurve->BasisCurve()); return p->Focal(); @@ -1835,7 +1835,7 @@ void Geom2dArcOfParabola::setFocal(double length) } } -unsigned int Geom2dArcOfParabola::getMemSize (void) const +unsigned int Geom2dArcOfParabola::getMemSize () const { return sizeof(Geom2d_Parabola) + 2 *sizeof(double); } @@ -1895,7 +1895,7 @@ void Geom2dArcOfParabola::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dArcOfParabola::getPyObject(void) +PyObject *Geom2dArcOfParabola::getPyObject() { return new ArcOfParabola2dPy(static_cast(this->clone())); } @@ -1930,13 +1930,13 @@ void Geom2dLine::setLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir) this->myCurve->SetDirection(gp_Dir2d(Dir.x,Dir.y)); } -Base::Vector2d Geom2dLine::getPos(void) const +Base::Vector2d Geom2dLine::getPos() const { gp_Pnt2d Pos = this->myCurve->Lin2d().Location(); return Base::Vector2d(Pos.X(),Pos.Y()); } -Base::Vector2d Geom2dLine::getDir(void) const +Base::Vector2d Geom2dLine::getDir() const { gp_Dir2d Dir = this->myCurve->Lin2d().Direction(); return Base::Vector2d(Dir.X(),Dir.Y()); @@ -1947,13 +1947,13 @@ const Handle(Geom2d_Geometry)& Geom2dLine::handle() const return myCurve; } -Geometry2d *Geom2dLine::clone(void) const +Geometry2d *Geom2dLine::clone() const { Geom2dLine *newLine = new Geom2dLine(myCurve); return newLine; } -unsigned int Geom2dLine::getMemSize (void) const +unsigned int Geom2dLine::getMemSize () const { return sizeof(Geom2d_Line); } @@ -2004,7 +2004,7 @@ void Geom2dLine::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dLine::getPyObject(void) +PyObject *Geom2dLine::getPyObject() { return new Line2dPy(static_cast(this->clone())); } @@ -2039,7 +2039,7 @@ const Handle(Geom2d_Geometry)& Geom2dLineSegment::handle() const return myCurve; } -Geometry2d *Geom2dLineSegment::clone(void)const +Geometry2d *Geom2dLineSegment::clone()const { Geom2dLineSegment *tempCurve = new Geom2dLineSegment(); tempCurve->myCurve = Handle(Geom2d_TrimmedCurve)::DownCast(myCurve->Copy()); @@ -2087,7 +2087,7 @@ void Geom2dLineSegment::setPoints(const Base::Vector2d& Start, const Base::Vecto } } -unsigned int Geom2dLineSegment::getMemSize (void) const +unsigned int Geom2dLineSegment::getMemSize () const { return sizeof(Geom2d_TrimmedCurve) + sizeof(Geom2d_Line); } @@ -2139,7 +2139,7 @@ void Geom2dLineSegment::Restore(Base::XMLReader &reader) } } -PyObject *Geom2dLineSegment::getPyObject(void) +PyObject *Geom2dLineSegment::getPyObject() { return new Line2dSegmentPy(static_cast(this->clone())); } @@ -2166,7 +2166,7 @@ Geom2dOffsetCurve::~Geom2dOffsetCurve() { } -Geometry2d *Geom2dOffsetCurve::clone(void) const +Geometry2d *Geom2dOffsetCurve::clone() const { Geom2dOffsetCurve *newCurve = new Geom2dOffsetCurve(myCurve); return newCurve; @@ -2182,7 +2182,7 @@ const Handle(Geom2d_Geometry)& Geom2dOffsetCurve::handle() const return this->myCurve; } -unsigned int Geom2dOffsetCurve::getMemSize (void) const +unsigned int Geom2dOffsetCurve::getMemSize () const { throw Base::NotImplementedError("Geom2dOffsetCurve::getMemSize"); } @@ -2197,7 +2197,7 @@ void Geom2dOffsetCurve::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("Geom2dOffsetCurve::Restore"); } -PyObject *Geom2dOffsetCurve::getPyObject(void) +PyObject *Geom2dOffsetCurve::getPyObject() { return new OffsetCurve2dPy(static_cast(this->clone())); } @@ -2229,13 +2229,13 @@ const Handle(Geom2d_Geometry)& Geom2dTrimmedCurve::handle() const return myCurve; } -Geometry2d *Geom2dTrimmedCurve::clone(void) const +Geometry2d *Geom2dTrimmedCurve::clone() const { Geom2dTrimmedCurve *newCurve = new Geom2dTrimmedCurve(myCurve); return newCurve; } -unsigned int Geom2dTrimmedCurve::getMemSize (void) const +unsigned int Geom2dTrimmedCurve::getMemSize () const { throw Base::NotImplementedError("Geom2dTrimmedCurve::getMemSize"); } @@ -2250,7 +2250,7 @@ void Geom2dTrimmedCurve::Restore(Base::XMLReader &/*reader*/) throw Base::NotImplementedError("Geom2dTrimmedCurve::Restore"); } -PyObject *Geom2dTrimmedCurve::getPyObject(void) +PyObject *Geom2dTrimmedCurve::getPyObject() { Handle(Geom2d_Curve) basis = this->myCurve->BasisCurve(); if (basis.IsNull()) diff --git a/src/Mod/Part/App/Geometry2d.h b/src/Mod/Part/App/Geometry2d.h index 43241db924..d8605dfdf6 100644 --- a/src/Mod/Part/App/Geometry2d.h +++ b/src/Mod/Part/App/Geometry2d.h @@ -50,18 +50,18 @@ namespace Part { class PartExport Geometry2d : public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~Geometry2d(); + ~Geometry2d() override; virtual TopoDS_Shape toShape() const = 0; virtual const Handle(Geom2d_Geometry)& handle() const = 0; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; /// returns a cloned object - virtual Geometry2d *clone(void) const = 0; + virtual Geometry2d *clone() const = 0; protected: Geometry2d(); @@ -73,25 +73,25 @@ private: class PartExport Geom2dPoint : public Geometry2d { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dPoint(); Geom2dPoint(const Handle(Geom2d_CartesianPoint)&); Geom2dPoint(const Base::Vector2d&); - virtual ~Geom2dPoint(); - virtual Geometry2d *clone(void) const; - virtual TopoDS_Shape toShape() const; + ~Geom2dPoint() override; + Geometry2d *clone() const override; + TopoDS_Shape toShape() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; - Base::Vector2d getPoint(void)const; + Base::Vector2d getPoint()const; void setPoint(const Base::Vector2d&); private: @@ -100,12 +100,12 @@ private: class PartExport Geom2dCurve : public Geometry2d { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dCurve(); - virtual ~Geom2dCurve(); + ~Geom2dCurve() override; - virtual TopoDS_Shape toShape() const; + TopoDS_Shape toShape() const override; bool tangent(double u, gp_Dir2d&) const; Base::Vector2d pointAtParameter(double u) const; Base::Vector2d firstDerivativeAtParameter(double u) const; @@ -117,22 +117,22 @@ public: class PartExport Geom2dBezierCurve : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dBezierCurve(); Geom2dBezierCurve(const Handle(Geom2d_BezierCurve)&); - virtual ~Geom2dBezierCurve(); - virtual Geometry2d *clone(void) const; + ~Geom2dBezierCurve() override; + Geometry2d *clone() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize (void) const; - virtual void Save (Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize () const override; + void Save (Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_BezierCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_BezierCurve) myCurve; @@ -140,12 +140,12 @@ private: class PartExport Geom2dBSplineCurve : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dBSplineCurve(); Geom2dBSplineCurve(const Handle(Geom2d_BSplineCurve)&); - virtual ~Geom2dBSplineCurve(); - virtual Geometry2d *clone(void) const; + ~Geom2dBSplineCurve() override; + Geometry2d *clone() const override; /*! * Set the poles and tangents for the cubic Hermite spline @@ -174,14 +174,14 @@ public: std::list toBiArcs(double tolerance) const; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_BSplineCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: void createArcs(double tolerance, std::list& new_spans, @@ -196,22 +196,22 @@ private: class PartExport Geom2dConic : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); protected: Geom2dConic(); public: - virtual ~Geom2dConic(); - virtual Geometry2d *clone(void) const = 0; + ~Geom2dConic() override; + Geometry2d *clone() const override = 0; - Base::Vector2d getLocation(void) const; + Base::Vector2d getLocation() const; void setLocation(const Base::Vector2d& Center); bool isReversed() const; - virtual unsigned int getMemSize(void) const = 0; - virtual PyObject *getPyObject(void) = 0; + unsigned int getMemSize() const override = 0; + PyObject *getPyObject() override = 0; - const Handle(Geom2d_Geometry)& handle() const = 0; + const Handle(Geom2d_Geometry)& handle() const override = 0; protected: void SaveAxis(Base::Writer& writer, const gp_Ax22d&) const; @@ -220,15 +220,15 @@ protected: class PartExport Geom2dArcOfConic : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); protected: Geom2dArcOfConic(); public: - virtual ~Geom2dArcOfConic(); - virtual Geometry2d *clone(void) const = 0; + ~Geom2dArcOfConic() override; + Geometry2d *clone() const override = 0; - Base::Vector2d getLocation(void) const; + Base::Vector2d getLocation() const; void setLocation(const Base::Vector2d& Center); bool isReversed() const; @@ -238,10 +238,10 @@ public: void getRange(double& u, double& v) const; void setRange(double u, double v); - virtual unsigned int getMemSize(void) const = 0; - virtual PyObject *getPyObject(void) = 0; + unsigned int getMemSize() const override = 0; + PyObject *getPyObject() override = 0; - const Handle(Geom2d_Geometry)& handle() const = 0; + const Handle(Geom2d_Geometry)& handle() const override = 0; protected: void SaveAxis(Base::Writer& writer, const gp_Ax22d&, double u, double v) const; @@ -250,24 +250,24 @@ protected: class PartExport Geom2dCircle : public Geom2dConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dCircle(); Geom2dCircle(const Handle(Geom2d_Circle)&); - virtual ~Geom2dCircle(); - virtual Geometry2d *clone(void) const; + ~Geom2dCircle() override; + Geometry2d *clone() const override; - double getRadius(void) const; + double getRadius() const; void setRadius(double Radius); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; static Base::Vector2d getCircleCenter (const Base::Vector2d &p1, const Base::Vector2d &p2, const Base::Vector2d &p3); @@ -277,25 +277,25 @@ private: class PartExport Geom2dArcOfCircle : public Geom2dArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dArcOfCircle(); Geom2dArcOfCircle(const Handle(Geom2d_Circle)&); - virtual ~Geom2dArcOfCircle(); - virtual Geometry2d *clone(void) const; + ~Geom2dArcOfCircle() override; + Geometry2d *clone() const override; - double getRadius(void) const; + double getRadius() const; void setRadius(double Radius); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; @@ -303,29 +303,29 @@ private: class PartExport Geom2dEllipse : public Geom2dConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dEllipse(); Geom2dEllipse(const Handle(Geom2d_Ellipse)&); - virtual ~Geom2dEllipse(); - virtual Geometry2d *clone(void) const; + ~Geom2dEllipse() override; + Geometry2d *clone() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); Base::Vector2d getMajorAxisDir() const; void setMajorAxisDir(Base::Vector2d newdir); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_Ellipse) &e); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_Ellipse) myCurve; @@ -333,29 +333,29 @@ private: class PartExport Geom2dArcOfEllipse : public Geom2dArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dArcOfEllipse(); Geom2dArcOfEllipse(const Handle(Geom2d_Ellipse)&); - virtual ~Geom2dArcOfEllipse(); - virtual Geometry2d *clone(void) const; + ~Geom2dArcOfEllipse() override; + Geometry2d *clone() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); Base::Vector2d getMajorAxisDir() const; void setMajorAxisDir(Base::Vector2d newdir); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; @@ -363,26 +363,26 @@ private: class PartExport Geom2dHyperbola : public Geom2dConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dHyperbola(); Geom2dHyperbola(const Handle(Geom2d_Hyperbola)&); - virtual ~Geom2dHyperbola(); - virtual Geometry2d *clone(void) const; + ~Geom2dHyperbola() override; + Geometry2d *clone() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_Hyperbola) myCurve; @@ -390,27 +390,27 @@ private: class PartExport Geom2dArcOfHyperbola : public Geom2dArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dArcOfHyperbola(); Geom2dArcOfHyperbola(const Handle(Geom2d_Hyperbola)&); - virtual ~Geom2dArcOfHyperbola(); - virtual Geometry2d *clone(void) const; + ~Geom2dArcOfHyperbola() override; + Geometry2d *clone() const override; - double getMajorRadius(void) const; + double getMajorRadius() const; void setMajorRadius(double Radius); - double getMinorRadius(void) const; + double getMinorRadius() const; void setMinorRadius(double Radius); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; @@ -418,24 +418,24 @@ private: class PartExport Geom2dParabola : public Geom2dConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dParabola(); Geom2dParabola(const Handle(Geom2d_Parabola)&); - virtual ~Geom2dParabola(); - virtual Geometry2d *clone(void) const; + ~Geom2dParabola() override; + Geometry2d *clone() const override; - double getFocal(void) const; + double getFocal() const; void setFocal(double length); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_Parabola) myCurve; @@ -443,25 +443,25 @@ private: class PartExport Geom2dArcOfParabola : public Geom2dArcOfConic { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dArcOfParabola(); Geom2dArcOfParabola(const Handle(Geom2d_Parabola)&); - virtual ~Geom2dArcOfParabola(); - virtual Geometry2d *clone(void) const; + ~Geom2dArcOfParabola() override; + Geometry2d *clone() const override; - double getFocal(void) const; + double getFocal() const; void setFocal(double length); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; @@ -469,26 +469,26 @@ private: class PartExport Geom2dLine : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dLine(); Geom2dLine(const Handle(Geom2d_Line)&); Geom2dLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir); - virtual ~Geom2dLine(); - virtual Geometry2d *clone(void) const; + ~Geom2dLine() override; + Geometry2d *clone() const override; void setLine(const Base::Vector2d& Pos, const Base::Vector2d& Dir); - Base::Vector2d getPos(void) const; - Base::Vector2d getDir(void) const; + Base::Vector2d getPos() const; + Base::Vector2d getDir() const; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_Line) myCurve; @@ -496,11 +496,11 @@ private: class PartExport Geom2dLineSegment : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dLineSegment(); - virtual ~Geom2dLineSegment(); - virtual Geometry2d *clone(void) const; + ~Geom2dLineSegment() override; + Geometry2d *clone() const override; Base::Vector2d getStartPoint() const; Base::Vector2d getEndPoint() const; @@ -509,14 +509,14 @@ public: const Base::Vector2d& p2); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; @@ -524,23 +524,23 @@ private: class PartExport Geom2dOffsetCurve : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dOffsetCurve(); Geom2dOffsetCurve(const Handle(Geom2d_Curve)&, double); Geom2dOffsetCurve(const Handle(Geom2d_OffsetCurve)&); - virtual ~Geom2dOffsetCurve(); - virtual Geometry2d *clone(void) const; + ~Geom2dOffsetCurve() override; + Geometry2d *clone() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_OffsetCurve)& c); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_OffsetCurve) myCurve; @@ -548,22 +548,22 @@ private: class PartExport Geom2dTrimmedCurve : public Geom2dCurve { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Geom2dTrimmedCurve(); - Geom2dTrimmedCurve(const Handle(Geom2d_TrimmedCurve)&); - virtual ~Geom2dTrimmedCurve(); - virtual Geometry2d *clone(void) const; + explicit Geom2dTrimmedCurve(const Handle(Geom2d_TrimmedCurve)&); + ~Geom2dTrimmedCurve() override; + Geometry2d *clone() const override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; // Base implementer ---------------------------- - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; void setHandle(const Handle(Geom2d_TrimmedCurve)&); - const Handle(Geom2d_Geometry)& handle() const; + const Handle(Geom2d_Geometry)& handle() const override; private: Handle(Geom2d_TrimmedCurve) myCurve; diff --git a/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp b/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp index 4bd64c3b9e..1d27427e24 100644 --- a/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryBoolExtensionPyImp.cpp @@ -29,13 +29,13 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryBoolExtensionPy::representation(void) const +std::string GeometryBoolExtensionPy::representation() const { std::stringstream str; bool val = getGeometryBoolExtensionPtr()->getValue(); str << "getName().size()>0) + if(!getGeometryBoolExtensionPtr()->getName().empty()) str << "\'" << getGeometryBoolExtensionPtr()->getName() << "\', "; str << (val?"True":"False") << ") >"; @@ -81,7 +81,7 @@ int GeometryBoolExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Boolean GeometryBoolExtensionPy::getValue(void) const +Py::Boolean GeometryBoolExtensionPy::getValue() const { return Py::Boolean(this->getGeometryBoolExtensionPtr()->getValue()); } diff --git a/src/Mod/Part/App/GeometryCurvePyImp.cpp b/src/Mod/Part/App/GeometryCurvePyImp.cpp index 1b17d1e969..f0c4d7904b 100644 --- a/src/Mod/Part/App/GeometryCurvePyImp.cpp +++ b/src/Mod/Part/App/GeometryCurvePyImp.cpp @@ -80,7 +80,7 @@ extern const Py::Object makeTrimmedCurvePy(const Handle(Geom_Curve)& c, double f using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryCurvePy::representation(void) const +std::string GeometryCurvePy::representation() const { return ""; } @@ -975,7 +975,7 @@ PyObject* GeometryCurvePy::continuityWith(PyObject *args) return nullptr; } -Py::String GeometryCurvePy::getContinuity(void) const +Py::String GeometryCurvePy::getContinuity() const { GeomAbs_Shape c = Handle(Geom_Curve)::DownCast (getGeometryPtr()->handle())->Continuity(); @@ -1009,13 +1009,13 @@ Py::String GeometryCurvePy::getContinuity(void) const return Py::String(str); } -Py::Float GeometryCurvePy::getFirstParameter(void) const +Py::Float GeometryCurvePy::getFirstParameter() const { return Py::Float(Handle(Geom_Curve)::DownCast (getGeometryPtr()->handle())->FirstParameter()); } -Py::Float GeometryCurvePy::getLastParameter(void) const +Py::Float GeometryCurvePy::getLastParameter() const { return Py::Float(Handle(Geom_Curve)::DownCast (getGeometryPtr()->handle())->LastParameter()); @@ -1135,7 +1135,7 @@ PyObject* GeometryCurvePy::intersect(PyObject *args) return nullptr; } -Py::Object GeometryCurvePy::getRotation(void) const +Py::Object GeometryCurvePy::getRotation() const { Handle(Geom_Conic) s = Handle(Geom_Conic)::DownCast(getGeometryPtr()->handle()); if(!s) diff --git a/src/Mod/Part/App/GeometryDefaultExtension.cpp b/src/Mod/Part/App/GeometryDefaultExtension.cpp index 4fecdd4d6a..d66cdb8479 100644 --- a/src/Mod/Part/App/GeometryDefaultExtension.cpp +++ b/src/Mod/Part/App/GeometryDefaultExtension.cpp @@ -66,7 +66,7 @@ void GeometryDefaultExtension::saveAttributes(Base::Writer &writer) const } template -std::unique_ptr GeometryDefaultExtension::copy(void) const +std::unique_ptr GeometryDefaultExtension::copy() const { std::unique_ptr> cpy = std::make_unique>(); @@ -93,7 +93,7 @@ std::unique_ptr GeometryDefaultExtension::copy(void) } template -PyObject * GeometryDefaultExtension::getPyObject(void) +PyObject * GeometryDefaultExtension::getPyObject() { THROWM(Base::NotImplementedError,"Python object not implemented for default geometry extension template type. Template Specialisation missing."); // use template specialisation to provide the actual object } @@ -108,7 +108,7 @@ namespace Part { TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryIntExtension,Part::GeometryPersistenceExtension) template <> -PyObject * GeometryDefaultExtension::getPyObject(void) +PyObject * GeometryDefaultExtension::getPyObject() { return new GeometryIntExtensionPy(new GeometryIntExtension(*this)); } @@ -125,7 +125,7 @@ void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryStringExtension,Part::GeometryPersistenceExtension) template <> -PyObject * GeometryDefaultExtension::getPyObject(void) +PyObject * GeometryDefaultExtension::getPyObject() { return new GeometryStringExtensionPy(new GeometryStringExtension(*this)); } @@ -134,7 +134,7 @@ PyObject * GeometryDefaultExtension::getPyObject(void) TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryBoolExtension,Part::GeometryPersistenceExtension) template <> -PyObject * GeometryDefaultExtension::getPyObject(void) +PyObject * GeometryDefaultExtension::getPyObject() { return new GeometryBoolExtensionPy(new GeometryBoolExtension(*this)); } @@ -151,7 +151,7 @@ void GeometryDefaultExtension::restoreAttributes(Base::XMLReader &reader) TYPESYSTEM_SOURCE_TEMPLATE_T(Part::GeometryDoubleExtension,Part::GeometryPersistenceExtension) template <> -PyObject * GeometryDefaultExtension::getPyObject(void) +PyObject * GeometryDefaultExtension::getPyObject() { return new GeometryDoubleExtensionPy(new GeometryDoubleExtension(*this)); } diff --git a/src/Mod/Part/App/GeometryDefaultExtension.h b/src/Mod/Part/App/GeometryDefaultExtension.h index 9ab4bdfdd3..44c0c3d190 100644 --- a/src/Mod/Part/App/GeometryDefaultExtension.h +++ b/src/Mod/Part/App/GeometryDefaultExtension.h @@ -35,20 +35,20 @@ namespace Part { TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: inline GeometryDefaultExtension(); - GeometryDefaultExtension(const T& val, std::string name = std::string()); - virtual ~GeometryDefaultExtension() override = default; + explicit GeometryDefaultExtension(const T& val, std::string name = std::string()); + ~GeometryDefaultExtension() override = default; inline void setValue(const T& val) {value = val;}; inline const T &getValue() const {return value;}; - virtual std::unique_ptr copy(void) const override; + std::unique_ptr copy() const override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; protected: - virtual void copyAttributes(Part::GeometryExtension * cpy) const override; - virtual void restoreAttributes(Base::XMLReader &reader) override; - virtual void saveAttributes(Base::Writer &writer) const override; + void copyAttributes(Part::GeometryExtension * cpy) const override; + void restoreAttributes(Base::XMLReader &reader) override; + void saveAttributes(Base::Writer &writer) const override; private: GeometryDefaultExtension(const GeometryDefaultExtension&) = default; diff --git a/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp b/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp index 0d1a0e23e4..8e9d0a2c75 100644 --- a/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryDoubleExtensionPyImp.cpp @@ -31,13 +31,13 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryDoubleExtensionPy::representation(void) const +std::string GeometryDoubleExtensionPy::representation() const { std::stringstream str; double val = getGeometryDoubleExtensionPtr()->getValue(); str << "getName().size()>0) + if(!getGeometryDoubleExtensionPtr()->getName().empty()) str << "\'" << getGeometryDoubleExtensionPtr()->getName() << "\', "; str << val << ") >"; @@ -83,7 +83,7 @@ int GeometryDoubleExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Float GeometryDoubleExtensionPy::getValue(void) const +Py::Float GeometryDoubleExtensionPy::getValue() const { return Py::Float(this->getGeometryDoubleExtensionPtr()->getValue()); } diff --git a/src/Mod/Part/App/GeometryExtension.cpp b/src/Mod/Part/App/GeometryExtension.cpp index 96c0c8f119..d6cd885324 100644 --- a/src/Mod/Part/App/GeometryExtension.cpp +++ b/src/Mod/Part/App/GeometryExtension.cpp @@ -62,7 +62,7 @@ void GeometryPersistenceExtension::saveAttributes(Base::Writer &writer) const { const std::string name = getName(); - if(name.size() > 0) + if(!name.empty()) writer.Stream() << "\" name=\"" << name; } diff --git a/src/Mod/Part/App/GeometryExtension.h b/src/Mod/Part/App/GeometryExtension.h index 228d537530..0626603020 100644 --- a/src/Mod/Part/App/GeometryExtension.h +++ b/src/Mod/Part/App/GeometryExtension.h @@ -36,13 +36,13 @@ class Geometry; class PartExport GeometryExtension: public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~GeometryExtension() = default; + ~GeometryExtension() override = default; - virtual std::unique_ptr copy(void) const = 0; + virtual std::unique_ptr copy() const = 0; - virtual PyObject *getPyObject(void) = 0; + PyObject *getPyObject() override = 0; PyObject* copyPyObject() const; inline void setName(const std::string& str) {name = str;} @@ -67,9 +67,9 @@ private: class PartExport GeometryPersistenceExtension : public Part::GeometryExtension { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - virtual ~GeometryPersistenceExtension() = default; + ~GeometryPersistenceExtension() override = default; // Own Persistence implementer - Not Base::Persistence - managed by Part::Geometry void Save(Base::Writer &/*writer*/) const; diff --git a/src/Mod/Part/App/GeometryExtensionPyImp.cpp b/src/Mod/Part/App/GeometryExtensionPyImp.cpp index ae5ac1af5a..2f434389e2 100644 --- a/src/Mod/Part/App/GeometryExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryExtensionPyImp.cpp @@ -30,7 +30,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryExtensionPy::representation(void) const +std::string GeometryExtensionPy::representation() const { return ""; } @@ -76,7 +76,7 @@ PyObject* GeometryExtensionPy::copy(PyObject *args) return cpy; } -Py::String GeometryExtensionPy::getName(void) const +Py::String GeometryExtensionPy::getName() const { std::string name = this->getGeometryExtensionPtr()->getName(); diff --git a/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp b/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp index d16d44a618..3b8cfc3e17 100644 --- a/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryIntExtensionPyImp.cpp @@ -29,13 +29,13 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryIntExtensionPy::representation(void) const +std::string GeometryIntExtensionPy::representation() const { std::stringstream str; long val = getGeometryIntExtensionPtr()->getValue(); str << "getName().size()>0) + if(!getGeometryIntExtensionPtr()->getName().empty()) str << "\'" << getGeometryIntExtensionPtr()->getName() << "\', "; str << val << ") >"; @@ -81,7 +81,7 @@ int GeometryIntExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Long GeometryIntExtensionPy::getValue(void) const +Py::Long GeometryIntExtensionPy::getValue() const { return Py::Long(this->getGeometryIntExtensionPtr()->getValue()); } diff --git a/src/Mod/Part/App/GeometryMigrationExtension.cpp b/src/Mod/Part/App/GeometryMigrationExtension.cpp index 806412d54a..48ec344025 100644 --- a/src/Mod/Part/App/GeometryMigrationExtension.cpp +++ b/src/Mod/Part/App/GeometryMigrationExtension.cpp @@ -44,7 +44,7 @@ void GeometryMigrationExtension::copyAttributes(Part::GeometryExtension * cpy) c static_cast(cpy)->GeometryMigrationFlags = this->GeometryMigrationFlags; } -std::unique_ptr GeometryMigrationExtension::copy(void) const +std::unique_ptr GeometryMigrationExtension::copy() const { auto cpy = std::make_unique(); @@ -57,7 +57,7 @@ std::unique_ptr GeometryMigrationExtension::copy(void) #endif } -PyObject * GeometryMigrationExtension::getPyObject(void) +PyObject * GeometryMigrationExtension::getPyObject() { THROWM(Base::NotImplementedError, "GeometryMigrationExtension does not have a Python counterpart"); } diff --git a/src/Mod/Part/App/GeometryMigrationExtension.h b/src/Mod/Part/App/GeometryMigrationExtension.h index a9c68c5272..9195c632a9 100644 --- a/src/Mod/Part/App/GeometryMigrationExtension.h +++ b/src/Mod/Part/App/GeometryMigrationExtension.h @@ -53,11 +53,11 @@ public: }; GeometryMigrationExtension(); - virtual ~GeometryMigrationExtension() override = default; + ~GeometryMigrationExtension() override = default; - virtual std::unique_ptr copy(void) const override; + std::unique_ptr copy() const override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; virtual bool getConstruction() const {return ConstructionState;} @@ -67,7 +67,7 @@ public: virtual void setMigrationType(int flag, bool v=true) { GeometryMigrationFlags.set((size_t)(flag), v); }; protected: - virtual void copyAttributes(Part::GeometryExtension * cpy) const override; + void copyAttributes(Part::GeometryExtension * cpy) const override; private: GeometryMigrationExtension(const GeometryMigrationExtension&) = default; diff --git a/src/Mod/Part/App/GeometryPyImp.cpp b/src/Mod/Part/App/GeometryPyImp.cpp index 1215901435..88db0fdfe7 100644 --- a/src/Mod/Part/App/GeometryPyImp.cpp +++ b/src/Mod/Part/App/GeometryPyImp.cpp @@ -43,7 +43,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryPy::representation(void) const +std::string GeometryPy::representation() const { return ""; } @@ -425,7 +425,7 @@ PyObject* GeometryPy::getExtensions(PyObject *args) } -Py::String GeometryPy::getTag(void) const +Py::String GeometryPy::getTag() const { std::string tmp = boost::uuids::to_string(getGeometryPtr()->getTag()); return Py::String(tmp); diff --git a/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp b/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp index 294f3a9ce1..b5a03a6db5 100644 --- a/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp +++ b/src/Mod/Part/App/GeometryStringExtensionPyImp.cpp @@ -33,12 +33,12 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometryStringExtensionPy::representation(void) const +std::string GeometryStringExtensionPy::representation() const { std::stringstream str; str << "getName().size()>0) + if(!getGeometryStringExtensionPtr()->getName().empty()) str << "\'" << getGeometryStringExtensionPtr()->getName() << "\', "; str << getGeometryStringExtensionPtr()->getValue() << ") >"; @@ -84,7 +84,7 @@ int GeometryStringExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::String GeometryStringExtensionPy::getValue(void) const +Py::String GeometryStringExtensionPy::getValue() const { return Py::String(this->getGeometryStringExtensionPtr()->getValue()); } diff --git a/src/Mod/Part/App/GeometrySurfacePyImp.cpp b/src/Mod/Part/App/GeometrySurfacePyImp.cpp index fdbf4069b9..aecc71d843 100644 --- a/src/Mod/Part/App/GeometrySurfacePyImp.cpp +++ b/src/Mod/Part/App/GeometrySurfacePyImp.cpp @@ -85,7 +85,7 @@ const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c) using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string GeometrySurfacePy::representation(void) const +std::string GeometrySurfacePy::representation() const { return ""; } @@ -687,7 +687,7 @@ PyObject* GeometrySurfacePy::VPeriod(PyObject * args) } } -Py::String GeometrySurfacePy::getContinuity(void) const +Py::String GeometrySurfacePy::getContinuity() const { GeomAbs_Shape c = Handle(Geom_Surface)::DownCast (getGeometryPtr()->handle())->Continuity(); @@ -876,7 +876,7 @@ PyObject* GeometrySurfacePy::intersect(PyObject *args) return nullptr; } -Py::Object GeometrySurfacePy::getRotation(void) const +Py::Object GeometrySurfacePy::getRotation() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp b/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp index 9cd15a9956..8337afd4b2 100644 --- a/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/HLRBRep_AlgoPyImp.cpp @@ -58,7 +58,7 @@ int HLRBRep_AlgoPy::PyInit(PyObject* /*args*/, PyObject* /*kwds*/) } // returns a string which represents the object e.g. when printed in python -std::string HLRBRep_AlgoPy::representation(void) const +std::string HLRBRep_AlgoPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp b/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp index 10103b18c2..e5c296dd7e 100644 --- a/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/HLRBRep_PolyAlgoPyImp.cpp @@ -72,7 +72,7 @@ int HLRBRep_PolyAlgoPy::PyInit(PyObject* args, PyObject* /*kwds*/) } // returns a string which represents the object e.g. when printed in python -std::string HLRBRep_PolyAlgoPy::representation(void) const +std::string HLRBRep_PolyAlgoPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp b/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp index 9e39f386a6..9cd935c9c0 100644 --- a/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/HLRToShapePyImp.cpp @@ -50,7 +50,7 @@ int HLRToShapePy::PyInit(PyObject* args, PyObject* /*kwds*/) } // returns a string which represents the object e.g. when printed in python -std::string HLRToShapePy::representation(void) const +std::string HLRToShapePy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp b/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp index d31cc0f34b..6d2978ec84 100644 --- a/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp +++ b/src/Mod/Part/App/HLRBRep/PolyHLRToShapePyImp.cpp @@ -52,7 +52,7 @@ int PolyHLRToShapePy::PyInit(PyObject* args, PyObject* /*kwds*/) } // returns a string which represents the object e.g. when printed in python -std::string PolyHLRToShapePy::representation(void) const +std::string PolyHLRToShapePy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/HyperbolaPyImp.cpp b/src/Mod/Part/App/HyperbolaPyImp.cpp index b3a65c4d99..0abf235705 100644 --- a/src/Mod/Part/App/HyperbolaPyImp.cpp +++ b/src/Mod/Part/App/HyperbolaPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string HyperbolaPy::representation(void) const +std::string HyperbolaPy::representation() const { return ""; } @@ -125,7 +125,7 @@ int HyperbolaPy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Float HyperbolaPy::getMajorRadius(void) const +Py::Float HyperbolaPy::getMajorRadius() const { Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); return Py::Float(hyperbola->MajorRadius()); @@ -137,7 +137,7 @@ void HyperbolaPy::setMajorRadius(Py::Float arg) hyperbola->SetMajorRadius((double)arg); } -Py::Float HyperbolaPy::getMinorRadius(void) const +Py::Float HyperbolaPy::getMinorRadius() const { Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); return Py::Float(hyperbola->MinorRadius()); @@ -149,20 +149,20 @@ void HyperbolaPy::setMinorRadius(Py::Float arg) hyperbola->SetMinorRadius((double)arg); } -Py::Float HyperbolaPy::getFocal(void) const +Py::Float HyperbolaPy::getFocal() const { Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); return Py::Float(hyperbola->Focal()); } -Py::Object HyperbolaPy::getFocus1(void) const +Py::Object HyperbolaPy::getFocus1() const { Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); gp_Pnt loc = hyperbola->Focus1(); return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -Py::Object HyperbolaPy::getFocus2(void) const +Py::Object HyperbolaPy::getFocus2() const { Handle(Geom_Hyperbola) hyperbola = Handle(Geom_Hyperbola)::DownCast(getGeomHyperbolaPtr()->handle()); gp_Pnt loc = hyperbola->Focus2(); diff --git a/src/Mod/Part/App/ImportStep.cpp b/src/Mod/Part/App/ImportStep.cpp index fc33bf4ecd..92624c5bf2 100644 --- a/src/Mod/Part/App/ImportStep.cpp +++ b/src/Mod/Part/App/ImportStep.cpp @@ -25,6 +25,7 @@ # include # include # include +# include # include # include # include @@ -43,6 +44,7 @@ #include #include +#include #include #include @@ -54,6 +56,213 @@ using namespace Part; + +void ImportExportSettings::initialize() +{ + // set the user-defined settings + Base::Reference hGrp = App::GetApplication().GetUserParameter() + .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/Part"); + initGeneral(hGrp); + initSTEP(hGrp); + initIGES(hGrp); +} + +void ImportExportSettings::initGeneral(Base::Reference hGrp) +{ + // General + Base::Reference hGenGrp = hGrp->GetGroup("General"); + // http://www.opencascade.org/org/forum/thread_20801/ + // read.surfacecurve.mode: + // A preference for the computation of curves in an entity which has both 2D and 3D representation. + // Each TopoDS_Edge in TopoDS_Face must have a 3D and 2D curve that references the surface. + // If both 2D and 3D representation of the entity are present, the computation of these curves depends on + // the following values of parameter: + // 0: "Default" - no preference, both curves are taken + // 3: "3DUse_Preferred" - 3D curves are used to rebuild 2D ones + // Additional modes for IGES + // 2: "2DUse_Preferred" - the 2D is used to rebuild the 3D in case of their inconsistency + // -2: "2DUse_Forced" - the 2D is always used to rebuild the 3D (even if 2D is present in the file) + // -3: "3DUse_Forced" - the 3D is always used to rebuild the 2D (even if 2D is present in the file) + int readsurfacecurve = hGenGrp->GetInt("ReadSurfaceCurveMode", 0); + Interface_Static::SetIVal("read.surfacecurve.mode", readsurfacecurve); + + // write.surfacecurve.mode (STEP-only): + // This parameter indicates whether parametric curves (curves in parametric space of surface) should be + // written into the STEP file. This parameter can be set to Off in order to minimize the size of the resulting + // STEP file. + // Off (0) : writes STEP files without pcurves. This mode decreases the size of the resulting file. + // On (1) : (default) writes pcurves to STEP file + int writesurfacecurve = hGenGrp->GetInt("WriteSurfaceCurveMode", 0); + Interface_Static::SetIVal("write.surfacecurve.mode", writesurfacecurve); +} + +void ImportExportSettings::initIGES(Base::Reference hGrp) +{ + //IGES handling + Base::Reference hIgesGrp = hGrp->GetGroup("IGES"); + int value = Interface_Static::IVal("write.iges.brep.mode"); + bool brep = hIgesGrp->GetBool("BrepMode", value > 0); + Interface_Static::SetIVal("write.iges.brep.mode",brep ? 1 : 0); + Interface_Static::SetCVal("write.iges.header.company", hIgesGrp->GetASCII("Company").c_str()); + Interface_Static::SetCVal("write.iges.header.author", hIgesGrp->GetASCII("Author").c_str()); + Interface_Static::SetCVal("write.iges.header.product", hIgesGrp->GetASCII("Product", + Interface_Static::CVal("write.iges.header.product")).c_str()); + + int unitIges = hIgesGrp->GetInt("Unit", 0); + switch (unitIges) { + case 1: + Interface_Static::SetCVal("write.iges.unit","M"); + break; + case 2: + Interface_Static::SetCVal("write.iges.unit","INCH"); + break; + default: + Interface_Static::SetCVal("write.iges.unit","MM"); + break; + } +} + +void ImportExportSettings::initSTEP(Base::Reference hGrp) +{ + //STEP handling + Base::Reference hStepGrp = hGrp->GetGroup("STEP"); + int unitStep = hStepGrp->GetInt("Unit", 0); + switch (unitStep) { + case 1: + Interface_Static::SetCVal("write.step.unit","M"); + break; + case 2: + Interface_Static::SetCVal("write.step.unit","INCH"); + break; + default: + Interface_Static::SetCVal("write.step.unit","MM"); + break; + } + + std::string ap = hStepGrp->GetASCII("Scheme", Interface_Static::CVal("write.step.schema")); + Interface_Static::SetCVal("write.step.schema", ap.c_str()); + Interface_Static::SetCVal("write.step.product.name", hStepGrp->GetASCII("Product", + Interface_Static::CVal("write.step.product.name")).c_str()); +} + +ImportExportSettings::ImportExportSettings() +{ + pGroup = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Import"); +} + +void ImportExportSettings::setReadShapeCompoundMode(bool on) +{ + auto grp = pGroup->GetGroup("hSTEP"); + grp->SetBool("ReadShapeCompoundMode", on); +} + +bool ImportExportSettings::getReadShapeCompoundMode() const +{ + auto grp = pGroup->GetGroup("hSTEP"); + return grp->GetBool("ReadShapeCompoundMode", true); +} + +void ImportExportSettings::setExportHiddenObject(bool on) +{ + pGroup->SetBool("ExportHiddenObject", on); +} + +bool ImportExportSettings::getExportHiddenObject() const +{ + return pGroup->GetBool("ExportHiddenObject", true); +} + +void ImportExportSettings::setImportHiddenObject(bool on) +{ + pGroup->SetBool("ImportHiddenObject", on); +} + +bool ImportExportSettings::getImportHiddenObject() const +{ + return pGroup->GetBool("ImportHiddenObject", false); +} + +void ImportExportSettings::setExportLegacy(bool on) +{ + pGroup->SetBool("ExportLegacy", on); +} + +bool ImportExportSettings::getExportLegacy() const +{ + return pGroup->GetBool("ExportLegacy", false); +} + +void ImportExportSettings::setExportKeepPlacement(bool on) +{ + pGroup->SetBool("ExportKeepPlacement", on); +} + +bool ImportExportSettings::getExportKeepPlacement() const +{ + return pGroup->GetBool("ExportKeepPlacement", false); +} + +void ImportExportSettings::setUseLinkGroup(bool on) +{ + pGroup->SetBool("UseLinkGroup", on); +} + +bool ImportExportSettings::getUseLinkGroup() const +{ + return pGroup->GetBool("UseLinkGroup", false); +} + +void ImportExportSettings::setUseBaseName(bool on) +{ + pGroup->SetBool("UseBaseName", on); +} + +bool ImportExportSettings::getUseBaseName() const +{ + return pGroup->GetBool("UseBaseName", false); +} + +void ImportExportSettings::setReduceObjects(bool on) +{ + pGroup->SetBool("ReduceObjects", on); +} + +bool ImportExportSettings::getReduceObjects() const +{ + return pGroup->GetBool("ReduceObjects", false); +} + +void ImportExportSettings::setExpandCompound(bool on) +{ + pGroup->SetBool("ExpandCompound", on); +} + +bool ImportExportSettings::getExpandCompound() const +{ + return pGroup->GetBool("ExpandCompound", false); +} + +void ImportExportSettings::setShowProgress(bool on) +{ + pGroup->SetBool("ShowProgress", on); +} + +bool ImportExportSettings::getShowProgress() const +{ + return pGroup->GetBool("ShowProgress", false); +} + +void ImportExportSettings::setImportMode(ImportExportSettings::ImportMode mode) +{ + pGroup->SetInt("ImportMode", static_cast(mode)); +} + +ImportExportSettings::ImportMode ImportExportSettings::getImportMode() const +{ + return static_cast(pGroup->GetInt("ImportMode", 0)); +} + + namespace Part { bool ReadColors (const Handle(XSControl_WorkSession) &WS, std::map& hash_col); bool ReadNames (const Handle(XSControl_WorkSession) &WS); diff --git a/src/Mod/Part/App/ImportStep.h b/src/Mod/Part/App/ImportStep.h index 84163393f5..ddb984dce4 100644 --- a/src/Mod/Part/App/ImportStep.h +++ b/src/Mod/Part/App/ImportStep.h @@ -24,6 +24,7 @@ #define _ImportStep_h_ #include +#include namespace App { @@ -33,6 +34,50 @@ class Document; namespace Part { +class PartExport ImportExportSettings +{ +public: + enum class ImportMode { + SingleDocument = 0, + GroupPerDocument = 1, + GroupPerDirectory = 2, + ObjectPerDocument = 3, + ObjectPerDirectory = 4, + }; + + static void initialize(); + ImportExportSettings(); + void setReadShapeCompoundMode(bool); + bool getReadShapeCompoundMode() const; + void setExportHiddenObject(bool); + bool getExportHiddenObject() const; + void setImportHiddenObject(bool); + bool getImportHiddenObject() const; + void setExportLegacy(bool); + bool getExportLegacy() const; + void setExportKeepPlacement(bool); + bool getExportKeepPlacement() const; + void setUseLinkGroup(bool); + bool getUseLinkGroup() const; + void setUseBaseName(bool); + bool getUseBaseName() const; + void setReduceObjects(bool); + bool getReduceObjects() const; + void setExpandCompound(bool); + bool getExpandCompound() const; + void setShowProgress(bool); + bool getShowProgress() const; + void setImportMode(ImportMode); + ImportMode getImportMode() const; + +private: + static void initGeneral(Base::Reference hGrp); + static void initSTEP(Base::Reference hGrp); + static void initIGES(Base::Reference hGrp); + +private: + ParameterGrp::handle pGroup; +}; /** The part shape property */ diff --git a/src/Mod/Part/App/LinePyImp.cpp b/src/Mod/Part/App/LinePyImp.cpp index 2a43b36023..b593074341 100644 --- a/src/Mod/Part/App/LinePyImp.cpp +++ b/src/Mod/Part/App/LinePyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string LinePy::representation(void) const +std::string LinePy::representation() const { return ""; } @@ -119,7 +119,7 @@ int LinePy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Object LinePy::getLocation(void) const +Py::Object LinePy::getLocation() const { Handle(Geom_Line) this_curve = Handle(Geom_Line)::DownCast (this->getGeomLinePtr()->handle()); @@ -169,7 +169,7 @@ void LinePy::setLocation(Py::Object arg) } } -Py::Object LinePy::getDirection(void) const +Py::Object LinePy::getDirection() const { Handle(Geom_Line) this_curve = Handle(Geom_Line)::DownCast (this->getGeomLinePtr()->handle()); diff --git a/src/Mod/Part/App/OffsetCurvePyImp.cpp b/src/Mod/Part/App/OffsetCurvePyImp.cpp index 6b18074a0b..2b5f132473 100644 --- a/src/Mod/Part/App/OffsetCurvePyImp.cpp +++ b/src/Mod/Part/App/OffsetCurvePyImp.cpp @@ -38,7 +38,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string OffsetCurvePy::representation(void) const +std::string OffsetCurvePy::representation() const { return ""; } @@ -82,7 +82,7 @@ int OffsetCurvePy::PyInit(PyObject* args, PyObject* /*kwd*/) } } -Py::Float OffsetCurvePy::getOffsetValue(void) const +Py::Float OffsetCurvePy::getOffsetValue() const { Handle(Geom_OffsetCurve) curve = Handle(Geom_OffsetCurve)::DownCast(getGeometryPtr()->handle()); return Py::Float(curve->Offset()); @@ -94,7 +94,7 @@ void OffsetCurvePy::setOffsetValue(Py::Float arg) curve->SetOffsetValue((double)arg); } -Py::Object OffsetCurvePy::getOffsetDirection(void) const +Py::Object OffsetCurvePy::getOffsetDirection() const { Handle(Geom_OffsetCurve) curve = Handle(Geom_OffsetCurve)::DownCast(getGeometryPtr()->handle()); const gp_Dir& dir = curve->Direction(); @@ -121,7 +121,7 @@ void OffsetCurvePy::setOffsetDirection(Py::Object arg) } } -Py::Object OffsetCurvePy::getBasisCurve(void) const +Py::Object OffsetCurvePy::getBasisCurve() const { Handle(Geom_OffsetCurve) curve = Handle(Geom_OffsetCurve)::DownCast(getGeometryPtr()->handle()); Handle(Geom_Curve) basis = curve->BasisCurve(); diff --git a/src/Mod/Part/App/OffsetSurfacePyImp.cpp b/src/Mod/Part/App/OffsetSurfacePyImp.cpp index 792333c817..29a8a3ac2f 100644 --- a/src/Mod/Part/App/OffsetSurfacePyImp.cpp +++ b/src/Mod/Part/App/OffsetSurfacePyImp.cpp @@ -34,7 +34,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string OffsetSurfacePy::representation(void) const +std::string OffsetSurfacePy::representation() const { return ""; } @@ -75,7 +75,7 @@ int OffsetSurfacePy::PyInit(PyObject* args, PyObject* /*kwd*/) } } -Py::Float OffsetSurfacePy::getOffsetValue(void) const +Py::Float OffsetSurfacePy::getOffsetValue() const { Handle(Geom_OffsetSurface) surf = Handle(Geom_OffsetSurface)::DownCast(getGeometryPtr()->handle()); return Py::Float(surf->Offset()); @@ -87,7 +87,7 @@ void OffsetSurfacePy::setOffsetValue(Py::Float arg) surf->SetOffsetValue((double)arg); } -Py::Object OffsetSurfacePy::getBasisSurface(void) const +Py::Object OffsetSurfacePy::getBasisSurface() const { Handle(Geom_OffsetSurface) surf = Handle(Geom_OffsetSurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/OpenCascadeAll.h b/src/Mod/Part/App/OpenCascadeAll.h index b4b8afc233..ec0ee1a14a 100644 --- a/src/Mod/Part/App/OpenCascadeAll.h +++ b/src/Mod/Part/App/OpenCascadeAll.h @@ -380,6 +380,7 @@ #include #include #include +#include #include #include #include diff --git a/src/Mod/Part/App/ParabolaPyImp.cpp b/src/Mod/Part/App/ParabolaPyImp.cpp index 83947e9ed0..d7c676802c 100644 --- a/src/Mod/Part/App/ParabolaPyImp.cpp +++ b/src/Mod/Part/App/ParabolaPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string ParabolaPy::representation(void) const +std::string ParabolaPy::representation() const { return ""; } @@ -157,7 +157,7 @@ PyObject* ParabolaPy::compute(PyObject *args) Py_Return; } -Py::Float ParabolaPy::getFocal(void) const +Py::Float ParabolaPy::getFocal() const { Handle(Geom_Parabola) curve = Handle(Geom_Parabola)::DownCast(getGeometryPtr()->handle()); return Py::Float(curve->Focal()); @@ -169,7 +169,7 @@ void ParabolaPy::setFocal(Py::Float arg) curve->SetFocal((double)arg); } -Py::Object ParabolaPy::getFocus(void) const +Py::Object ParabolaPy::getFocus() const { Handle(Geom_Parabola) c = Handle(Geom_Parabola)::DownCast (getGeometryPtr()->handle()); @@ -177,7 +177,7 @@ Py::Object ParabolaPy::getFocus(void) const return Py::Vector(Base::Vector3d(loc.X(), loc.Y(), loc.Z())); } -Py::Float ParabolaPy::getParameter(void) const +Py::Float ParabolaPy::getParameter() const { Handle(Geom_Parabola) curve = Handle(Geom_Parabola)::DownCast(getGeometryPtr()->handle()); return Py::Float(curve->Parameter()); diff --git a/src/Mod/Part/App/Part2DObject.cpp b/src/Mod/Part/App/Part2DObject.cpp index 32f83bfac8..43faeffb3f 100644 --- a/src/Mod/Part/App/Part2DObject.cpp +++ b/src/Mod/Part/App/Part2DObject.cpp @@ -75,7 +75,7 @@ App::DocumentObjectExecReturn *Part2DObject::execute(void) void Part2DObject::transformPlacement(const Base::Placement &transform) { - if (Support.getValues().size() > 0) { + if (!Support.getValues().empty()) { //part->transformPlacement(transform); positionBySupport(); } else { diff --git a/src/Mod/Part/App/Part2DObject.h b/src/Mod/Part/App/Part2DObject.h index 4291c38019..add761e15e 100644 --- a/src/Mod/Part/App/Part2DObject.h +++ b/src/Mod/Part/App/Part2DObject.h @@ -55,10 +55,10 @@ class PartExport Part2DObject : public Part::Feature, public Part::AttachExtensi public: Part2DObject(); - virtual void transformPlacement(const Base::Placement &transform) override; + void transformPlacement(const Base::Placement &transform) override; /// returns the number of construction lines (to be used as axes) - virtual int getAxisCount(void) const; + virtual int getAxisCount() const; /// retrieves an axis iterating through the construction lines of the sketch (indices start at 0) virtual Base::Axis getAxis(int axId) const; /// verify and accept the assigned geometry @@ -85,10 +85,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartGui::ViewProvider2DObject"; } //@} diff --git a/src/Mod/Part/App/Part2DObjectPyImp.cpp b/src/Mod/Part/App/Part2DObjectPyImp.cpp index fb0dd3b01b..cce74f31d6 100644 --- a/src/Mod/Part/App/Part2DObjectPyImp.cpp +++ b/src/Mod/Part/App/Part2DObjectPyImp.cpp @@ -33,7 +33,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string Part2DObjectPy::representation(void) const +std::string Part2DObjectPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/PartFeature.cpp b/src/Mod/Part/App/PartFeature.cpp index b91065fc0e..30a2717984 100644 --- a/src/Mod/Part/App/PartFeature.cpp +++ b/src/Mod/Part/App/PartFeature.cpp @@ -74,7 +74,7 @@ FC_LOG_LEVEL_INIT("Part",true,true) PROPERTY_SOURCE(Part::Feature, App::GeoFeature) -Feature::Feature(void) +Feature::Feature() { ADD_PROPERTY(Shape, (TopoDS_Shape())); } @@ -83,12 +83,12 @@ Feature::~Feature() { } -short Feature::mustExecute(void) const +short Feature::mustExecute() const { return GeoFeature::mustExecute(); } -App::DocumentObjectExecReturn *Feature::recompute(void) +App::DocumentObjectExecReturn *Feature::recompute() { try { return App::GeoFeature::recompute(); @@ -101,13 +101,13 @@ App::DocumentObjectExecReturn *Feature::recompute(void) } } -App::DocumentObjectExecReturn *Feature::execute(void) +App::DocumentObjectExecReturn *Feature::execute() { this->Shape.touch(); return GeoFeature::execute(); } -PyObject *Feature::getPyObject(void) +PyObject *Feature::getPyObject() { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 @@ -231,7 +231,7 @@ struct ShapeCache { return; if(strcmp(propName,"Shape")==0 || strcmp(propName,"Group")==0 - || strstr(propName,"Touched")!=nullptr) + || strstr(propName,"Touched")) slotClear(obj); } @@ -423,7 +423,7 @@ static TopoShape _getTopoShape(const App::DocumentObject *obj, const char *subna subObj = owner->resolve(sub.c_str(), &parent, &childName,nullptr,nullptr,&mat,false); if(!parent || !subObj) continue; - if(linkStack.size() + if(!linkStack.empty() && parent->getExtensionByType(true,false)) { visible = linkStack.back()->isElementVisible(childName.c_str()); @@ -450,7 +450,7 @@ static TopoShape _getTopoShape(const App::DocumentObject *obj, const char *subna shapes.push_back(shape); } - if(linkStack.size() && linkStack.back()==owner) + if(!linkStack.empty() && linkStack.back()==owner) linkStack.pop_back(); if(shapes.empty()) @@ -645,7 +645,7 @@ ShapeHistory Feature::joinHistory(const ShapeHistory& oldH, const ShapeHistory& } /// returns the type name of the ViewProvider -const char* Feature::getViewProviderName(void) const { +const char* Feature::getViewProviderName() const { return "PartGui::ViewProviderPart"; } @@ -681,10 +681,10 @@ PROPERTY_SOURCE(Part::FeatureExt, Part::Feature) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Part::FeaturePython, Part::Feature) -template<> const char* Part::FeaturePython::getViewProviderName(void) const { +template<> const char* Part::FeaturePython::getViewProviderName() const { return "PartGui::ViewProviderPython"; } -template<> PyObject* Part::FeaturePython::getPyObject(void) { +template<> PyObject* Part::FeaturePython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new FeaturePythonPyT(this),true); diff --git a/src/Mod/Part/App/PartFeature.h b/src/Mod/Part/App/PartFeature.h index 9bcfd0d9e3..13c5591b21 100644 --- a/src/Mod/Part/App/PartFeature.h +++ b/src/Mod/Part/App/PartFeature.h @@ -48,25 +48,25 @@ class PartExport Feature : public App::GeoFeature public: /// Constructor - Feature(void); - virtual ~Feature(); + Feature(); + ~Feature() override; PropertyPartShape Shape; /** @name methods override feature */ //@{ - virtual short mustExecute() const override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const override; - virtual const App::PropertyComplexGeoData* getPropertyOfGeometry() const override; + const char* getViewProviderName() const override; + const App::PropertyComplexGeoData* getPropertyOfGeometry() const override; - virtual PyObject* getPyObject() override; + PyObject* getPyObject() override; TopLoc_Location getLocation() const; - virtual DocumentObject *getSubObject(const char *subname, PyObject **pyObj, + DocumentObject *getSubObject(const char *subname, PyObject **pyObj, Base::Matrix4D *mat, bool transform, int depth) const override; /** Convenience function to extract shape from fully qualified subname @@ -109,10 +109,10 @@ public: protected: /// recompute only this object - virtual App::DocumentObjectExecReturn *recompute() override; + App::DocumentObjectExecReturn *recompute() override; /// recalculate the feature - virtual App::DocumentObjectExecReturn *execute() override; - virtual void onChanged(const App::Property* prop) override; + App::DocumentObjectExecReturn *execute() override; + void onChanged(const App::Property* prop) override; /** * Build a history of changes * MakeShape: The operation that created the changes, e.g. BRepAlgoAPI_Common @@ -127,7 +127,7 @@ protected: class FilletBase : public Part::Feature { - PROPERTY_HEADER(Part::FilletBase); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FilletBase); public: FilletBase(); @@ -135,7 +135,7 @@ public: App::PropertyLink Base; PropertyFilletEdges Edges; - short mustExecute() const; + short mustExecute() const override; }; typedef App::FeaturePythonT FeaturePython; @@ -145,10 +145,10 @@ typedef App::FeaturePythonT FeaturePython; */ class PartExport FeatureExt : public Feature { - PROPERTY_HEADER(Part::FeatureExt); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FeatureExt); public: - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderPartExt"; } }; diff --git a/src/Mod/Part/App/PartFeaturePyImp.cpp b/src/Mod/Part/App/PartFeaturePyImp.cpp index b4e1d618d8..7f184ea346 100644 --- a/src/Mod/Part/App/PartFeaturePyImp.cpp +++ b/src/Mod/Part/App/PartFeaturePyImp.cpp @@ -32,7 +32,7 @@ using namespace Part; // returns a string which represent the object e.g. when printed in python -std::string PartFeaturePy::representation(void) const +std::string PartFeaturePy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/PartFeatureReference.cpp b/src/Mod/Part/App/PartFeatureReference.cpp index 0a2bfd4cdf..74d1aa0b5e 100644 --- a/src/Mod/Part/App/PartFeatureReference.cpp +++ b/src/Mod/Part/App/PartFeatureReference.cpp @@ -37,7 +37,7 @@ using namespace Part; PROPERTY_SOURCE(Part::FeatureReference, App::GeoFeature) -FeatureReference::FeatureReference(void) +FeatureReference::FeatureReference() { ADD_PROPERTY(Reference, (nullptr)); } @@ -46,12 +46,12 @@ FeatureReference::~FeatureReference() { } -short FeatureReference::mustExecute(void) const +short FeatureReference::mustExecute() const { return GeoFeature::mustExecute(); } -App::DocumentObjectExecReturn *FeatureReference::execute(void) +App::DocumentObjectExecReturn *FeatureReference::execute() { return App::DocumentObject::StdReturn; } diff --git a/src/Mod/Part/App/PartFeatureReference.h b/src/Mod/Part/App/PartFeatureReference.h index f6b6074f31..4ed2035e12 100644 --- a/src/Mod/Part/App/PartFeatureReference.h +++ b/src/Mod/Part/App/PartFeatureReference.h @@ -37,24 +37,24 @@ class PartFeaturePy; */ class PartExport FeatureReference : public App::GeoFeature { - PROPERTY_HEADER(Part::FeatureReference); + PROPERTY_HEADER_WITH_OVERRIDE(Part::FeatureReference); public: /// Constructor - FeatureReference(void); - virtual ~FeatureReference(); + FeatureReference(); + ~FeatureReference() override; App::PropertyLink Reference; /** @name methods override feature */ //@{ /// recalculate the feature - virtual App::DocumentObjectExecReturn *execute(void); - virtual short mustExecute(void) const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderPartReference"; } protected: diff --git a/src/Mod/Part/App/PartFeatures.cpp b/src/Mod/Part/App/PartFeatures.cpp index 9d39428935..51fe06145c 100644 --- a/src/Mod/Part/App/PartFeatures.cpp +++ b/src/Mod/Part/App/PartFeatures.cpp @@ -111,7 +111,7 @@ App::DocumentObjectExecReturn* RuledSurface::getShape(const App::PropertyLinkSub return nullptr; } -App::DocumentObjectExecReturn *RuledSurface::execute(void) +App::DocumentObjectExecReturn *RuledSurface::execute() { try { App::DocumentObjectExecReturn* ret; @@ -278,7 +278,7 @@ void Loft::onChanged(const App::Property* prop) Part::Feature::onChanged(prop); } -App::DocumentObjectExecReturn *Loft::execute(void) +App::DocumentObjectExecReturn *Loft::execute() { if (Sections.getSize() == 0) return new App::DocumentObjectExecReturn("No sections linked."); @@ -394,7 +394,7 @@ void Sweep::onChanged(const App::Property* prop) Part::Feature::onChanged(prop); } -App::DocumentObjectExecReturn *Sweep::execute(void) +App::DocumentObjectExecReturn *Sweep::execute() { if (Sections.getSize() == 0) return new App::DocumentObjectExecReturn("No sections linked."); @@ -615,7 +615,7 @@ void Thickness::handleChangedPropertyType(Base::XMLReader &reader, const char *T } } -App::DocumentObjectExecReturn *Thickness::execute(void) +App::DocumentObjectExecReturn *Thickness::execute() { App::DocumentObject* source = Faces.getValue(); if (!source) @@ -663,7 +663,7 @@ Refine::Refine() ADD_PROPERTY_TYPE(Source,(nullptr),"Refine",App::Prop_None,"Source shape"); } -App::DocumentObjectExecReturn *Refine::execute(void) +App::DocumentObjectExecReturn *Refine::execute() { Part::Feature* source = Source.getValue(); if (!source) @@ -688,7 +688,7 @@ Reverse::Reverse() ADD_PROPERTY_TYPE(Source, (nullptr), "Reverse", App::Prop_None, "Source shape"); } -App::DocumentObjectExecReturn* Reverse::execute(void) +App::DocumentObjectExecReturn* Reverse::execute() { App::DocumentObject* source = Source.getValue(); Part::TopoShape topoShape = Part::Feature::getShape(source); diff --git a/src/Mod/Part/App/PartFeatures.h b/src/Mod/Part/App/PartFeatures.h index 1b25bee920..88e2b57660 100644 --- a/src/Mod/Part/App/PartFeatures.h +++ b/src/Mod/Part/App/PartFeatures.h @@ -34,7 +34,7 @@ namespace Part class RuledSurface : public Part::Feature { - PROPERTY_HEADER(Part::RuledSurface); + PROPERTY_HEADER_WITH_OVERRIDE(Part::RuledSurface); public: RuledSurface(); @@ -46,15 +46,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderRuledSurface"; } //@} protected: - void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; private: App::DocumentObjectExecReturn* getShape(const App::PropertyLinkSub& link, TopoDS_Shape&) const; @@ -65,7 +65,7 @@ private: class Loft : public Part::Feature { - PROPERTY_HEADER(Part::Loft); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Loft); public: Loft(); @@ -79,15 +79,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderLoft"; } //@} protected: - void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; private: static App::PropertyIntegerConstraint::Constraints Degrees; @@ -95,7 +95,7 @@ private: class Sweep : public Part::Feature { - PROPERTY_HEADER(Part::Sweep); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Sweep); public: Sweep(); @@ -109,15 +109,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderSweep"; } //@} protected: - void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; private: static const char* TransitionEnums[]; @@ -125,7 +125,7 @@ private: class Thickness : public Part::Feature { - PROPERTY_HEADER(Part::Thickness); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Thickness); public: Thickness(); @@ -140,15 +140,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderThickness"; } //@} protected: - void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop); + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop) override; private: static const char* ModeEnums[]; @@ -157,7 +157,7 @@ private: class Refine : public Part::Feature { - PROPERTY_HEADER(Part::Refine); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Refine); public: Refine(); @@ -167,8 +167,8 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute() override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderRefine"; } //@} @@ -176,7 +176,7 @@ public: class Reverse : public Part::Feature { - PROPERTY_HEADER(Part::Reverse); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Reverse); public: Reverse(); @@ -186,8 +186,8 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn* execute(void); - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn* execute() override; + const char* getViewProviderName() const override { return "PartGui::ViewProviderReverse"; } //@} diff --git a/src/Mod/Part/App/PlanePyImp.cpp b/src/Mod/Part/App/PlanePyImp.cpp index 0ec88baec3..37a26e00a4 100644 --- a/src/Mod/Part/App/PlanePyImp.cpp +++ b/src/Mod/Part/App/PlanePyImp.cpp @@ -44,7 +44,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string PlanePy::representation(void) const +std::string PlanePy::representation() const { return ""; } @@ -167,7 +167,7 @@ int PlanePy::PyInit(PyObject* args, PyObject* kwds) return -1; } -Py::Object PlanePy::getPosition(void) const +Py::Object PlanePy::getPosition() const { Handle(Geom_Plane) this_surf = Handle(Geom_Plane)::DownCast (this->getGeomPlanePtr()->handle()); @@ -207,7 +207,7 @@ void PlanePy::setPosition(Py::Object arg) } } -Py::Object PlanePy::getAxis(void) const +Py::Object PlanePy::getAxis() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/PlateSurfacePyImp.cpp b/src/Mod/Part/App/PlateSurfacePyImp.cpp index 1233510ead..d02f5a811a 100644 --- a/src/Mod/Part/App/PlateSurfacePyImp.cpp +++ b/src/Mod/Part/App/PlateSurfacePyImp.cpp @@ -41,7 +41,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string PlateSurfacePy::representation(void) const +std::string PlateSurfacePy::representation() const { return ""; } diff --git a/src/Mod/Part/App/PointPyImp.cpp b/src/Mod/Part/App/PointPyImp.cpp index 18faf0f5fe..d90946744d 100644 --- a/src/Mod/Part/App/PointPyImp.cpp +++ b/src/Mod/Part/App/PointPyImp.cpp @@ -41,7 +41,7 @@ using namespace Part; extern const char* gce_ErrorStatusText(gce_ErrorType et); // returns a string which represents the object e.g. when printed in python -std::string PointPy::representation(void) const +std::string PointPy::representation() const { std::stringstream str; Base::Vector3d coords = getGeomPointPtr()->getPoint(); @@ -122,7 +122,7 @@ PyObject* PointPy::toShape(PyObject *args) return nullptr; } -Py::Float PointPy::getX(void) const +Py::Float PointPy::getX() const { Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast (this->getGeomPointPtr()->handle()); @@ -142,7 +142,7 @@ void PointPy::setX(Py::Float X) } } -Py::Float PointPy::getY(void) const +Py::Float PointPy::getY() const { Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast (this->getGeomPointPtr()->handle()); @@ -162,7 +162,7 @@ void PointPy::setY(Py::Float Y) } } -Py::Float PointPy::getZ(void) const +Py::Float PointPy::getZ() const { Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast (this->getGeomPointPtr()->handle()); diff --git a/src/Mod/Part/App/PrimitiveFeature.cpp b/src/Mod/Part/App/PrimitiveFeature.cpp index 0ca8b6285a..34b5bc7e2d 100644 --- a/src/Mod/Part/App/PrimitiveFeature.cpp +++ b/src/Mod/Part/App/PrimitiveFeature.cpp @@ -69,7 +69,7 @@ using namespace Part; PROPERTY_SOURCE_ABSTRACT_WITH_EXTENSIONS(Part::Primitive, Part::Feature) -Primitive::Primitive(void) +Primitive::Primitive() { AttachExtension::initExtension(this); touch(); @@ -79,12 +79,12 @@ Primitive::~Primitive() { } -short Primitive::mustExecute(void) const +short Primitive::mustExecute() const { return Feature::mustExecute(); } -App::DocumentObjectExecReturn* Primitive::execute(void) { +App::DocumentObjectExecReturn* Primitive::execute() { return Part::Feature::execute(); } @@ -97,7 +97,7 @@ App::DocumentObjectExecReturn* Primitive::execute(void) { namespace Part { PYTHON_TYPE_DEF(PrimitivePy, PartFeaturePy) PYTHON_TYPE_IMP(PrimitivePy, PartFeaturePy) -} +}//explicit bombs #if defined(__clang__) # pragma clang diagnostic pop @@ -183,7 +183,7 @@ short Vertex::mustExecute() const return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Vertex::execute(void) +App::DocumentObjectExecReturn *Vertex::execute() { gp_Pnt point; point.SetX(this->X.getValue()); @@ -241,7 +241,7 @@ short Line::mustExecute() const return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Line::execute(void) +App::DocumentObjectExecReturn *Line::execute() { gp_Pnt point1; point1.SetX(this->X1.getValue()); @@ -293,7 +293,7 @@ short Plane::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Plane::execute(void) +App::DocumentObjectExecReturn *Plane::execute() { double L = this->Length.getValue(); double W = this->Width.getValue(); @@ -341,7 +341,7 @@ App::DocumentObjectExecReturn *Plane::execute(void) PROPERTY_SOURCE(Part::Sphere, Part::Primitive) -Sphere::Sphere(void) +Sphere::Sphere() { ADD_PROPERTY_TYPE(Radius,(5.0),"Sphere",App::Prop_None,"The radius of the sphere"); Radius.setConstraints(&quantityRange); @@ -366,7 +366,7 @@ short Sphere::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Sphere::execute(void) +App::DocumentObjectExecReturn *Sphere::execute() { // Build a sphere if (Radius.getValue() < Precision::Confusion()) @@ -389,7 +389,7 @@ App::DocumentObjectExecReturn *Sphere::execute(void) PROPERTY_SOURCE(Part::Ellipsoid, Part::Primitive) -Ellipsoid::Ellipsoid(void) +Ellipsoid::Ellipsoid() { ADD_PROPERTY_TYPE(Radius1,(2.0),"Ellipsoid",App::Prop_None,"The radius of the ellipsoid"); Radius1.setConstraints(&quantityRange); @@ -422,7 +422,7 @@ short Ellipsoid::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Ellipsoid::execute(void) +App::DocumentObjectExecReturn *Ellipsoid::execute() { // Build a sphere if (Radius1.getValue() < Precision::Confusion()) @@ -471,7 +471,7 @@ App::DocumentObjectExecReturn *Ellipsoid::execute(void) PROPERTY_SOURCE(Part::Cylinder, Part::Primitive) -Cylinder::Cylinder(void) +Cylinder::Cylinder() { ADD_PROPERTY_TYPE(Radius,(2.0),"Cylinder",App::Prop_None,"The radius of the cylinder"); ADD_PROPERTY_TYPE(Height,(10.0f),"Cylinder",App::Prop_None,"The height of the cylinder"); @@ -492,7 +492,7 @@ short Cylinder::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Cylinder::execute(void) +App::DocumentObjectExecReturn *Cylinder::execute() { // Build a cylinder if (Radius.getValue() < Precision::Confusion()) @@ -522,7 +522,7 @@ App::PropertyIntegerConstraint::Constraints Prism::polygonRange = {3,INT_MAX,1}; PROPERTY_SOURCE(Part::Prism, Part::Primitive) -Prism::Prism(void) +Prism::Prism() { ADD_PROPERTY_TYPE(Polygon, (6.0), "Prism", App::Prop_None, "Number of sides in the polygon, of the prism"); ADD_PROPERTY_TYPE(Circumradius, (2.0), "Prism", App::Prop_None, "Circumradius (centre to vertex) of the polygon, of the prism"); @@ -543,7 +543,7 @@ short Prism::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Prism::execute(void) +App::DocumentObjectExecReturn *Prism::execute() { // Build a prism if (Polygon.getValue() < 3) @@ -581,7 +581,7 @@ App::PropertyIntegerConstraint::Constraints RegularPolygon::polygon = {3,INT_MAX PROPERTY_SOURCE(Part::RegularPolygon, Part::Primitive) -RegularPolygon::RegularPolygon(void) +RegularPolygon::RegularPolygon() { ADD_PROPERTY_TYPE(Polygon,(6.0),"RegularPolygon",App::Prop_None,"Number of sides in the regular polygon"); ADD_PROPERTY_TYPE(Circumradius,(2.0),"RegularPolygon",App::Prop_None,"Circumradius (centre to vertex) of the polygon"); @@ -597,7 +597,7 @@ short RegularPolygon::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *RegularPolygon::execute(void) +App::DocumentObjectExecReturn *RegularPolygon::execute() { // Build a regular polygon if (Polygon.getValue() < 3) @@ -632,7 +632,7 @@ App::DocumentObjectExecReturn *RegularPolygon::execute(void) PROPERTY_SOURCE(Part::Cone, Part::Primitive) -Cone::Cone(void) +Cone::Cone() { ADD_PROPERTY_TYPE(Radius1,(2.0),"Cone",App::Prop_None,"The radius of the cone"); ADD_PROPERTY_TYPE(Radius2,(4.0),"Cone",App::Prop_None,"The radius of the cone"); @@ -654,7 +654,7 @@ short Cone::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Cone::execute(void) +App::DocumentObjectExecReturn *Cone::execute() { if (Radius1.getValue() < 0) return new App::DocumentObjectExecReturn("Radius of cone too small"); @@ -681,7 +681,7 @@ App::DocumentObjectExecReturn *Cone::execute(void) PROPERTY_SOURCE(Part::Torus, Part::Primitive) -Torus::Torus(void) +Torus::Torus() { ADD_PROPERTY_TYPE(Radius1,(10.0),"Torus",App::Prop_None,"The radius of the torus"); Radius1.setConstraints(&quantityRange); @@ -710,7 +710,7 @@ short Torus::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Torus::execute(void) +App::DocumentObjectExecReturn *Torus::execute() { if (Radius1.getValue() < Precision::Confusion()) return new App::DocumentObjectExecReturn("Radius of torus too small"); @@ -736,7 +736,7 @@ PROPERTY_SOURCE(Part::Helix, Part::Primitive) const char* Part::Helix::LocalCSEnums[]= {"Right-handed","Left-handed",nullptr}; const char* Part::Helix::StyleEnums []= {"Old style","New style",nullptr}; -Helix::Helix(void) +Helix::Helix() { ADD_PROPERTY_TYPE(Pitch, (1.0),"Helix",App::Prop_None,"The pitch of the helix"); Pitch.setConstraints(&quantityRange); @@ -788,7 +788,7 @@ short Helix::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Helix::execute(void) +App::DocumentObjectExecReturn *Helix::execute() { try { Standard_Real myPitch = Pitch.getValue(); @@ -816,7 +816,7 @@ App::DocumentObjectExecReturn *Helix::execute(void) PROPERTY_SOURCE(Part::Spiral, Part::Primitive) -Spiral::Spiral(void) +Spiral::Spiral() { ADD_PROPERTY_TYPE(Growth, (1.0),"Spiral",App::Prop_None,"The growth of the spiral per rotation"); Growth.setConstraints(&quantityRange); @@ -855,7 +855,7 @@ short Spiral::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Spiral::execute(void) +App::DocumentObjectExecReturn *Spiral::execute() { try { Standard_Real myNumRot = Rotations.getValue(); @@ -907,7 +907,7 @@ short Wedge::mustExecute() const return Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Wedge::execute(void) +App::DocumentObjectExecReturn *Wedge::execute() { double xmin = Xmin.getValue(); double ymin = Ymin.getValue(); @@ -1002,7 +1002,7 @@ short Ellipse::mustExecute() const return Part::Primitive::mustExecute(); } -App::DocumentObjectExecReturn *Ellipse::execute(void) +App::DocumentObjectExecReturn *Ellipse::execute() { if (this->MinorRadius.getValue() > this->MajorRadius.getValue()) return new App::DocumentObjectExecReturn("Minor radius greater than major radius"); diff --git a/src/Mod/Part/App/PrimitiveFeature.h b/src/Mod/Part/App/PrimitiveFeature.h index 9c5d0801fa..33c6b5a3a6 100644 --- a/src/Mod/Part/App/PrimitiveFeature.h +++ b/src/Mod/Part/App/PrimitiveFeature.h @@ -36,12 +36,12 @@ class PartExport Primitive : public Part::Feature, public Part::AttachExtension public: Primitive(); - virtual ~Primitive(); + ~Primitive() override; /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; PyObject* getPyObject() override; //@} @@ -49,17 +49,17 @@ public: protected: void Restore(Base::XMLReader &reader) override; void onChanged (const App::Property* prop) override; - virtual void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; }; class PartExport Vertex : public Part::Primitive { - PROPERTY_HEADER(Part::Vertex); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Vertex); public: Vertex(); - virtual ~Vertex(); + ~Vertex() override; App::PropertyDistance X; App::PropertyDistance Y; @@ -68,11 +68,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - void onChanged(const App::Property*); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderPointParametric"; } //@} @@ -80,11 +80,11 @@ public: class PartExport Line : public Part::Primitive { - PROPERTY_HEADER(Part::Line); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Line); public: Line(); - virtual ~Line(); + ~Line() override; App::PropertyDistance X1; App::PropertyDistance Y1; @@ -96,11 +96,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - void onChanged(const App::Property*); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderLineParametric"; } //@} @@ -108,7 +108,7 @@ public: class PartExport Plane : public Primitive { - PROPERTY_HEADER(Part::Plane); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Plane); public: Plane(); @@ -119,10 +119,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderPlaneParametric"; } //@} @@ -130,7 +130,7 @@ public: class PartExport Sphere : public Primitive { - PROPERTY_HEADER(Part::Sphere); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Sphere); public: Sphere(); @@ -143,10 +143,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderSphereParametric"; } //@} @@ -154,7 +154,7 @@ public: class PartExport Ellipsoid : public Primitive { - PROPERTY_HEADER(Part::Ellipsoid); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Ellipsoid); public: Ellipsoid(); @@ -169,10 +169,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderEllipsoid"; } }; @@ -180,7 +180,7 @@ public: class PartExport Cylinder : public Primitive, public PrismExtension { - PROPERTY_HEADER(Part::Cylinder); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Cylinder); public: Cylinder(); @@ -192,10 +192,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderCylinderParametric"; } //@} @@ -204,7 +204,7 @@ public: class PartExport Prism : public Primitive, public PrismExtension { - PROPERTY_HEADER(Part::Prism); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Prism); public: Prism(); @@ -216,10 +216,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderPrism"; } //@} @@ -229,7 +229,7 @@ private: class PartExport RegularPolygon : public Primitive { - PROPERTY_HEADER(Part::RegularPolygon); + PROPERTY_HEADER_WITH_OVERRIDE(Part::RegularPolygon); public: RegularPolygon(); @@ -240,10 +240,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderRegularPolygon"; } //@} @@ -253,7 +253,7 @@ private: class PartExport Cone : public Primitive { - PROPERTY_HEADER(Part::Cone); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Cone); public: Cone(); @@ -266,10 +266,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderConeParametric"; } //@} @@ -277,7 +277,7 @@ public: class PartExport Torus : public Primitive { - PROPERTY_HEADER(Part::Torus); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Torus); public: Torus(); @@ -291,10 +291,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderTorusParametric"; } //@} @@ -302,7 +302,7 @@ public: class PartExport Helix : public Primitive { - PROPERTY_HEADER(Part::Helix); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Helix); public: Helix(); @@ -318,16 +318,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderHelixParametric"; } //@} protected: - void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; private: static const char* LocalCSEnums[]; @@ -336,7 +336,7 @@ private: class PartExport Spiral : public Primitive { - PROPERTY_HEADER(Part::Spiral); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Spiral); public: Spiral(); @@ -349,21 +349,21 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderSpiralParametric"; } //@} protected: - void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; }; class PartExport Wedge : public Primitive { - PROPERTY_HEADER(Part::Wedge); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Wedge); public: Wedge(); @@ -382,25 +382,25 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderWedge"; } //@} protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; class PartExport Ellipse : public Part::Primitive { - PROPERTY_HEADER(Part::Ellipse); + PROPERTY_HEADER_WITH_OVERRIDE(Part::Ellipse); public: Ellipse(); - virtual ~Ellipse(); + ~Ellipse() override; App::PropertyLength MajorRadius; App::PropertyLength MinorRadius; @@ -410,18 +410,18 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - void onChanged(const App::Property*); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void onChanged(const App::Property*) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartGui::ViewProviderEllipseParametric"; } //@} protected: - void Restore(Base::XMLReader &reader); - void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName); + void Restore(Base::XMLReader &reader) override; + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; private: static App::PropertyQuantityConstraint::Constraints angleRange; diff --git a/src/Mod/Part/App/PrismExtension.h b/src/Mod/Part/App/PrismExtension.h index dff9b5dcfe..919cf1de99 100644 --- a/src/Mod/Part/App/PrismExtension.h +++ b/src/Mod/Part/App/PrismExtension.h @@ -35,10 +35,10 @@ namespace Part class PartExport PrismExtension : public App::DocumentObjectExtension { - EXTENSION_PROPERTY_HEADER(Part::PrismExtension); + EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(Part::PrismExtension); public: PrismExtension(); - virtual ~PrismExtension(); + ~PrismExtension() override; App::PropertyAngle FirstAngle; @@ -46,11 +46,11 @@ public: TopoDS_Shape makePrism(double height, const TopoDS_Face& face) const; - virtual short int extensionMustExecute(void); - virtual App::DocumentObjectExecReturn *extensionExecute(void); + short int extensionMustExecute() override; + App::DocumentObjectExecReturn *extensionExecute() override; protected: - virtual void extensionOnChanged(const App::Property* /*prop*/); + void extensionOnChanged(const App::Property* /*prop*/) override; }; } // namespace Part diff --git a/src/Mod/Part/App/PropertyGeometryList.cpp b/src/Mod/Part/App/PropertyGeometryList.cpp index cfdd64fdc6..26ea2096be 100644 --- a/src/Mod/Part/App/PropertyGeometryList.cpp +++ b/src/Mod/Part/App/PropertyGeometryList.cpp @@ -65,7 +65,7 @@ void PropertyGeometryList::setSize(int newSize) _lValueList.resize(newSize); } -int PropertyGeometryList::getSize(void) const +int PropertyGeometryList::getSize() const { return static_cast(_lValueList.size()); } @@ -118,7 +118,7 @@ void PropertyGeometryList::set1Value(int idx, std::unique_ptr &&lValue hasSetValue(); } -PyObject *PropertyGeometryList::getPyObject(void) +PyObject *PropertyGeometryList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) @@ -219,7 +219,7 @@ void PropertyGeometryList::Restore(Base::XMLReader &reader) setValues(std::move(values)); } -App::Property *PropertyGeometryList::Copy(void) const +App::Property *PropertyGeometryList::Copy() const { PropertyGeometryList *p = new PropertyGeometryList(); p->setValues(_lValueList); @@ -232,7 +232,7 @@ void PropertyGeometryList::Paste(const Property &from) setValues(FromList._lValueList); } -unsigned int PropertyGeometryList::getMemSize(void) const +unsigned int PropertyGeometryList::getMemSize() const { int size = sizeof(PropertyGeometryList); for (int i = 0; i < getSize(); i++) diff --git a/src/Mod/Part/App/PropertyGeometryList.h b/src/Mod/Part/App/PropertyGeometryList.h index 3a31b07f9b..05fae85a4b 100644 --- a/src/Mod/Part/App/PropertyGeometryList.h +++ b/src/Mod/Part/App/PropertyGeometryList.h @@ -40,7 +40,7 @@ class Geometry; class PartExport PropertyGeometryList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: /** @@ -53,10 +53,10 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyGeometryList(); + ~PropertyGeometryList() override; - virtual void setSize(int newSize); - virtual int getSize(void) const; + void setSize(int newSize) override; + int getSize() const override; /** Sets the property */ @@ -69,22 +69,22 @@ public: return _lValueList[idx]; } - const std::vector &getValues(void) const { + const std::vector &getValues() const { return _lValueList; } void set1Value(int idx, std::unique_ptr &&); - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save(Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save(Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual App::Property *Copy(void) const; - virtual void Paste(const App::Property &from); + App::Property *Copy() const override; + void Paste(const App::Property &from) override; - virtual unsigned int getMemSize(void) const; + unsigned int getMemSize() const override; private: std::vector _lValueList; diff --git a/src/Mod/Part/App/PropertyTopoShape.h b/src/Mod/Part/App/PropertyTopoShape.h index 0a0fe92fd6..14fe472f06 100644 --- a/src/Mod/Part/App/PropertyTopoShape.h +++ b/src/Mod/Part/App/PropertyTopoShape.h @@ -40,11 +40,11 @@ namespace Part */ class PartExport PropertyPartShape : public App::PropertyComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyPartShape(); - ~PropertyPartShape(); + ~PropertyPartShape() override; /** @name Getter/setter */ //@{ @@ -53,48 +53,48 @@ public: /// set the part shape void setValue(const TopoDS_Shape&); /// get the part shape - const TopoDS_Shape& getValue(void) const; + const TopoDS_Shape& getValue() const; const TopoShape& getShape() const; - const Data::ComplexGeoData* getComplexData() const; + const Data::ComplexGeoData* getComplexData() const override; //@} /** @name Modification */ //@{ /// Set the placement of the geometry - void setTransform(const Base::Matrix4D& rclTrf); + void setTransform(const Base::Matrix4D& rclTrf) override; /// Get the placement of the geometry - Base::Matrix4D getTransform() const; + Base::Matrix4D getTransform() const override; /// Transform the real shape data - void transformGeometry(const Base::Matrix4D &rclMat); + void transformGeometry(const Base::Matrix4D &rclMat) override; //@} /** @name Getting basic geometric entities */ //@{ /** Returns the bounding box around the underlying mesh kernel */ - Base::BoundBox3d getBoundingBox() const; + Base::BoundBox3d getBoundingBox() const override; //@} /** @name Python interface */ //@{ - PyObject* getPyObject(void); - void setPyObject(PyObject *value); + PyObject* getPyObject() override; + void setPyObject(PyObject *value) override; //@} /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - App::Property *Copy(void) const; - void Paste(const App::Property &from); - unsigned int getMemSize (void) const; + App::Property *Copy() const override; + void Paste(const App::Property &from) override; + unsigned int getMemSize () const override; //@} /// Get valid paths for this property; used by auto completer - virtual void getPaths(std::vector & paths) const; + void getPaths(std::vector & paths) const override; private: void saveToFile(Base::Writer &writer) const; @@ -119,16 +119,16 @@ struct PartExport ShapeHistory { class PartExport PropertyShapeHistory : public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyShapeHistory(); - ~PropertyShapeHistory(); + ~PropertyShapeHistory() override; - virtual void setSize(int newSize) { + void setSize(int newSize) override { _lValueList.resize(newSize); } - virtual int getSize(void) const { + int getSize() const override { return _lValueList.size(); } @@ -138,23 +138,23 @@ public: void setValues (const std::vector& values); - const std::vector &getValues(void) const { + const std::vector &getValues() const { return _lValueList; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const { + unsigned int getMemSize () const override { return _lValueList.size() * sizeof(ShapeHistory); } @@ -172,16 +172,16 @@ struct PartExport FilletElement { class PartExport PropertyFilletEdges : public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyFilletEdges(); - ~PropertyFilletEdges(); + ~PropertyFilletEdges() override; - virtual void setSize(int newSize) { + void setSize(int newSize) override { _lValueList.resize(newSize); } - virtual int getSize(void) const { + int getSize() const override { return _lValueList.size(); } @@ -191,23 +191,23 @@ public: void setValues (const std::vector& values); - const std::vector &getValues(void) const { + const std::vector &getValues() const { return _lValueList; } - virtual PyObject *getPyObject(void); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy() const override; + void Paste(const Property &from) override; - virtual unsigned int getMemSize (void) const { + unsigned int getMemSize () const override { return _lValueList.size() * sizeof(FilletElement); } diff --git a/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp b/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp index 09a7658b88..ab808449f4 100644 --- a/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp +++ b/src/Mod/Part/App/RectangularTrimmedSurfacePyImp.cpp @@ -36,7 +36,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string RectangularTrimmedSurfacePy::representation(void) const +std::string RectangularTrimmedSurfacePy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPy.xml b/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPy.xml index 0443561a37..76159957e0 100644 --- a/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPy.xml +++ b/src/Mod/Part/App/ShapeFix/ShapeFix_ShellPy.xml @@ -62,7 +62,7 @@ Modes : isAccountMultiConex - mode for account cases of multiconnexity. If this mode is equal to Standard_True, separate shells will be created in the cases of multiconnexity. If this mode is equal to Standard_False, -one shell will be created without account of multiconnexity.By defautt - Standard_True; +one shell will be created without account of multiconnexity. By default - Standard_True; NonManifold - mode for creation of non-manifold shells. If this mode is equal to Standard_True one non-manifold will be created from shell contains multishared edges. Else if this mode is equal to Standard_False only diff --git a/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp b/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp index 7f6120cbcd..849568b52c 100644 --- a/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp +++ b/src/Mod/Part/App/ShapeUpgrade/UnifySameDomainPyImp.cpp @@ -106,7 +106,7 @@ PyObject* UnifySameDomainPy::initialize(PyObject *args, PyObject* kwds) } // returns a string which represents the object e.g. when printed in python -std::string UnifySameDomainPy::representation(void) const +std::string UnifySameDomainPy::representation() const { return std::string(""); } diff --git a/src/Mod/Part/App/SpherePyImp.cpp b/src/Mod/Part/App/SpherePyImp.cpp index 554677caf9..9f76fa4b3a 100644 --- a/src/Mod/Part/App/SpherePyImp.cpp +++ b/src/Mod/Part/App/SpherePyImp.cpp @@ -37,7 +37,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string SpherePy::representation(void) const +std::string SpherePy::representation() const { Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast (getGeomSpherePtr()->handle()); @@ -75,7 +75,7 @@ int SpherePy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Float SpherePy::getRadius(void) const +Py::Float SpherePy::getRadius() const { Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast (getGeomSpherePtr()->handle()); @@ -89,21 +89,21 @@ void SpherePy::setRadius(Py::Float arg) sphere->SetRadius((double)arg); } -Py::Float SpherePy::getArea(void) const +Py::Float SpherePy::getArea() const { Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast (getGeomSpherePtr()->handle()); return Py::Float(sphere->Area()); } -Py::Float SpherePy::getVolume(void) const +Py::Float SpherePy::getVolume() const { Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast (getGeomSpherePtr()->handle()); return Py::Float(sphere->Volume()); } -Py::Object SpherePy::getCenter(void) const +Py::Object SpherePy::getCenter() const { Handle(Geom_SphericalSurface) sphere = Handle(Geom_SphericalSurface)::DownCast (getGeomSpherePtr()->handle()); @@ -133,7 +133,7 @@ void SpherePy::setCenter(Py::Object arg) } } -Py::Object SpherePy::getAxis(void) const +Py::Object SpherePy::getAxis() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp b/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp index 670bf36ebf..be53783f48 100644 --- a/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp +++ b/src/Mod/Part/App/SurfaceOfExtrusionPyImp.cpp @@ -38,7 +38,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string SurfaceOfExtrusionPy::representation(void) const +std::string SurfaceOfExtrusionPy::representation() const { return std::string(""); } @@ -81,7 +81,7 @@ int SurfaceOfExtrusionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } -Py::Object SurfaceOfExtrusionPy::getDirection(void) const +Py::Object SurfaceOfExtrusionPy::getDirection() const { Handle(Geom_SurfaceOfLinearExtrusion) curve = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast (getGeometryPtr()->handle()); @@ -115,7 +115,7 @@ namespace Part { extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); } -Py::Object SurfaceOfExtrusionPy::getBasisCurve(void) const +Py::Object SurfaceOfExtrusionPy::getBasisCurve() const { Handle(Geom_SurfaceOfLinearExtrusion) surf = Handle(Geom_SurfaceOfLinearExtrusion)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp b/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp index f338abab48..df7164cb16 100644 --- a/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp +++ b/src/Mod/Part/App/SurfaceOfRevolutionPyImp.cpp @@ -36,7 +36,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string SurfaceOfRevolutionPy::representation(void) const +std::string SurfaceOfRevolutionPy::representation() const { return std::string(""); } @@ -83,7 +83,7 @@ int SurfaceOfRevolutionPy::PyInit(PyObject* args, PyObject* /*kwd*/) } } -Py::Object SurfaceOfRevolutionPy::getLocation(void) const +Py::Object SurfaceOfRevolutionPy::getLocation() const { Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast (getGeometryPtr()->handle()); @@ -113,7 +113,7 @@ void SurfaceOfRevolutionPy::setLocation(Py::Object arg) } } -Py::Object SurfaceOfRevolutionPy::getDirection(void) const +Py::Object SurfaceOfRevolutionPy::getDirection() const { Handle(Geom_SurfaceOfRevolution) curve = Handle(Geom_SurfaceOfRevolution)::DownCast (getGeometryPtr()->handle()); @@ -147,7 +147,7 @@ namespace Part { extern const Py::Object makeGeometryCurvePy(const Handle(Geom_Curve)& c); } -Py::Object SurfaceOfRevolutionPy::getBasisCurve(void) const +Py::Object SurfaceOfRevolutionPy::getBasisCurve() const { Handle(Geom_SurfaceOfRevolution) surf = Handle(Geom_SurfaceOfRevolution)::DownCast (getGeometryPtr()->handle()); diff --git a/src/Mod/Part/App/Tools.h b/src/Mod/Part/App/Tools.h index 7ca1eee67e..8510d19885 100644 --- a/src/Mod/Part/App/Tools.h +++ b/src/Mod/Part/App/Tools.h @@ -52,7 +52,7 @@ template <> struct vec_traits { typedef gp_Pnt vec_type; typedef double float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.X(), v.Y(), v.Z()); } @@ -64,7 +64,7 @@ template <> struct vec_traits { typedef gp_Vec vec_type; typedef double float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.X(), v.Y(), v.Z()); } @@ -76,7 +76,7 @@ template <> struct vec_traits { typedef gp_Dir vec_type; typedef double float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.X(), v.Y(), v.Z()); } @@ -88,7 +88,7 @@ template <> struct vec_traits { typedef gp_XYZ vec_type; typedef double float_type; - vec_traits(const vec_type& v) : v(v){} + explicit vec_traits(const vec_type& v) : v(v){} inline std::tuple get() const { return std::make_tuple(v.X(), v.Y(), v.Z()); } diff --git a/src/Mod/Part/App/TopoShape.cpp b/src/Mod/Part/App/TopoShape.cpp index 553032962c..c09c9903df 100644 --- a/src/Mod/Part/App/TopoShape.cpp +++ b/src/Mod/Part/App/TopoShape.cpp @@ -297,7 +297,7 @@ TopoShape::TopoShape(const TopoShape& shape) Tag = shape.Tag; } -std::vector TopoShape::getElementTypes(void) const +std::vector TopoShape::getElementTypes() const { static const std::vector temp = {"Face","Edge","Vertex"}; return temp; @@ -469,7 +469,7 @@ TopAbs_ShapeEnum TopoShape::shapeType(const char *type, bool silent) { if(type) { initShapeNameMap(); for(size_t idx=0;idx<_ShapeNames.size();++idx) { - if(_ShapeNames[idx].size() && boost::starts_with(type,_ShapeNames[idx])) + if(!_ShapeNames[idx].empty() && boost::starts_with(type,_ShapeNames[idx])) return (TopAbs_ShapeEnum)idx; } } @@ -507,11 +507,11 @@ TopAbs_ShapeEnum TopoShape::shapeType(bool silent) const { const std::string &TopoShape::shapeName(TopAbs_ShapeEnum type, bool silent) { initShapeNameMap(); - if(type>=0 && type<_ShapeNames.size() && _ShapeNames[type].size()) + if(type>=0 && type<_ShapeNames.size() && !_ShapeNames[type].empty()) return _ShapeNames[type]; if(!silent) FC_THROWM(Base::CADKernelError, "invalid shape type '" << type << "'"); - static std::string ret(""); + static std::string ret; return ret; } @@ -642,7 +642,7 @@ void TopoShape::setTransform(const Base::Matrix4D& rclTrf) _Shape.Location(loc); } -Base::Matrix4D TopoShape::getTransform(void) const +Base::Matrix4D TopoShape::getTransform() const { Base::Matrix4D mtrx; gp_Trsf Trf = _Shape.Location().Transformation(); @@ -670,7 +670,7 @@ void TopoShape::setShapePlacement(const Base::Placement& rclTrf) /*! * \obsolete */ -Base::Placement TopoShape::getShapePlacement(void) const +Base::Placement TopoShape::getShapePlacement() const { TopLoc_Location loc = _Shape.Location(); gp_Trsf trsf = loc.Transformation(); @@ -1136,7 +1136,7 @@ void TopoShape::exportLineSet(std::ostream& str) const } } -Base::BoundBox3d TopoShape::getBoundBox(void) const +Base::BoundBox3d TopoShape::getBoundBox() const { Base::BoundBox3d box; try { @@ -1218,7 +1218,7 @@ unsigned int TopoShape_RefCountShapes(const TopoDS_Shape& aShape) return size; } -unsigned int TopoShape::getMemSize (void) const +unsigned int TopoShape::getMemSize () const { if (!_Shape.IsNull()) { // Count total amount of references of TopoDS_Shape objects @@ -1378,33 +1378,33 @@ namespace Part { std::vector buildShapeEnumVector() { std::vector names; - names.push_back("Compound"); //TopAbs_COMPOUND - names.push_back("Compound Solid"); //TopAbs_COMPSOLID - names.push_back("Solid"); //TopAbs_SOLID - names.push_back("Shell"); //TopAbs_SHELL - names.push_back("Face"); //TopAbs_FACE - names.push_back("Wire"); //TopAbs_WIRE - names.push_back("Edge"); //TopAbs_EDGE - names.push_back("Vertex"); //TopAbs_VERTEX - names.push_back("Shape"); //TopAbs_SHAPE + names.emplace_back("Compound"); //TopAbs_COMPOUND + names.emplace_back("Compound Solid"); //TopAbs_COMPSOLID + names.emplace_back("Solid"); //TopAbs_SOLID + names.emplace_back("Shell"); //TopAbs_SHELL + names.emplace_back("Face"); //TopAbs_FACE + names.emplace_back("Wire"); //TopAbs_WIRE + names.emplace_back("Edge"); //TopAbs_EDGE + names.emplace_back("Vertex"); //TopAbs_VERTEX + names.emplace_back("Shape"); //TopAbs_SHAPE return names; } std::vector buildBOPCheckResultVector() { std::vector results; - results.push_back("BOPAlgo CheckUnknown"); //BOPAlgo_CheckUnknown - results.push_back("BOPAlgo BadType"); //BOPAlgo_BadType - results.push_back("BOPAlgo SelfIntersect"); //BOPAlgo_SelfIntersect - results.push_back("BOPAlgo TooSmallEdge"); //BOPAlgo_TooSmallEdge - results.push_back("BOPAlgo NonRecoverableFace"); //BOPAlgo_NonRecoverableFace - results.push_back("BOPAlgo IncompatibilityOfVertex"); //BOPAlgo_IncompatibilityOfVertex - results.push_back("BOPAlgo IncompatibilityOfEdge"); //BOPAlgo_IncompatibilityOfEdge - results.push_back("BOPAlgo IncompatibilityOfFace"); //BOPAlgo_IncompatibilityOfFace - results.push_back("BOPAlgo OperationAborted"); //BOPAlgo_OperationAborted - results.push_back("BOPAlgo GeomAbs_C0"); //BOPAlgo_GeomAbs_C0 - results.push_back("BOPAlgo_InvalidCurveOnSurface"); //BOPAlgo_InvalidCurveOnSurface - results.push_back("BOPAlgo NotValid"); //BOPAlgo_NotValid + results.emplace_back("BOPAlgo CheckUnknown"); //BOPAlgo_CheckUnknown + results.emplace_back("BOPAlgo BadType"); //BOPAlgo_BadType + results.emplace_back("BOPAlgo SelfIntersect"); //BOPAlgo_SelfIntersect + results.emplace_back("BOPAlgo TooSmallEdge"); //BOPAlgo_TooSmallEdge + results.emplace_back("BOPAlgo NonRecoverableFace"); //BOPAlgo_NonRecoverableFace + results.emplace_back("BOPAlgo IncompatibilityOfVertex"); //BOPAlgo_IncompatibilityOfVertex + results.emplace_back("BOPAlgo IncompatibilityOfEdge"); //BOPAlgo_IncompatibilityOfEdge + results.emplace_back("BOPAlgo IncompatibilityOfFace"); //BOPAlgo_IncompatibilityOfFace + results.emplace_back("BOPAlgo OperationAborted"); //BOPAlgo_OperationAborted + results.emplace_back("BOPAlgo GeomAbs_C0"); //BOPAlgo_GeomAbs_C0 + results.emplace_back("BOPAlgo_InvalidCurveOnSurface"); //BOPAlgo_InvalidCurveOnSurface + results.emplace_back("BOPAlgo NotValid"); //BOPAlgo_NotValid return results; } } @@ -2015,10 +2015,13 @@ TopoDS_Shape TopoShape::makePipeShell(const TopTools_ListOfShape& profiles, mkPipeShell.Add(TopoDS_Shape(it.Value())); } - if (!mkPipeShell.IsReady()) Standard_Failure::Raise("shape is not ready to build"); - else mkPipeShell.Build(); + if (!mkPipeShell.IsReady()) + throw Standard_Failure("shape is not ready to build"); - if (make_solid) mkPipeShell.MakeSolid(); + mkPipeShell.Build(); + + if (make_solid) + mkPipeShell.MakeSolid(); return mkPipeShell.Shape(); } @@ -2800,7 +2803,7 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b shapesToProcess.push_back(this->_Shape); } - if(shapesToProcess.size() > 0) { + if(!shapesToProcess.empty()) { //although 2d offset supports offsetting a face directly, it seems there is //no way to do a collective offset of multiple faces. So, we are doing it @@ -2952,7 +2955,7 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b openWires.push_back(w); wiresForMakingFaces = closedWires; - if (!allowOpenResult || openWires.size() == 0){ + if (!allowOpenResult || openWires.empty()){ //just ignore all open wires } else { @@ -3027,7 +3030,7 @@ TopoDS_Shape TopoShape::makeOffset2D(double offset, short joinType, bool fill, b } //make faces - if (wiresForMakingFaces.size()>0){ + if (!wiresForMakingFaces.empty()){ FaceMakerBullseye mkFace; mkFace.setPlane(workingPlane); for(TopoDS_Wire &w : wiresForMakingFaces){ @@ -3378,7 +3381,7 @@ struct MeshVertex : x(X),y(Y),z(Z),i(0) { } - MeshVertex(const Base::Vector3d& p) + explicit MeshVertex(const Base::Vector3d& p) : x(p.x),y(p.y),z(p.z),i(0) { } @@ -4010,13 +4013,13 @@ TopoShape &TopoShape::makeWires(const TopoShape &shape, const char *op, bool fix TopTools_IndexedMapOfShape anIndices; TopExp::MapShapes(shape.getShape(), TopAbs_EDGE, anIndices); for(int i=1;i<=anIndices.Extent();++i) - edge_list.push_back(anIndices.FindKey(i)); + edge_list.emplace_back(anIndices.FindKey(i)); edges.reserve(edge_list.size()); wires.reserve(edge_list.size()); // sort them together to wires - while (edge_list.size() > 0) { + while (!edge_list.empty()) { BRepBuilderAPI_MakeWire mkWire; // add and erase first edge edges.push_back(edge_list.front()); @@ -4053,7 +4056,7 @@ TopoShape &TopoShape::makeWires(const TopoShape &shape, const char *op, bool fix // Assuming FixReorder() just reorder and don't change the underlying // edges, we get the wire and do a name mapping now, as the following // two operations (FixConnected and FixClosed) may change the edges. - wires.push_back(aFix.Wire()); + wires.emplace_back(aFix.Wire()); aFix.FixConnected(); aFix.FixClosed(); @@ -4099,7 +4102,7 @@ TopoShape &TopoShape::makeFace(const TopoShape &shape, const char *op, const cha std::vector shapes; if(shape.shapeType() == TopAbs_COMPOUND) { for(TopoDS_Iterator it(shape.getShape());it.More();it.Next()) - shapes.push_back(it.Value()); + shapes.emplace_back(it.Value()); } else shapes.push_back(shape); return makeFace(shapes,op,maker); diff --git a/src/Mod/Part/App/TopoShape.h b/src/Mod/Part/App/TopoShape.h index 1b9b177583..21a377350a 100644 --- a/src/Mod/Part/App/TopoShape.h +++ b/src/Mod/Part/App/TopoShape.h @@ -54,10 +54,10 @@ class PartExport NullShapeException : public Base::ValueError public: /// Construction NullShapeException(); - NullShapeException(const char * sMessage); - NullShapeException(const std::string& sMessage); + explicit NullShapeException(const char * sMessage); + explicit NullShapeException(const std::string& sMessage); /// Destruction - virtual ~NullShapeException() throw() {} + ~NullShapeException() throw() override {} }; /* A special sub-class to indicate boolean failures @@ -67,20 +67,20 @@ class PartExport BooleanException : public Base::CADKernelError public: /// Construction BooleanException(); - BooleanException(const char * sMessage); - BooleanException(const std::string& sMessage); + explicit BooleanException(const char * sMessage); + explicit BooleanException(const std::string& sMessage); /// Destruction - virtual ~BooleanException() throw() {} + ~BooleanException() throw() override {} }; class PartExport ShapeSegment : public Data::Segment { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: ShapeSegment(const TopoDS_Shape &ShapeIn):Shape(ShapeIn){} ShapeSegment(){} - virtual std::string getName() const; + std::string getName() const override; TopoDS_Shape Shape; }; @@ -91,13 +91,13 @@ public: */ class PartExport TopoShape : public Data::ComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: TopoShape(); - TopoShape(const TopoDS_Shape&); + TopoShape(const TopoDS_Shape&);//explicit bombs TopoShape(const TopoShape&); - ~TopoShape(); + ~TopoShape() override; inline void setShape(const TopoDS_Shape& shape) { this->_Shape = shape; @@ -112,16 +112,16 @@ public: /** @name Placement control */ //@{ /// set the transformation of the CasCade Shape - void setTransform(const Base::Matrix4D& rclTrf); + void setTransform(const Base::Matrix4D& rclTrf) override; /// set the transformation of the CasCade Shape void setShapePlacement(const Base::Placement& rclTrf); /// get the transformation of the CasCade Shape - Base::Placement getShapePlacement(void) const; + Base::Placement getShapePlacement() const; /// get the transformation of the CasCade Shape - Base::Matrix4D getTransform(void) const; + Base::Matrix4D getTransform() const override; /// Bound box from the CasCade shape - Base::BoundBox3d getBoundBox(void)const; - virtual bool getCenterOfGravity(Base::Vector3d& center) const; + Base::BoundBox3d getBoundBox()const override; + bool getCenterOfGravity(Base::Vector3d& center) const override; static void convertTogpTrsf(const Base::Matrix4D& mtrx, gp_Trsf& trsf); static void convertToMatrix(const gp_Trsf& trsf, Base::Matrix4D& mtrx); static Base::Matrix4D convert(const gp_Trsf& trsf); @@ -134,21 +134,21 @@ public: * List of different subelement types * it is NOT a list of the subelements itself */ - virtual std::vector getElementTypes(void) const; - virtual unsigned long countSubElements(const char* Type) const; + std::vector getElementTypes() const override; + unsigned long countSubElements(const char* Type) const override; /// get the subelement by type and number - virtual Data::Segment* getSubElement(const char* Type, unsigned long) const; + Data::Segment* getSubElement(const char* Type, unsigned long) const override; /** Get lines from segment */ - virtual void getLinesFromSubElement( + void getLinesFromSubElement( const Data::Segment*, std::vector &Points, - std::vector &lines) const; + std::vector &lines) const override; /** Get faces from segment */ - virtual void getFacesFromSubElement( + void getFacesFromSubElement( const Data::Segment*, std::vector &Points, std::vector &PointNormals, - std::vector &faces) const; + std::vector &faces) const override; //@} /// get the Topo"sub"Shape with the given name TopoDS_Shape getSubShape(const char* Type, bool silent=false) const; @@ -161,17 +161,17 @@ public: bool hasSubShape(TopAbs_ShapeEnum type) const; /// get the Topo"sub"Shape with the given name PyObject * getPySubShape(const char* Type, bool silent=false) const; - PyObject * getPyObject(); - void setPyObject(PyObject*); + PyObject * getPyObject() override; + void setPyObject(PyObject*) override; /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); - unsigned int getMemSize (void) const; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; + unsigned int getMemSize () const override; //@} /** @name Input/Output */ @@ -282,7 +282,7 @@ public: /** @name Manipulation*/ //@{ - void transformGeometry(const Base::Matrix4D &rclMat); + void transformGeometry(const Base::Matrix4D &rclMat) override; TopoDS_Shape transformGShape(const Base::Matrix4D&, bool copy = false) const; bool transformShape(const Base::Matrix4D&, bool copy, bool checkScale=false); TopoDS_Shape mirror(const gp_Ax2&) const; @@ -300,11 +300,11 @@ public: /** @name Getting basic geometric entities */ //@{ /** Get points from object with given accuracy */ - virtual void getPoints(std::vector &Points, + void getPoints(std::vector &Points, std::vector &Normals, - float Accuracy, uint16_t flags=0) const; - virtual void getFaces(std::vector &Points,std::vector &faces, - float Accuracy, uint16_t flags=0) const; + float Accuracy, uint16_t flags=0) const override; + void getFaces(std::vector &Points,std::vector &faces, + float Accuracy, uint16_t flags=0) const override; void setFaces(const std::vector &Points, const std::vector &faces, double tolerance=1.0e-06); void getDomains(std::vector&) const; diff --git a/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp b/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp index 416a30bdbd..cf2f42c20d 100644 --- a/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeCompSolidPyImp.cpp @@ -39,7 +39,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TopoShapeCompSolidPy::representation(void) const +std::string TopoShapeCompSolidPy::representation() const { std::stringstream str; str << ""; diff --git a/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp b/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp index 93f8f4de73..37f9c170e8 100644 --- a/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeCompoundPyImp.cpp @@ -44,7 +44,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TopoShapeCompoundPy::representation(void) const +std::string TopoShapeCompoundPy::representation() const { std::stringstream str; str << ""; diff --git a/src/Mod/Part/App/TopoShapeEdgePyImp.cpp b/src/Mod/Part/App/TopoShapeEdgePyImp.cpp index 6d2dbf75d0..e207f030ba 100644 --- a/src/Mod/Part/App/TopoShapeEdgePyImp.cpp +++ b/src/Mod/Part/App/TopoShapeEdgePyImp.cpp @@ -91,7 +91,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TopoShapeEdgePy::representation(void) const +std::string TopoShapeEdgePy::representation() const { std::stringstream str; str << ""; @@ -769,7 +769,7 @@ Py::String TopoShapeEdgePy::getContinuity() const return Py::String(cont); } -Py::Float TopoShapeEdgePy::getTolerance(void) const +Py::Float TopoShapeEdgePy::getTolerance() const { const TopoDS_Edge& e = TopoDS::Edge(getTopoShapePtr()->getShape()); return Py::Float(BRep_Tool::Tolerance(e)); @@ -782,7 +782,7 @@ void TopoShapeEdgePy::setTolerance(Py::Float tol) aBuilder.UpdateEdge(e, (double)tol); } -Py::Float TopoShapeEdgePy::getLength(void) const +Py::Float TopoShapeEdgePy::getLength() const { const TopoDS_Edge& e = TopoDS::Edge(getTopoShapePtr()->getShape()); BRepAdaptor_Curve adapt(e); @@ -884,7 +884,7 @@ Py::Object TopoShapeEdgePy::getCurve() const throw Py::TypeError("undefined curve type"); } -Py::Tuple TopoShapeEdgePy::getParameterRange(void) const +Py::Tuple TopoShapeEdgePy::getParameterRange() const { const TopoDS_Edge& e = TopoDS::Edge(getTopoShapePtr()->getShape()); BRepAdaptor_Curve adapt(e); @@ -897,7 +897,7 @@ Py::Tuple TopoShapeEdgePy::getParameterRange(void) const return t; } -Py::Float TopoShapeEdgePy::getFirstParameter(void) const +Py::Float TopoShapeEdgePy::getFirstParameter() const { const TopoDS_Edge& e = TopoDS::Edge(getTopoShapePtr()->getShape()); BRepAdaptor_Curve adapt(e); @@ -905,7 +905,7 @@ Py::Float TopoShapeEdgePy::getFirstParameter(void) const return Py::Float(t); } -Py::Float TopoShapeEdgePy::getLastParameter(void) const +Py::Float TopoShapeEdgePy::getLastParameter() const { const TopoDS_Edge& e = TopoDS::Edge(getTopoShapePtr()->getShape()); BRepAdaptor_Curve adapt(e); @@ -913,7 +913,7 @@ Py::Float TopoShapeEdgePy::getLastParameter(void) const return Py::Float(t); } -Py::Object TopoShapeEdgePy::getMass(void) const +Py::Object TopoShapeEdgePy::getMass() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -921,7 +921,7 @@ Py::Object TopoShapeEdgePy::getMass(void) const return Py::Float(c); } -Py::Object TopoShapeEdgePy::getCenterOfMass(void) const +Py::Object TopoShapeEdgePy::getCenterOfMass() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -929,7 +929,7 @@ Py::Object TopoShapeEdgePy::getCenterOfMass(void) const return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); } -Py::Object TopoShapeEdgePy::getMatrixOfInertia(void) const +Py::Object TopoShapeEdgePy::getMatrixOfInertia() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -943,7 +943,7 @@ Py::Object TopoShapeEdgePy::getMatrixOfInertia(void) const return Py::Matrix(mat); } -Py::Object TopoShapeEdgePy::getStaticMoments(void) const +Py::Object TopoShapeEdgePy::getStaticMoments() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -956,7 +956,7 @@ Py::Object TopoShapeEdgePy::getStaticMoments(void) const return tuple; } -Py::Dict TopoShapeEdgePy::getPrincipalProperties(void) const +Py::Dict TopoShapeEdgePy::getPrincipalProperties() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -989,7 +989,7 @@ Py::Dict TopoShapeEdgePy::getPrincipalProperties(void) const return dict; } -Py::Boolean TopoShapeEdgePy::getClosed(void) const +Py::Boolean TopoShapeEdgePy::getClosed() const { if (getTopoShapePtr()->getShape().IsNull()) throw Py::RuntimeError("Cannot determine the 'Closed'' flag of an empty shape"); @@ -997,7 +997,7 @@ Py::Boolean TopoShapeEdgePy::getClosed(void) const return Py::Boolean(ok ? true : false); } -Py::Boolean TopoShapeEdgePy::getDegenerated(void) const +Py::Boolean TopoShapeEdgePy::getDegenerated() const { Standard_Boolean ok = BRep_Tool::Degenerated(TopoDS::Edge(getTopoShapePtr()->getShape())); return Py::Boolean(ok ? true : false); diff --git a/src/Mod/Part/App/TopoShapeFacePyImp.cpp b/src/Mod/Part/App/TopoShapeFacePyImp.cpp index 039514992b..127e41db41 100644 --- a/src/Mod/Part/App/TopoShapeFacePyImp.cpp +++ b/src/Mod/Part/App/TopoShapeFacePyImp.cpp @@ -97,7 +97,7 @@ namespace Part { } // returns a string which represent the object e.g. when printed in python -std::string TopoShapeFacePy::representation(void) const +std::string TopoShapeFacePy::representation() const { std::stringstream str; str << ""; @@ -982,7 +982,7 @@ Py::Object TopoShapeFacePy::getSurface() const throw Py::TypeError("undefined surface type"); } -Py::Float TopoShapeFacePy::getTolerance(void) const +Py::Float TopoShapeFacePy::getTolerance() const { const TopoDS_Face& f = TopoDS::Face(getTopoShapePtr()->getShape()); return Py::Float(BRep_Tool::Tolerance(f)); @@ -995,7 +995,7 @@ void TopoShapeFacePy::setTolerance(Py::Float tol) aBuilder.UpdateFace(f, (double)tol); } -Py::Tuple TopoShapeFacePy::getParameterRange(void) const +Py::Tuple TopoShapeFacePy::getParameterRange() const { const TopoDS_Face& f = TopoDS::Face(getTopoShapePtr()->getShape()); BRepAdaptor_Surface adapt(f); @@ -1013,7 +1013,7 @@ Py::Tuple TopoShapeFacePy::getParameterRange(void) const } // deprecated -Py::Object TopoShapeFacePy::getWire(void) const +Py::Object TopoShapeFacePy::getWire() const { try { Py::Object sys_out(PySys_GetObject("stdout")); @@ -1027,7 +1027,7 @@ Py::Object TopoShapeFacePy::getWire(void) const return getOuterWire(); } -Py::Object TopoShapeFacePy::getOuterWire(void) const +Py::Object TopoShapeFacePy::getOuterWire() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); if (shape.IsNull()) @@ -1043,7 +1043,7 @@ Py::Object TopoShapeFacePy::getOuterWire(void) const } } -Py::Object TopoShapeFacePy::getMass(void) const +Py::Object TopoShapeFacePy::getMass() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -1051,7 +1051,7 @@ Py::Object TopoShapeFacePy::getMass(void) const return Py::Float(c); } -Py::Object TopoShapeFacePy::getCenterOfMass(void) const +Py::Object TopoShapeFacePy::getCenterOfMass() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -1059,7 +1059,7 @@ Py::Object TopoShapeFacePy::getCenterOfMass(void) const return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); } -Py::Object TopoShapeFacePy::getMatrixOfInertia(void) const +Py::Object TopoShapeFacePy::getMatrixOfInertia() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -1073,7 +1073,7 @@ Py::Object TopoShapeFacePy::getMatrixOfInertia(void) const return Py::Matrix(mat); } -Py::Object TopoShapeFacePy::getStaticMoments(void) const +Py::Object TopoShapeFacePy::getStaticMoments() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -1086,7 +1086,7 @@ Py::Object TopoShapeFacePy::getStaticMoments(void) const return tuple; } -Py::Dict TopoShapeFacePy::getPrincipalProperties(void) const +Py::Dict TopoShapeFacePy::getPrincipalProperties() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); diff --git a/src/Mod/Part/App/TopoShapePyImp.cpp b/src/Mod/Part/App/TopoShapePyImp.cpp index a73d7d523f..6e080ec58b 100644 --- a/src/Mod/Part/App/TopoShapePyImp.cpp +++ b/src/Mod/Part/App/TopoShapePyImp.cpp @@ -67,6 +67,7 @@ #endif #include +#include #include #include #include @@ -103,7 +104,7 @@ using namespace Part; #endif // returns a string which represents the object e.g. when printed in python -std::string TopoShapePy::representation(void) const +std::string TopoShapePy::representation() const { std::stringstream str; str << ""; @@ -405,7 +406,8 @@ PyObject* TopoShapePy::exportBinary(PyObject *args) try { // read binary brep - std::ofstream str(input, std::ios::out | std::ios::binary); + Base::FileInfo fi(input); + Base::ofstream str(fi, std::ios::out | std::ios::binary); getTopoShapePtr()->exportBinary(str); str.close(); } @@ -516,7 +518,8 @@ PyObject* TopoShapePy::importBinary(PyObject *args) try { // read binary brep - std::ifstream str(input, std::ios::in | std::ios::binary); + Base::FileInfo fi(input); + Base::ifstream str(fi, std::ios::in | std::ios::binary); getTopoShapePtr()->importBinary(str); str.close(); } @@ -2184,7 +2187,8 @@ PyObject* TopoShapePy::isInside(PyObject *args) gp_Pnt vertex = gp_Pnt(pnt.x,pnt.y,pnt.z); if (shape.ShapeType() == TopAbs_VERTEX || shape.ShapeType() == TopAbs_EDGE || - shape.ShapeType() == TopAbs_WIRE) { + shape.ShapeType() == TopAbs_WIRE || + shape.ShapeType() == TopAbs_FACE) { BRepBuilderAPI_MakeVertex mkVertex(vertex); BRepExtrema_DistShapeShape extss; @@ -2811,7 +2815,7 @@ void TopoShapePy::setLocation(Py::Object o) } #endif -Py::String TopoShapePy::getShapeType(void) const +Py::String TopoShapePy::getShapeType() const { TopoDS_Shape sh = getTopoShapePtr()->getShape(); if (sh.IsNull()) @@ -2852,7 +2856,7 @@ Py::String TopoShapePy::getShapeType(void) const return Py::String(name); } -Py::String TopoShapePy::getOrientation(void) const +Py::String TopoShapePy::getOrientation() const { TopoDS_Shape sh = getTopoShapePtr()->getShape(); if (sh.IsNull()) @@ -2906,7 +2910,7 @@ void TopoShapePy::setOrientation(Py::String arg) getTopoShapePtr()->setShape(sh); } -Py::List TopoShapePy::getSubShapes(void) const +Py::List TopoShapePy::getSubShapes() const { Py::List ret; const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); @@ -2939,47 +2943,47 @@ template Py::List getShapes(const TopoShape* shapePtr) return ret; } -Py::List TopoShapePy::getFaces(void) const +Py::List TopoShapePy::getFaces() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getVertexes(void) const +Py::List TopoShapePy::getVertexes() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getShells(void) const +Py::List TopoShapePy::getShells() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getSolids(void) const +Py::List TopoShapePy::getSolids() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getCompSolids(void) const +Py::List TopoShapePy::getCompSolids() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getEdges(void) const +Py::List TopoShapePy::getEdges() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getWires(void) const +Py::List TopoShapePy::getWires() const { return getShapes(getTopoShapePtr()); } -Py::List TopoShapePy::getCompounds(void) const +Py::List TopoShapePy::getCompounds() const { return getShapes(getTopoShapePtr()); } -Py::Float TopoShapePy::getLength(void) const +Py::Float TopoShapePy::getLength() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); if (shape.IsNull()) @@ -2989,7 +2993,7 @@ Py::Float TopoShapePy::getLength(void) const return Py::Float(props.Mass()); } -Py::Float TopoShapePy::getArea(void) const +Py::Float TopoShapePy::getArea() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); if (shape.IsNull()) @@ -2999,7 +3003,7 @@ Py::Float TopoShapePy::getArea(void) const return Py::Float(props.Mass()); } -Py::Float TopoShapePy::getVolume(void) const +Py::Float TopoShapePy::getVolume() const { const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); if (shape.IsNull()) diff --git a/src/Mod/Part/App/TopoShapeShellPyImp.cpp b/src/Mod/Part/App/TopoShapeShellPyImp.cpp index 9add67ec72..25f9892026 100644 --- a/src/Mod/Part/App/TopoShapeShellPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeShellPyImp.cpp @@ -50,7 +50,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TopoShapeShellPy::representation(void) const +std::string TopoShapeShellPy::representation() const { // Note: As the return type is 'const char*' we cannot create a temporary // char array neither on the stack because the array would be freed when @@ -199,7 +199,7 @@ PyObject* TopoShapeShellPy::makeHalfSpace(PyObject *args) } } -Py::Object TopoShapeShellPy::getMass(void) const +Py::Object TopoShapeShellPy::getMass() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -207,7 +207,7 @@ Py::Object TopoShapeShellPy::getMass(void) const return Py::Float(c); } -Py::Object TopoShapeShellPy::getCenterOfMass(void) const +Py::Object TopoShapeShellPy::getCenterOfMass() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -215,7 +215,7 @@ Py::Object TopoShapeShellPy::getCenterOfMass(void) const return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); } -Py::Object TopoShapeShellPy::getMatrixOfInertia(void) const +Py::Object TopoShapeShellPy::getMatrixOfInertia() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -229,7 +229,7 @@ Py::Object TopoShapeShellPy::getMatrixOfInertia(void) const return Py::Matrix(mat); } -Py::Object TopoShapeShellPy::getStaticMoments(void) const +Py::Object TopoShapeShellPy::getStaticMoments() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); @@ -242,7 +242,7 @@ Py::Object TopoShapeShellPy::getStaticMoments(void) const return tuple; } -Py::Dict TopoShapeShellPy::getPrincipalProperties(void) const +Py::Dict TopoShapeShellPy::getPrincipalProperties() const { GProp_GProps props; BRepGProp::SurfaceProperties(getTopoShapePtr()->getShape(), props); diff --git a/src/Mod/Part/App/TopoShapeSolidPyImp.cpp b/src/Mod/Part/App/TopoShapeSolidPyImp.cpp index e5b13afc9c..3b069d8e06 100644 --- a/src/Mod/Part/App/TopoShapeSolidPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeSolidPyImp.cpp @@ -58,7 +58,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TopoShapeSolidPy::representation(void) const +std::string TopoShapeSolidPy::representation() const { std::stringstream str; str << ""; @@ -134,7 +134,7 @@ int TopoShapeSolidPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } -Py::Object TopoShapeSolidPy::getMass(void) const +Py::Object TopoShapeSolidPy::getMass() const { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); @@ -142,7 +142,7 @@ Py::Object TopoShapeSolidPy::getMass(void) const return Py::Float(c); } -Py::Object TopoShapeSolidPy::getCenterOfMass(void) const +Py::Object TopoShapeSolidPy::getCenterOfMass() const { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); @@ -150,7 +150,7 @@ Py::Object TopoShapeSolidPy::getCenterOfMass(void) const return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); } -Py::Object TopoShapeSolidPy::getMatrixOfInertia(void) const +Py::Object TopoShapeSolidPy::getMatrixOfInertia() const { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); @@ -164,7 +164,7 @@ Py::Object TopoShapeSolidPy::getMatrixOfInertia(void) const return Py::Matrix(mat); } -Py::Object TopoShapeSolidPy::getStaticMoments(void) const +Py::Object TopoShapeSolidPy::getStaticMoments() const { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); @@ -177,7 +177,7 @@ Py::Object TopoShapeSolidPy::getStaticMoments(void) const return tuple; } -Py::Dict TopoShapeSolidPy::getPrincipalProperties(void) const +Py::Dict TopoShapeSolidPy::getPrincipalProperties() const { GProp_GProps props; BRepGProp::VolumeProperties(getTopoShapePtr()->getShape(), props); @@ -210,7 +210,7 @@ Py::Dict TopoShapeSolidPy::getPrincipalProperties(void) const return dict; } -Py::Object TopoShapeSolidPy::getOuterShell(void) const +Py::Object TopoShapeSolidPy::getOuterShell() const { TopoDS_Shell shell; const TopoDS_Shape& shape = getTopoShapePtr()->getShape(); diff --git a/src/Mod/Part/App/TopoShapeVertexPyImp.cpp b/src/Mod/Part/App/TopoShapeVertexPyImp.cpp index fcbac65cd0..158211ef0c 100644 --- a/src/Mod/Part/App/TopoShapeVertexPyImp.cpp +++ b/src/Mod/Part/App/TopoShapeVertexPyImp.cpp @@ -44,7 +44,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TopoShapeVertexPy::representation(void) const +std::string TopoShapeVertexPy::representation() const { std::stringstream str; str << ""; @@ -137,7 +137,7 @@ int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/) return 0; } -Py::Float TopoShapeVertexPy::getTolerance(void) const +Py::Float TopoShapeVertexPy::getTolerance() const { const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape()); return Py::Float(BRep_Tool::Tolerance(v)); @@ -150,7 +150,7 @@ void TopoShapeVertexPy::setTolerance(Py::Float tol) aBuilder.UpdateVertex(v, (double)tol); } -Py::Float TopoShapeVertexPy::getX(void) const +Py::Float TopoShapeVertexPy::getX() const { try { const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape()); @@ -162,7 +162,7 @@ Py::Float TopoShapeVertexPy::getX(void) const } } -Py::Float TopoShapeVertexPy::getY(void) const +Py::Float TopoShapeVertexPy::getY() const { try { const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape()); @@ -174,7 +174,7 @@ Py::Float TopoShapeVertexPy::getY(void) const } } -Py::Float TopoShapeVertexPy::getZ(void) const +Py::Float TopoShapeVertexPy::getZ() const { try { const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape()); @@ -186,7 +186,7 @@ Py::Float TopoShapeVertexPy::getZ(void) const } } -Py::Object TopoShapeVertexPy::getPoint(void) const +Py::Object TopoShapeVertexPy::getPoint() const { try { const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape()); diff --git a/src/Mod/Part/App/TopoShapeWirePyImp.cpp b/src/Mod/Part/App/TopoShapeWirePyImp.cpp index 3a89674785..bd18e40401 100644 --- a/src/Mod/Part/App/TopoShapeWirePyImp.cpp +++ b/src/Mod/Part/App/TopoShapeWirePyImp.cpp @@ -63,7 +63,7 @@ namespace Part { // returns a string which represents the object e.g. when printed in python -std::string TopoShapeWirePy::representation(void) const +std::string TopoShapeWirePy::representation() const { std::stringstream str; str << ""; @@ -612,7 +612,7 @@ Py::String TopoShapeWirePy::getContinuity() const return Py::String(cont); } -Py::Object TopoShapeWirePy::getMass(void) const +Py::Object TopoShapeWirePy::getMass() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -620,7 +620,7 @@ Py::Object TopoShapeWirePy::getMass(void) const return Py::Float(c); } -Py::Object TopoShapeWirePy::getCenterOfMass(void) const +Py::Object TopoShapeWirePy::getCenterOfMass() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -628,7 +628,7 @@ Py::Object TopoShapeWirePy::getCenterOfMass(void) const return Py::Vector(Base::Vector3d(c.X(),c.Y(),c.Z())); } -Py::Object TopoShapeWirePy::getMatrixOfInertia(void) const +Py::Object TopoShapeWirePy::getMatrixOfInertia() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -642,7 +642,7 @@ Py::Object TopoShapeWirePy::getMatrixOfInertia(void) const return Py::Matrix(mat); } -Py::Object TopoShapeWirePy::getStaticMoments(void) const +Py::Object TopoShapeWirePy::getStaticMoments() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -655,7 +655,7 @@ Py::Object TopoShapeWirePy::getStaticMoments(void) const return tuple; } -Py::Dict TopoShapeWirePy::getPrincipalProperties(void) const +Py::Dict TopoShapeWirePy::getPrincipalProperties() const { GProp_GProps props; BRepGProp::LinearProperties(getTopoShapePtr()->getShape(), props); @@ -688,7 +688,7 @@ Py::Dict TopoShapeWirePy::getPrincipalProperties(void) const return dict; } -Py::List TopoShapeWirePy::getOrderedEdges(void) const +Py::List TopoShapeWirePy::getOrderedEdges() const { Py::List ret; @@ -701,7 +701,7 @@ Py::List TopoShapeWirePy::getOrderedEdges(void) const return ret; } -Py::List TopoShapeWirePy::getOrderedVertexes(void) const +Py::List TopoShapeWirePy::getOrderedVertexes() const { Py::List ret; diff --git a/src/Mod/Part/App/TopologyPy.cpp b/src/Mod/Part/App/TopologyPy.cpp index 8fc0351617..732d70fb16 100644 --- a/src/Mod/Part/App/TopologyPy.cpp +++ b/src/Mod/Part/App/TopologyPy.cpp @@ -59,7 +59,7 @@ using namespace Part; //=========================================================================== -// TopoShapePyOld - Warpper for the TopoDS classes +// TopoShapePyOld - Wrapper for the TopoDS classes //=========================================================================== //-------------------------------------------------------------------------- diff --git a/src/Mod/Part/App/ToroidPyImp.cpp b/src/Mod/Part/App/ToroidPyImp.cpp index 71eb2f0508..508142e7bd 100644 --- a/src/Mod/Part/App/ToroidPyImp.cpp +++ b/src/Mod/Part/App/ToroidPyImp.cpp @@ -37,7 +37,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string ToroidPy::representation(void) const +std::string ToroidPy::representation() const { return ""; } @@ -62,7 +62,7 @@ int ToroidPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Float ToroidPy::getMajorRadius(void) const +Py::Float ToroidPy::getMajorRadius() const { Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast (getGeomToroidPtr()->handle()); @@ -81,7 +81,7 @@ void ToroidPy::setMajorRadius(Py::Float arg) } } -Py::Float ToroidPy::getMinorRadius(void) const +Py::Float ToroidPy::getMinorRadius() const { Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast (getGeomToroidPtr()->handle()); @@ -100,7 +100,7 @@ void ToroidPy::setMinorRadius(Py::Float arg) } } -Py::Object ToroidPy::getCenter(void) const +Py::Object ToroidPy::getCenter() const { Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast (getGeomToroidPtr()->handle()); @@ -124,7 +124,7 @@ void ToroidPy::setCenter(Py::Object arg) } } -Py::Object ToroidPy::getAxis(void) const +Py::Object ToroidPy::getAxis() const { Handle(Geom_ElementarySurface) s = Handle(Geom_ElementarySurface)::DownCast (getGeometryPtr()->handle()); @@ -167,14 +167,14 @@ void ToroidPy::setAxis(Py::Object arg) } } -Py::Float ToroidPy::getArea(void) const +Py::Float ToroidPy::getArea() const { Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast (getGeomToroidPtr()->handle()); return Py::Float(torus->Area()); } -Py::Float ToroidPy::getVolume(void) const +Py::Float ToroidPy::getVolume() const { Handle(Geom_ToroidalSurface) torus = Handle(Geom_ToroidalSurface)::DownCast (getGeomToroidPtr()->handle()); diff --git a/src/Mod/Part/App/TrimmedCurvePyImp.cpp b/src/Mod/Part/App/TrimmedCurvePyImp.cpp index 7a3e1913de..b4eb7fa7cb 100644 --- a/src/Mod/Part/App/TrimmedCurvePyImp.cpp +++ b/src/Mod/Part/App/TrimmedCurvePyImp.cpp @@ -33,7 +33,7 @@ using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string TrimmedCurvePy::representation(void) const +std::string TrimmedCurvePy::representation() const { return ""; } diff --git a/src/Mod/Part/App/edgecluster.cpp b/src/Mod/Part/App/edgecluster.cpp index 45789f6894..155ff215a7 100644 --- a/src/Mod/Part/App/edgecluster.cpp +++ b/src/Mod/Part/App/edgecluster.cpp @@ -42,7 +42,7 @@ Edgecluster::Edgecluster(const std::vector& unsorted_edges) m_final_cluster.clear(); } -Edgecluster::~Edgecluster(void) +Edgecluster::~Edgecluster() { } diff --git a/src/Mod/Part/App/edgecluster.h b/src/Mod/Part/App/edgecluster.h index a29208b84d..7a93164279 100644 --- a/src/Mod/Part/App/edgecluster.h +++ b/src/Mod/Part/App/edgecluster.h @@ -61,10 +61,10 @@ typedef std::vector > tEdgeClusterVector; class PartExport Edgecluster { public: - Edgecluster(const std::vector& usorted_edges); - virtual ~Edgecluster(void); + explicit Edgecluster(const std::vector& usorted_edges); + virtual ~Edgecluster(); - tEdgeClusterVector GetClusters(void); + tEdgeClusterVector GetClusters(); private: void Perform(); diff --git a/src/Mod/Part/App/modelRefine.cpp b/src/Mod/Part/App/modelRefine.cpp index 3ae916200e..4e7e21d12c 100644 --- a/src/Mod/Part/App/modelRefine.cpp +++ b/src/Mod/Part/App/modelRefine.cpp @@ -622,7 +622,7 @@ TopoDS_Face FaceTypedCylinder::buildFace(const FaceVectorType &faces) const static TopoDS_Face dummy; std::vector boundaries; boundarySplit(faces, boundaries); - if (boundaries.size() < 1) + if (boundaries.empty()) return dummy; //make wires @@ -638,7 +638,7 @@ TopoDS_Face FaceTypedCylinder::buildFace(const FaceVectorType &faces) const return dummy; allWires.push_back(wireMaker.Wire()); } - if (allWires.size() < 1) + if (allWires.empty()) return dummy; // Sort wires by size, that is, the innermost wire comes last @@ -1089,7 +1089,7 @@ bool FaceUniter::process() } } } - if (facesToSew.size() > 0) + if (!facesToSew.empty()) { modifiedSignal = true; workShell = ModelRefine::removeFaces(workShell, facesToRemove); @@ -1217,7 +1217,11 @@ Part::BRepBuilderAPI_RefineModel::BRepBuilderAPI_RefineModel(const TopoDS_Shape& Build(); } +#if OCC_VERSION_HEX >= 0x070600 +void Part::BRepBuilderAPI_RefineModel::Build(const Message_ProgressRange&) +#else void Part::BRepBuilderAPI_RefineModel::Build() +#endif { if (myShape.IsNull()) Standard_Failure::Raise("Cannot remove splitter from empty shape"); diff --git a/src/Mod/Part/App/modelRefine.h b/src/Mod/Part/App/modelRefine.h index 4186d1c1db..3bc7b0fee5 100644 --- a/src/Mod/Part/App/modelRefine.h +++ b/src/Mod/Part/App/modelRefine.h @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -75,9 +76,9 @@ namespace ModelRefine private: FaceTypedPlane(); public: - virtual bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const; - virtual GeomAbs_SurfaceType getType() const; - virtual TopoDS_Face buildFace(const FaceVectorType &faces) const; + bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const override; + GeomAbs_SurfaceType getType() const override; + TopoDS_Face buildFace(const FaceVectorType &faces) const override; friend FaceTypedPlane& getPlaneObject(); }; FaceTypedPlane& getPlaneObject(); @@ -87,13 +88,13 @@ namespace ModelRefine private: FaceTypedCylinder(); public: - virtual bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const; - virtual GeomAbs_SurfaceType getType() const; - virtual TopoDS_Face buildFace(const FaceVectorType &faces) const; + bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const override; + GeomAbs_SurfaceType getType() const override; + TopoDS_Face buildFace(const FaceVectorType &faces) const override; friend FaceTypedCylinder& getCylinderObject(); protected: - virtual void boundarySplit(const FaceVectorType &facesIn, std::vector &boundariesOut) const; + void boundarySplit(const FaceVectorType &facesIn, std::vector &boundariesOut) const override; }; FaceTypedCylinder& getCylinderObject(); @@ -102,9 +103,9 @@ namespace ModelRefine private: FaceTypedBSpline(); public: - virtual bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const; - virtual GeomAbs_SurfaceType getType() const; - virtual TopoDS_Face buildFace(const FaceVectorType &faces) const; + bool isEqual(const TopoDS_Face &faceOne, const TopoDS_Face &faceTwo) const override; + GeomAbs_SurfaceType getType() const override; + TopoDS_Face buildFace(const FaceVectorType &faces) const override; friend FaceTypedBSpline& getBSplineObject(); }; FaceTypedBSpline& getBSplineObject(); @@ -198,9 +199,13 @@ class PartExport BRepBuilderAPI_RefineModel : public BRepBuilderAPI_MakeShape { public: BRepBuilderAPI_RefineModel(const TopoDS_Shape&); - void Build(); - const TopTools_ListOfShape& Modified(const TopoDS_Shape& S); - Standard_Boolean IsDeleted(const TopoDS_Shape& S); +#if OCC_VERSION_HEX >= 0x070600 + void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) override; +#else + void Build() override; +#endif + const TopTools_ListOfShape& Modified(const TopoDS_Shape& S) override; + Standard_Boolean IsDeleted(const TopoDS_Shape& S) override; private: void LogModifications(const ModelRefine::FaceUniter& uniter); diff --git a/src/Mod/Part/Gui/AppPartGui.cpp b/src/Mod/Part/Gui/AppPartGui.cpp index cfc6f4d05b..3b1614f905 100644 --- a/src/Mod/Part/Gui/AppPartGui.cpp +++ b/src/Mod/Part/Gui/AppPartGui.cpp @@ -9,7 +9,6 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ # include @@ -20,19 +19,21 @@ #include #include #include +#include #include #include #include "AttacherTexts.h" #include "PropertyEnumAttacherItem.h" +#include "DlgSettings3DViewPartImp.h" +#include "DlgSettingsGeneral.h" +#include "DlgSettingsMeasure.h" +#include "DlgSettingsObjectColor.h" +#include "TaskDimension.h" #include "SoBrepEdgeSet.h" #include "SoBrepFaceSet.h" #include "SoBrepPointSet.h" #include "SoFCShapeObject.h" -#include "TaskDimension.h" -#include "DlgSettings3DViewPartImp.h" -#include "DlgSettingsGeneral.h" -#include "DlgSettingsObjectColor.h" #include "ViewProvider.h" #include "ViewProvider2DObject.h" #include "ViewProviderAttachExtension.h" @@ -64,9 +65,9 @@ // use a different name to CreateCommand() -void CreatePartCommands(void); -void CreateSimplePartCommands(void); -void CreateParamPartCommands(void); +void CreatePartCommands(); +void CreateSimplePartCommands(); +void CreateParamPartCommands(); void loadPartResource() { @@ -84,7 +85,7 @@ public: initialize("This module is the PartGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; @@ -207,9 +208,11 @@ PyMOD_INIT_FUNC(PartGui) } // register preferences pages + Gui::Dialog::DlgPreferencesImp::setGroupData("Part/Part Design", "Part design", QObject::tr("Part and Part Design workbench")); (void)new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Part/Part Design")); (void)new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Part/Part Design")); (void)new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Part/Part Design")); + (void)new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Part/Part Design")); (void)new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Import-Export")); (void)new Gui::PrefPageProducer(QT_TRANSLATE_NOOP("QObject", "Import-Export")); Gui::ViewProviderBuilder::add( diff --git a/src/Mod/Part/Gui/AttacherTexts.cpp b/src/Mod/Part/Gui/AttacherTexts.cpp index 8f4963e514..865cad5d41 100644 --- a/src/Mod/Part/Gui/AttacherTexts.cpp +++ b/src/Mod/Part/Gui/AttacherTexts.cpp @@ -19,14 +19,17 @@ * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ + #include "PreCompiled.h" #ifndef _PreComp_ # include #endif -#include "AttacherTexts.h" -#include + #include +#include "AttacherTexts.h" + + using namespace Attacher; namespace AttacherGui { diff --git a/src/Mod/Part/Gui/AttacherTexts.h b/src/Mod/Part/Gui/AttacherTexts.h index 2deb659230..83cd40e50f 100644 --- a/src/Mod/Part/Gui/AttacherTexts.h +++ b/src/Mod/Part/Gui/AttacherTexts.h @@ -28,11 +28,9 @@ #ifndef PARTATTACHERTEXTS_H #define PARTATTACHERTEXTS_H - #include #include #include -#include #include diff --git a/src/Mod/Part/Gui/BoxSelection.cpp b/src/Mod/Part/Gui/BoxSelection.cpp index 7ce3362dc3..77bf3ef8e9 100644 --- a/src/Mod/Part/Gui/BoxSelection.cpp +++ b/src/Mod/Part/Gui/BoxSelection.cpp @@ -20,35 +20,23 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ # include # include -# include -# include # include # include # include # include -# include -# include -# include # include -# include -# include -# include # include # include -# include #endif -#include "BoxSelection.h" -#include "ViewProviderExt.h" - +#include +#include #include -#include #include #include #include @@ -57,9 +45,8 @@ #include #include -#include -#include -#include +#include "BoxSelection.h" +#include "ViewProviderExt.h" using namespace PartGui; @@ -71,10 +58,10 @@ public: : Gui::SelectionFilterGate() { } - ~FaceSelectionGate() + ~FaceSelectionGate() override { } - bool allow(App::Document*, App::DocumentObject*, const char*sSubName) + bool allow(App::Document*, App::DocumentObject*, const char*sSubName) override { if (!sSubName || sSubName[0] == '\0') return false; diff --git a/src/Mod/Part/Gui/CMakeLists.txt b/src/Mod/Part/Gui/CMakeLists.txt index 43d8b3d1ff..4f1aeda1fc 100644 --- a/src/Mod/Part/Gui/CMakeLists.txt +++ b/src/Mod/Part/Gui/CMakeLists.txt @@ -13,6 +13,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ) link_directories(${OCC_LIBRARY_DIR}) @@ -60,6 +61,7 @@ set(PartGui_UIC_SRCS DlgRevolution.ui DlgSettings3DViewPart.ui DlgSettingsGeneral.ui + DlgSettingsMeasure.ui DlgSettingsObjectColor.ui DlgProjectionOnSurface.ui SectionCutting.ui @@ -131,9 +133,15 @@ SET(PartGui_SRCS DlgSettingsGeneral.cpp DlgSettingsGeneral.h DlgSettingsGeneral.ui + DlgSettingsMeasure.cpp + DlgSettingsMeasure.h + DlgSettingsMeasure.ui DlgSettingsObjectColor.cpp DlgSettingsObjectColor.h DlgSettingsObjectColor.ui + DlgSettingsMeasure.cpp + DlgSettingsMeasure.h + DlgSettingsMeasure.ui DlgProjectionOnSurface.cpp DlgProjectionOnSurface.h DlgProjectionOnSurface.ui diff --git a/src/Mod/Part/Gui/Command.cpp b/src/Mod/Part/Gui/Command.cpp index d6ee2f9e14..b8f61c3bc3 100644 --- a/src/Mod/Part/Gui/Command.cpp +++ b/src/Mod/Part/Gui/Command.cpp @@ -151,7 +151,7 @@ void CmdPartBox2::activated(int iMsg) updateActive(); } -bool CmdPartBox2::isActive(void) +bool CmdPartBox2::isActive() { if (getActiveGuiDocument()) return true; @@ -192,7 +192,7 @@ void CmdPartBox3::activated(int iMsg) updateActive(); } -bool CmdPartBox3::isActive(void) +bool CmdPartBox3::isActive() { if (getActiveGuiDocument()) return true; @@ -224,7 +224,7 @@ void CmdPartPrimitives::activated(int iMsg) Gui::Control().showDialog(dlg); } -bool CmdPartPrimitives::isActive(void) +bool CmdPartPrimitives::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -359,7 +359,7 @@ void CmdPartCut::activated(int iMsg) commitCommand(); } -bool CmdPartCut::isActive(void) +bool CmdPartCut::isActive() { return getSelection().countObjectsOfType( App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink)==2; @@ -459,7 +459,7 @@ void CmdPartCommon::activated(int iMsg) commitCommand(); } -bool CmdPartCommon::isActive(void) +bool CmdPartCommon::isActive() { return getSelection().countObjectsOfType( App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) >= 1; @@ -559,7 +559,7 @@ void CmdPartFuse::activated(int iMsg) commitCommand(); } -bool CmdPartFuse::isActive(void) +bool CmdPartFuse::isActive() { return getSelection().countObjectsOfType( App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) >= 1; @@ -603,7 +603,7 @@ void CmdPartCompJoinFeatures::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompJoinFeatures::createAction(void) +Gui::Action * CmdPartCompJoinFeatures::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -663,7 +663,7 @@ void CmdPartCompJoinFeatures::languageChange() } } -bool CmdPartCompJoinFeatures::isActive(void) +bool CmdPartCompJoinFeatures::isActive() { if (getActiveGuiDocument()) return true; @@ -711,7 +711,7 @@ void CmdPartCompSplitFeatures::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompSplitFeatures::createAction(void) +Gui::Action * CmdPartCompSplitFeatures::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -781,7 +781,7 @@ void CmdPartCompSplitFeatures::languageChange() } } -bool CmdPartCompSplitFeatures::isActive(void) +bool CmdPartCompSplitFeatures::isActive() { if (getActiveGuiDocument()) return true; @@ -827,7 +827,7 @@ void CmdPartCompCompoundTools::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompCompoundTools::createAction(void) +Gui::Action * CmdPartCompCompoundTools::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -887,7 +887,7 @@ void CmdPartCompCompoundTools::languageChange() } } -bool CmdPartCompCompoundTools::isActive(void) +bool CmdPartCompCompoundTools::isActive() { if (getActiveGuiDocument()) return true; @@ -948,7 +948,7 @@ void CmdPartCompound::activated(int iMsg) commitCommand(); } -bool CmdPartCompound::isActive(void) +bool CmdPartCompound::isActive() { return getSelection().countObjectsOfType( App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) >= 1; @@ -997,7 +997,7 @@ void CmdPartSection::activated(int iMsg) commitCommand(); } -bool CmdPartSection::isActive(void) +bool CmdPartSection::isActive() { return getSelection().countObjectsOfType(App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) == 2; } @@ -1057,7 +1057,7 @@ void CmdPartImport::activated(int iMsg) } } -bool CmdPartImport::isActive(void) +bool CmdPartImport::isActive() { if (getActiveGuiDocument()) return true; @@ -1108,7 +1108,7 @@ void CmdPartExport::activated(int iMsg) } } -bool CmdPartExport::isActive(void) +bool CmdPartExport::isActive() { return Gui::Selection().countObjectsOfType(App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) > 0; } @@ -1153,7 +1153,7 @@ void CmdPartImportCurveNet::activated(int iMsg) } } -bool CmdPartImportCurveNet::isActive(void) +bool CmdPartImportCurveNet::isActive() { if (getActiveGuiDocument()) return true; @@ -1202,8 +1202,8 @@ void CmdPartMakeSolid::activated(int iMsg) "__o__.Shape=__s__\n" "del __s__, __o__" ) - .arg(QLatin1String((*it)->getNameInDocument())) - .arg(QLatin1String((*it)->Label.getValue())); + .arg(QLatin1String((*it)->getNameInDocument()), + QLatin1String((*it)->Label.getValue())); } else if (type == TopAbs_SHELL) { str = QString::fromLatin1( @@ -1214,8 +1214,8 @@ void CmdPartMakeSolid::activated(int iMsg) "__o__.Shape=__s__\n" "del __s__, __o__" ) - .arg(QLatin1String((*it)->getNameInDocument())) - .arg(QLatin1String((*it)->Label.getValue())); + .arg(QLatin1String((*it)->getNameInDocument()), + QLatin1String((*it)->Label.getValue())); } else { Base::Console().Message("%s is ignored because it is neither a shell nor a compound.\n", @@ -1234,7 +1234,7 @@ void CmdPartMakeSolid::activated(int iMsg) } } -bool CmdPartMakeSolid::isActive(void) +bool CmdPartMakeSolid::isActive() { return Gui::Selection().countObjectsOfType (App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) > 0; @@ -1297,7 +1297,7 @@ void CmdPartReverseShape::activated(int iMsg) updateActive(); } -bool CmdPartReverseShape::isActive(void) +bool CmdPartReverseShape::isActive() { return PartGui::hasShapesInSelection(); } @@ -1328,7 +1328,7 @@ void CmdPartBoolean::activated(int iMsg) Gui::Control().showDialog(dlg); } -bool CmdPartBoolean::isActive(void) +bool CmdPartBoolean::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1356,7 +1356,7 @@ void CmdPartExtrude::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskExtrusion()); } -bool CmdPartExtrude::isActive(void) +bool CmdPartExtrude::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1407,7 +1407,7 @@ void CmdPartMakeFace::activated(int iMsg) } } -bool CmdPartMakeFace::isActive(void) +bool CmdPartMakeFace::isActive() { return (Gui::Selection().countObjectsOfType(App::DocumentObject::getClassTypeId(), nullptr, Gui::ResolveMode::FollowLink) > 0 && !Gui::Control().activeDialog()); @@ -1436,7 +1436,7 @@ void CmdPartRevolve::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskRevolution()); } -bool CmdPartRevolve::isActive(void) +bool CmdPartRevolve::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1464,7 +1464,7 @@ void CmdPartFillet::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskFilletEdges(nullptr)); } -bool CmdPartFillet::isActive(void) +bool CmdPartFillet::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1492,7 +1492,7 @@ void CmdPartChamfer::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskChamferEdges(nullptr)); } -bool CmdPartChamfer::isActive(void) +bool CmdPartChamfer::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1520,7 +1520,7 @@ void CmdPartMirror::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskMirroring()); } -bool CmdPartMirror::isActive(void) +bool CmdPartMirror::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1557,7 +1557,7 @@ void CmdPartCrossSections::activated(int iMsg) Gui::Control().showDialog(dlg); } -bool CmdPartCrossSections::isActive(void) +bool CmdPartCrossSections::isActive() { bool hasShapes = PartGui::hasShapesInSelection(); return (hasShapes && !Gui::Control().activeDialog()); @@ -1587,7 +1587,7 @@ void CmdPartBuilder::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskShapeBuilder()); } -bool CmdPartBuilder::isActive(void) +bool CmdPartBuilder::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1616,7 +1616,7 @@ void CmdPartLoft::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskLoft()); } -bool CmdPartLoft::isActive(void) +bool CmdPartLoft::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1645,7 +1645,7 @@ void CmdPartSweep::activated(int iMsg) Gui::Control().showDialog(new PartGui::TaskSweep()); } -bool CmdPartSweep::isActive(void) +bool CmdPartSweep::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -1701,7 +1701,7 @@ void CmdPartOffset::activated(int iMsg) copyVisual(offset.c_str(), "PointColor", shape->getNameInDocument()); } -bool CmdPartOffset::isActive(void) +bool CmdPartOffset::isActive() { { bool hasShapes = PartGui::hasShapesInSelection(); @@ -1767,7 +1767,7 @@ void CmdPartOffset2D::activated(int iMsg) copyVisual(offset.c_str(), "PointColor", shape->getNameInDocument()); } -bool CmdPartOffset2D::isActive(void) +bool CmdPartOffset2D::isActive() { bool hasShapes = PartGui::hasShapesInSelection(); std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); @@ -1810,7 +1810,7 @@ void CmdPartCompOffset::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdPartCompOffset::createAction(void) +Gui::Action * CmdPartCompOffset::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1860,7 +1860,7 @@ void CmdPartCompOffset::languageChange() } } -bool CmdPartCompOffset::isActive(void) +bool CmdPartCompOffset::isActive() { bool hasShapes = PartGui::hasShapesInSelection(); std::vector docobjs = Gui::Selection().getObjectsOfType(App::DocumentObject::getClassTypeId()); @@ -1901,7 +1901,7 @@ void CmdPartThickness::activated(int iMsg) topoShape = Part::Feature::getTopoShape(obj); if (!topoShape.isNull()) { for (std::vector::const_iterator it = subnames.begin(); it != subnames.end(); ++it) { - subShapes.push_back(topoShape.getSubShape(subnames[0].c_str())); + subShapes.emplace_back(topoShape.getSubShape(subnames[0].c_str())); } for (std::vector::iterator it = subShapes.begin(); it != subShapes.end(); ++it) { TopoDS_Shape dsShape = (*it).getShape(); @@ -1953,7 +1953,7 @@ void CmdPartThickness::activated(int iMsg) copyVisual(thick.c_str(), "PointColor", obj->getNameInDocument()); } -bool CmdPartThickness::isActive(void) +bool CmdPartThickness::isActive() { Base::Type partid = Base::Type::fromName("Part::Feature"); bool objectsSelected = Gui::Selection().countObjectsOfType(partid, nullptr, Gui::ResolveMode::FollowLink) > 0; @@ -2045,7 +2045,7 @@ void CmdShapeInfo::activated(int iMsg) // } } -bool CmdShapeInfo::isActive(void) +bool CmdShapeInfo::isActive() { App::Document* doc = App::GetApplication().getActiveDocument(); if (!doc || doc->countObjectsOfType(Part::Feature::getClassTypeId()) == 0) @@ -2093,7 +2093,7 @@ void CmdPartRuledSurface::activated(int iMsg) } if (ok && selobjs.size() <= 2) { - if (selobjs.size() >= 1) { + if (!selobjs.empty()) { const std::vector& subnames1= selobjs[0].getSubNames(); docobj1 = selobjs[0].getObject(); obj1 = docobj1->getNameInDocument(); @@ -2103,7 +2103,7 @@ void CmdPartRuledSurface::activated(int iMsg) ok = false; } if (ok && subnames1.size() <= 2) { - if (subnames1.size() >= 1) { + if (!subnames1.empty()) { curve1 = Part::Feature::getTopoShape(docobj1, subnames1[0].c_str(), true /*need element*/).getShape(); link1 = subnames1[0]; } @@ -2111,7 +2111,7 @@ void CmdPartRuledSurface::activated(int iMsg) curve2 = Part::Feature::getTopoShape(docobj1, subnames1[1].c_str(), true /*need element*/).getShape(); link2 = subnames1[1]; } - if (subnames1.size() == 0) { + if (subnames1.empty()) { curve1 = shape1.getShape(); } } else { @@ -2131,7 +2131,7 @@ void CmdPartRuledSurface::activated(int iMsg) curve2 = Part::Feature::getTopoShape(docobj2, subnames2[0].c_str(), true /*need element*/).getShape(); link2 = subnames2[0]; } else { - if (subnames2.size() == 0) { + if (subnames2.empty()) { curve2 = shape2.getShape(); } } @@ -2162,7 +2162,7 @@ void CmdPartRuledSurface::activated(int iMsg) updateActive(); } -bool CmdPartRuledSurface::isActive(void) +bool CmdPartRuledSurface::isActive() { return getActiveGuiDocument(); } @@ -2194,7 +2194,7 @@ void CmdCheckGeometry::activated(int iMsg) Gui::Control().showDialog(dlg); } -bool CmdCheckGeometry::isActive(void) +bool CmdCheckGeometry::isActive() { bool hasShapes = PartGui::hasShapesInSelection(); return (hasShapes && !Gui::Control().activeDialog()); @@ -2232,7 +2232,7 @@ void CmdColorPerFace::activated(int iMsg) vp->changeFaceColors(); } -bool CmdColorPerFace::isActive(void) +bool CmdColorPerFace::isActive() { Base::Type partid = Base::Type::fromName("Part::Feature"); bool objectSelected = Gui::Selection().countObjectsOfType(partid) == 1; @@ -2265,7 +2265,7 @@ void CmdMeasureLinear::activated(int iMsg) PartGui::goDimensionLinearRoot(); } -bool CmdMeasureLinear::isActive(void) +bool CmdMeasureLinear::isActive() { return hasActiveDocument(); } @@ -2294,7 +2294,7 @@ void CmdMeasureAngular::activated(int iMsg) PartGui::goDimensionAngularRoot(); } -bool CmdMeasureAngular::isActive(void) +bool CmdMeasureAngular::isActive() { return hasActiveDocument(); } @@ -2324,7 +2324,7 @@ void CmdMeasureRefresh::activated(int iMsg) PartGui::refreshDimensions(); } -bool CmdMeasureRefresh::isActive(void) +bool CmdMeasureRefresh::isActive() { return hasActiveDocument(); } @@ -2353,7 +2353,7 @@ void CmdMeasureClearAll::activated(int iMsg) PartGui::eraseAllDimensions(); } -bool CmdMeasureClearAll::isActive(void) +bool CmdMeasureClearAll::isActive() { return hasActiveDocument(); } @@ -2390,7 +2390,7 @@ void CmdMeasureToggleAll::activated(int iMsg) group->SetBool("DimensionsVisible", true); } -bool CmdMeasureToggleAll::isActive(void) +bool CmdMeasureToggleAll::isActive() { return hasActiveDocument(); } @@ -2421,7 +2421,7 @@ void CmdMeasureToggle3d::activated(int iMsg) PartGui::toggle3d(); } -bool CmdMeasureToggle3d::isActive(void) +bool CmdMeasureToggle3d::isActive() { return hasActiveDocument(); } @@ -2453,7 +2453,7 @@ void CmdMeasureToggleDelta::activated(int iMsg) PartGui::toggleDelta(); } -bool CmdMeasureToggleDelta::isActive(void) +bool CmdMeasureToggleDelta::isActive() { return hasActiveDocument(); } @@ -2484,7 +2484,7 @@ void CmdBoxSelection::activated(int iMsg) sel->start(TopAbs_FACE); } -bool CmdBoxSelection::isActive(void) +bool CmdBoxSelection::isActive() { return hasActiveDocument(); } @@ -2516,7 +2516,7 @@ void CmdPartProjectionOnSurface::activated(int iMsg) Gui::Control().showDialog(dlg); } -bool CmdPartProjectionOnSurface::isActive(void) +bool CmdPartProjectionOnSurface::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -2540,7 +2540,7 @@ CmdPartSectionCut::CmdPartSectionCut() eType = AlterDoc | Alter3DView; } -Gui::Action* CmdPartSectionCut::createAction(void) +Gui::Action* CmdPartSectionCut::createAction() { Gui::Action* pcAction = (Gui::Action*)Gui::Command::createAction(); #if 0 @@ -2558,14 +2558,14 @@ void CmdPartSectionCut::activated(int iMsg) } } -bool CmdPartSectionCut::isActive(void) +bool CmdPartSectionCut::isActive() { return hasActiveDocument(); } //--------------------------------------------------------------- -void CreatePartCommands(void) +void CreatePartCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Part/Gui/CommandSimple.cpp b/src/Mod/Part/Gui/CommandSimple.cpp index 87263d5a99..72dfd89aa9 100644 --- a/src/Mod/Part/Gui/CommandSimple.cpp +++ b/src/Mod/Part/Gui/CommandSimple.cpp @@ -81,7 +81,7 @@ void CmdPartSimpleCylinder::activated(int iMsg) } } -bool CmdPartSimpleCylinder::isActive(void) +bool CmdPartSimpleCylinder::isActive() { if (getActiveGuiDocument()) return true; @@ -114,7 +114,7 @@ void CmdPartShapeFromMesh::activated(int iMsg) dlg.exec(); } -bool CmdPartShapeFromMesh::isActive(void) +bool CmdPartShapeFromMesh::isActive() { Base::Type meshid = Base::Type::fromName("Mesh::Feature"); return Gui::Selection().countObjectsOfType(meshid) > 0; @@ -163,7 +163,7 @@ void CmdPartPointsFromMesh::activated(int iMsg) commitCommand(); } -bool CmdPartPointsFromMesh::isActive(void) +bool CmdPartPointsFromMesh::isActive() { Base::Type meshid = Base::Type::fromName("Mesh::Feature"); return Gui::Selection().countObjectsOfType(meshid) > 0; @@ -239,7 +239,7 @@ void CmdPartSimpleCopy::activated(int iMsg) _copyShape("Simple copy",true); } -bool CmdPartSimpleCopy::isActive(void) +bool CmdPartSimpleCopy::isActive() { return Gui::Selection().hasSelection(); } @@ -267,7 +267,7 @@ void CmdPartTransformedCopy::activated(int iMsg) _copyShape("Transformed copy",false); } -bool CmdPartTransformedCopy::isActive(void) +bool CmdPartTransformedCopy::isActive() { return Gui::Selection().hasSelection(); } @@ -295,7 +295,7 @@ void CmdPartElementCopy::activated(int iMsg) _copyShape("Element copy",false,true); } -bool CmdPartElementCopy::isActive(void) +bool CmdPartElementCopy::isActive() { return Gui::Selection().hasSelection(); } @@ -355,7 +355,7 @@ void CmdPartRefineShape::activated(int iMsg) } } -bool CmdPartRefineShape::isActive(void) +bool CmdPartRefineShape::isActive() { return Gui::Selection().hasSelection(); } @@ -421,7 +421,7 @@ void CmdPartDefeaturing::activated(int iMsg) updateActive(); } -bool CmdPartDefeaturing::isActive(void) +bool CmdPartDefeaturing::isActive() { Base::Type partid = Base::Type::fromName("Part::Feature"); std::vector objs = Gui::Selection().getSelectionEx(nullptr, partid); @@ -439,7 +439,7 @@ bool CmdPartDefeaturing::isActive(void) //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void CreateSimplePartCommands(void) +void CreateSimplePartCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPartSimpleCylinder()); diff --git a/src/Mod/Part/Gui/CrossSections.cpp b/src/Mod/Part/Gui/CrossSections.cpp index c31f2b458a..1a7e9196b2 100644 --- a/src/Mod/Part/Gui/CrossSections.cpp +++ b/src/Mod/Part/Gui/CrossSections.cpp @@ -20,46 +20,41 @@ * * ***************************************************************************/ - #include "PreCompiled.h" + #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include # include # include -# include # include -# include -# include + +# include +# include +# include +# include + # include # include # include -# include # include # include #endif -#include "ui_CrossSections.h" -#include "CrossSections.h" -#include -#include #include -#include -#include +#include +#include #include +#include #include #include #include #include -#include -#include -#include +#include +#include +#include + +#include "CrossSections.h" +#include "ui_CrossSections.h" + using namespace PartGui; namespace bp = boost::placeholders; @@ -84,19 +79,19 @@ public: this->pcRoot->addChild(coords); this->pcRoot->addChild(planes); } - ~ViewProviderCrossSections() + ~ViewProviderCrossSections() override { coords->unref(); planes->unref(); } - void updateData(const App::Property*) + void updateData(const App::Property*) override { } - const char* getDefaultDisplayMode() const + const char* getDefaultDisplayMode() const override { return ""; } - std::vector getDisplayModes(void) const + std::vector getDisplayModes(void) const override { return std::vector(); } @@ -260,8 +255,8 @@ void CrossSections::apply() Gui::Command::runCommand(Gui::Command::App, QString::fromLatin1( "wires=list()\n" "shape=FreeCAD.getDocument(\"%1\").%2.Shape\n") - .arg(QLatin1String(doc->getName())) - .arg(QLatin1String((*it)->getNameInDocument())).toLatin1()); + .arg(QLatin1String(doc->getName()), + QLatin1String((*it)->getNameInDocument())).toLatin1()); for (std::vector::iterator jt = d.begin(); jt != d.end(); ++jt) { Gui::Command::runCommand(Gui::Command::App, QString::fromLatin1( @@ -277,8 +272,8 @@ void CrossSections::apply() "slice.Shape=comp\n" "slice.purgeTouched()\n" "del slice,comp,wires,shape") - .arg(QLatin1String(doc->getName())) - .arg(QLatin1String(s.c_str())).toLatin1()); + .arg(QLatin1String(doc->getName()), + QLatin1String(s.c_str())).toLatin1()); seq.next(); } diff --git a/src/Mod/Part/Gui/CrossSections.h b/src/Mod/Part/Gui/CrossSections.h index e5e003e3af..104e591c99 100644 --- a/src/Mod/Part/Gui/CrossSections.h +++ b/src/Mod/Part/Gui/CrossSections.h @@ -23,12 +23,14 @@ #ifndef PARTGUI_CROSSSECTIONS_H #define PARTGUI_CROSSSECTIONS_H -#include -#include -#include #include #include +#include +#include +#include + + namespace Gui { class View3DInventor; } @@ -44,14 +46,14 @@ class CrossSections : public QDialog enum Plane { XY, XZ, YZ }; public: - CrossSections(const Base::BoundBox3d& bb, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~CrossSections(); - void accept(); + explicit CrossSections(const Base::BoundBox3d& bb, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~CrossSections() override; + void accept() override; void apply(); protected: - void changeEvent(QEvent *e); - void keyPressEvent(QKeyEvent*); + void changeEvent(QEvent *e) override; + void keyPressEvent(QKeyEvent*) override; private Q_SLOTS: void on_xyPlane_clicked(); @@ -82,14 +84,14 @@ class TaskCrossSections : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskCrossSections(const Base::BoundBox3d& bb); - ~TaskCrossSections(); + explicit TaskCrossSections(const Base::BoundBox3d& bb); + ~TaskCrossSections() override; public: - bool accept(); - void clicked(int id); + bool accept() override; + void clicked(int id) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Part/Gui/DlgBooleanOperation.cpp b/src/Mod/Part/Gui/DlgBooleanOperation.cpp index 11f144e1aa..9d3fa9fa74 100644 --- a/src/Mod/Part/Gui/DlgBooleanOperation.cpp +++ b/src/Mod/Part/Gui/DlgBooleanOperation.cpp @@ -52,11 +52,11 @@ namespace PartGui { class BooleanOperationItem : public QTreeWidgetItem { public: - BooleanOperationItem(int type = Type) + explicit BooleanOperationItem(int type = Type) : QTreeWidgetItem(type) { } - void setData (int column, int role, const QVariant & value) + void setData (int column, int role, const QVariant & value) override { QTreeWidgetItem::setData(column, role, value); if (role == Qt::CheckStateRole && value.toBool()) { diff --git a/src/Mod/Part/Gui/DlgBooleanOperation.h b/src/Mod/Part/Gui/DlgBooleanOperation.h index 1f08df86f1..cc3bacd37c 100644 --- a/src/Mod/Part/Gui/DlgBooleanOperation.h +++ b/src/Mod/Part/Gui/DlgBooleanOperation.h @@ -42,8 +42,8 @@ class DlgBooleanOperation : public QWidget Q_OBJECT public: - DlgBooleanOperation(QWidget* parent = nullptr); - ~DlgBooleanOperation(); + explicit DlgBooleanOperation(QWidget* parent = nullptr); + ~DlgBooleanOperation() override; void accept(); private: @@ -54,7 +54,7 @@ private: bool hasSolids(const App::DocumentObject*) const; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; public Q_SLOTS: void on_swapButton_clicked(); @@ -75,16 +75,16 @@ class TaskBooleanOperation : public Gui::TaskView::TaskDialog public: TaskBooleanOperation(); - ~TaskBooleanOperation(); + ~TaskBooleanOperation() override; public: - void clicked(int); + void clicked(int) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Apply | QDialogButtonBox::Close; } - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return true; } - virtual bool needsFullSpace() const + bool needsFullSpace() const override { return true; } private: diff --git a/src/Mod/Part/Gui/DlgExtrusion.cpp b/src/Mod/Part/Gui/DlgExtrusion.cpp index 13f6931f03..890a264394 100644 --- a/src/Mod/Part/Gui/DlgExtrusion.cpp +++ b/src/Mod/Part/Gui/DlgExtrusion.cpp @@ -67,7 +67,7 @@ public: { canSelect = false; } - bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override { this->canSelect = false; @@ -276,7 +276,7 @@ void DlgExtrusion::onSelectionChanged(const Gui::SelectionChanges& msg) App::DocumentObject& DlgExtrusion::getShapeToExtrude() const { std::vector objs = this->getShapesToExtrude(); - if (objs.size() == 0) + if (objs.empty()) throw Base::ValueError("No shapes selected"); return *(objs[0]); } @@ -553,7 +553,7 @@ void DlgExtrusion::getAxisLink(App::PropertyLinkSub& lnk) const return; } else if (parts.size() == 2) { std::vector subs; - subs.push_back(std::string(parts[1].toLatin1().constData())); + subs.emplace_back(parts[1].toLatin1().constData()); lnk.setValue(obj,subs); } } @@ -702,7 +702,7 @@ void DlgExtrusion::writeParametersToFeature(App::DocumentObject &feature, App::D App::PropertyLinkSub lnk; this->getAxisLink(lnk); std::stringstream linkstr; - if(lnk.getValue() == nullptr){ + if (!lnk.getValue()) { linkstr << "None"; } else { linkstr << "(App.getDocument(\"" << lnk.getValue()->getDocument()->getName() <<"\")." << lnk.getValue()->getNameInDocument(); diff --git a/src/Mod/Part/Gui/DlgExtrusion.h b/src/Mod/Part/Gui/DlgExtrusion.h index 86426a67f0..0490eab73c 100644 --- a/src/Mod/Part/Gui/DlgExtrusion.h +++ b/src/Mod/Part/Gui/DlgExtrusion.h @@ -28,6 +28,7 @@ #include #include +#include class TopoDS_Shape; @@ -40,10 +41,10 @@ class DlgExtrusion : public QDialog, public Gui::SelectionObserver public: DlgExtrusion(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgExtrusion(); - void accept(); + ~DlgExtrusion() override; + void accept() override; void apply(); - void reject(); + void reject() override; Base::Vector3d getDir() const; void setDir(Base::Vector3d newDir); @@ -64,8 +65,8 @@ public: protected: void findShapes(); bool canExtrude(const TopoDS_Shape&) const; - void changeEvent(QEvent *e); - void keyPressEvent(QKeyEvent*); + void changeEvent(QEvent *e) override; + void keyPressEvent(QKeyEvent*) override; private Q_SLOTS: void on_rbDirModeCustom_toggled(bool on); @@ -81,7 +82,7 @@ private Q_SLOTS: private: ///updates enabling of controls void on_DirMode_changed(); - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; ///returns link to any of selected source shapes. Throws if nothing is selected for extrusion. App::DocumentObject& getShapeToExtrude() const; ///if dirMode is not custom, it tries to compute the actual extrusion direction. Also, it does some auto-magic manipulation of length value. @@ -103,14 +104,14 @@ class TaskExtrusion : public Gui::TaskView::TaskDialog public: TaskExtrusion(); - ~TaskExtrusion(); + ~TaskExtrusion() override; public: - bool accept(); - bool reject(); - void clicked(int); + bool accept() override; + bool reject() override; + void clicked(int) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Close; } private: diff --git a/src/Mod/Part/Gui/DlgFilletEdges.cpp b/src/Mod/Part/Gui/DlgFilletEdges.cpp index 06bfc7f55f..f204995f6a 100644 --- a/src/Mod/Part/Gui/DlgFilletEdges.cpp +++ b/src/Mod/Part/Gui/DlgFilletEdges.cpp @@ -131,7 +131,7 @@ FilletRadiusModel::FilletRadiusModel(QObject * parent) : QStandardItemModel(pare void FilletRadiusModel::updateCheckStates() { // See http://www.qtcentre.org/threads/18856-Checkboxes-in-Treeview-do-not-get-refreshed?s=b0fea2bfc66da1098413ae9f2a651a68&p=93201#post93201 - /*emit*/ layoutChanged(); + Q_EMIT layoutChanged(); } Qt::ItemFlags FilletRadiusModel::flags (const QModelIndex & index) const @@ -146,7 +146,7 @@ bool FilletRadiusModel::setData (const QModelIndex & index, const QVariant & val { bool ok = QStandardItemModel::setData(index, value, role); if (role == Qt::CheckStateRole) { - toggleCheckState(index); + Q_EMIT toggleCheckState(index); } return ok; } @@ -170,7 +170,7 @@ namespace PartGui { bool allowEdge; App::DocumentObject*& object; public: - EdgeFaceSelection(App::DocumentObject*& obj) + explicit EdgeFaceSelection(App::DocumentObject*& obj) : Gui::SelectionFilterGate(nullPointer()), allowEdge(true), object(obj) { } @@ -182,7 +182,7 @@ namespace PartGui { { allowEdge = false; } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override { if (pObj != this->object) return false; @@ -214,7 +214,7 @@ namespace PartGui { { public: App::DocumentObject* obj; - SelectionObjectCompare(App::DocumentObject* obj) : obj(obj) + explicit SelectionObjectCompare(App::DocumentObject* obj) : obj(obj) { } bool operator()(const Gui::SelectionObject& sel) const @@ -431,7 +431,7 @@ void DlgFilletEdges::onSelectEdge(const QString& subelement, int type) void DlgFilletEdges::onSelectEdgesOfFace(const QString& subelement, int type) { bool ok; - int index = subelement.mid(4).toInt(&ok); + int index = subelement.midRef(4).toInt(&ok); if (ok) { try { const TopoDS_Shape& face = d->all_faces.FindKey(index); @@ -914,7 +914,7 @@ bool DlgFilletEdges::accept() code = QString::fromLatin1( "FreeCAD.ActiveDocument.addObject(\"%1\",\"%2\")\n" "FreeCAD.ActiveDocument.%2.Base = FreeCAD.ActiveDocument.%3\n") - .arg(type).arg(name).arg(shape); + .arg(type, name, shape); } code += QString::fromLatin1("__fillets__ = []\n"); for (int i=0; irowCount(); ++i) { @@ -950,7 +950,7 @@ bool DlgFilletEdges::accept() "FreeCAD.ActiveDocument.%1.Edges = __fillets__\n" "del __fillets__\n" "FreeCADGui.ActiveDocument.%2.Visibility = False\n") - .arg(name).arg(shape); + .arg(name, shape); Gui::Command::runCommand(Gui::Command::App, code.toLatin1()); activeDoc->commitTransaction(); activeDoc->recompute(); diff --git a/src/Mod/Part/Gui/DlgFilletEdges.h b/src/Mod/Part/Gui/DlgFilletEdges.h index ed54db0bb1..d2c2d3b8f6 100644 --- a/src/Mod/Part/Gui/DlgFilletEdges.h +++ b/src/Mod/Part/Gui/DlgFilletEdges.h @@ -47,17 +47,17 @@ class FilletRadiusDelegate : public QItemDelegate Q_OBJECT public: - FilletRadiusDelegate(QObject *parent = nullptr); + explicit FilletRadiusDelegate(QObject *parent = nullptr); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, - const QModelIndex &index) const; + const QModelIndex &index) const override; - void setEditorData(QWidget *editor, const QModelIndex &index) const; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const; + const QModelIndex &index) const override; void updateEditorGeometry(QWidget *editor, - const QStyleOptionViewItem &option, const QModelIndex &index) const; + const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; class FilletRadiusModel : public QStandardItemModel @@ -65,12 +65,12 @@ class FilletRadiusModel : public QStandardItemModel Q_OBJECT public: - FilletRadiusModel(QObject * parent = nullptr); + explicit FilletRadiusModel(QObject * parent = nullptr); - Qt::ItemFlags flags (const QModelIndex & index) const; + Qt::ItemFlags flags (const QModelIndex & index) const override; bool setData (const QModelIndex & index, const QVariant & value, - int role = Qt::EditRole); - QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const; + int role = Qt::EditRole) override; + QVariant data(const QModelIndex&, int role = Qt::DisplayRole) const override; void updateCheckStates(); Q_SIGNALS: @@ -85,17 +85,17 @@ public: enum FilletType { FILLET, CHAMFER }; DlgFilletEdges(FilletType type, Part::FilletBase*, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgFilletEdges(); + ~DlgFilletEdges() override; bool accept(); protected: void findShapes(); void setupFillet(const std::vector&); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; virtual const char* getFilletType() const; private: - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void onDeleteObject(const App::DocumentObject&); void onDeleteDocument(const App::Document&); void onSelectEdge(const QString& subelement, int type); @@ -125,8 +125,8 @@ class FilletEdgesDialog : public QDialog public: FilletEdgesDialog(DlgFilletEdges::FilletType type, Part::FilletBase* fillet, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~FilletEdgesDialog(); - void accept(); + ~FilletEdgesDialog() override; + void accept() override; private: DlgFilletEdges* widget; @@ -137,11 +137,11 @@ class DlgChamferEdges : public DlgFilletEdges Q_OBJECT public: - DlgChamferEdges(Part::FilletBase*, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgChamferEdges(); + explicit DlgChamferEdges(Part::FilletBase*, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgChamferEdges() override; protected: - virtual const char* getFilletType() const; + const char* getFilletType() const override; }; class TaskFilletEdges : public Gui::TaskView::TaskDialog @@ -149,18 +149,18 @@ class TaskFilletEdges : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskFilletEdges(Part::Fillet*); - ~TaskFilletEdges(); + explicit TaskFilletEdges(Part::Fillet*); + ~TaskFilletEdges() override; public: - virtual void open(); - virtual void clicked(int); - virtual bool accept(); - virtual bool reject(); + void open() override; + void clicked(int) override; + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } - virtual bool needsFullSpace() const + bool needsFullSpace() const override { return true; } private: @@ -173,18 +173,18 @@ class TaskChamferEdges : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskChamferEdges(Part::Chamfer*); - ~TaskChamferEdges(); + explicit TaskChamferEdges(Part::Chamfer*); + ~TaskChamferEdges() override; public: - virtual void open(); - virtual void clicked(int); - virtual bool accept(); - virtual bool reject(); + void open() override; + void clicked(int) override; + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } - virtual bool needsFullSpace() const + bool needsFullSpace() const override { return true; } private: diff --git a/src/Mod/Part/Gui/DlgPartBoxImp.h b/src/Mod/Part/Gui/DlgPartBoxImp.h index 5180e3867b..95a8fbf3b5 100644 --- a/src/Mod/Part/Gui/DlgPartBoxImp.h +++ b/src/Mod/Part/Gui/DlgPartBoxImp.h @@ -34,8 +34,8 @@ class DlgPartBoxImp : public Gui::LocationDialogUiImp Q_OBJECT public: - DlgPartBoxImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgPartBoxImp(); + explicit DlgPartBoxImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgPartBoxImp() override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/DlgPartCylinderImp.h b/src/Mod/Part/Gui/DlgPartCylinderImp.h index 09ebbe6ec8..a83671ac5c 100644 --- a/src/Mod/Part/Gui/DlgPartCylinderImp.h +++ b/src/Mod/Part/Gui/DlgPartCylinderImp.h @@ -34,8 +34,8 @@ class DlgPartCylinderImp : public Gui::LocationDialogUiImp Q_OBJECT public: - DlgPartCylinderImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgPartCylinderImp(); + explicit DlgPartCylinderImp(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgPartCylinderImp() override; double getRadius() const; double getLength() const; diff --git a/src/Mod/Part/Gui/DlgPartImportIgesImp.h b/src/Mod/Part/Gui/DlgPartImportIgesImp.h index f514abe35f..afe22a5980 100644 --- a/src/Mod/Part/Gui/DlgPartImportIgesImp.h +++ b/src/Mod/Part/Gui/DlgPartImportIgesImp.h @@ -33,8 +33,8 @@ class DlgPartImportIgesImp : public QDialog Q_OBJECT public: - DlgPartImportIgesImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgPartImportIgesImp(); + explicit DlgPartImportIgesImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + ~DlgPartImportIgesImp() override; public Q_SLOTS: virtual void OnApply(); diff --git a/src/Mod/Part/Gui/DlgPartImportStepImp.h b/src/Mod/Part/Gui/DlgPartImportStepImp.h index 86539f6066..d27cf02ab8 100644 --- a/src/Mod/Part/Gui/DlgPartImportStepImp.h +++ b/src/Mod/Part/Gui/DlgPartImportStepImp.h @@ -34,8 +34,8 @@ class DlgPartImportStepImp : public QDialog Q_OBJECT public: - DlgPartImportStepImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgPartImportStepImp(); + explicit DlgPartImportStepImp( QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + ~DlgPartImportStepImp() override; public Q_SLOTS: virtual void OnApply(); diff --git a/src/Mod/Part/Gui/DlgPrimitives.cpp b/src/Mod/Part/Gui/DlgPrimitives.cpp index adfc5e2749..0b1c9cacd9 100644 --- a/src/Mod/Part/Gui/DlgPrimitives.cpp +++ b/src/Mod/Part/Gui/DlgPrimitives.cpp @@ -71,8 +71,7 @@ namespace PartGui { QString activeObjectName = QString::fromLatin1(activePart->getNameInDocument()); return QString::fromLatin1("App.ActiveDocument.getObject('%1\')." "addObject(App.ActiveDocument.getObject('%2\'))\n") - .arg(activeObjectName) - .arg(objectName); + .arg(activeObjectName, objectName); } return QString::fromLatin1("# Object %1 created at document root").arg(objectName); } @@ -165,13 +164,13 @@ public: CircleFromThreePoints() : Picker() { } - bool pickedPoint(const SoPickedPoint * point) + bool pickedPoint(const SoPickedPoint * point) override { SbVec3f pnt = point->getPoint(); - points.push_back(gp_Pnt(pnt[0],pnt[1],pnt[2])); + points.emplace_back(pnt[0],pnt[1],pnt[2]); return points.size() == 3; } - QString command(App::Document* doc) const + QString command(App::Document* doc) const override { GC_MakeArcOfCircle arc(points[0], points[1], points[2]); if (!arc.IsDone()) @@ -726,38 +725,41 @@ void DlgPrimitives::on_buttonCircleFromThreePoints_clicked() QString DlgPrimitives::createPlane(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Plane\",\"%1\")\n" "App.ActiveDocument.%1.Length=%2\n" "App.ActiveDocument.%1.Width=%3\n" "App.ActiveDocument.%1.Placement=%4\n" "App.ActiveDocument.%1.Label='%5'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->planeLength->value())) - .arg(Base::UnitsApi::toNumber(ui->planeWidth->value())) - .arg(placement) - .arg(tr("Plane")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->planeLength->value(), format), + Base::UnitsApi::toNumber(ui->planeWidth->value(), format), + placement, + tr("Plane")); } QString DlgPrimitives::createBox(const QString& objectName, const QString& placement) const { - return QString::fromLatin1( + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); + return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Box\",\"%1\")\n" "App.ActiveDocument.%1.Length=%2\n" "App.ActiveDocument.%1.Width=%3\n" "App.ActiveDocument.%1.Height=%4\n" "App.ActiveDocument.%1.Placement=%5\n" "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->boxLength->value())) - .arg(Base::UnitsApi::toNumber(ui->boxWidth->value())) - .arg(Base::UnitsApi::toNumber(ui->boxHeight->value())) - .arg(placement) - .arg(tr("Box")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->boxLength->value(), format), + Base::UnitsApi::toNumber(ui->boxWidth->value(), format), + Base::UnitsApi::toNumber(ui->boxHeight->value(), format), + placement, + tr("Box")); } QString DlgPrimitives::createCylinder(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Cylinder\",\"%1\")\n" "App.ActiveDocument.%1.Radius=%2\n" @@ -767,18 +769,19 @@ QString DlgPrimitives::createCylinder(const QString& objectName, const QString& "App.ActiveDocument.%1.SecondAngle=%6\n" "App.ActiveDocument.%1.Placement=%7\n" "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->cylinderRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderAngle->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderXSkew->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderYSkew->value())) - .arg(placement) - .arg(tr("Cylinder")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->cylinderRadius->value(), format), + Base::UnitsApi::toNumber(ui->cylinderHeight->value(), format), + Base::UnitsApi::toNumber(ui->cylinderAngle->value(), format), + Base::UnitsApi::toNumber(ui->cylinderXSkew->value(), format), + Base::UnitsApi::toNumber(ui->cylinderYSkew->value(), format), + placement, + tr("Cylinder")); } QString DlgPrimitives::createCone(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Cone\",\"%1\")\n" "App.ActiveDocument.%1.Radius1=%2\n" @@ -787,17 +790,18 @@ QString DlgPrimitives::createCone(const QString& objectName, const QString& plac "App.ActiveDocument.%1.Angle=%5\n" "App.ActiveDocument.%1.Placement=%6\n" "App.ActiveDocument.%1.Label='%7'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->coneRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->coneRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->coneHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->coneAngle->value())) - .arg(placement) - .arg(tr("Cone")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->coneRadius1->value(), format), + Base::UnitsApi::toNumber(ui->coneRadius2->value(), format), + Base::UnitsApi::toNumber(ui->coneHeight->value(), format), + Base::UnitsApi::toNumber(ui->coneAngle->value(), format), + placement, + tr("Cone")); } QString DlgPrimitives::createSphere(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Sphere\",\"%1\")\n" "App.ActiveDocument.%1.Radius=%2\n" @@ -806,17 +810,18 @@ QString DlgPrimitives::createSphere(const QString& objectName, const QString& pl "App.ActiveDocument.%1.Angle3=%5\n" "App.ActiveDocument.%1.Placement=%6\n" "App.ActiveDocument.%1.Label='%7'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->sphereRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle2->value())) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle3->value())) - .arg(placement) - .arg(tr("Sphere")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->sphereRadius->value(), format), + Base::UnitsApi::toNumber(ui->sphereAngle1->value(), format), + Base::UnitsApi::toNumber(ui->sphereAngle2->value(), format), + Base::UnitsApi::toNumber(ui->sphereAngle3->value(), format), + placement, + tr("Sphere")); } QString DlgPrimitives::createEllipsoid(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Ellipsoid\",\"%1\")\n" "App.ActiveDocument.%1.Radius1=%2\n" @@ -827,19 +832,20 @@ QString DlgPrimitives::createEllipsoid(const QString& objectName, const QString& "App.ActiveDocument.%1.Angle3=%7\n" "App.ActiveDocument.%1.Placement=%8\n" "App.ActiveDocument.%1.Label='%9'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius3->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle2->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle3->value())) - .arg(placement) - .arg(tr("Ellipsoid")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidRadius3->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidAngle1->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidAngle2->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidAngle3->value(), format), + placement, + tr("Ellipsoid")); } QString DlgPrimitives::createTorus(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Torus\",\"%1\")\n" "App.ActiveDocument.%1.Radius1=%2\n" @@ -849,18 +855,19 @@ QString DlgPrimitives::createTorus(const QString& objectName, const QString& pla "App.ActiveDocument.%1.Angle3=%6\n" "App.ActiveDocument.%1.Placement=%7\n" "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->torusRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->torusRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->torusAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->torusAngle2->value())) - .arg(Base::UnitsApi::toNumber(ui->torusAngle3->value())) - .arg(placement) - .arg(tr("Torus")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->torusRadius1->value(), format), + Base::UnitsApi::toNumber(ui->torusRadius2->value(), format), + Base::UnitsApi::toNumber(ui->torusAngle1->value(), format), + Base::UnitsApi::toNumber(ui->torusAngle2->value(), format), + Base::UnitsApi::toNumber(ui->torusAngle3->value(), format), + placement, + tr("Torus")); } QString DlgPrimitives::createPrism(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Prism\",\"%1\")\n" "App.ActiveDocument.%1.Polygon=%2\n" @@ -870,18 +877,19 @@ QString DlgPrimitives::createPrism(const QString& objectName, const QString& pla "App.ActiveDocument.%1.SecondAngle=%6\n" "App.ActiveDocument.%1.Placement=%7\n" "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName) - .arg(ui->prismPolygon->value()) - .arg(Base::UnitsApi::toNumber(ui->prismCircumradius->value())) - .arg(Base::UnitsApi::toNumber(ui->prismHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->prismXSkew->value())) - .arg(Base::UnitsApi::toNumber(ui->prismYSkew->value())) - .arg(placement) - .arg(tr("Prism")); + .arg(objectName, + QString::number(ui->prismPolygon->value()), + Base::UnitsApi::toNumber(ui->prismCircumradius->value(), format), + Base::UnitsApi::toNumber(ui->prismHeight->value(), format), + Base::UnitsApi::toNumber(ui->prismXSkew->value(), format), + Base::UnitsApi::toNumber(ui->prismYSkew->value(), format), + placement, + tr("Prism")); } QString DlgPrimitives::createWedge(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Wedge\",\"%1\")\n" "App.ActiveDocument.%1.Xmin=%2\n" @@ -896,23 +904,24 @@ QString DlgPrimitives::createWedge(const QString& objectName, const QString& pla "App.ActiveDocument.%1.Z2max=%11\n" "App.ActiveDocument.%1.Placement=%12\n" "App.ActiveDocument.%1.Label='%13'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->wedgeXmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeYmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeX2min->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZ2min->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeXmax->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeYmax->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZmax->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeX2max->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZ2max->value())) - .arg(placement) - .arg(tr("Wedge")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->wedgeXmin->value(), format), + Base::UnitsApi::toNumber(ui->wedgeYmin->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZmin->value(), format), + Base::UnitsApi::toNumber(ui->wedgeX2min->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZ2min->value(), format), + Base::UnitsApi::toNumber(ui->wedgeXmax->value(), format), + Base::UnitsApi::toNumber(ui->wedgeYmax->value(), format)) + .arg(Base::UnitsApi::toNumber(ui->wedgeZmax->value(), format), + Base::UnitsApi::toNumber(ui->wedgeX2max->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZ2max->value(), format), + placement, + tr("Wedge")); } QString DlgPrimitives::createHelix(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Helix\",\"%1\")\n" "App.ActiveDocument.%1.Pitch=%2\n" @@ -923,18 +932,19 @@ QString DlgPrimitives::createHelix(const QString& objectName, const QString& pla "App.ActiveDocument.%1.Style=1\n" "App.ActiveDocument.%1.Placement=%7\n" "App.ActiveDocument.%1.Label='%8'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->helixPitch->value())) - .arg(Base::UnitsApi::toNumber(ui->helixHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->helixRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->helixAngle->value())) - .arg(ui->helixLocalCS->currentIndex()) - .arg(placement) - .arg(tr("Helix")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->helixPitch->value(), format), + Base::UnitsApi::toNumber(ui->helixHeight->value(), format), + Base::UnitsApi::toNumber(ui->helixRadius->value(), format), + Base::UnitsApi::toNumber(ui->helixAngle->value(), format), + QString::number(ui->helixLocalCS->currentIndex()), + placement, + tr("Helix")); } QString DlgPrimitives::createSpiral(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Spiral\",\"%1\")\n" "App.ActiveDocument.%1.Growth=%2\n" @@ -942,16 +952,17 @@ QString DlgPrimitives::createSpiral(const QString& objectName, const QString& pl "App.ActiveDocument.%1.Radius=%4\n" "App.ActiveDocument.%1.Placement=%5\n" "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->spiralGrowth->value())) - .arg(Base::UnitsApi::toNumber(ui->spiralRotation->value())) - .arg(Base::UnitsApi::toNumber(ui->spiralRadius->value())) - .arg(placement) - .arg(tr("Spiral")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->spiralGrowth->value(), format), + Base::UnitsApi::toNumber(ui->spiralRotation->value(), format), + Base::UnitsApi::toNumber(ui->spiralRadius->value(), format), + placement, + tr("Spiral")); } QString DlgPrimitives::createCircle(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Circle\",\"%1\")\n" "App.ActiveDocument.%1.Radius=%2\n" @@ -959,16 +970,17 @@ QString DlgPrimitives::createCircle(const QString& objectName, const QString& pl "App.ActiveDocument.%1.Angle2=%4\n" "App.ActiveDocument.%1.Placement=%5\n" "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->circleRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->circleAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->circleAngle2->value())) - .arg(placement) - .arg(tr("Circle")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->circleRadius->value(), format), + Base::UnitsApi::toNumber(ui->circleAngle1->value(), format), + Base::UnitsApi::toNumber(ui->circleAngle2->value(), format), + placement, + tr("Circle")); } QString DlgPrimitives::createEllipse(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Ellipse\",\"%1\")\n" "App.ActiveDocument.%1.MajorRadius=%2\n" @@ -977,17 +989,18 @@ QString DlgPrimitives::createEllipse(const QString& objectName, const QString& p "App.ActiveDocument.%1.Angle2=%5\n" "App.ActiveDocument.%1.Placement=%6\n" "App.ActiveDocument.%1.Label='%7'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->ellipseMajorRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipseMinorRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipseAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipseAngle2->value())) - .arg(placement) - .arg(tr("Ellipse")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->ellipseMajorRadius->value(), format), + Base::UnitsApi::toNumber(ui->ellipseMinorRadius->value(), format), + Base::UnitsApi::toNumber(ui->ellipseAngle1->value(), format), + Base::UnitsApi::toNumber(ui->ellipseAngle2->value(), format), + placement, + tr("Ellipse")); } QString DlgPrimitives::createVertex(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Vertex\",\"%1\")\n" "App.ActiveDocument.%1.X=%2\n" @@ -995,16 +1008,17 @@ QString DlgPrimitives::createVertex(const QString& objectName, const QString& pl "App.ActiveDocument.%1.Z=%4\n" "App.ActiveDocument.%1.Placement=%5\n" "App.ActiveDocument.%1.Label='%6'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->vertexX->value())) - .arg(Base::UnitsApi::toNumber(ui->vertexY->value())) - .arg(Base::UnitsApi::toNumber(ui->vertexZ->value())) - .arg(placement) - .arg(tr("Vertex")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->vertexX->value(), format), + Base::UnitsApi::toNumber(ui->vertexY->value(), format), + Base::UnitsApi::toNumber(ui->vertexZ->value(), format), + placement, + tr("Vertex")); } QString DlgPrimitives::createLine(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::Line\",\"%1\")\n" "App.ActiveDocument.%1.X1=%2\n" @@ -1015,30 +1029,31 @@ QString DlgPrimitives::createLine(const QString& objectName, const QString& plac "App.ActiveDocument.%1.Z2=%7\n" "App.ActiveDocument.%1.Placement=%8\n" "App.ActiveDocument.%1.Label='%9'\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->edgeX1->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeY1->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeZ1->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeX2->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeY2->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeZ2->value())) - .arg(placement) - .arg(tr("Line")); + .arg(objectName, + Base::UnitsApi::toNumber(ui->edgeX1->value(), format), + Base::UnitsApi::toNumber(ui->edgeY1->value(), format), + Base::UnitsApi::toNumber(ui->edgeZ1->value(), format), + Base::UnitsApi::toNumber(ui->edgeX2->value(), format), + Base::UnitsApi::toNumber(ui->edgeY2->value(), format), + Base::UnitsApi::toNumber(ui->edgeZ2->value(), format), + placement, + tr("Line")); } QString DlgPrimitives::createRegularPolygon(const QString& objectName, const QString& placement) const { + Base::QuantityFormat format(Base::QuantityFormat::Fixed, Base::UnitsApi::getDecimals()); return QString::fromLatin1( "App.ActiveDocument.addObject(\"Part::RegularPolygon\",\"%1\")\n" "App.ActiveDocument.%1.Polygon=%2\n" "App.ActiveDocument.%1.Circumradius=%3\n" "App.ActiveDocument.%1.Placement=%4\n" "App.ActiveDocument.%1.Label='%5'\n") - .arg(objectName) - .arg(ui->regularPolygonPolygon->value()) - .arg(Base::UnitsApi::toNumber(ui->regularPolygonCircumradius->value())) - .arg(placement) - .arg(tr("Regular polygon")); + .arg(objectName, + QString::number(ui->regularPolygonPolygon->value()), + Base::UnitsApi::toNumber(ui->regularPolygonCircumradius->value(), format), + placement, + tr("Regular polygon")); } void DlgPrimitives::createPrimitive(const QString& placement) @@ -1137,10 +1152,10 @@ QString DlgPrimitives::changePlane(const QString& objectName, const QString& pla "%1.Length=%2\n" "%1.Width=%3\n" "%1.Placement=%4\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->planeLength->value())) - .arg(Base::UnitsApi::toNumber(ui->planeWidth->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->planeLength->value()), + Base::UnitsApi::toNumber(ui->planeWidth->value()), + placement); } QString DlgPrimitives::changeBox(const QString& objectName, const QString& placement) const @@ -1150,11 +1165,11 @@ QString DlgPrimitives::changeBox(const QString& objectName, const QString& place "%1.Width=%3\n" "%1.Height=%4\n" "%1.Placement=%5\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->boxLength->value())) - .arg(Base::UnitsApi::toNumber(ui->boxWidth->value())) - .arg(Base::UnitsApi::toNumber(ui->boxHeight->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->boxLength->value()), + Base::UnitsApi::toNumber(ui->boxWidth->value()), + Base::UnitsApi::toNumber(ui->boxHeight->value()), + placement); } QString DlgPrimitives::changeCylinder(const QString& objectName, const QString& placement) const @@ -1164,11 +1179,11 @@ QString DlgPrimitives::changeCylinder(const QString& objectName, const QString& "%1.Height=%3\n" "%1.Angle=%4\n" "%1.Placement=%5\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->cylinderRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->cylinderAngle->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->cylinderRadius->value()), + Base::UnitsApi::toNumber(ui->cylinderHeight->value()), + Base::UnitsApi::toNumber(ui->cylinderAngle->value()), + placement); } QString DlgPrimitives::changeCone(const QString& objectName, const QString& placement) const @@ -1179,12 +1194,12 @@ QString DlgPrimitives::changeCone(const QString& objectName, const QString& plac "%1.Height=%4\n" "%1.Angle=%5\n" "%1.Placement=%6\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->coneRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->coneRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->coneHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->coneAngle->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->coneRadius1->value()), + Base::UnitsApi::toNumber(ui->coneRadius2->value()), + Base::UnitsApi::toNumber(ui->coneHeight->value()), + Base::UnitsApi::toNumber(ui->coneAngle->value()), + placement); } QString DlgPrimitives::changeSphere(const QString& objectName, const QString& placement) const @@ -1195,12 +1210,12 @@ QString DlgPrimitives::changeSphere(const QString& objectName, const QString& pl "%1.Angle2=%4\n" "%1.Angle3=%5\n" "%1.Placement=%6\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->sphereRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle2->value())) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle3->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->sphereRadius->value()), + Base::UnitsApi::toNumber(ui->sphereAngle1->value()), + Base::UnitsApi::toNumber(ui->sphereAngle2->value()), + Base::UnitsApi::toNumber(ui->sphereAngle3->value()), + placement); } QString DlgPrimitives::changeEllipsoid(const QString& objectName, const QString& placement) const @@ -1213,14 +1228,14 @@ QString DlgPrimitives::changeEllipsoid(const QString& objectName, const QString& "%1.Angle2=%6\n" "%1.Angle3=%7\n" "%1.Placement=%8\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius3->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle2->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle3->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value()), + Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value()), + Base::UnitsApi::toNumber(ui->ellipsoidRadius3->value()), + Base::UnitsApi::toNumber(ui->ellipsoidAngle1->value()), + Base::UnitsApi::toNumber(ui->ellipsoidAngle2->value()), + Base::UnitsApi::toNumber(ui->ellipsoidAngle3->value()), + placement); } QString DlgPrimitives::changeTorus(const QString& objectName, const QString& placement) const @@ -1232,13 +1247,13 @@ QString DlgPrimitives::changeTorus(const QString& objectName, const QString& pla "%1.Angle2=%5\n" "%1.Angle3=%6\n" "%1.Placement=%7\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->torusRadius1->value())) - .arg(Base::UnitsApi::toNumber(ui->torusRadius2->value())) - .arg(Base::UnitsApi::toNumber(ui->torusAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->torusAngle2->value())) - .arg(Base::UnitsApi::toNumber(ui->torusAngle3->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->torusRadius1->value()), + Base::UnitsApi::toNumber(ui->torusRadius2->value()), + Base::UnitsApi::toNumber(ui->torusAngle1->value()), + Base::UnitsApi::toNumber(ui->torusAngle2->value()), + Base::UnitsApi::toNumber(ui->torusAngle3->value()), + placement); } QString DlgPrimitives::changePrism(const QString& objectName, const QString& placement) const @@ -1250,13 +1265,13 @@ QString DlgPrimitives::changePrism(const QString& objectName, const QString& pla "%1.FirstAngle=%5\n" "%1.SecondAngle=%6\n" "%1.Placement=%7\n") - .arg(objectName) - .arg(ui->prismPolygon->value()) - .arg(Base::UnitsApi::toNumber(ui->prismCircumradius->value())) - .arg(Base::UnitsApi::toNumber(ui->prismHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->prismXSkew->value())) - .arg(Base::UnitsApi::toNumber(ui->prismYSkew->value())) - .arg(placement); + .arg(objectName, + QString::number(ui->prismPolygon->value()), + Base::UnitsApi::toNumber(ui->prismCircumradius->value()), + Base::UnitsApi::toNumber(ui->prismHeight->value()), + Base::UnitsApi::toNumber(ui->prismXSkew->value()), + Base::UnitsApi::toNumber(ui->prismYSkew->value()), + placement); } QString DlgPrimitives::changeWedge(const QString& objectName, const QString& placement) const @@ -1273,18 +1288,18 @@ QString DlgPrimitives::changeWedge(const QString& objectName, const QString& pla "%1.X2max=%10\n" "%1.Z2max=%11\n" "%1.Placement=%12\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->wedgeXmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeYmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeX2min->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZ2min->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeXmax->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeYmax->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZmax->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeX2max->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeZ2max->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->wedgeXmin->value()), + Base::UnitsApi::toNumber(ui->wedgeYmin->value()), + Base::UnitsApi::toNumber(ui->wedgeZmin->value()), + Base::UnitsApi::toNumber(ui->wedgeX2min->value()), + Base::UnitsApi::toNumber(ui->wedgeZ2min->value()), + Base::UnitsApi::toNumber(ui->wedgeXmax->value()), + Base::UnitsApi::toNumber(ui->wedgeYmax->value()), + Base::UnitsApi::toNumber(ui->wedgeZmax->value())) + .arg(Base::UnitsApi::toNumber(ui->wedgeX2max->value()), + Base::UnitsApi::toNumber(ui->wedgeZ2max->value()), + placement); } QString DlgPrimitives::changeHelix(const QString& objectName, const QString& placement) const @@ -1296,13 +1311,13 @@ QString DlgPrimitives::changeHelix(const QString& objectName, const QString& pla "%1.Angle=%5\n" "%1.LocalCoord=%6\n" "%1.Placement=%7\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->helixPitch->value())) - .arg(Base::UnitsApi::toNumber(ui->helixHeight->value())) - .arg(Base::UnitsApi::toNumber(ui->helixRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->helixAngle->value())) - .arg(ui->helixLocalCS->currentIndex()) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->helixPitch->value()), + Base::UnitsApi::toNumber(ui->helixHeight->value()), + Base::UnitsApi::toNumber(ui->helixRadius->value()), + Base::UnitsApi::toNumber(ui->helixAngle->value()), + QString::number(ui->helixLocalCS->currentIndex()), + placement); } QString DlgPrimitives::changeSpiral(const QString& objectName, const QString& placement) const @@ -1312,11 +1327,11 @@ QString DlgPrimitives::changeSpiral(const QString& objectName, const QString& pl "%1.Rotations=%3\n" "%1.Radius=%4\n" "%1.Placement=%5\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->spiralGrowth->value())) - .arg(Base::UnitsApi::toNumber(ui->spiralRotation->value())) - .arg(Base::UnitsApi::toNumber(ui->spiralRadius->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->spiralGrowth->value()), + Base::UnitsApi::toNumber(ui->spiralRotation->value()), + Base::UnitsApi::toNumber(ui->spiralRadius->value()), + placement); } QString DlgPrimitives::changeCircle(const QString& objectName, const QString& placement) const @@ -1326,11 +1341,11 @@ QString DlgPrimitives::changeCircle(const QString& objectName, const QString& pl "%1.Angle1=%3\n" "%1.Angle2=%4\n" "%1.Placement=%5\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->circleRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->circleAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->circleAngle2->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->circleRadius->value()), + Base::UnitsApi::toNumber(ui->circleAngle1->value()), + Base::UnitsApi::toNumber(ui->circleAngle2->value()), + placement); } QString DlgPrimitives::changeEllipse(const QString& objectName, const QString& placement) const @@ -1341,12 +1356,12 @@ QString DlgPrimitives::changeEllipse(const QString& objectName, const QString& p "%1.Angle1=%4\n" "%1.Angle2=%5\n" "%1.Placement=%6\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->ellipseMajorRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipseMinorRadius->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipseAngle1->value())) - .arg(Base::UnitsApi::toNumber(ui->ellipseAngle2->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->ellipseMajorRadius->value()), + Base::UnitsApi::toNumber(ui->ellipseMinorRadius->value()), + Base::UnitsApi::toNumber(ui->ellipseAngle1->value()), + Base::UnitsApi::toNumber(ui->ellipseAngle2->value()), + placement); } QString DlgPrimitives::changeVertex(const QString& objectName, const QString& placement) const @@ -1356,11 +1371,11 @@ QString DlgPrimitives::changeVertex(const QString& objectName, const QString& pl "%1.Y=%3\n" "%1.Z=%4\n" "%1.Placement=%5\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->vertexX->value())) - .arg(Base::UnitsApi::toNumber(ui->vertexY->value())) - .arg(Base::UnitsApi::toNumber(ui->vertexZ->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->vertexX->value()), + Base::UnitsApi::toNumber(ui->vertexY->value()), + Base::UnitsApi::toNumber(ui->vertexZ->value()), + placement); } QString DlgPrimitives::changeLine(const QString& objectName, const QString& placement) const @@ -1373,14 +1388,14 @@ QString DlgPrimitives::changeLine(const QString& objectName, const QString& plac "%1.Y2=%6\n" "%1.Z2=%7\n" "%1.Placement=%8\n") - .arg(objectName) - .arg(Base::UnitsApi::toNumber(ui->edgeX1->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeY1->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeZ1->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeX2->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeY2->value())) - .arg(Base::UnitsApi::toNumber(ui->edgeZ2->value())) - .arg(placement); + .arg(objectName, + Base::UnitsApi::toNumber(ui->edgeX1->value()), + Base::UnitsApi::toNumber(ui->edgeY1->value()), + Base::UnitsApi::toNumber(ui->edgeZ1->value()), + Base::UnitsApi::toNumber(ui->edgeX2->value()), + Base::UnitsApi::toNumber(ui->edgeY2->value()), + Base::UnitsApi::toNumber(ui->edgeZ2->value()), + placement); } QString DlgPrimitives::changeRegularPolygon(const QString& objectName, const QString& placement) const @@ -1389,10 +1404,10 @@ QString DlgPrimitives::changeRegularPolygon(const QString& objectName, const QSt "%1.Polygon=%2\n" "%1.Circumradius=%3\n" "%1.Placement=%4\n") - .arg(objectName) - .arg(ui->regularPolygonPolygon->value()) - .arg(Base::UnitsApi::toNumber(ui->regularPolygonCircumradius->value())) - .arg(placement); + .arg(objectName, + QString::number(ui->regularPolygonPolygon->value()), + Base::UnitsApi::toNumber(ui->regularPolygonCircumradius->value()), + placement); } void DlgPrimitives::accept(const QString& placement) @@ -1403,8 +1418,8 @@ void DlgPrimitives::accept(const QString& placement) App::Document* doc = featurePtr->getDocument(); Base::Type type = featurePtr->getTypeId(); QString objectName = QString::fromLatin1("App.getDocument(\"%1\").%2") - .arg(QString::fromLatin1(doc->getName())) - .arg(QString::fromLatin1(featurePtr->getNameInDocument())); + .arg(QString::fromLatin1(doc->getName()), + QString::fromLatin1(featurePtr->getNameInDocument())); // read values from the properties if (type == Part::Plane::getClassTypeId()) { diff --git a/src/Mod/Part/Gui/DlgPrimitives.h b/src/Mod/Part/Gui/DlgPrimitives.h index cf5d46b973..80b62e97a9 100644 --- a/src/Mod/Part/Gui/DlgPrimitives.h +++ b/src/Mod/Part/Gui/DlgPrimitives.h @@ -67,8 +67,8 @@ class DlgPrimitives : public QWidget Q_OBJECT public: - DlgPrimitives(QWidget* parent = nullptr, Part::Primitive* feature = nullptr); - ~DlgPrimitives(); + explicit DlgPrimitives(QWidget* parent = nullptr, Part::Primitive* feature = nullptr); + ~DlgPrimitives() override; void createPrimitive(const QString&); void accept(const QString&); void reject(); @@ -142,8 +142,8 @@ class Location : public QWidget Q_OBJECT public: - Location(QWidget* parent = nullptr, Part::Feature* feature = nullptr); - ~Location(); + explicit Location(QWidget* parent = nullptr, Part::Feature* feature = nullptr); + ~Location() override; QString toPlacement() const; private Q_SLOTS: @@ -164,13 +164,13 @@ class TaskPrimitives : public Gui::TaskView::TaskDialog public: TaskPrimitives(); - ~TaskPrimitives(); + ~TaskPrimitives() override; public: - bool accept(); - bool reject(); - QDialogButtonBox::StandardButtons getStandardButtons() const; - void modifyStandardButtons(QDialogButtonBox*); + bool accept() override; + bool reject() override; + QDialogButtonBox::StandardButtons getStandardButtons() const override; + void modifyStandardButtons(QDialogButtonBox*) override; private: DlgPrimitives* widget; @@ -182,13 +182,13 @@ class TaskPrimitivesEdit : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskPrimitivesEdit(Part::Primitive* feature); - ~TaskPrimitivesEdit(); + explicit TaskPrimitivesEdit(Part::Primitive* feature); + ~TaskPrimitivesEdit() override; public: - bool accept(); - bool reject(); - QDialogButtonBox::StandardButtons getStandardButtons() const; + bool accept() override; + bool reject() override; + QDialogButtonBox::StandardButtons getStandardButtons() const override; private: DlgPrimitives* widget; diff --git a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp index 5f56dc00b6..f366bf2482 100644 --- a/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp +++ b/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp @@ -81,9 +81,9 @@ public: { canSelect = false; } - ~EdgeSelection() {} + ~EdgeSelection() override {} - bool allow(App::Document* /*pDoc*/, App::DocumentObject* iPObj, const char* sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* iPObj, const char* sSubName) override { Part::Feature* aPart = dynamic_cast(iPObj); if (!aPart) @@ -115,9 +115,9 @@ public: { canSelect = false; } - ~FaceSelection() {} + ~FaceSelection() override {} - bool allow(App::Document* /*pDoc*/, App::DocumentObject* iPObj, const char* sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* iPObj, const char* sSubName) override { Part::Feature* aPart = dynamic_cast(iPObj); if (!aPart) @@ -188,7 +188,7 @@ DlgProjectionOnSurface::DlgProjectionOnSurface(QWidget *parent) DlgProjectionOnSurface::~DlgProjectionOnSurface() { delete ui; - for ( auto it : m_projectionSurfaceVec) + for (const auto& it : m_projectionSurfaceVec) { try { higlight_object(it.partFeature, it.partName, false, 0); @@ -203,7 +203,7 @@ DlgProjectionOnSurface::~DlgProjectionOnSurface() vp->Transparency.setValue(it.transparency); } } - for (auto it : m_shapeVec) + for (const auto& it : m_shapeVec) { try { higlight_object(it.partFeature, it.partName, false, 0); @@ -230,13 +230,13 @@ void PartGui::DlgProjectionOnSurface::slotDeletedObject(const App::DocumentObjec } } -void PartGui::DlgProjectionOnSurface::apply(void) +void PartGui::DlgProjectionOnSurface::apply() { if (m_partDocument) m_partDocument->commitTransaction(); } -void PartGui::DlgProjectionOnSurface::reject(void) +void PartGui::DlgProjectionOnSurface::reject() { if (m_partDocument) m_partDocument->abortTransaction(); @@ -322,7 +322,7 @@ void PartGui::DlgProjectionOnSurface::onSelectionChanged(const Gui::SelectionCha { m_projectionSurfaceVec.clear(); store_current_selected_parts(m_projectionSurfaceVec, 0xffff0000); - if (m_projectionSurfaceVec.size()) + if (!m_projectionSurfaceVec.empty()) { PartGui::ViewProviderPartExt* vp = dynamic_cast(Gui::Application::Instance->getViewProvider(m_projectionSurfaceVec.back().partFeature)); if (vp) @@ -338,7 +338,7 @@ void PartGui::DlgProjectionOnSurface::onSelectionChanged(const Gui::SelectionCha } } -void PartGui::DlgProjectionOnSurface::get_camera_direction(void) +void PartGui::DlgProjectionOnSurface::get_camera_direction() { auto mainWindow = Gui::getMainWindow(); @@ -363,7 +363,7 @@ void PartGui::DlgProjectionOnSurface::store_current_selected_parts(std::vector selObj = Gui::Selection().getSelectionEx(); - if (selObj.size()) + if (!selObj.empty()) { for (auto it = selObj.begin(); it != selObj.end(); ++it) { @@ -383,7 +383,7 @@ void PartGui::DlgProjectionOnSurface::store_current_selected_parts(std::vectorSelectable.getValue(); currentShapeStore.transparency = vp->Transparency.getValue(); } - if (it->getSubNames().size() ) + if (!it->getSubNames().empty() ) { auto parentShape = currentShapeStore.inputShape; for (auto itName = selObj.front().getSubNames().begin(); itName != selObj.front().getSubNames().end(); ++itName) @@ -451,7 +451,7 @@ bool PartGui::DlgProjectionOnSurface::store_part_in_vector(SShapeStore& iCurrent auto valZ = ui->doubleSpinBoxDirZ->value(); iCurrentShape.aProjectionDir = gp_Dir(valX, valY, valZ); - if ( m_projectionSurfaceVec.size() ) + if ( !m_projectionSurfaceVec.empty() ) { iCurrentShape.surfaceToProject = m_projectionSurfaceVec.front().aFace; } @@ -468,14 +468,14 @@ void PartGui::DlgProjectionOnSurface::create_projection_wire(std::vector::max(); @@ -534,15 +534,15 @@ TopoDS_Shape PartGui::DlgProjectionOnSurface::create_compound(const std::vector< TopoDS_Builder aBuilder; aBuilder.MakeCompound(aCompound); - for (auto it : iShapeVec) + for (const auto& it : iShapeVec) { if ( m_currentShowType == "edges" ) { - for (auto it2 : it.aProjectedEdgeVec) + for (const auto& it2 : it.aProjectedEdgeVec) { aBuilder.Add(aCompound, it2); } - for (auto it2 : it.aProjectedWireVec) + for (const auto& it2 : it.aProjectedWireVec) { aBuilder.Add(aCompound, it2); } @@ -552,7 +552,7 @@ TopoDS_Shape PartGui::DlgProjectionOnSurface::create_compound(const std::vector< { if (it.aProjectedFace.IsNull()) { - for (auto it2 : it.aProjectedWireVec) + for (const auto& it2 : it.aProjectedWireVec) { if (!it2.IsNull()) { @@ -573,17 +573,17 @@ TopoDS_Shape PartGui::DlgProjectionOnSurface::create_compound(const std::vector< { aBuilder.Add(aCompound, it.aProjectedFace); } - else if (it.aProjectedWireVec.size()) + else if (!it.aProjectedWireVec.empty()) { - for ( auto itWire : it.aProjectedWireVec ) + for (const auto& itWire : it.aProjectedWireVec ) { if ( itWire.IsNull() ) continue; aBuilder.Add(aCompound, itWire); } } - else if (it.aProjectedEdgeVec.size()) + else if (!it.aProjectedEdgeVec.empty()) { - for (auto itEdge : it.aProjectedEdgeVec) + for (const auto& itEdge : it.aProjectedEdgeVec) { if (itEdge.IsNull()) continue; aBuilder.Add(aCompound, itEdge); @@ -731,7 +731,7 @@ void PartGui::DlgProjectionOnSurface::create_projection_face_from_wire(std::vect //create a wire of all edges in parametric space on the surface of the face to projected // --> otherwise BRepBuilderAPI_MakeFace can not make a face from the wire! - for (auto itWireVec : itCurrentShape.aProjectedWireVec) + for (const auto& itWireVec : itCurrentShape.aProjectedWireVec) { std::vector edgeVec; for (TopExp_Explorer aExplorer(itWireVec, TopAbs_EDGE); aExplorer.More(); aExplorer.Next()) @@ -827,7 +827,7 @@ TopoDS_Wire PartGui::DlgProjectionOnSurface::sort_and_heal_wire(const std::vecto Handle(TopTools_HSequenceOfShape) aWireHandle; Handle(TopTools_HSequenceOfShape) aWireWireHandle; - for (auto it : iEdgeVec) + for (const auto& it : iEdgeVec) { shapeList->Append(it); } @@ -903,7 +903,7 @@ void PartGui::DlgProjectionOnSurface::store_wire_in_vector(const SShapeStore& iC } std::vector edgeVec; - for ( auto it : aWireVec ) + for (const auto& it : aWireVec ) { bool edgeExists = false; for (TopExp_Explorer aExplorer(it, TopAbs_EDGE); aExplorer.More(); aExplorer.Next()) @@ -923,7 +923,7 @@ void PartGui::DlgProjectionOnSurface::store_wire_in_vector(const SShapeStore& iC if (indexMap.IsEmpty()) return; - for ( auto it : edgeVec ) + for (const auto& it : edgeVec ) { if ( it.IsSame(iCurrentShape.inputShape)) continue; if (!indexMap.Contains(it)) diff --git a/src/Mod/Part/Gui/DlgProjectionOnSurface.h b/src/Mod/Part/Gui/DlgProjectionOnSurface.h index 5130fe9850..ce6c8e6fbf 100644 --- a/src/Mod/Part/Gui/DlgProjectionOnSurface.h +++ b/src/Mod/Part/Gui/DlgProjectionOnSurface.h @@ -53,10 +53,10 @@ class DlgProjectionOnSurface : public QWidget, public: explicit DlgProjectionOnSurface(QWidget *parent = nullptr); - ~DlgProjectionOnSurface(); + ~DlgProjectionOnSurface() override; - void apply(void); - void reject(void); + void apply(); + void reject(); private Q_SLOTS: @@ -97,10 +97,10 @@ private: }; //from Gui::SelectionObserver - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; - void get_camera_direction(void); + void get_camera_direction(); void store_current_selected_parts(std::vector& iStoreVec, const unsigned int iColor); bool store_part_in_vector(SShapeStore& iCurrentShape, std::vector& iStoreVec); void create_projection_wire(std::vector& iCurrentShape); @@ -120,9 +120,9 @@ private: private: /** Checks if the given document is about to be closed */ - virtual void slotDeletedDocument(const App::Document& Doc); + void slotDeletedDocument(const App::Document& Doc) override; /** Checks if the given object is about to be removed. */ - virtual void slotDeletedObject(const App::DocumentObject& Obj); + void slotDeletedObject(const App::DocumentObject& Obj) override; private: Ui::DlgProjectionOnSurface *ui; @@ -152,14 +152,14 @@ class TaskProjectionOnSurface : public Gui::TaskView::TaskDialog public: TaskProjectionOnSurface(); - ~TaskProjectionOnSurface(); + ~TaskProjectionOnSurface() override; public: - bool accept(); - bool reject(); - void clicked(int); + bool accept() override; + bool reject() override; + void clicked(int) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } diff --git a/src/Mod/Part/Gui/DlgRevolution.cpp b/src/Mod/Part/Gui/DlgRevolution.cpp index 08e8aea594..1eef30a5ee 100644 --- a/src/Mod/Part/Gui/DlgRevolution.cpp +++ b/src/Mod/Part/Gui/DlgRevolution.cpp @@ -72,7 +72,7 @@ public: { canSelect = false; } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override { this->canSelect = false; @@ -181,7 +181,7 @@ void DlgRevolution::getAxisLink(App::PropertyLinkSub &lnk) const return; } else if (parts.size() == 2) { std::vector subs; - subs.push_back(std::string(parts[1].toLatin1().constData())); + subs.emplace_back(parts[1].toLatin1().constData()); lnk.setValue(obj,subs); } } @@ -378,8 +378,8 @@ void DlgRevolution::accept() QString strAxisLink; if (axisLink.getValue()){ strAxisLink = QString::fromLatin1("(App.ActiveDocument.%1, %2)") - .arg(QString::fromLatin1(axisLink.getValue()->getNameInDocument())) - .arg(axisLink.getSubValues().size() == 1 ? + .arg(QString::fromLatin1(axisLink.getValue()->getNameInDocument()), + axisLink.getSubValues().size() == 1 ? QString::fromLatin1("\"%1\"").arg(QString::fromLatin1(axisLink.getSubValues()[0].c_str())) : QString() ); } else { @@ -410,7 +410,7 @@ void DlgRevolution::accept() "FreeCAD.ActiveDocument.%2.AxisLink = %12\n" "FreeCAD.ActiveDocument.%2.Symmetric = %13\n" "FreeCADGui.ActiveDocument.%3.Visibility = False\n") - .arg(type).arg(name).arg(shape) //%1, 2, 3 + .arg(type, name, shape) //%1, 2, 3 .arg(axis.x,0,'f',15) //%4 .arg(axis.y,0,'f',15) //%5 .arg(axis.z,0,'f',15) //%6 @@ -418,9 +418,9 @@ void DlgRevolution::accept() .arg(pos.y, 0,'f',15) //%8 .arg(pos.z, 0,'f',15) //%9 .arg(getAngle(),0,'f',15) //%10 - .arg(solid) //%11 - .arg(strAxisLink) //%12 - .arg(symmetric) //13 + .arg(solid, //%11 + strAxisLink, //%12 + symmetric) //%13 ; Gui::Command::runCommand(Gui::Command::App, code.toLatin1()); QByteArray to = name.toLatin1(); @@ -522,7 +522,7 @@ void DlgRevolution::onSelectionChanged(const Gui::SelectionChanges& msg) App::DocumentObject&DlgRevolution::getShapeToRevolve() const { std::vector objs = this->getShapesToRevolve(); - if (objs.size() == 0) + if (objs.empty()) throw Base::ValueError("No shapes selected"); return *(objs[0]); } diff --git a/src/Mod/Part/Gui/DlgRevolution.h b/src/Mod/Part/Gui/DlgRevolution.h index 52e6d19ba5..6b2908cfea 100644 --- a/src/Mod/Part/Gui/DlgRevolution.h +++ b/src/Mod/Part/Gui/DlgRevolution.h @@ -36,9 +36,9 @@ class DlgRevolution : public QDialog, public Gui::SelectionObserver Q_OBJECT public: - DlgRevolution(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~DlgRevolution(); - void accept(); + explicit DlgRevolution(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~DlgRevolution() override; + void accept() override; Base::Vector3d getDirection() const; Base::Vector3d getPosition() const; @@ -55,8 +55,8 @@ public: bool validate(); protected: - void changeEvent(QEvent *e); - void keyPressEvent(QKeyEvent*); + void changeEvent(QEvent *e) override; + void keyPressEvent(QKeyEvent*) override; private Q_SLOTS: void on_selectLine_clicked(); @@ -67,7 +67,7 @@ private Q_SLOTS: private: void findShapes(); - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; ///returns link to any of selected source shapes. Throws if nothing is selected for extrusion. App::DocumentObject& getShapeToRevolve() const; @@ -87,12 +87,12 @@ class TaskRevolution : public Gui::TaskView::TaskDialog public: TaskRevolution(); - ~TaskRevolution(); + ~TaskRevolution() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h b/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h index 6cc1237b7d..fbcff0ec65 100644 --- a/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h +++ b/src/Mod/Part/Gui/DlgSettings3DViewPartImp.h @@ -39,13 +39,13 @@ class DlgSettings3DViewPart : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettings3DViewPart(QWidget* parent = nullptr); - ~DlgSettings3DViewPart(); + explicit DlgSettings3DViewPart(QWidget* parent = nullptr); + ~DlgSettings3DViewPart() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private Q_SLOTS: void on_maxDeviation_valueChanged(double); diff --git a/src/Mod/Part/Gui/DlgSettingsGeneral.cpp b/src/Mod/Part/Gui/DlgSettingsGeneral.cpp index fbd6762478..fb4b5318e5 100644 --- a/src/Mod/Part/Gui/DlgSettingsGeneral.cpp +++ b/src/Mod/Part/Gui/DlgSettingsGeneral.cpp @@ -31,6 +31,7 @@ #include #include +#include #include "DlgSettingsGeneral.h" #include "ui_DlgSettingsGeneral.h" @@ -216,6 +217,18 @@ DlgImportExportStep::DlgImportExportStep(QWidget* parent) QRegExpValidator* authorValidator = new QRegExpValidator(ui->lineEditAuthor); authorValidator->setRegExp(rx); ui->lineEditAuthor->setValidator(authorValidator); + + Part::ImportExportSettings settings; + ui->checkBoxMergeCompound->setChecked(settings.getReadShapeCompoundMode()); + ui->checkBoxExportHiddenObj->setChecked(settings.getExportHiddenObject()); + ui->checkBoxImportHiddenObj->setChecked(settings.getImportHiddenObject()); + ui->checkBoxExportLegacy->setChecked(settings.getExportLegacy()); + ui->checkBoxKeepPlacement->setChecked(settings.getExportKeepPlacement()); + ui->checkBoxUseLinkGroup->setChecked(settings.getUseLinkGroup()); + ui->checkBoxUseBaseName->setChecked(settings.getUseBaseName()); + ui->checkBoxReduceObjects->setChecked(settings.getReduceObjects()); + ui->checkBoxExpandCompound->setChecked(settings.getExpandCompound()); + ui->checkBoxShowProgress->setChecked(settings.getShowProgress()); } /** diff --git a/src/Mod/Part/Gui/DlgSettingsGeneral.h b/src/Mod/Part/Gui/DlgSettingsGeneral.h index c04efccb5c..25935dc9b6 100644 --- a/src/Mod/Part/Gui/DlgSettingsGeneral.h +++ b/src/Mod/Part/Gui/DlgSettingsGeneral.h @@ -36,13 +36,13 @@ class DlgSettingsGeneral : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsGeneral(QWidget* parent = nullptr); - ~DlgSettingsGeneral(); + explicit DlgSettingsGeneral(QWidget* parent = nullptr); + ~DlgSettingsGeneral() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; @@ -54,13 +54,13 @@ class DlgImportExportIges : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgImportExportIges(QWidget* parent = nullptr); - ~DlgImportExportIges(); + explicit DlgImportExportIges(QWidget* parent = nullptr); + ~DlgImportExportIges() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; @@ -73,13 +73,13 @@ class DlgImportExportStep : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgImportExportStep(QWidget* parent = nullptr); - ~DlgImportExportStep(); + explicit DlgImportExportStep(QWidget* parent = nullptr); + ~DlgImportExportStep() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Part/Gui/DlgSettingsMeasure.cpp b/src/Mod/Part/Gui/DlgSettingsMeasure.cpp new file mode 100644 index 0000000000..c202818e0b --- /dev/null +++ b/src/Mod/Part/Gui/DlgSettingsMeasure.cpp @@ -0,0 +1,94 @@ +/*************************************************************************** + * Copyright (c) 2022 * + * * + * 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 "DlgSettingsMeasure.h" +#include "ui_DlgSettingsMeasure.h" + + +using namespace PartGui; + +DlgSettingsMeasure::DlgSettingsMeasure(QWidget* parent) + : PreferencePage(parent) , ui(new Ui_DlgSettingsMeasure) +{ + ui->setupUi(this); + connect(ui->pushButtonRefresh, &QPushButton::clicked, this, &DlgSettingsMeasure::onMeasureRefresh); +} + +/** + * Destroys the object and frees any allocated resources + */ +DlgSettingsMeasure::~DlgSettingsMeasure() +{ + // no need to delete child widgets, Qt does it all for us +} + +void DlgSettingsMeasure::saveSettings() +{ + ui->dim3dColorButton->onSave(); + ui->dimDeltaColorButton->onSave(); + ui->dimAngularColorButton->onSave(); + + ui->fontSizeSpinBox->onSave(); + ui->fontNameComboBox->onSave(); + + ui->fontStyleBoldCheckBox->onSave(); + ui->fontStyleItalicCheckBox->onSave(); +} + +void DlgSettingsMeasure::loadSettings() +{ + ui->dim3dColorButton->onRestore(); + ui->dimDeltaColorButton->onRestore(); + ui->dimAngularColorButton->onRestore(); + + ui->fontSizeSpinBox->onRestore(); + ui->fontNameComboBox->onRestore(); + ui->fontNameComboBox->addItems(QStringList({QString::fromUtf8("defaultFont")})); + + ui->fontStyleBoldCheckBox->onRestore(); + ui->fontStyleItalicCheckBox->onRestore(); +} + +/** + * Sets the strings of the subwidgets using the current language. + */ +void DlgSettingsMeasure::changeEvent(QEvent *e) +{ + if (e->type() == QEvent::LanguageChange) { + ui->retranslateUi(this); + } + else { + QWidget::changeEvent(e); + } +} + +void DlgSettingsMeasure::onMeasureRefresh() +{ + DlgSettingsMeasure::saveSettings(); + Gui::Command::runCommand(Gui::Command::Gui, "Gui.runCommand('Part_Measure_Refresh',0)"); +} + +#include "moc_DlgSettingsMeasure.cpp" diff --git a/src/Mod/Part/Gui/DlgSettingsMeasure.h b/src/Mod/Part/Gui/DlgSettingsMeasure.h new file mode 100644 index 0000000000..2f347ef2c2 --- /dev/null +++ b/src/Mod/Part/Gui/DlgSettingsMeasure.h @@ -0,0 +1,58 @@ +/*************************************************************************** + * Copyright (c) 2022 * + * * + * 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 PARTGUI_DIALOG_DLGSETTINGSMEASURE_H +#define PARTGUI_DIALOG_DLGSETTINGSMEASURE_H + +#include +#include + +namespace PartGui { +class Ui_DlgSettingsMeasure; + +/** + * The DlgSettingsMeasure class implements a preference page to change color + * and font settings for Measure Dimensions + */ +class DlgSettingsMeasure : public Gui::Dialog::PreferencePage +{ + Q_OBJECT + +public: + explicit DlgSettingsMeasure(QWidget* parent = nullptr); + ~DlgSettingsMeasure() override; + + void saveSettings() override; + void loadSettings() override; + +protected: + void changeEvent(QEvent *e) override; + +private: + std::unique_ptr ui; + void onMeasureRefresh(); +}; + +} // namespace PartGui + +#endif // PARTGUI_DIALOG_DLGSETTINGSMEASURE_H diff --git a/src/Mod/Part/Gui/DlgSettingsMeasure.ui b/src/Mod/Part/Gui/DlgSettingsMeasure.ui new file mode 100644 index 0000000000..c6bbd9fa1c --- /dev/null +++ b/src/Mod/Part/Gui/DlgSettingsMeasure.ui @@ -0,0 +1,279 @@ + + + PartGui::DlgSettingsMeasure + + + + 0 + 0 + 400 + 282 + + + + + 0 + 0 + + + + Measure + + + + + + Dimension settings + + + + + + + + + 255 + 0 + 0 + + + + Dimensions3dColor + + + Mod/Part + + + + + + + 3D color + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 0 + 255 + 0 + + + + DimensionsDeltaColor + + + Mod/Part + + + + + + + Delta color + + + + + + + + 0 + 0 + 255 + + + + DimensionsAngularColor + + + Mod/Part + + + + + + + Angular color + + + + + + + + + + + + + + + 80 + 28 + + + + 30 + + + DimensionsFontSize + + + Mod/Part + + + + + + + Font size + + + + + + + + 75 + true + + + + Bold + + + DimensionsFontStyleBold + + + Mod/Part + + + + + + + + true + + + + Italic + + + DimensionsFontStyleItalic + + + Mod/Part + + + + + + + defaultFont + + + DimensionsFontName + + + Mod/Part + + + + + + + Font name + + + + + + + + + + + Refresh existing measures + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + Gui::ColorButton + QPushButton +
Gui/Widgets.h
+
+ + Gui::PrefSpinBox + QSpinBox +
Gui/PrefWidgets.h
+
+ + Gui::PrefColorButton + Gui::ColorButton +
Gui/PrefWidgets.h
+
+ + Gui::PrefCheckBox + QCheckBox +
Gui/PrefWidgets.h
+
+ + Gui::PrefFontBox + QFontComboBox +
Gui/PrefWidgets.h
+
+
+ + +
diff --git a/src/Mod/Part/Gui/DlgSettingsObjectColor.h b/src/Mod/Part/Gui/DlgSettingsObjectColor.h index 2b2c2a5868..ad6e143f36 100644 --- a/src/Mod/Part/Gui/DlgSettingsObjectColor.h +++ b/src/Mod/Part/Gui/DlgSettingsObjectColor.h @@ -40,14 +40,14 @@ class DlgSettingsObjectColor : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsObjectColor(QWidget* parent = nullptr); - ~DlgSettingsObjectColor(); + explicit DlgSettingsObjectColor(QWidget* parent = nullptr); + ~DlgSettingsObjectColor() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Part/Gui/Mirroring.cpp b/src/Mod/Part/Gui/Mirroring.cpp index cb800e05bb..fbf77c417e 100644 --- a/src/Mod/Part/Gui/Mirroring.cpp +++ b/src/Mod/Part/Gui/Mirroring.cpp @@ -20,24 +20,22 @@ * * ***************************************************************************/ - #include "PreCompiled.h" + #ifndef _PreComp_ + +// to avoid compiler warnings of redefining contents of basic.h +// later by #include +# define _USE_MATH_DEFINES +# include + +# include # include # include # include -# include -# include -# include -# include #endif -#include "Mirroring.h" -#include "ui_Mirroring.h" -#include "../App/PartFeature.h" -#include #include -#include #include #include #include @@ -51,6 +49,11 @@ #include #include #include +#include + +#include "Mirroring.h" +#include "ui_Mirroring.h" + using namespace PartGui; @@ -171,7 +174,7 @@ bool Mirroring::accept() "__doc__.ActiveObject.Normal=(%4,%5,%6)\n" "__doc__.ActiveObject.Base=(%7,%8,%9)\n" "del __doc__") - .arg(this->document).arg(shape).arg(label) + .arg(this->document, shape, label) .arg(normx).arg(normy).arg(normz) .arg(basex).arg(basey).arg(basez); Gui::Command::runCommand(Gui::Command::App, code.toLatin1()); diff --git a/src/Mod/Part/Gui/Mirroring.h b/src/Mod/Part/Gui/Mirroring.h index a133fce923..1fbfc1fee9 100644 --- a/src/Mod/Part/Gui/Mirroring.h +++ b/src/Mod/Part/Gui/Mirroring.h @@ -40,12 +40,12 @@ class Mirroring : public QWidget Q_OBJECT public: - Mirroring(QWidget* parent = nullptr); - ~Mirroring(); + explicit Mirroring(QWidget* parent = nullptr); + ~Mirroring() override; bool accept(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: void findShapes(); @@ -61,16 +61,16 @@ class TaskMirroring : public Gui::TaskView::TaskDialog public: TaskMirroring(); - ~TaskMirroring(); + ~TaskMirroring() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return false; } - virtual bool needsFullSpace() const + bool needsFullSpace() const override { return false; } private: diff --git a/src/Mod/Part/Gui/PropertyEnumAttacherItem.h b/src/Mod/Part/Gui/PropertyEnumAttacherItem.h index 5d62d5aa02..65715b8806 100644 --- a/src/Mod/Part/Gui/PropertyEnumAttacherItem.h +++ b/src/Mod/Part/Gui/PropertyEnumAttacherItem.h @@ -40,9 +40,9 @@ class PartGuiExport PropertyEnumAttacherItem: public Gui::PropertyEditor::Proper public: PROPERTYITEM_HEADER - virtual QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const; - virtual void setEditorData(QWidget* editor, const QVariant& data) const; - virtual QVariant editorData(QWidget* editor) const; + QWidget* createEditor(QWidget* parent, const QObject* receiver, const char* method) const override; + void setEditorData(QWidget* editor, const QVariant& data) const override; + QVariant editorData(QWidget* editor) const override; protected Q_SLOTS: void openTask(); diff --git a/src/Mod/Part/Gui/ReferenceHighlighter.cpp b/src/Mod/Part/Gui/ReferenceHighlighter.cpp index c6599094ba..480a57db64 100644 --- a/src/Mod/Part/Gui/ReferenceHighlighter.cpp +++ b/src/Mod/Part/Gui/ReferenceHighlighter.cpp @@ -114,7 +114,7 @@ void ReferenceHighlighter::getVertexColors(const std::vector& eleme colors.resize(vMap.Extent(), defaultColor); if (!elements.empty()) { - for (std::string e : elements) { + for (const std::string& e : elements) { if (boost::starts_with(e, "Vertex")) { getVertexColor(e, colors); } @@ -185,7 +185,7 @@ void ReferenceHighlighter::getEdgeColors(const std::vector& element colors.resize(eMap.Extent(), defaultColor); if (!elements.empty()) { - for (std::string e : elements) { + for (const std::string& e : elements) { if (boost::starts_with(e, "Edge")) { getEdgeColor(e, colors); } @@ -217,7 +217,7 @@ void ReferenceHighlighter::getFaceColors(const std::vector& element colors.resize(fMap.Extent(), defaultColor); if (!elements.empty()) { - for (std::string e : elements) { + for (const std::string& e : elements) { if (boost::starts_with(e, "Face")) { getFaceColor(e, colors); } diff --git a/src/Mod/Part/Gui/ReferenceHighlighter.h b/src/Mod/Part/Gui/ReferenceHighlighter.h index 89fd3c10bc..de501c032b 100644 --- a/src/Mod/Part/Gui/ReferenceHighlighter.h +++ b/src/Mod/Part/Gui/ReferenceHighlighter.h @@ -20,16 +20,18 @@ * * ***************************************************************************/ - #ifndef PARTGUI_REFERENCEHIGHLIGHTER_H #define PARTGUI_REFERENCEHIGHLIGHTER_H +#include + #include #include -#include + #include #include + namespace PartGui { /*! diff --git a/src/Mod/Part/Gui/SectionCutting.cpp b/src/Mod/Part/Gui/SectionCutting.cpp index cadd3daa60..67dd0ed3b2 100644 --- a/src/Mod/Part/Gui/SectionCutting.cpp +++ b/src/Mod/Part/Gui/SectionCutting.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -111,7 +112,7 @@ SectionCut::SectionCut(QWidget* parent) // now store those that are currently visible for (auto it = ObjectsList.begin(); it != ObjectsList.end(); ++it) { if ((*it)->Visibility.getValue()) - ObjectsListVisible.push_back(*it); + ObjectsListVisible.emplace_back(*it); } // lambda function to set color and transparency @@ -1136,8 +1137,8 @@ void SectionCut::onCutYvalueChanged(double val) pcCut->recomputeFeature(true); // refresh X limits // this is done by - // first making the cut X box visible, the setting the limits only for X - // if x-limit in box direcion is larger than object, reset value to saved limit + // first making the cut X box visible, then setting the limits only for X + // if x-limit in box direction is larger than object, reset value to saved limit if (hasBoxX) { auto CutBoxX = doc->getObject(BoxXName); if (!CutBoxX) @@ -1229,8 +1230,8 @@ void SectionCut::onCutZvalueChanged(double val) pcCut->recomputeFeature(true); // refresh X and Y limits // this is done e.g. for X by - // first making the cut X box visible, the setting the limits only for X - // if x-limit in box direcion is larger than object, reset value to saved limit + // first making the cut X box visible, then setting the limits only for X + // if x-limit in box direction is larger than object, reset value to saved limit SbBox3f CutBoundingBox; if (hasBoxX) { auto CutBoxX = doc->getObject(BoxXName); @@ -1531,7 +1532,7 @@ void SectionCut::onRefreshCutPBclicked() // now store those that are currently visible for (auto it = ObjectsList.begin(); it != ObjectsList.end(); ++it) { if ((*it)->Visibility.getValue()) { - ObjectsListVisible.push_back(*it); + ObjectsListVisible.emplace_back(*it); } } // reset defaults diff --git a/src/Mod/Part/Gui/SectionCutting.h b/src/Mod/Part/Gui/SectionCutting.h index ff2a65ca97..81fbd493f1 100644 --- a/src/Mod/Part/Gui/SectionCutting.h +++ b/src/Mod/Part/Gui/SectionCutting.h @@ -23,8 +23,12 @@ #ifndef PARTGUI_SECTIONCUTTING_H #define PARTGUI_SECTIONCUTTING_H +#include #include +#include +class QDoubleSpinBox; +class QSlider; namespace PartGui { @@ -36,8 +40,8 @@ class SectionCut : public QDialog public: static SectionCut* makeDockWidget(QWidget* parent = nullptr); - SectionCut(QWidget* parent = nullptr); - ~SectionCut(); + explicit SectionCut(QWidget* parent = nullptr); + ~SectionCut() override; protected Q_SLOTS: void onGroupBoxXtoggled(); @@ -61,7 +65,7 @@ protected Q_SLOTS: void onTransparencyChanged(int); public: - void reject(); + void reject() override; private: Ui_SectionCut* ui; diff --git a/src/Mod/Part/Gui/ShapeFromMesh.cpp b/src/Mod/Part/Gui/ShapeFromMesh.cpp index c570f6cf2b..aa28182200 100644 --- a/src/Mod/Part/Gui/ShapeFromMesh.cpp +++ b/src/Mod/Part/Gui/ShapeFromMesh.cpp @@ -20,20 +20,20 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ # include #endif -#include "ShapeFromMesh.h" -#include "ui_ShapeFromMesh.h" #include -#include #include #include #include +#include "ShapeFromMesh.h" +#include "ui_ShapeFromMesh.h" + + using namespace PartGui; diff --git a/src/Mod/Part/Gui/ShapeFromMesh.h b/src/Mod/Part/Gui/ShapeFromMesh.h index eca9455e79..49f23f37ca 100644 --- a/src/Mod/Part/Gui/ShapeFromMesh.h +++ b/src/Mod/Part/Gui/ShapeFromMesh.h @@ -34,10 +34,10 @@ class ShapeFromMesh : public QDialog Q_OBJECT public: - ShapeFromMesh(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~ShapeFromMesh(); + explicit ShapeFromMesh(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~ShapeFromMesh() override; - virtual void accept(); + void accept() override; private: void perform(); diff --git a/src/Mod/Part/Gui/SoBrepEdgeSet.cpp b/src/Mod/Part/Gui/SoBrepEdgeSet.cpp index 61ff3369ae..e9e65d2c7b 100644 --- a/src/Mod/Part/Gui/SoBrepEdgeSet.cpp +++ b/src/Mod/Part/Gui/SoBrepEdgeSet.cpp @@ -129,7 +129,7 @@ void SoBrepEdgeSet::GLRender(SoGLRenderAction *action) if(!action->isRenderingDelayedPaths()) renderHighlight(action,ctx); - if(ctx && ctx->selectionIndex.size()) { + if(ctx && !ctx->selectionIndex.empty()) { if(ctx->isSelectAll()) { if(ctx2) { ctx2->selectionColor = ctx->selectionColor; @@ -143,7 +143,7 @@ void SoBrepEdgeSet::GLRender(SoGLRenderAction *action) if(!action->isRenderingDelayedPaths()) renderSelection(action,ctx); } - if(ctx2 && ctx2->selectionIndex.size()) + if(ctx2 && !ctx2->selectionIndex.empty()) renderSelection(action,ctx2,false); else inherited::GLRender(action); @@ -152,7 +152,7 @@ void SoBrepEdgeSet::GLRender(SoGLRenderAction *action) //#if !defined(FC_OS_WIN32) if(!action->isRenderingDelayedPaths()) renderHighlight(action,ctx); - if(ctx && ctx->selectionIndex.size()) + if(ctx && !ctx->selectionIndex.empty()) renderSelection(action,ctx); if(action->isRenderingDelayedPaths()) renderHighlight(action,ctx); @@ -373,7 +373,7 @@ void SoBrepEdgeSet::doAction(SoAction* action) }else if(section == index) ctx->hl.push_back(cindices[i]); } - if(ctx->hl.size()) + if(!ctx->hl.empty()) ctx->highlightIndex = index; else ctx->highlightIndex = -1; @@ -440,7 +440,7 @@ void SoBrepEdgeSet::doAction(SoAction* action) return; } ctx->sl.clear(); - if(ctx->selectionIndex.size()) { + if(!ctx->selectionIndex.empty()) { const int32_t* cindices = this->coordIndex.getValues(0); int numcindices = this->coordIndex.getNum(); auto it = ctx->selectionIndex.begin(); diff --git a/src/Mod/Part/Gui/SoBrepEdgeSet.h b/src/Mod/Part/Gui/SoBrepEdgeSet.h index aad298b186..b2ac29606a 100644 --- a/src/Mod/Part/Gui/SoBrepEdgeSet.h +++ b/src/Mod/Part/Gui/SoBrepEdgeSet.h @@ -52,17 +52,17 @@ public: SoBrepEdgeSet(); protected: - virtual ~SoBrepEdgeSet() {}; - virtual void GLRender(SoGLRenderAction *action); - virtual void GLRenderBelowPath(SoGLRenderAction * action); - virtual void doAction(SoAction* action); - virtual SoDetail * createLineSegmentDetail( + ~SoBrepEdgeSet() override {}; + void GLRender(SoGLRenderAction *action) override; + void GLRenderBelowPath(SoGLRenderAction * action) override; + void doAction(SoAction* action) override; + SoDetail * createLineSegmentDetail( SoRayPickAction *action, const SoPrimitiveVertex *v1, const SoPrimitiveVertex *v2, - SoPickedPoint *pp); + SoPickedPoint *pp) override; - virtual void getBoundingBox(SoGetBoundingBoxAction * action); + void getBoundingBox(SoGetBoundingBoxAction * action) override; private: struct SelContext; diff --git a/src/Mod/Part/Gui/SoBrepFaceSet.cpp b/src/Mod/Part/Gui/SoBrepFaceSet.cpp index b716daa39d..5ebb702337 100644 --- a/src/Mod/Part/Gui/SoBrepFaceSet.cpp +++ b/src/Mod/Part/Gui/SoBrepFaceSet.cpp @@ -536,7 +536,7 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) return; if(selContext2->checkGlobal(ctx)) ctx = selContext2; - if(ctx && (!ctx->selectionIndex.size() && ctx->highlightIndex<0)) + if(ctx && (ctx->selectionIndex.empty() && ctx->highlightIndex<0)) ctx.reset(); auto state = action->getState(); @@ -592,7 +592,7 @@ void SoBrepFaceSet::GLRender(SoGLRenderAction *action) if(!action->isRenderingDelayedPaths()) renderHighlight(action,ctx); - if(ctx && ctx->selectionIndex.size()) { + if(ctx && !ctx->selectionIndex.empty()) { if(ctx->isSelectAll()) { if(ctx2) { ctx2->selectionColor = ctx->selectionColor; @@ -735,7 +735,7 @@ bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction *action, SelContext && ((ctx && Gui::Selection().needPickedList()) || trans0!=0.0 || - (ctx2 && ctx2->colors.size()))) + (ctx2 && !ctx2->colors.empty()))) { state->push(); @@ -857,7 +857,7 @@ bool SoBrepFaceSet::overrideMaterialBinding(SoGLRenderAction *action, SelContext } } - if(ctx && ctx->selectionIndex.size()) { + if(ctx && !ctx->selectionIndex.empty()) { packedColors.push_back(ctx->selectionColor.getPackedValue(trans0)); for(auto idx : ctx->selectionIndex) { if(idx>=0 && idxisRenderingDelayedPaths()) renderHighlight(action,ctx); - if(ctx && ctx->selectionIndex.size()) { + if(ctx && !ctx->selectionIndex.empty()) { if(ctx->isSelectAll()) { - if(ctx2 && ctx2->selectionIndex.size()) { + if(ctx2 && !ctx2->selectionIndex.empty()) { ctx2->selectionColor = ctx->selectionColor; renderSelection(action,ctx2); }else @@ -133,7 +133,7 @@ void SoBrepPointSet::GLRender(SoGLRenderAction *action) if(!action->isRenderingDelayedPaths()) renderSelection(action,ctx); } - if(ctx2 && ctx2->selectionIndex.size()) + if(ctx2 && !ctx2->selectionIndex.empty()) renderSelection(action,ctx2,false); else inherited::GLRender(action); @@ -142,7 +142,7 @@ void SoBrepPointSet::GLRender(SoGLRenderAction *action) //#if !defined(FC_OS_WIN32) if(!action->isRenderingDelayedPaths()) renderHighlight(action,ctx); - if(ctx && ctx->selectionIndex.size()) + if(ctx && !ctx->selectionIndex.empty()) renderSelection(action,ctx); if(action->isRenderingDelayedPaths()) renderHighlight(action,ctx); diff --git a/src/Mod/Part/Gui/SoBrepPointSet.h b/src/Mod/Part/Gui/SoBrepPointSet.h index 84c256ab20..69bb7484f2 100644 --- a/src/Mod/Part/Gui/SoBrepPointSet.h +++ b/src/Mod/Part/Gui/SoBrepPointSet.h @@ -52,12 +52,12 @@ public: SoBrepPointSet(); protected: - virtual ~SoBrepPointSet() {}; - virtual void GLRender(SoGLRenderAction *action); - virtual void GLRenderBelowPath(SoGLRenderAction * action); - virtual void doAction(SoAction* action); + ~SoBrepPointSet() override {}; + void GLRender(SoGLRenderAction *action) override; + void GLRenderBelowPath(SoGLRenderAction * action) override; + void doAction(SoAction* action) override; - virtual void getBoundingBox(SoGetBoundingBoxAction * action); + void getBoundingBox(SoGetBoundingBoxAction * action) override; private: typedef Gui::SoFCSelectionContext SelContext; diff --git a/src/Mod/Part/Gui/SoFCShapeObject.h b/src/Mod/Part/Gui/SoFCShapeObject.h index aaa4679c0b..b931156021 100644 --- a/src/Mod/Part/Gui/SoFCShapeObject.h +++ b/src/Mod/Part/Gui/SoFCShapeObject.h @@ -49,10 +49,10 @@ public: SoSFColor lineColor; protected: - virtual ~SoFCControlPoints() {}; - virtual void GLRender(SoGLRenderAction *action); - virtual void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er); - virtual void generatePrimitives(SoAction *action); + ~SoFCControlPoints() override {}; + void GLRender(SoGLRenderAction *action) override; + void computeBBox(SoAction *action, SbBox3f &box, SbVec3f ¢er) override; + void generatePrimitives(SoAction *action) override; private: void drawControlPoints(const SbVec3f *,int32_t) const; diff --git a/src/Mod/Part/Gui/TaskAttacher.cpp b/src/Mod/Part/Gui/TaskAttacher.cpp index ec5cdfa665..27bbc6066f 100644 --- a/src/Mod/Part/Gui/TaskAttacher.cpp +++ b/src/Mod/Part/Gui/TaskAttacher.cpp @@ -68,7 +68,7 @@ namespace bp = boost::placeholders; // Create reference name from PropertyLinkSub values in a translatable fashion const QString makeRefString(const App::DocumentObject* obj, const std::string& sub) { - if (obj == nullptr) + if (!obj) return QObject::tr("No reference selected"); if (obj->getTypeId().isDerivedFrom(App::OriginFeature::getClassTypeId()) || @@ -99,14 +99,14 @@ void TaskAttacher::makeRefStrings(std::vector& refstrings, std::vector< refnames = pcAttach->Support.getSubValues(); for (size_t r = 0; r < 4; r++) { - if ((r < refs.size()) && (refs[r] != nullptr)) { + if ((r < refs.size()) && (refs[r])) { refstrings.push_back(makeRefString(refs[r], refnames[r])); // for Origin or Datum features refnames is empty but we need a non-empty return value if (refnames[r].empty()) refnames[r] = refs[r]->getNameInDocument(); } else { refstrings.push_back(QObject::tr("No reference selected")); - refnames.push_back(""); + refnames.emplace_back(""); } } } @@ -289,7 +289,7 @@ void TaskAttacher::updateReferencesUI() pcAttach->attacher().suggestMapModes(this->lastSuggestResult); if (this->lastSuggestResult.message != SuggestResult::srOK) { - if(this->lastSuggestResult.nextRefTypeHint.size() > 0){ + if(!this->lastSuggestResult.nextRefTypeHint.empty()){ //message = "Need more references"; } } else { @@ -419,7 +419,7 @@ void TaskAttacher::onSelectionChanged(const Gui::SelectionChanges& msg) } QLineEdit* line = getLine(iActiveRef); - if (line != nullptr) { + if (line) { line->blockSignals(true); line->setText(makeRefString(selObj, subname)); line->setProperty("RefName", QByteArray(subname.c_str())); @@ -429,7 +429,7 @@ void TaskAttacher::onSelectionChanged(const Gui::SelectionChanges& msg) if (autoNext) { if (iActiveRef == -1){ //nothing to do - } else if (iActiveRef == 4 || this->lastSuggestResult.nextRefTypeHint.size() == 0){ + } else if (iActiveRef == 4 || this->lastSuggestResult.nextRefTypeHint.empty()){ iActiveRef = -1; } else { iActiveRef++; @@ -563,7 +563,7 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) return; QLineEdit* line = getLine(idx); - if (line == nullptr) + if (!line) return; if (text.length() == 0) { @@ -607,7 +607,7 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) parts.push_back(QString::fromLatin1("")); // Check whether this is the name of an App::Plane or Part::Datum feature App::DocumentObject* obj = ViewProvider->getObject()->getDocument()->getObject(parts[0].toLatin1()); - if (obj == nullptr) + if (!obj) return; std::string subElement; @@ -661,7 +661,7 @@ void TaskAttacher::onRefName(const QString& text, unsigned idx) refnames[idx] = subElement.c_str(); } else { refs.push_back(obj); - refnames.push_back(subElement.c_str()); + refnames.emplace_back(subElement.c_str()); } pcAttach->Support.setValues(refs, refnames); updateListOfModes(); @@ -692,7 +692,7 @@ void TaskAttacher::updateRefButton(int idx) bool enable = true; if (idx > numrefs) enable = false; - if (idx == numrefs && this->lastSuggestResult.nextRefTypeHint.size() == 0) + if (idx == numrefs && this->lastSuggestResult.nextRefTypeHint.empty()) enable = false; b->setEnabled(enable); @@ -806,7 +806,7 @@ void TaskAttacher::updateListOfModes() ui->listOfModes->blockSignals(true); ui->listOfModes->clear(); QListWidgetItem* iSelect = nullptr; - if (modesInList.size()>0) { + if (!modesInList.empty()) { for (size_t i = 0 ; i < modesInList.size() ; ++i){ eMapMode mmode = modesInList[i]; std::vector mstr = AttacherGui::getUIStrings(pcAttach->attacher().getTypeId(),mmode); @@ -999,7 +999,7 @@ void TaskAttacher::visibilityAutomation(bool opening_not_closing) App::DocumentObject *editObj = ViewProvider->getObject(); std::string editSubName; auto sels = Gui::Selection().getSelection(nullptr, Gui::ResolveMode::NoResolve, true); - if(sels.size() && sels[0].pResolvedObject + if(!sels.empty() && sels[0].pResolvedObject && sels[0].pResolvedObject->getLinkedObject()==editObj) { editObj = sels[0].pObject; diff --git a/src/Mod/Part/Gui/TaskAttacher.h b/src/Mod/Part/Gui/TaskAttacher.h index a92f708777..4b6acf9b19 100644 --- a/src/Mod/Part/Gui/TaskAttacher.h +++ b/src/Mod/Part/Gui/TaskAttacher.h @@ -56,10 +56,10 @@ public: typedef std::function VisibilityFunction; - TaskAttacher(Gui::ViewProviderDocumentObject *ViewProvider, QWidget *parent = nullptr, + explicit TaskAttacher(Gui::ViewProviderDocumentObject *ViewProvider, QWidget *parent = nullptr, QString picture = QString(), QString text = QString::fromLatin1("Attachment"), VisibilityFunction func = 0); - ~TaskAttacher(); + ~TaskAttacher() override; bool getFlip(void) const; @@ -151,8 +151,8 @@ class PartGuiExport TaskDlgAttacher : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgAttacher(Gui::ViewProviderDocumentObject *ViewProvider, bool createBox = true); - ~TaskDlgAttacher(); + explicit TaskDlgAttacher(Gui::ViewProviderDocumentObject *ViewProvider, bool createBox = true); + ~TaskDlgAttacher() override; Gui::ViewProviderDocumentObject* getViewProvider() const { return ViewProvider; } @@ -160,19 +160,19 @@ public: public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument(void) const override { return false; } /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons(void) const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } protected: diff --git a/src/Mod/Part/Gui/TaskCheckGeometry.cpp b/src/Mod/Part/Gui/TaskCheckGeometry.cpp index 88ca697467..b78c296f44 100644 --- a/src/Mod/Part/Gui/TaskCheckGeometry.cpp +++ b/src/Mod/Part/Gui/TaskCheckGeometry.cpp @@ -207,13 +207,12 @@ ResultEntry::~ResultEntry() void ResultEntry::buildEntryName() { ResultEntry *parentEntry = this; - while(parentEntry->parent != nullptr) - { - ResultEntry *temp = parentEntry->parent; - if (temp->parent == nullptr) - break; - parentEntry = parentEntry->parent; - } + while (parentEntry->parent != nullptr) { + ResultEntry *temp = parentEntry->parent; + if (!temp->parent) + break; + parentEntry = parentEntry->parent; + } QString stringOut; QTextStream stream(&stringOut); @@ -838,10 +837,10 @@ bool TaskCheckGeometryResults::split(QString &input, QString &doc, QString &obje QString PartGui::buildSelectionName(const ResultEntry *entry, const TopoDS_Shape &shape) { const ResultEntry *parentEntry = entry; - while(parentEntry->parent != nullptr) + while(parentEntry->parent) { ResultEntry *temp = parentEntry->parent; - if (temp->parent == nullptr) + if (!temp->parent) break; parentEntry = parentEntry->parent; } diff --git a/src/Mod/Part/Gui/TaskCheckGeometry.h b/src/Mod/Part/Gui/TaskCheckGeometry.h index 841510aec8..18d8eff990 100644 --- a/src/Mod/Part/Gui/TaskCheckGeometry.h +++ b/src/Mod/Part/Gui/TaskCheckGeometry.h @@ -81,14 +81,14 @@ class ResultModel : public QAbstractItemModel { Q_OBJECT public: - ResultModel(QObject *parent = nullptr); - ~ResultModel(); - QModelIndex index(int row, int column, const QModelIndex &parent) const; - QModelIndex parent(const QModelIndex &child) const; - virtual int rowCount(const QModelIndex &parent) const; - virtual int columnCount(const QModelIndex &parent) const; - virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; + explicit ResultModel(QObject *parent = nullptr); + ~ResultModel() override; + QModelIndex index(int row, int column, const QModelIndex &parent) const override; + QModelIndex parent(const QModelIndex &child) const override; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; // virtual Qt::ItemFlags flags (const QModelIndex &index) const; void setResults(ResultEntry *resultsIn); @@ -102,8 +102,8 @@ class TaskCheckGeometryResults : public QWidget { Q_OBJECT public: - TaskCheckGeometryResults(QWidget *parent = nullptr); - ~TaskCheckGeometryResults(); + explicit TaskCheckGeometryResults(QWidget *parent = nullptr); + ~TaskCheckGeometryResults() override; QString getShapeContentString(); void goCheck(); @@ -143,13 +143,13 @@ class TaskCheckGeometryDialog : public Gui::TaskView::TaskDialog Q_OBJECT public: TaskCheckGeometryDialog(); - ~TaskCheckGeometryDialog(); + ~TaskCheckGeometryDialog() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override {return QDialogButtonBox::Ok | QDialogButtonBox::Close;} - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override {return false;} - virtual bool needsFullSpace() const {return true;} + bool needsFullSpace() const override {return true;} private Q_SLOTS: void on_runBOPCheckBox_toggled(bool isOn); @@ -190,9 +190,9 @@ private: QCheckBox *mergeVertexModeCheckBox; QCheckBox *mergeEdgeModeCheckBox; QCheckBox *curveOnSurfaceModeCheckBox; - bool accept(); - bool reject(); - virtual void modifyStandardButtons(QDialogButtonBox*); + bool accept() override; + bool reject() override; + void modifyStandardButtons(QDialogButtonBox*) override; QPushButton *okBtn; QPushButton *settingsBtn; QPushButton *resultsBtn; @@ -202,16 +202,16 @@ class BOPProgressIndicator : public Message_ProgressIndicator { public: BOPProgressIndicator (const QString &title, QWidget* parent); - virtual ~BOPProgressIndicator (); + ~BOPProgressIndicator () override; #if OCC_VERSION_HEX < 0x070500 - virtual Standard_Boolean Show (const Standard_Boolean theForce = Standard_True); + Standard_Boolean Show (const Standard_Boolean theForce = Standard_True) override; #else - virtual void Show (const Message_ProgressScope& theScope, - const Standard_Boolean isForce); - virtual void Reset(); + void Show (const Message_ProgressScope& theScope, + const Standard_Boolean isForce) override; + void Reset() override; #endif - virtual Standard_Boolean UserBreak(); + Standard_Boolean UserBreak() override; private: int steps; diff --git a/src/Mod/Part/Gui/TaskDimension.cpp b/src/Mod/Part/Gui/TaskDimension.cpp index 8ca37dd9a8..e73df5fb99 100644 --- a/src/Mod/Part/Gui/TaskDimension.cpp +++ b/src/Mod/Part/Gui/TaskDimension.cpp @@ -224,6 +224,21 @@ void PartGui::dumpLinearResults(const BRepExtrema_DistShapeShape &measure) Base::Console().Message(out.str().c_str()); } +auto PartGui::getDimensionsFontName() +{ + ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp/Preferences/Mod/Part"); + std::string fontName = group->GetASCII("DimensionsFontName", "defaultFont") + + (group->GetBool("DimensionsFontStyleBold", false) ? " :Bold" : "") + + (group->GetBool("DimensionsFontStyleItalic", false) ? " :Italic" : ""); + return fontName; +} + +auto PartGui::getDimensionsFontSize() +{ + ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp/Preferences/Mod/Part"); + return group->GetInt("DimensionsFontSize", 30); +} + Gui::View3DInventorViewer * PartGui::getViewer() { Gui::Document *doc = Gui::Application::Instance->activeDocument(); @@ -240,12 +255,9 @@ Gui::View3DInventorViewer * PartGui::getViewer() void PartGui::addLinearDimensions(const BRepExtrema_DistShapeShape &measure) { - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("View"); - App::Color c(1.0,0.0,0.0); - c.fromHexString(group->GetASCII("Dimensions3dColor", c.asHexString().c_str())); - App::Color d(0.0,1.0,0.0); - d.fromHexString(group->GetASCII("DimensionsDeltaColor", d.asHexString().c_str())); + ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp/Preferences/Mod/Part"); + App::Color c((uint32_t) group->GetUnsigned("Dimensions3dColor", 0xFF000000)); + App::Color d((uint32_t) group->GetUnsigned("DimensionsDeltaColor", 0x00FF0000)); Gui::View3DInventorViewer *viewer = getViewer(); if (!viewer) @@ -503,8 +515,8 @@ void PartGui::DimensionLinear::setupDimension() textSep->addChild(textTransform); SoFont *fontNode = new SoFont(); - fontNode->name.setValue("defaultFont"); - fontNode->size.setValue(30); + fontNode->name.setValue(getDimensionsFontName().c_str()); + fontNode->size.setValue(getDimensionsFontSize()); textSep->addChild(fontNode); SoText2 *textNode = new SoText2(); @@ -662,7 +674,7 @@ void PartGui::TaskMeasureLinear::selection1Slot(bool checked) { if (!checked) { - if (selections1.selections.size() > 0) + if (!selections1.selections.empty()) stepped->setIconDone(0); return; } @@ -1106,10 +1118,8 @@ void PartGui::goDimensionAngularNoTask(const VectorAdapter &vector1Adapter, cons dimSys = dimSys.transpose(); } - ParameterGrp::handle group = App::GetApplication().GetUserParameter(). - GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("View"); - App::Color c(0.0,0.0,1.0); - c.fromHexString(group->GetASCII("DimensionsAngularColor", c.asHexString().c_str())); + ParameterGrp::handle group = App::GetApplication().GetUserParameter().GetGroup("BaseApp/Preferences/Mod/Part"); + App::Color c((uint32_t) group->GetUnsigned("DimensionsAngularColor", 0x0000FF00)); DimensionAngular *dimension = new DimensionAngular(); dimension->ref(); @@ -1288,8 +1298,8 @@ void PartGui::DimensionAngular::setupDimension() textSep->addChild(textTransform); SoFont *fontNode = new SoFont(); - fontNode->name.setValue("defaultFont"); - fontNode->size.setValue(30); + fontNode->name.setValue(getDimensionsFontName().c_str()); + fontNode->size.setValue(getDimensionsFontSize()); textSep->addChild(fontNode); SoText2 *textNode = new SoText2(); @@ -1454,7 +1464,7 @@ void PartGui::SteppedSelection::buildPixmaps() void PartGui::SteppedSelection::selectionSlot(bool checked) { QPushButton *sender = qobject_cast(QObject::sender()); - assert(sender != nullptr); + assert(sender); std::vector::iterator it; for (it = buttons.begin(); it != buttons.end(); ++it) if (it->first == sender) @@ -1810,7 +1820,7 @@ void PartGui::TaskMeasureAngular::selection1Slot(bool checked) } else { - if (selections1.selections.size() > 0) + if (!selections1.selections.empty()) stepped->setIconDone(0); } } diff --git a/src/Mod/Part/Gui/TaskDimension.h b/src/Mod/Part/Gui/TaskDimension.h index b1a9729831..5d68fbec9e 100644 --- a/src/Mod/Part/Gui/TaskDimension.h +++ b/src/Mod/Part/Gui/TaskDimension.h @@ -108,7 +108,10 @@ namespace PartGui void ensure3dDimensionVisible(); /*convert a vertex to vector*/ gp_Vec convert(const TopoDS_Vertex &vertex); - + + auto getDimensionsFontName(); + auto getDimensionsFontSize(); + class DimensionLinear : public SoSeparatorKit { SO_KIT_HEADER(DimensionLinear); @@ -122,7 +125,7 @@ class DimensionLinear : public SoSeparatorKit public: DimensionLinear(); static void initClass(); - virtual SbBool affectsState() const; + SbBool affectsState() const override; void setupDimension(); SoSFVec3f point1; @@ -135,7 +138,7 @@ protected: SoSFVec3f origin; private: - virtual ~DimensionLinear(); + ~DimensionLinear() override; }; /*kit for anglular dimensions*/ @@ -152,7 +155,7 @@ class DimensionAngular : public SoSeparatorKit public: DimensionAngular(); static void initClass(); - virtual SbBool affectsState() const; + SbBool affectsState() const override; SoSFFloat radius;//radians. SoSFFloat angle;//radians. @@ -161,7 +164,7 @@ public: SoSFMatrix matrix; void setupDimension(); private: - virtual ~DimensionAngular(); + ~DimensionAngular() override; }; /*used for generating points for arc display*/ @@ -179,9 +182,9 @@ public: SoEngineOutput points; SoEngineOutput pointCount; protected: - virtual void evaluate(); + void evaluate() override; private: - virtual ~ArcEngine(){} + ~ArcEngine() override{} void defaultValues(); //some non error values if something goes wrong. }; @@ -190,8 +193,8 @@ class SteppedSelection : public QWidget { Q_OBJECT public: - SteppedSelection(const uint &buttonCountIn, QWidget *parent = nullptr); - ~SteppedSelection(); + explicit SteppedSelection(const uint &buttonCountIn, QWidget *parent = nullptr); + ~SteppedSelection() override; QPushButton* getButton(const uint &index); void setIconDone(const uint &index); @@ -244,14 +247,14 @@ class TaskMeasureLinear : public Gui::TaskView::TaskDialog, public Gui::Selectio Q_OBJECT public: TaskMeasureLinear(); - ~TaskMeasureLinear(); + ~TaskMeasureLinear() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override {return QDialogButtonBox::Close;} - virtual bool isAllowedAlterDocument(void) const {return false;} - virtual bool needsFullSpace() const {return false;} + bool isAllowedAlterDocument() const override {return false;} + bool needsFullSpace() const override {return false;} protected: - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; protected Q_SLOTS: void selection1Slot(bool checked); @@ -305,9 +308,9 @@ public: bool isValid() const {return status;} /*!get the calculated vector. * @return the vector. use isValid to ensure correct results.*/ - operator gp_Vec() const {return vector;} + operator gp_Vec() const {return vector;}//explicit bombs /*!build occ line used for extrema calculation*/ - operator gp_Lin() const; + operator gp_Lin() const;//explicit bombs gp_Vec getPickPoint() const {return origin;} private: @@ -323,14 +326,14 @@ class TaskMeasureAngular : public Gui::TaskView::TaskDialog, public Gui::Selecti Q_OBJECT public: TaskMeasureAngular(); - ~TaskMeasureAngular(); + ~TaskMeasureAngular() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override {return QDialogButtonBox::Close;} - virtual bool isAllowedAlterDocument(void) const {return false;} - virtual bool needsFullSpace() const {return false;} + bool isAllowedAlterDocument() const override {return false;} + bool needsFullSpace() const override {return false;} protected: - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; protected Q_SLOTS: void selection1Slot(bool checked); diff --git a/src/Mod/Part/Gui/TaskFaceColors.cpp b/src/Mod/Part/Gui/TaskFaceColors.cpp index 38df9f65ef..2d66da422a 100644 --- a/src/Mod/Part/Gui/TaskFaceColors.cpp +++ b/src/Mod/Part/Gui/TaskFaceColors.cpp @@ -70,11 +70,11 @@ namespace PartGui { { const App::DocumentObject* object; public: - FaceSelection(const App::DocumentObject* obj) + explicit FaceSelection(const App::DocumentObject* obj) : Gui::SelectionFilterGate(), object(obj) { } - bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject* pObj, const char* sSubName) override { if (pObj != this->object) return false; @@ -102,7 +102,7 @@ public: Connection connectDelObj; Connection connectUndoDoc; - Private(ViewProviderPartExt* vp) : ui(new Ui_TaskFaceColors()), view(nullptr), vp(vp) + explicit Private(ViewProviderPartExt* vp) : ui(new Ui_TaskFaceColors()), view(nullptr), vp(vp) { obj = vp->getObject(); doc = Gui::Application::Instance->getDocument(obj->getDocument()); diff --git a/src/Mod/Part/Gui/TaskFaceColors.h b/src/Mod/Part/Gui/TaskFaceColors.h index 6afd8f751c..5051a01da3 100644 --- a/src/Mod/Part/Gui/TaskFaceColors.h +++ b/src/Mod/Part/Gui/TaskFaceColors.h @@ -40,8 +40,8 @@ class FaceColors : public QWidget, public Gui::SelectionObserver Q_OBJECT public: - FaceColors(ViewProviderPartExt* vp, QWidget* parent = nullptr); - ~FaceColors(); + explicit FaceColors(ViewProviderPartExt* vp, QWidget* parent = nullptr); + ~FaceColors() override; void open(); bool accept(); @@ -53,8 +53,8 @@ private Q_SLOTS: void on_boxSelection_toggled(bool checked); protected: - void onSelectionChanged(const Gui::SelectionChanges& msg); - void changeEvent(QEvent *e); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void changeEvent(QEvent *e) override; void slotUndoDocument(const Gui::Document& Doc); void slotDeleteDocument(const Gui::Document&); void slotDeleteObject(const Gui::ViewProvider&); @@ -70,16 +70,16 @@ class TaskFaceColors : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskFaceColors(ViewProviderPartExt* vp); - ~TaskFaceColors(); + explicit TaskFaceColors(ViewProviderPartExt* vp); + ~TaskFaceColors() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Part/Gui/TaskLoft.cpp b/src/Mod/Part/Gui/TaskLoft.cpp index ba039e95ac..7234b9a956 100644 --- a/src/Mod/Part/Gui/TaskLoft.cpp +++ b/src/Mod/Part/Gui/TaskLoft.cpp @@ -200,7 +200,7 @@ bool LoftWidget::accept() "App.getDocument('%5').ActiveObject.Solid=%2\n" "App.getDocument('%5').ActiveObject.Ruled=%3\n" "App.getDocument('%5').ActiveObject.Closed=%4\n" - ).arg(list).arg(solid).arg(ruled).arg(closed).arg(QString::fromLatin1(d->document.c_str())); + ).arg(list, solid, ruled, closed, QString::fromLatin1(d->document.c_str())); Gui::Document* doc = Gui::Application::Instance->getDocument(d->document.c_str()); if (!doc) diff --git a/src/Mod/Part/Gui/TaskLoft.h b/src/Mod/Part/Gui/TaskLoft.h index 8f117f6689..ea3a63ce67 100644 --- a/src/Mod/Part/Gui/TaskLoft.h +++ b/src/Mod/Part/Gui/TaskLoft.h @@ -36,8 +36,8 @@ class LoftWidget : public QWidget Q_OBJECT public: - LoftWidget(QWidget* parent = nullptr); - ~LoftWidget(); + explicit LoftWidget(QWidget* parent = nullptr); + ~LoftWidget() override; bool accept(); bool reject(); @@ -46,7 +46,7 @@ private Q_SLOTS: void onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*); private: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void findShapes(); private: @@ -60,15 +60,15 @@ class TaskLoft : public Gui::TaskView::TaskDialog public: TaskLoft(); - ~TaskLoft(); + ~TaskLoft() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Part/Gui/TaskOffset.h b/src/Mod/Part/Gui/TaskOffset.h index 8833e36e53..f53030a40d 100644 --- a/src/Mod/Part/Gui/TaskOffset.h +++ b/src/Mod/Part/Gui/TaskOffset.h @@ -35,8 +35,8 @@ class OffsetWidget : public QWidget Q_OBJECT public: - OffsetWidget(Part::Offset*, QWidget* parent = nullptr); - ~OffsetWidget(); + explicit OffsetWidget(Part::Offset*, QWidget* parent = nullptr); + ~OffsetWidget() override; bool accept(); bool reject(); @@ -52,7 +52,7 @@ private Q_SLOTS: void on_updateView_toggled(bool); private: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: class Private; @@ -64,17 +64,17 @@ class TaskOffset : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskOffset(Part::Offset*); - ~TaskOffset(); + explicit TaskOffset(Part::Offset*); + ~TaskOffset() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; Part::Offset* getObject() const; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Part/Gui/TaskShapeBuilder.cpp b/src/Mod/Part/Gui/TaskShapeBuilder.cpp index d0585b6968..628762dc53 100644 --- a/src/Mod/Part/Gui/TaskShapeBuilder.cpp +++ b/src/Mod/Part/Gui/TaskShapeBuilder.cpp @@ -70,7 +70,7 @@ namespace PartGui { { this->mode = mode; } - bool allow(App::Document*, App::DocumentObject* obj, const char*sSubName) + bool allow(App::Document*, App::DocumentObject* obj, const char*sSubName) override { if (!obj || !obj->isDerivedFrom(Part::Feature::getClassTypeId())) return false; @@ -255,7 +255,7 @@ void ShapeBuilderWidget::createEdgeFromVertex() "if _.isNull(): raise RuntimeError('Failed to create edge')\n" "App.ActiveDocument.addObject('Part::Feature','Edge').Shape=_\n" "del _\n" - ).arg(elements[0]).arg(elements[1]); + ).arg(elements[0], elements[1]); try { Gui::Application::Instance->activeDocument()->openCommand(QT_TRANSLATE_NOOP("Command", "Edge")); diff --git a/src/Mod/Part/Gui/TaskShapeBuilder.h b/src/Mod/Part/Gui/TaskShapeBuilder.h index 2129553f41..0daf4267f0 100644 --- a/src/Mod/Part/Gui/TaskShapeBuilder.h +++ b/src/Mod/Part/Gui/TaskShapeBuilder.h @@ -36,8 +36,8 @@ class ShapeBuilderWidget : public QWidget, Q_OBJECT public: - ShapeBuilderWidget(QWidget* parent = nullptr); - ~ShapeBuilderWidget(); + explicit ShapeBuilderWidget(QWidget* parent = nullptr); + ~ShapeBuilderWidget() override; bool accept(); bool reject(); @@ -48,7 +48,7 @@ private Q_SLOTS: void switchMode(int); private: - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: void createEdgeFromVertex(); @@ -57,7 +57,7 @@ private: void createFaceFromEdge(); void createShellFromFace(); void createSolidFromShell(); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: class Private; @@ -70,15 +70,15 @@ class TaskShapeBuilder : public Gui::TaskView::TaskDialog public: TaskShapeBuilder(); - ~TaskShapeBuilder(); + ~TaskShapeBuilder() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Close; } private: diff --git a/src/Mod/Part/Gui/TaskSweep.cpp b/src/Mod/Part/Gui/TaskSweep.cpp index 643e0b6bc9..4ab3a2334f 100644 --- a/src/Mod/Part/Gui/TaskSweep.cpp +++ b/src/Mod/Part/Gui/TaskSweep.cpp @@ -82,7 +82,7 @@ public: : Gui::SelectionFilterGate(nullPointer()) { } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override { if (!sSubName || sSubName[0] == '\0') { // If selecting again the same edge the passed sub-element is empty. If the whole @@ -359,11 +359,11 @@ bool SweepWidget::accept() "App.getDocument('%5').ActiveObject.Solid=%3\n" "App.getDocument('%5').ActiveObject.Frenet=%4\n" ) - .arg(list) - .arg(QLatin1String(selection.c_str())) - .arg(solid) - .arg(frenet) - .arg(QString::fromLatin1(d->document.c_str())); + .arg(list, + QLatin1String(selection.c_str()), + solid, + frenet, + QString::fromLatin1(d->document.c_str())); Gui::Document* doc = Gui::Application::Instance->getDocument(d->document.c_str()); if (!doc) diff --git a/src/Mod/Part/Gui/TaskSweep.h b/src/Mod/Part/Gui/TaskSweep.h index 323003c8b9..b4051e226e 100644 --- a/src/Mod/Part/Gui/TaskSweep.h +++ b/src/Mod/Part/Gui/TaskSweep.h @@ -40,8 +40,8 @@ class SweepWidget : public QWidget Q_OBJECT public: - SweepWidget(QWidget* parent = nullptr); - ~SweepWidget(); + explicit SweepWidget(QWidget* parent = nullptr); + ~SweepWidget() override; bool accept(); bool reject(); @@ -51,7 +51,7 @@ private Q_SLOTS: void on_buttonPath_toggled(bool); private: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void findShapes(); bool isPathValid(const Gui::SelectionObject& sel) const; @@ -66,15 +66,15 @@ class TaskSweep : public Gui::TaskView::TaskDialog public: TaskSweep(); - ~TaskSweep(); + ~TaskSweep() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Help; } private: diff --git a/src/Mod/Part/Gui/TaskThickness.cpp b/src/Mod/Part/Gui/TaskThickness.cpp index 5c6f7146ff..f3eebf4bd6 100644 --- a/src/Mod/Part/Gui/TaskThickness.cpp +++ b/src/Mod/Part/Gui/TaskThickness.cpp @@ -70,11 +70,11 @@ public: { const App::DocumentObject* object; public: - FaceSelection(const App::DocumentObject* obj) + explicit FaceSelection(const App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()), object(obj) { } - bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) + bool allow(App::Document* /*pDoc*/, App::DocumentObject*pObj, const char*sSubName) override { if (pObj != this->object) return false; diff --git a/src/Mod/Part/Gui/TaskThickness.h b/src/Mod/Part/Gui/TaskThickness.h index 8d27492ba2..6cb6fa5279 100644 --- a/src/Mod/Part/Gui/TaskThickness.h +++ b/src/Mod/Part/Gui/TaskThickness.h @@ -35,8 +35,8 @@ class ThicknessWidget : public QWidget Q_OBJECT public: - ThicknessWidget(Part::Thickness*, QWidget* parent = nullptr); - ~ThicknessWidget(); + explicit ThicknessWidget(Part::Thickness*, QWidget* parent = nullptr); + ~ThicknessWidget() override; bool accept(); bool reject(); @@ -52,7 +52,7 @@ private Q_SLOTS: void on_updateView_toggled(bool); private: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: class Private; @@ -64,17 +64,17 @@ class TaskThickness : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskThickness(Part::Thickness*); - ~TaskThickness(); + explicit TaskThickness(Part::Thickness*); + ~TaskThickness() override; public: - void open(); - bool accept(); - bool reject(); - void clicked(int); + void open() override; + bool accept() override; + bool reject() override; + void clicked(int) override; Part::Thickness* getObject() const; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Part/Gui/ViewProvider.cpp b/src/Mod/Part/Gui/ViewProvider.cpp index 5a3c91ef98..f44a7fe282 100644 --- a/src/Mod/Part/Gui/ViewProvider.cpp +++ b/src/Mod/Part/Gui/ViewProvider.cpp @@ -44,7 +44,7 @@ ViewProviderPart::~ViewProviderPart() { } -bool ViewProviderPart::doubleClicked(void) +bool ViewProviderPart::doubleClicked() { try { QString text = QObject::tr("Edit %1").arg(QString::fromUtf8(getObject()->Label.getValue())); diff --git a/src/Mod/Part/Gui/ViewProvider.h b/src/Mod/Part/Gui/ViewProvider.h index 7246e32ce7..8e224b8a3c 100644 --- a/src/Mod/Part/Gui/ViewProvider.h +++ b/src/Mod/Part/Gui/ViewProvider.h @@ -37,21 +37,21 @@ class ViewProviderShapeBuilder : public Gui::ViewProviderBuilder { public: ViewProviderShapeBuilder(){} - ~ViewProviderShapeBuilder(){} - virtual void buildNodes(const App::Property*, std::vector&) const; + ~ViewProviderShapeBuilder() override{} + void buildNodes(const App::Property*, std::vector&) const override; void createShape(const App::Property*, SoSeparator*) const; }; class PartGuiExport ViewProviderPart : public ViewProviderPartExt { - PROPERTY_HEADER(PartGui::ViewProviderPart); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPart); public: /// constructor ViewProviderPart(); /// destructor - virtual ~ViewProviderPart(); - virtual bool doubleClicked(void); + ~ViewProviderPart() override; + bool doubleClicked(void) override; protected: void applyColor(const Part::ShapeHistory& hist, diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.cpp b/src/Mod/Part/Gui/ViewProvider2DObject.cpp index d5af5b35cf..f0578cd822 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.cpp +++ b/src/Mod/Part/Gui/ViewProvider2DObject.cpp @@ -20,7 +20,6 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ @@ -51,7 +50,6 @@ using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -92,7 +90,7 @@ ViewProvider2DObjectGrid::~ViewProvider2DObjectGrid() // ********************************************************************************** -SoSeparator* ViewProvider2DObjectGrid::createGrid(void) +SoSeparator* ViewProvider2DObjectGrid::createGrid() { //double dx = 10 * GridSize.getValue(); // carpet size //double dy = 10 * GridSize.getValue(); @@ -201,7 +199,8 @@ SoSeparator* ViewProvider2DObjectGrid::createGrid(void) 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.", lines, maxNumberOfLines.getValue()); + 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); return GridRoot; @@ -359,16 +358,16 @@ ViewProvider2DObject::~ViewProvider2DObject() { } -std::vector ViewProvider2DObject::getDisplayModes(void) const +std::vector ViewProvider2DObject::getDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderGeometryObject::getDisplayModes(); // add your own modes - StrList.push_back("Flat Lines"); + StrList.emplace_back("Flat Lines"); //StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProvider2DObject.h b/src/Mod/Part/Gui/ViewProvider2DObject.h index 135265d0b8..4d59e81403 100644 --- a/src/Mod/Part/Gui/ViewProvider2DObject.h +++ b/src/Mod/Part/Gui/ViewProvider2DObject.h @@ -39,26 +39,26 @@ namespace PartGui { class PartGuiExport ViewProvider2DObject : public PartGui::ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProvider2DObject); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProvider2DObject); public: /// constructor ViewProvider2DObject(); /// destructor - virtual ~ViewProvider2DObject(); - virtual std::vector getDisplayModes(void) const; - virtual const char* getDefaultDisplayMode() const; + ~ViewProvider2DObject() override; + std::vector getDisplayModes() const override; + const char* getDefaultDisplayMode() const override; }; class PartGuiExport ViewProvider2DObjectGrid : public ViewProvider2DObject { - PROPERTY_HEADER(PartGui::ViewProvider2DObjectGrid); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProvider2DObjectGrid); public: /// constructor ViewProvider2DObjectGrid(); /// destructor - virtual ~ViewProvider2DObjectGrid(); + ~ViewProvider2DObjectGrid() override; /// Property to switch the grid on and off App::PropertyBool ShowGrid; @@ -70,19 +70,19 @@ public: App::PropertyBool GridAutoSize; App::PropertyInteger maxNumberOfLines; - virtual void attach(App::DocumentObject *); - virtual void updateData(const App::Property*); + void attach(App::DocumentObject *) override; + void updateData(const App::Property*) override; /// creates the grid - SoSeparator* createGrid(void); + SoSeparator* createGrid(); protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; /// get called by the container whenever a property has been changed - virtual void onChanged(const App::Property* prop); - virtual void Restore(Base::XMLReader &reader); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + void onChanged(const App::Property* prop) override; + void Restore(Base::XMLReader &reader) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; SoSeparator *GridRoot; diff --git a/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp b/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp index 6d65ec5923..b2b6d48d6f 100644 --- a/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp +++ b/src/Mod/Part/Gui/ViewProviderAttachExtension.cpp @@ -20,25 +20,25 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ # ifdef _MSC_VER # define _USE_MATH_DEFINES # include -# endif //_MSC_VER +# endif # include # include #endif -#include "ViewProviderAttachExtension.h" -#include "TaskAttacher.h" -#include - #include #include #include +#include + +#include "ViewProviderAttachExtension.h" +#include "TaskAttacher.h" + using namespace PartGui; diff --git a/src/Mod/Part/Gui/ViewProviderAttachExtension.h b/src/Mod/Part/Gui/ViewProviderAttachExtension.h index 1669235c12..e3869cab61 100644 --- a/src/Mod/Part/Gui/ViewProviderAttachExtension.h +++ b/src/Mod/Part/Gui/ViewProviderAttachExtension.h @@ -20,14 +20,13 @@ * * ***************************************************************************/ - #ifndef GUI_VIEWPROVIDERATTACHEXTENSION_H #define GUI_VIEWPROVIDERATTACHEXTENSION_H -#include #include #include + namespace PartGui { @@ -37,13 +36,13 @@ class PartGuiExport ViewProviderAttachExtension : public Gui::ViewProviderExtens public: /// Constructor - ViewProviderAttachExtension(void); - virtual ~ViewProviderAttachExtension() = default; + ViewProviderAttachExtension(); + ~ViewProviderAttachExtension() override = default; - virtual QIcon extensionMergeColorfullOverlayIcons (const QIcon & orig) const override; + QIcon extensionMergeColorfullOverlayIcons (const QIcon & orig) const override; - virtual void extensionUpdateData(const App::Property*) override; - virtual void extensionSetupContextMenu(QMenu*, QObject*, const char*) override; + void extensionUpdateData(const App::Property*) override; + void extensionSetupContextMenu(QMenu*, QObject*, const char*) override; private: void showAttachmentEditor(); diff --git a/src/Mod/Part/Gui/ViewProviderBoolean.cpp b/src/Mod/Part/Gui/ViewProviderBoolean.cpp index 86c591056b..34bb110c64 100644 --- a/src/Mod/Part/Gui/ViewProviderBoolean.cpp +++ b/src/Mod/Part/Gui/ViewProviderBoolean.cpp @@ -20,23 +20,20 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ -# include # include # include -# include -# include #endif -#include "ViewProviderBoolean.h" #include #include -#include -#include #include +#include + +#include "ViewProviderBoolean.h" + using namespace PartGui; @@ -50,7 +47,7 @@ ViewProviderBoolean::~ViewProviderBoolean() { } -std::vector ViewProviderBoolean::claimChildren(void)const +std::vector ViewProviderBoolean::claimChildren()const { std::vector temp; temp.push_back(static_cast(getObject())->Base.getValue()); @@ -59,7 +56,7 @@ std::vector ViewProviderBoolean::claimChildren(void)const return temp; } -QIcon ViewProviderBoolean::getIcon(void) const +QIcon ViewProviderBoolean::getIcon() const { App::DocumentObject* obj = getObject(); if (obj) { @@ -130,6 +127,12 @@ void ViewProviderBoolean::updateData(const App::Property* prop) applyColor(hist[1], colTool, colBool); } + // If the view provider has set a transparency then override the values + // of the input shapes + if (Transparency.getValue() > 0) { + applyTransparency(Transparency.getValue(), colBool); + } + this->DiffuseColor.setValues(colBool); } } @@ -166,12 +169,12 @@ ViewProviderMultiFuse::~ViewProviderMultiFuse() { } -std::vector ViewProviderMultiFuse::claimChildren(void)const +std::vector ViewProviderMultiFuse::claimChildren()const { return std::vector(static_cast(getObject())->Shapes.getValues()); } -QIcon ViewProviderMultiFuse::getIcon(void) const +QIcon ViewProviderMultiFuse::getIcon() const { return Gui::BitmapFactory().iconFromTheme("Part_Fuse"); } @@ -218,6 +221,12 @@ void ViewProviderMultiFuse::updateData(const App::Property* prop) } } + // If the view provider has set a transparency then override the values + // of the input shapes + if (Transparency.getValue() > 0) { + applyTransparency(Transparency.getValue(), colBool); + } + this->DiffuseColor.setValues(colBool); } else if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) { @@ -297,12 +306,12 @@ ViewProviderMultiCommon::~ViewProviderMultiCommon() { } -std::vector ViewProviderMultiCommon::claimChildren(void)const +std::vector ViewProviderMultiCommon::claimChildren()const { return std::vector(static_cast(getObject())->Shapes.getValues()); } -QIcon ViewProviderMultiCommon::getIcon(void) const +QIcon ViewProviderMultiCommon::getIcon() const { return Gui::BitmapFactory().iconFromTheme("Part_Common"); } @@ -349,6 +358,12 @@ void ViewProviderMultiCommon::updateData(const App::Property* prop) } } + // If the view provider has set a transparency then override the values + // of the input shapes + if (Transparency.getValue() > 0) { + applyTransparency(Transparency.getValue(), colBool); + } + this->DiffuseColor.setValues(colBool); } else if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) { diff --git a/src/Mod/Part/Gui/ViewProviderBoolean.h b/src/Mod/Part/Gui/ViewProviderBoolean.h index 3c379309ab..996496a1e6 100644 --- a/src/Mod/Part/Gui/ViewProviderBoolean.h +++ b/src/Mod/Part/Gui/ViewProviderBoolean.h @@ -31,71 +31,71 @@ namespace PartGui { class PartGuiExport ViewProviderBoolean : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderBoolean); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderBoolean); public: /// constructor ViewProviderBoolean(); /// destructor - virtual ~ViewProviderBoolean(); + ~ViewProviderBoolean() override; /// grouping handling - std::vector claimChildren(void) const; - QIcon getIcon(void) const; - void updateData(const App::Property*); - bool onDelete(const std::vector &); + std::vector claimChildren() const override; + QIcon getIcon() const override; + void updateData(const App::Property*) override; + bool onDelete(const std::vector &) override; }; /// ViewProvider for the MultiFuse feature class PartGuiExport ViewProviderMultiFuse : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderMultiFuse); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderMultiFuse); public: /// constructor ViewProviderMultiFuse(); /// destructor - virtual ~ViewProviderMultiFuse(); + ~ViewProviderMultiFuse() override; /// grouping handling - std::vector claimChildren(void) const; - QIcon getIcon(void) const; - void updateData(const App::Property*); - bool onDelete(const std::vector &); + std::vector claimChildren() const override; + QIcon getIcon() const override; + void updateData(const App::Property*) override; + bool onDelete(const std::vector &) override; /// drag and drop - bool canDragObjects() const; - bool canDragObject(App::DocumentObject*) const; - void dragObject(App::DocumentObject*); - bool canDropObjects() const; - bool canDropObject(App::DocumentObject*) const; - void dropObject(App::DocumentObject*); + bool canDragObjects() const override; + bool canDragObject(App::DocumentObject*) const override; + void dragObject(App::DocumentObject*) override; + bool canDropObjects() const override; + bool canDropObject(App::DocumentObject*) const override; + void dropObject(App::DocumentObject*) override; }; /// ViewProvider for the MultiFuse feature class PartGuiExport ViewProviderMultiCommon : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderMultiCommon); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderMultiCommon); public: /// constructor ViewProviderMultiCommon(); /// destructor - virtual ~ViewProviderMultiCommon(); + ~ViewProviderMultiCommon() override; /// grouping handling - std::vector claimChildren(void) const; - QIcon getIcon(void) const; - void updateData(const App::Property*); - bool onDelete(const std::vector &); + std::vector claimChildren() const override; + QIcon getIcon() const override; + void updateData(const App::Property*) override; + bool onDelete(const std::vector &) override; /// drag and drop - bool canDragObjects() const; - bool canDragObject(App::DocumentObject*) const; - void dragObject(App::DocumentObject*); - bool canDropObjects() const; - bool canDropObject(App::DocumentObject*) const; - void dropObject(App::DocumentObject*); + bool canDragObjects() const override; + bool canDragObject(App::DocumentObject*) const override; + void dragObject(App::DocumentObject*) override; + bool canDropObjects() const override; + bool canDropObject(App::DocumentObject*) const override; + void dropObject(App::DocumentObject*) override; }; diff --git a/src/Mod/Part/Gui/ViewProviderBox.cpp b/src/Mod/Part/Gui/ViewProviderBox.cpp index 7d7f1f19ae..1189019c01 100644 --- a/src/Mod/Part/Gui/ViewProviderBox.cpp +++ b/src/Mod/Part/Gui/ViewProviderBox.cpp @@ -20,19 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderBox.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -53,16 +48,16 @@ ViewProviderBox::~ViewProviderBox() // ********************************************************************************** -std::vector ViewProviderBox::getDisplayModes(void) const +std::vector ViewProviderBox::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderBox.h b/src/Mod/Part/Gui/ViewProviderBox.h index 6ea74f83cb..39f1d1c1cd 100644 --- a/src/Mod/Part/Gui/ViewProviderBox.h +++ b/src/Mod/Part/Gui/ViewProviderBox.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderBox : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderBox); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderBox); public: /// constructor ViewProviderBox(); /// destructor - virtual ~ViewProviderBox(); + ~ViewProviderBox() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp b/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp index c299a857a1..5d5c9f7771 100644 --- a/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderCircleParametric.cpp @@ -20,15 +20,10 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderCircleParametric.h" - using namespace PartGui; using namespace std; @@ -53,14 +48,14 @@ ViewProviderCircleParametric::~ViewProviderCircleParametric() // ********************************************************************************** -std::vector ViewProviderCircleParametric::getDisplayModes(void) const +std::vector ViewProviderCircleParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderCircleParametric.h b/src/Mod/Part/Gui/ViewProviderCircleParametric.h index da4eb5388b..3800065666 100644 --- a/src/Mod/Part/Gui/ViewProviderCircleParametric.h +++ b/src/Mod/Part/Gui/ViewProviderCircleParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderCircleParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderCircleParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCircleParametric); public: /// constructor ViewProviderCircleParametric(); /// destructor - virtual ~ViewProviderCircleParametric(); + ~ViewProviderCircleParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes(void) const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderCompound.cpp b/src/Mod/Part/Gui/ViewProviderCompound.cpp index f98a5ba53a..7504eed898 100644 --- a/src/Mod/Part/Gui/ViewProviderCompound.cpp +++ b/src/Mod/Part/Gui/ViewProviderCompound.cpp @@ -20,7 +20,6 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ @@ -30,6 +29,7 @@ #include #include + #include "ViewProviderCompound.h" @@ -125,6 +125,12 @@ void ViewProviderCompound::updateData(const App::Property* prop) } } + // If the view provider has set a transparency then override the values + // of the input shapes + if (Transparency.getValue() > 0) { + applyTransparency(Transparency.getValue(), compCol); + } + this->DiffuseColor.setValues(compCol); } else if (prop->getTypeId().isDerivedFrom(App::PropertyLinkList::getClassTypeId())) { diff --git a/src/Mod/Part/Gui/ViewProviderCompound.h b/src/Mod/Part/Gui/ViewProviderCompound.h index e72b9b278b..642f8a7e63 100644 --- a/src/Mod/Part/Gui/ViewProviderCompound.h +++ b/src/Mod/Part/Gui/ViewProviderCompound.h @@ -31,26 +31,26 @@ namespace PartGui { class PartGuiExport ViewProviderCompound : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderCompound); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCompound); public: /// constructor ViewProviderCompound(); /// destructor - virtual ~ViewProviderCompound(); - std::vector claimChildren() const; - bool onDelete(const std::vector &); + ~ViewProviderCompound() override; + std::vector claimChildren() const override; + bool onDelete(const std::vector &) override; /// drag and drop - bool canDragObjects() const; - bool canDragObject(App::DocumentObject*) const; - void dragObject(App::DocumentObject*); - bool canDropObjects() const; - bool canDropObject(App::DocumentObject*) const; - void dropObject(App::DocumentObject*); + bool canDragObjects() const override; + bool canDragObject(App::DocumentObject*) const override; + void dragObject(App::DocumentObject*) override; + bool canDropObjects() const override; + bool canDropObject(App::DocumentObject*) const override; + void dropObject(App::DocumentObject*) override; protected: - void updateData(const App::Property*); + void updateData(const App::Property*) override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/ViewProviderConeParametric.cpp b/src/Mod/Part/Gui/ViewProviderConeParametric.cpp index e7619c758b..9cbd9831cc 100644 --- a/src/Mod/Part/Gui/ViewProviderConeParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderConeParametric.cpp @@ -20,19 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderConeParametric.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -53,16 +48,16 @@ ViewProviderConeParametric::~ViewProviderConeParametric() // ********************************************************************************** -std::vector ViewProviderConeParametric::getDisplayModes(void) const +std::vector ViewProviderConeParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderConeParametric.h b/src/Mod/Part/Gui/ViewProviderConeParametric.h index 230d7b258d..aaee45992f 100644 --- a/src/Mod/Part/Gui/ViewProviderConeParametric.h +++ b/src/Mod/Part/Gui/ViewProviderConeParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderConeParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderConeParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderConeParametric); public: /// constructor ViewProviderConeParametric(); /// destructor - virtual ~ViewProviderConeParametric(); + ~ViewProviderConeParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderCurveNet.cpp b/src/Mod/Part/Gui/ViewProviderCurveNet.cpp index 2ee423b1d8..fb5dd51d85 100644 --- a/src/Mod/Part/Gui/ViewProviderCurveNet.cpp +++ b/src/Mod/Part/Gui/ViewProviderCurveNet.cpp @@ -20,46 +20,37 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ # include # include -# include -# include # include +# include +# include +# include +# include # include # include # include # include # include # include -# include # include -# include -# include -# include +# include #endif -/// Here the FreeCAD includes sorted by Base,App,Gui...... +#include #include #include -#include -#include -#include #include -#include - -#include +#include #include "ViewProviderCurveNet.h" - using namespace PartGui; - //************************************************************************** // Construction/Destruction @@ -89,7 +80,7 @@ ViewProviderCurveNet::~ViewProviderCurveNet() void ViewProviderCurveNet::attach(App::DocumentObject *pcFeat) { // call parent attach method - ViewProviderGeometryObject::attach(pcFeat); + ViewProviderGeometryObject::attach(pcFeat); // clazy:exclude=skipped-base-method // setup the root and material for the edges SoSeparator* ModeRoot = new SoSeparator(); @@ -111,7 +102,7 @@ void ViewProviderCurveNet::attach(App::DocumentObject *pcFeat) void ViewProviderCurveNet::updateData(const App::Property* prop) { - Gui::ViewProviderGeometryObject::updateData(prop); + Gui::ViewProviderGeometryObject::updateData(prop); // clazy:exclude=skipped-base-method if (prop->getTypeId() == Part::PropertyPartShape::getClassTypeId()) { TopoDS_Shape cShape = static_cast(prop)->getValue(); if (cShape.IsNull()) @@ -138,13 +129,13 @@ void ViewProviderCurveNet::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode(ModeName); } -std::vector ViewProviderCurveNet::getDisplayModes(void) const +std::vector ViewProviderCurveNet::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Edge"); + StrList.emplace_back("Edge"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderCurveNet.h b/src/Mod/Part/Gui/ViewProviderCurveNet.h index 2d75003f44..09b708a509 100644 --- a/src/Mod/Part/Gui/ViewProviderCurveNet.h +++ b/src/Mod/Part/Gui/ViewProviderCurveNet.h @@ -43,27 +43,27 @@ namespace PartGui { class PartGuiExport ViewProviderCurveNet:public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderPart); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPart); public: /// constructor ViewProviderCurveNet(); /// destructor - virtual ~ViewProviderCurveNet(); + ~ViewProviderCurveNet() override; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); + void attach(App::DocumentObject *) override; + void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; /// Update the Part representation - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; virtual bool handleEvent(const SoEvent * const ev,Gui::View3DInventorViewer &Viewer); protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; struct Node { Gui::SoFCSelection *pcHighlight; diff --git a/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp b/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp index fbd404a68b..1502a0704b 100644 --- a/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderCylinderParametric.cpp @@ -20,19 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderCylinderParametric.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -53,16 +48,16 @@ ViewProviderCylinderParametric::~ViewProviderCylinderParametric() // ********************************************************************************** -std::vector ViewProviderCylinderParametric::getDisplayModes(void) const +std::vector ViewProviderCylinderParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderCylinderParametric.h b/src/Mod/Part/Gui/ViewProviderCylinderParametric.h index 39af793a07..1070cd2f75 100644 --- a/src/Mod/Part/Gui/ViewProviderCylinderParametric.h +++ b/src/Mod/Part/Gui/ViewProviderCylinderParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderCylinderParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderCylinderParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCylinderParametric); public: /// constructor ViewProviderCylinderParametric(); /// destructor - virtual ~ViewProviderCylinderParametric(); + ~ViewProviderCylinderParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp b/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp index 574fed4f4d..dd908763b6 100644 --- a/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderEllipseParametric.cpp @@ -20,19 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderEllipseParametric.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -53,14 +48,14 @@ ViewProviderEllipseParametric::~ViewProviderEllipseParametric() // ********************************************************************************** -std::vector ViewProviderEllipseParametric::getDisplayModes(void) const +std::vector ViewProviderEllipseParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderEllipseParametric.h b/src/Mod/Part/Gui/ViewProviderEllipseParametric.h index 8be4d7a183..f33ca2bb23 100644 --- a/src/Mod/Part/Gui/ViewProviderEllipseParametric.h +++ b/src/Mod/Part/Gui/ViewProviderEllipseParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderEllipseParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderEllipseParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderEllipseParametric); public: /// constructor ViewProviderEllipseParametric(); /// destructor - virtual ~ViewProviderEllipseParametric(); + ~ViewProviderEllipseParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderExt.cpp b/src/Mod/Part/Gui/ViewProviderExt.cpp index c0431075d8..467de2c505 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.cpp +++ b/src/Mod/Part/Gui/ViewProviderExt.cpp @@ -20,7 +20,6 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ @@ -40,8 +39,8 @@ # include # include # include -# include # include +# include # include # include # include @@ -65,20 +64,22 @@ # include # include # include +# include # include #endif +#include +#include + #include #include #include #include #include #include -#include -#include + #include #include -#include #include #include #include @@ -468,16 +469,16 @@ void ViewProviderPartExt::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode( ModeName ); } -std::vector ViewProviderPartExt::getDisplayModes(void) const +std::vector ViewProviderPartExt::getDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderGeometryObject::getDisplayModes(); // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } @@ -840,7 +841,7 @@ void ViewProviderPartExt::reload() void ViewProviderPartExt::updateData(const App::Property* prop) { const char *propName = prop->getName(); - if (propName && (strcmp(propName, "Shape") == 0 || strstr(propName, "Touched") != nullptr)) { + if (propName && (strcmp(propName, "Shape") == 0 || strstr(propName, "Touched"))) { // calculate the visual only if visible if (isUpdateForced() || Visibility.getValue()) updateVisual(); diff --git a/src/Mod/Part/Gui/ViewProviderExt.h b/src/Mod/Part/Gui/ViewProviderExt.h index 8be7f52c0a..d7a63cb2b0 100644 --- a/src/Mod/Part/Gui/ViewProviderExt.h +++ b/src/Mod/Part/Gui/ViewProviderExt.h @@ -20,22 +20,19 @@ * * ***************************************************************************/ - #ifndef PARTGUI_VIEWPROVIDERPARTEXT_H #define PARTGUI_VIEWPROVIDERPARTEXT_H +#include #include -#include -#include -#include -#include -#include + #include #include -#include + #include #include + class TopoDS_Shape; class TopoDS_Edge; class TopoDS_Wire; @@ -71,7 +68,7 @@ public: /// constructor ViewProviderPartExt(); /// destructor - virtual ~ViewProviderPartExt(); + ~ViewProviderPartExt() override; // Display properties App::PropertyFloatConstraint Deviation; @@ -92,16 +89,16 @@ public: // Faces (Gui::ViewProviderGeometryObject::ShapeColor and Gui::ViewProviderGeometryObject::ShapeMaterial apply) App::PropertyColorList DiffuseColor; - virtual void attach(App::DocumentObject *) override; - virtual void setDisplayMode(const char* ModeName) override; + void attach(App::DocumentObject *) override; + void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const override; + std::vector getDisplayModes(void) const override; /// Update the view representation void reload(); /// If no other task is pending it opens a dialog to allow to change face colors bool changeFaceColors(); - virtual void updateData(const App::Property*) override; + void updateData(const App::Property*) override; /** @name Selection handling * This group of methods do the selection handling. @@ -110,13 +107,13 @@ public: */ //@{ /// indicates if the ViewProvider use the new Selection model - virtual bool useNewSelectionModel(void) const override {return true;} + bool useNewSelectionModel(void) const override {return true;} /// return a hit element to the selection path or 0 - virtual std::string getElement(const SoDetail*) const override; - virtual SoDetail* getDetail(const char*) const override; - virtual std::vector getModelPoints(const SoPickedPoint *) const override; + std::string getElement(const SoDetail*) const override; + SoDetail* getDetail(const char*) const override; + std::vector getModelPoints(const SoPickedPoint *) const override; /// return the highlight lines for a given element or the whole shape - virtual std::vector getSelectionShape(const char* Element) const override; + std::vector getSelectionShape(const char* Element) const override; //@} /** @name Highlight handling @@ -135,15 +132,15 @@ public: /** @name Color management methods */ //@{ - virtual std::map getElementColors(const char *element=nullptr) const override; + std::map getElementColors(const char *element=nullptr) const override; //@} - virtual bool isUpdateForced() const override { + bool isUpdateForced() const override { return forceUpdateCount>0; } - virtual void forceUpdate(bool enable = true) override; + void forceUpdate(bool enable = true) override; - virtual bool allowOverride(const App::DocumentObject &) const override; + bool allowOverride(const App::DocumentObject &) const override; /** @name Edit methods */ //@{ @@ -156,7 +153,7 @@ protected: protected: /// get called by the container whenever a property has been changed - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; bool loadParameter(); void updateVisual(); diff --git a/src/Mod/Part/Gui/ViewProviderExtrusion.cpp b/src/Mod/Part/Gui/ViewProviderExtrusion.cpp index 436e61b0f4..cfe4310662 100644 --- a/src/Mod/Part/Gui/ViewProviderExtrusion.cpp +++ b/src/Mod/Part/Gui/ViewProviderExtrusion.cpp @@ -40,7 +40,7 @@ ViewProviderExtrusion::~ViewProviderExtrusion() { } -std::vector ViewProviderExtrusion::claimChildren(void)const +std::vector ViewProviderExtrusion::claimChildren()const { std::vector temp; temp.push_back(static_cast(getObject())->Base.getValue()); diff --git a/src/Mod/Part/Gui/ViewProviderExtrusion.h b/src/Mod/Part/Gui/ViewProviderExtrusion.h index 6012c25cf0..0468c357e1 100644 --- a/src/Mod/Part/Gui/ViewProviderExtrusion.h +++ b/src/Mod/Part/Gui/ViewProviderExtrusion.h @@ -31,16 +31,16 @@ namespace PartGui { class PartGuiExport ViewProviderExtrusion : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderExtrusion); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderExtrusion); public: /// constructor ViewProviderExtrusion(); /// destructor - virtual ~ViewProviderExtrusion(); + ~ViewProviderExtrusion() override; /// grouping handling - std::vector claimChildren(void)const; + std::vector claimChildren(void)const override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp b/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp index ccfd1e0503..6f5b9553e1 100644 --- a/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderHelixParametric.cpp @@ -50,8 +50,8 @@ std::vector ViewProviderHelixParametric::getDisplayModes(void) cons { // add your own modes std::vector StrList; - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } @@ -81,8 +81,8 @@ std::vector ViewProviderSpiralParametric::getDisplayModes(void) con { // add your own modes std::vector StrList; - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderHelixParametric.h b/src/Mod/Part/Gui/ViewProviderHelixParametric.h index a7b26b069a..368c954be7 100644 --- a/src/Mod/Part/Gui/ViewProviderHelixParametric.h +++ b/src/Mod/Part/Gui/ViewProviderHelixParametric.h @@ -32,15 +32,15 @@ namespace PartGui { class PartGuiExport ViewProviderHelixParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderHelixParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderHelixParametric); public: /// constructor ViewProviderHelixParametric(); /// destructor - virtual ~ViewProviderHelixParametric(); - std::vector getDisplayModes(void) const; - void setupContextMenu(QMenu*, QObject*, const char*); + ~ViewProviderHelixParametric() override; + std::vector getDisplayModes(void) const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; private: ViewProviderSplineExtension extension; @@ -48,15 +48,15 @@ private: class PartGuiExport ViewProviderSpiralParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderSpiralParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSpiralParametric); public: /// constructor ViewProviderSpiralParametric(); /// destructor - virtual ~ViewProviderSpiralParametric(); - std::vector getDisplayModes(void) const; - void setupContextMenu(QMenu*, QObject*, const char*); + ~ViewProviderSpiralParametric() override; + std::vector getDisplayModes(void) const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; private: ViewProviderSplineExtension extension; diff --git a/src/Mod/Part/Gui/ViewProviderImport.cpp b/src/Mod/Part/Gui/ViewProviderImport.cpp index 6b0239cc91..00c3eb9bc9 100644 --- a/src/Mod/Part/Gui/ViewProviderImport.cpp +++ b/src/Mod/Part/Gui/ViewProviderImport.cpp @@ -20,27 +20,13 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderImport.h" -#include - -/// Here the FreeCAD includes sorted by Base,App,Gui...... -#include -#include -#include -#include -#include -#include using namespace PartGui; - //************************************************************************** // Construction/Destruction diff --git a/src/Mod/Part/Gui/ViewProviderImport.h b/src/Mod/Part/Gui/ViewProviderImport.h index 0a05801a81..448767872d 100644 --- a/src/Mod/Part/Gui/ViewProviderImport.h +++ b/src/Mod/Part/Gui/ViewProviderImport.h @@ -38,17 +38,17 @@ namespace PartGui { class PartGuiExport ViewProviderImport : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderImport); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderImport); public: /// constructor ViewProviderImport(); /// destructor - virtual ~ViewProviderImport(); + ~ViewProviderImport() override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/ViewProviderLineParametric.cpp b/src/Mod/Part/Gui/ViewProviderLineParametric.cpp index 8166b73453..7f17b5a0b0 100644 --- a/src/Mod/Part/Gui/ViewProviderLineParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderLineParametric.cpp @@ -20,19 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderLineParametric.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -53,14 +48,14 @@ ViewProviderLineParametric::~ViewProviderLineParametric() // ********************************************************************************** -std::vector ViewProviderLineParametric::getDisplayModes(void) const +std::vector ViewProviderLineParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderLineParametric.h b/src/Mod/Part/Gui/ViewProviderLineParametric.h index aa4ea4d244..2c1b8406fb 100644 --- a/src/Mod/Part/Gui/ViewProviderLineParametric.h +++ b/src/Mod/Part/Gui/ViewProviderLineParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderLineParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderLineParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderLineParametric); public: /// constructor ViewProviderLineParametric(); /// destructor - virtual ~ViewProviderLineParametric(); + ~ViewProviderLineParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes(void) const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderMirror.cpp b/src/Mod/Part/Gui/ViewProviderMirror.cpp index 31368f4394..ed9bb368e8 100644 --- a/src/Mod/Part/Gui/ViewProviderMirror.cpp +++ b/src/Mod/Part/Gui/ViewProviderMirror.cpp @@ -20,43 +20,43 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ # include # include # include + # include # include # include -# include -# include + # include # include +# include # include # include # include # include -# include #endif -#include -#include -#include -#include -#include -#include #include #include #include +#include +#include +#include +#include +#include +#include + #include "ViewProviderMirror.h" #include "DlgFilletEdges.h" #include "TaskOffset.h" #include "TaskThickness.h" -using namespace PartGui; +using namespace PartGui; PROPERTY_SOURCE(PartGui::ViewProviderMirror, PartGui::ViewProviderPart) @@ -266,6 +266,12 @@ void ViewProviderFillet::updateData(const App::Property* prop) applyColor(hist[0], colBase, colFill); } + // If the view provider has set a transparency then override the values + // of the input shapes + if (Transparency.getValue() > 0) { + applyTransparency(Transparency.getValue(), colFill); + } + this->DiffuseColor.setValues(colFill); } } @@ -357,21 +363,29 @@ void ViewProviderChamfer::updateData(const App::Property* prop) TopExp::MapShapes(baseShape, TopAbs_FACE, baseMap); TopExp::MapShapes(chamShape, TopAbs_FACE, chamMap); - Gui::ViewProvider* vpBase = Gui::Application::Instance->getViewProvider(objBase); - std::vector colBase = static_cast(vpBase)->DiffuseColor.getValues(); - std::vector colCham; - colCham.resize(chamMap.Extent(), static_cast(vpBase)->ShapeColor.getValue()); - applyTransparency(static_cast(vpBase)->Transparency.getValue(),colBase); + auto vpBase = dynamic_cast(Gui::Application::Instance->getViewProvider(objBase)); + if (vpBase) { + std::vector colBase = static_cast(vpBase)->DiffuseColor.getValues(); + std::vector colCham; + colCham.resize(chamMap.Extent(), static_cast(vpBase)->ShapeColor.getValue()); + applyTransparency(static_cast(vpBase)->Transparency.getValue(),colBase); - if (static_cast(colBase.size()) == baseMap.Extent()) { - applyColor(hist[0], colBase, colCham); - } - else if (!colBase.empty() && colBase[0] != this->ShapeColor.getValue()) { - colBase.resize(baseMap.Extent(), colBase[0]); - applyColor(hist[0], colBase, colCham); - } + if (static_cast(colBase.size()) == baseMap.Extent()) { + applyColor(hist[0], colBase, colCham); + } + else if (!colBase.empty() && colBase[0] != this->ShapeColor.getValue()) { + colBase.resize(baseMap.Extent(), colBase[0]); + applyColor(hist[0], colBase, colCham); + } - this->DiffuseColor.setValues(colCham); + // If the view provider has set a transparency then override the values + // of the input shapes + if (Transparency.getValue() > 0) { + applyTransparency(Transparency.getValue(), colCham); + } + + this->DiffuseColor.setValues(colCham); + } } } } diff --git a/src/Mod/Part/Gui/ViewProviderMirror.h b/src/Mod/Part/Gui/ViewProviderMirror.h index 1753a66291..11ad437455 100644 --- a/src/Mod/Part/Gui/ViewProviderMirror.h +++ b/src/Mod/Part/Gui/ViewProviderMirror.h @@ -31,20 +31,20 @@ namespace PartGui { class PartGuiExport ViewProviderMirror : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderMirror); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderMirror); public: ViewProviderMirror(); - virtual ~ViewProviderMirror(); + ~ViewProviderMirror() override; /** @name Edit methods */ //@{ - void setupContextMenu(QMenu*, QObject*, const char*); - std::vector claimChildren() const; - bool onDelete(const std::vector &); + void setupContextMenu(QMenu*, QObject*, const char*) override; + std::vector claimChildren() const override; + bool onDelete(const std::vector &) override; protected: - bool setEdit(int ModNum); - void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; //@} private: @@ -58,114 +58,114 @@ private: class PartGuiExport ViewProviderFillet : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderFillet); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderFillet); public: ViewProviderFillet(); - virtual ~ViewProviderFillet(); + ~ViewProviderFillet() override; /** @name Edit methods */ //@{ - void setupContextMenu(QMenu*, QObject*, const char*); - std::vector claimChildren() const; - bool onDelete(const std::vector &); + void setupContextMenu(QMenu*, QObject*, const char*) override; + std::vector claimChildren() const override; + bool onDelete(const std::vector &) override; protected: - void updateData(const App::Property*); - bool setEdit(int ModNum); - void unsetEdit(int ModNum); + void updateData(const App::Property*) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; //@} }; class ViewProviderChamfer : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderChamfer); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderChamfer); public: /// constructor ViewProviderChamfer(); /// destructor - virtual ~ViewProviderChamfer(); + ~ViewProviderChamfer() override; /** @name Edit methods */ //@{ - void setupContextMenu(QMenu*, QObject*, const char*); - std::vector claimChildren() const; - bool onDelete(const std::vector &); + void setupContextMenu(QMenu*, QObject*, const char*) override; + std::vector claimChildren() const override; + bool onDelete(const std::vector &) override; protected: - void updateData(const App::Property*); - bool setEdit(int ModNum); - void unsetEdit(int ModNum); + void updateData(const App::Property*) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; //@} }; class ViewProviderRevolution : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderRevolution); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRevolution); public: /// constructor ViewProviderRevolution(); /// destructor - virtual ~ViewProviderRevolution(); + ~ViewProviderRevolution() override; /// grouping handling - std::vector claimChildren(void)const; - bool onDelete(const std::vector &); + std::vector claimChildren()const override; + bool onDelete(const std::vector &) override; }; class ViewProviderLoft : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderLoft); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderLoft); public: /// constructor ViewProviderLoft(); /// destructor - virtual ~ViewProviderLoft(); + ~ViewProviderLoft() override; /// grouping handling - std::vector claimChildren(void)const; - bool onDelete(const std::vector &); + std::vector claimChildren()const override; + bool onDelete(const std::vector &) override; }; class ViewProviderSweep : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderSweep); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSweep); public: /// constructor ViewProviderSweep(); /// destructor - virtual ~ViewProviderSweep(); + ~ViewProviderSweep() override; /// grouping handling - std::vector claimChildren(void)const; - bool onDelete(const std::vector &); + std::vector claimChildren()const override; + bool onDelete(const std::vector &) override; }; class ViewProviderOffset : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderOffset); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderOffset); public: /// constructor ViewProviderOffset(); /// destructor - virtual ~ViewProviderOffset(); + ~ViewProviderOffset() override; /// grouping handling - std::vector claimChildren(void)const; - void setupContextMenu(QMenu*, QObject*, const char*); - bool onDelete(const std::vector &); + std::vector claimChildren()const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool onDelete(const std::vector &) override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; class ViewProviderOffset2D : public ViewProviderOffset { - PROPERTY_HEADER(PartGui::ViewProviderOffset2D); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderOffset2D); public: ViewProviderOffset2D(){ @@ -175,44 +175,44 @@ public: class ViewProviderThickness : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderThickness); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderThickness); public: /// constructor ViewProviderThickness(); /// destructor - virtual ~ViewProviderThickness(); + ~ViewProviderThickness() override; /// grouping handling - std::vector claimChildren(void)const; - void setupContextMenu(QMenu*, QObject*, const char*); - bool onDelete(const std::vector &); + std::vector claimChildren()const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool onDelete(const std::vector &) override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; class ViewProviderRefine : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderRefine); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRefine); public: /// constructor ViewProviderRefine(); /// destructor - virtual ~ViewProviderRefine(); + ~ViewProviderRefine() override; }; class ViewProviderReverse : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderReverse); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderReverse); public: /// constructor ViewProviderReverse(); /// destructor - virtual ~ViewProviderReverse(); + ~ViewProviderReverse() override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/ViewProviderPlaneParametric.cpp b/src/Mod/Part/Gui/ViewProviderPlaneParametric.cpp index da3c999ef3..d13e8505d9 100644 --- a/src/Mod/Part/Gui/ViewProviderPlaneParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderPlaneParametric.cpp @@ -20,18 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderPlaneParametric.h" #include #include -using namespace PartGui; +using namespace PartGui; //************************************************************************** // Construction/Destruction @@ -49,16 +45,16 @@ ViewProviderPlaneParametric::~ViewProviderPlaneParametric() } -std::vector ViewProviderPlaneParametric::getDisplayModes(void) const +std::vector ViewProviderPlaneParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } @@ -76,7 +72,7 @@ ViewProviderFace::~ViewProviderFace() { } -std::vector ViewProviderFace::claimChildren(void) const +std::vector ViewProviderFace::claimChildren() const { return std::vector(static_cast(getObject())->Sources.getValues()); } diff --git a/src/Mod/Part/Gui/ViewProviderPlaneParametric.h b/src/Mod/Part/Gui/ViewProviderPlaneParametric.h index 20423224f0..91414db8d6 100644 --- a/src/Mod/Part/Gui/ViewProviderPlaneParametric.h +++ b/src/Mod/Part/Gui/ViewProviderPlaneParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderPlaneParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderPlaneParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPlaneParametric); public: /// constructor ViewProviderPlaneParametric(); /// destructor - virtual ~ViewProviderPlaneParametric(); + ~ViewProviderPlaneParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: @@ -54,19 +54,19 @@ protected: class PartGuiExport ViewProviderFace : public ViewProviderPlaneParametric { - PROPERTY_HEADER(PartGui::ViewProviderFace); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderFace); public: ViewProviderFace(); - virtual ~ViewProviderFace(); + ~ViewProviderFace() override; - virtual std::vector claimChildren(void) const; - virtual bool canDragObjects() const; - virtual bool canDragObject(App::DocumentObject*) const; - virtual void dragObject(App::DocumentObject*); - virtual bool canDropObjects() const; - virtual bool canDropObject(App::DocumentObject*) const; - virtual void dropObject(App::DocumentObject*); + std::vector claimChildren() const override; + bool canDragObjects() const override; + bool canDragObject(App::DocumentObject*) const override; + void dragObject(App::DocumentObject*) override; + bool canDropObjects() const override; + bool canDropObject(App::DocumentObject*) const override; + void dropObject(App::DocumentObject*) override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/ViewProviderPointParametric.cpp b/src/Mod/Part/Gui/ViewProviderPointParametric.cpp index f6a44bacfa..6ac37aee31 100644 --- a/src/Mod/Part/Gui/ViewProviderPointParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderPointParametric.cpp @@ -20,19 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderPointParametric.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -53,16 +48,16 @@ ViewProviderPointParametric::~ViewProviderPointParametric() // ********************************************************************************** -std::vector ViewProviderPointParametric::getDisplayModes(void) const +std::vector ViewProviderPointParametric::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderPointParametric.h b/src/Mod/Part/Gui/ViewProviderPointParametric.h index 443a08cfee..32ff1f6d0b 100644 --- a/src/Mod/Part/Gui/ViewProviderPointParametric.h +++ b/src/Mod/Part/Gui/ViewProviderPointParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderPointParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderPointParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPointParametric); public: /// constructor ViewProviderPointParametric(); /// destructor - virtual ~ViewProviderPointParametric(); + ~ViewProviderPointParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderPrimitive.cpp b/src/Mod/Part/Gui/ViewProviderPrimitive.cpp index 97415db6f6..018ac6dd88 100644 --- a/src/Mod/Part/Gui/ViewProviderPrimitive.cpp +++ b/src/Mod/Part/Gui/ViewProviderPrimitive.cpp @@ -20,7 +20,6 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ @@ -28,16 +27,8 @@ # include #endif -#include -#include -#include #include -#include -#include #include -#include - -#include #include #include "ViewProviderPrimitive.h" @@ -46,7 +37,6 @@ using namespace PartGui; - PROPERTY_SOURCE(PartGui::ViewProviderPrimitive, PartGui::ViewProviderPart) ViewProviderPrimitive::ViewProviderPrimitive() diff --git a/src/Mod/Part/Gui/ViewProviderPrimitive.h b/src/Mod/Part/Gui/ViewProviderPrimitive.h index 4c88f5daf2..cefacdf979 100644 --- a/src/Mod/Part/Gui/ViewProviderPrimitive.h +++ b/src/Mod/Part/Gui/ViewProviderPrimitive.h @@ -32,19 +32,19 @@ namespace PartGui { class PartGuiExport ViewProviderPrimitive : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderPrimitive); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPrimitive); public: /// constructor ViewProviderPrimitive(); /// destructor - virtual ~ViewProviderPrimitive(); + ~ViewProviderPrimitive() override; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; protected: - bool setEdit(int ModNum); - void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; private: ViewProviderAttachExtension extension; diff --git a/src/Mod/Part/Gui/ViewProviderPrism.cpp b/src/Mod/Part/Gui/ViewProviderPrism.cpp index b30b291dc2..28434e108c 100644 --- a/src/Mod/Part/Gui/ViewProviderPrism.cpp +++ b/src/Mod/Part/Gui/ViewProviderPrism.cpp @@ -20,18 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderPrism.h" + using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -50,16 +46,16 @@ ViewProviderPrism::~ViewProviderPrism() // ********************************************************************************** -std::vector ViewProviderPrism::getDisplayModes(void) const +std::vector ViewProviderPrism::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } @@ -82,16 +78,16 @@ ViewProviderWedge::~ViewProviderWedge() // ********************************************************************************** -std::vector ViewProviderWedge::getDisplayModes(void) const +std::vector ViewProviderWedge::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderPrism.h b/src/Mod/Part/Gui/ViewProviderPrism.h index 8c2c233cf1..e829215b87 100644 --- a/src/Mod/Part/Gui/ViewProviderPrism.h +++ b/src/Mod/Part/Gui/ViewProviderPrism.h @@ -32,15 +32,15 @@ namespace PartGui { class PartGuiExport ViewProviderPrism : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderPrism); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderPrism); public: /// constructor ViewProviderPrism(); /// destructor - virtual ~ViewProviderPrism(); + ~ViewProviderPrism() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: @@ -48,15 +48,15 @@ protected: class PartGuiExport ViewProviderWedge : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderWedge); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderWedge); public: /// constructor ViewProviderWedge(); /// destructor - virtual ~ViewProviderWedge(); + ~ViewProviderWedge() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderPython.cpp b/src/Mod/Part/Gui/ViewProviderPython.cpp index e0ce000aad..e7fa75fe1b 100644 --- a/src/Mod/Part/Gui/ViewProviderPython.cpp +++ b/src/Mod/Part/Gui/ViewProviderPython.cpp @@ -20,7 +20,6 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #include @@ -28,9 +27,10 @@ # include #endif #include -#include + #include "ViewProviderPython.h" + using namespace PartGui; PROPERTY_SOURCE(PartGui::ViewProviderCustom, PartGui::ViewProviderPart) diff --git a/src/Mod/Part/Gui/ViewProviderPython.h b/src/Mod/Part/Gui/ViewProviderPython.h index 24c705753e..945c123b07 100644 --- a/src/Mod/Part/Gui/ViewProviderPython.h +++ b/src/Mod/Part/Gui/ViewProviderPython.h @@ -31,17 +31,17 @@ namespace PartGui { class PartGuiExport ViewProviderCustom : public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderCustom); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderCustom); public: /// constructor ViewProviderCustom(); /// destructor - virtual ~ViewProviderCustom(); - virtual void updateData(const App::Property*); + ~ViewProviderCustom() override; + void updateData(const App::Property*) override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; std::map propView; }; diff --git a/src/Mod/Part/Gui/ViewProviderReference.cpp b/src/Mod/Part/Gui/ViewProviderReference.cpp index 513138ff07..fa9482dbf0 100644 --- a/src/Mod/Part/Gui/ViewProviderReference.cpp +++ b/src/Mod/Part/Gui/ViewProviderReference.cpp @@ -20,75 +20,24 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +// to avoid compiler warnings of redefining contents of basic.h +// later by #include "ViewProvider.h" +# define _USE_MATH_DEFINES +# include + # include -# include -# include +# include +# include #endif -/// Here the FreeCAD includes sorted by Base,App,Gui...... -#include -#include -#include -#include #include -#include -#include - +#include #include "ViewProvider.h" #include "ViewProviderReference.h" -#include "SoFCShapeObject.h" - -#include -#include using namespace PartGui; @@ -277,16 +226,16 @@ void ViewProviderPartReference::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode( ModeName ); } -std::vector ViewProviderPartReference::getDisplayModes(void) const +std::vector ViewProviderPartReference::getDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderGeometryObject::getDisplayModes(); // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderReference.h b/src/Mod/Part/Gui/ViewProviderReference.h index 134a6038b7..b7a0219b3b 100644 --- a/src/Mod/Part/Gui/ViewProviderReference.h +++ b/src/Mod/Part/Gui/ViewProviderReference.h @@ -35,12 +35,12 @@ class TopoDS_Shape; class TopoDS_Edge; class TopoDS_Wire; class TopoDS_Face; -class SoSeparator; -class SoGroup; +class SoSeparator; +class SoGroup; class SoSwitch; class SoVertexShape; -class SoPickedPoint; -class SoShapeHints; +class SoPickedPoint; +class SoShapeHints; class SoEventCallback; class SbVec3f; class SoSphere; diff --git a/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp b/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp index 52cceb6722..f2e33549fd 100644 --- a/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp +++ b/src/Mod/Part/Gui/ViewProviderRegularPolygon.cpp @@ -20,18 +20,14 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderRegularPolygon.h" + using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -52,14 +48,14 @@ ViewProviderRegularPolygon::~ViewProviderRegularPolygon() // ********************************************************************************** -std::vector ViewProviderRegularPolygon::getDisplayModes(void) const +std::vector ViewProviderRegularPolygon::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderRegularPolygon.h b/src/Mod/Part/Gui/ViewProviderRegularPolygon.h index 63f7dddbb5..0052fb993d 100644 --- a/src/Mod/Part/Gui/ViewProviderRegularPolygon.h +++ b/src/Mod/Part/Gui/ViewProviderRegularPolygon.h @@ -32,15 +32,15 @@ namespace PartGui { class PartGuiExport ViewProviderRegularPolygon : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderRegularPolygon); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRegularPolygon); public: /// constructor ViewProviderRegularPolygon(); /// destructor - virtual ~ViewProviderRegularPolygon(); + ~ViewProviderRegularPolygon() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; protected: diff --git a/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp b/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp index a92941c578..6e76556cdf 100644 --- a/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp +++ b/src/Mod/Part/Gui/ViewProviderRuledSurface.cpp @@ -20,23 +20,17 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - -#include "ViewProviderRuledSurface.h" +#include #include -#include -#include +#include "ViewProviderRuledSurface.h" using namespace PartGui; using namespace std; - //************************************************************************** // Construction/Destruction @@ -102,16 +96,16 @@ bool ViewProviderRuledSurface::onDelete(const std::vector &) // ********************************************************************************** -std::vector ViewProviderRuledSurface::getDisplayModes(void) const +std::vector ViewProviderRuledSurface::getDisplayModes() const { // get the modes of the father std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderRuledSurface.h b/src/Mod/Part/Gui/ViewProviderRuledSurface.h index 824e7da0c2..c8ce24edf4 100644 --- a/src/Mod/Part/Gui/ViewProviderRuledSurface.h +++ b/src/Mod/Part/Gui/ViewProviderRuledSurface.h @@ -20,33 +20,29 @@ * * ***************************************************************************/ - #ifndef PARTGUI_VIEWPROVIDERRULEDSURFACE_H #define PARTGUI_VIEWPROVIDERRULEDSURFACE_H #include "ViewProvider.h" - - namespace PartGui { class PartGuiExport ViewProviderRuledSurface:public ViewProviderPart { - PROPERTY_HEADER(PartGui::ViewProviderRuledSurface); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderRuledSurface); public: /// constructor ViewProviderRuledSurface(); /// destructor - virtual ~ViewProviderRuledSurface(); + ~ViewProviderRuledSurface() override; - std::vector getDisplayModes(void) const; - std::vector claimChildren() const; - void updateData(const App::Property*); - bool onDelete(const std::vector &); - + std::vector getDisplayModes(void) const override; + std::vector claimChildren() const override; + void updateData(const App::Property*) override; + bool onDelete(const std::vector &) override; protected: @@ -56,4 +52,3 @@ protected: #endif // PARTGUI_VIEWPROVIDERRULEDSURFACE_H - diff --git a/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp b/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp index a1a9e4b83d..427310794e 100644 --- a/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderSphereParametric.cpp @@ -20,12 +20,8 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderSphereParametric.h" using namespace PartGui; @@ -46,15 +42,15 @@ ViewProviderSphereParametric::~ViewProviderSphereParametric() } -std::vector ViewProviderSphereParametric::getDisplayModes(void) const +std::vector ViewProviderSphereParametric::getDisplayModes() const { std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } @@ -72,15 +68,15 @@ ViewProviderEllipsoid::~ViewProviderEllipsoid() { } -std::vector ViewProviderEllipsoid::getDisplayModes(void) const +std::vector ViewProviderEllipsoid::getDisplayModes() const { std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderSphereParametric.h b/src/Mod/Part/Gui/ViewProviderSphereParametric.h index d677739b48..fd4968bec9 100644 --- a/src/Mod/Part/Gui/ViewProviderSphereParametric.h +++ b/src/Mod/Part/Gui/ViewProviderSphereParametric.h @@ -30,15 +30,15 @@ namespace PartGui { class PartGuiExport ViewProviderSphereParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderSphereParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSphereParametric); public: /// constructor ViewProviderSphereParametric(); /// destructor - virtual ~ViewProviderSphereParametric(); + ~ViewProviderSphereParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes(void) const override; protected: @@ -46,14 +46,14 @@ protected: class PartGuiExport ViewProviderEllipsoid : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderEllipsoid); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderEllipsoid); public: /// constructor ViewProviderEllipsoid(); /// destructor - virtual ~ViewProviderEllipsoid(); - std::vector getDisplayModes(void) const; + ~ViewProviderEllipsoid() override; + std::vector getDisplayModes(void) const override; }; } // namespace PartGui diff --git a/src/Mod/Part/Gui/ViewProviderSpline.cpp b/src/Mod/Part/Gui/ViewProviderSpline.cpp index e876f4a192..5e747dce35 100644 --- a/src/Mod/Part/Gui/ViewProviderSpline.cpp +++ b/src/Mod/Part/Gui/ViewProviderSpline.cpp @@ -20,38 +20,36 @@ * * ***************************************************************************/ - #include "PreCompiled.h" #ifndef _PreComp_ +# include +# include + # include # include -# include -# include # include -# include # include +# include # include # include # include # include -# include # include # include # include +# include # include + # include # include # include -# include -# include #endif -#include -#include #include #include -#include "SoFCShapeObject.h" + #include "ViewProviderSpline.h" +#include "SoFCShapeObject.h" using namespace PartGui; diff --git a/src/Mod/Part/Gui/ViewProviderSpline.h b/src/Mod/Part/Gui/ViewProviderSpline.h index 1157782a70..93a069951b 100644 --- a/src/Mod/Part/Gui/ViewProviderSpline.h +++ b/src/Mod/Part/Gui/ViewProviderSpline.h @@ -36,15 +36,15 @@ class PartGuiExport ViewProviderSplineExtension : public Gui::ViewProviderExtens public: /// Constructor ViewProviderSplineExtension(); - virtual ~ViewProviderSplineExtension() = default; + ~ViewProviderSplineExtension() override = default; App::PropertyBool ControlPoints; - virtual void extensionUpdateData(const App::Property*) override; - virtual void extensionSetupContextMenu(QMenu*, QObject*, const char*) override; + void extensionUpdateData(const App::Property*) override; + void extensionSetupContextMenu(QMenu*, QObject*, const char*) override; protected: - virtual void extensionOnChanged(const App::Property* p) override; + void extensionOnChanged(const App::Property* p) override; void toggleControlPoints(bool); void showControlPoints(bool, const App::Property* prop); void showControlPointsOfEdge(const TopoDS_Edge&); @@ -55,15 +55,15 @@ protected: class PartGuiExport ViewProviderSpline : public ViewProviderPartExt { - PROPERTY_HEADER(PartGui::ViewProviderSpline); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderSpline); public: /// constructor ViewProviderSpline(); /// destructor - virtual ~ViewProviderSpline(); + ~ViewProviderSpline() override; - QIcon getIcon() const; + QIcon getIcon() const override; private: ViewProviderSplineExtension extension; diff --git a/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp b/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp index b32aa05111..7c2ed137ba 100644 --- a/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp +++ b/src/Mod/Part/Gui/ViewProviderTorusParametric.cpp @@ -20,15 +20,10 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include "ViewProviderTorusParametric.h" - using namespace PartGui; using namespace std; @@ -59,10 +54,10 @@ std::vector ViewProviderTorusParametric::getDisplayModes(void) cons std::vector StrList; // add your own modes - StrList.push_back("Flat Lines"); - StrList.push_back("Shaded"); - StrList.push_back("Wireframe"); - StrList.push_back("Points"); + StrList.emplace_back("Flat Lines"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Wireframe"); + StrList.emplace_back("Points"); return StrList; } diff --git a/src/Mod/Part/Gui/ViewProviderTorusParametric.h b/src/Mod/Part/Gui/ViewProviderTorusParametric.h index a36f8a5f55..836b8c0f7b 100644 --- a/src/Mod/Part/Gui/ViewProviderTorusParametric.h +++ b/src/Mod/Part/Gui/ViewProviderTorusParametric.h @@ -38,15 +38,15 @@ namespace PartGui { class PartGuiExport ViewProviderTorusParametric : public ViewProviderPrimitive { - PROPERTY_HEADER(PartGui::ViewProviderTorusParametric); + PROPERTY_HEADER_WITH_OVERRIDE(PartGui::ViewProviderTorusParametric); public: /// constructor ViewProviderTorusParametric(); /// destructor - virtual ~ViewProviderTorusParametric(); + ~ViewProviderTorusParametric() override; - std::vector getDisplayModes(void) const; + std::vector getDisplayModes(void) const override; protected: diff --git a/src/Mod/Part/Gui/Workbench.h b/src/Mod/Part/Gui/Workbench.h index 50dbeb1b99..22723bb99e 100644 --- a/src/Mod/Part/Gui/Workbench.h +++ b/src/Mod/Part/Gui/Workbench.h @@ -34,16 +34,16 @@ namespace PartGui { */ class PartGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace PartGui diff --git a/src/Mod/Part/TestPartApp.py b/src/Mod/Part/TestPartApp.py index 5b83b82a89..a8fec8d064 100644 --- a/src/Mod/Part/TestPartApp.py +++ b/src/Mod/Part/TestPartApp.py @@ -174,6 +174,24 @@ class PartTestBSplineCurve(unittest.TestCase): #closing doc FreeCAD.closeDocument("PartTest") +class PartTestBSplineSurface(unittest.TestCase): + def testTorusToSpline(self): + to = Part.Toroid() + bs = to.toBSpline() + bs.setUPeriodic() + bs.setVPeriodic() + self.assertGreater(len(bs.UKnotSequence), 0) + self.assertGreater(len(bs.VKnotSequence), 0) + + def testBounds(self): + to = Part.Toroid() + bs = to.toBSpline() + self.assertAlmostEqual(bs.bounds()[1], 2 * math.pi) + self.assertAlmostEqual(bs.bounds()[3], 2 * math.pi) + bs.scaleKnotsToBounds(0.0, 1.0, 0.0, 1.0) + self.assertAlmostEqual(bs.bounds()[1], 1.0) + self.assertAlmostEqual(bs.bounds()[3], 1.0) + class PartTestNormals(unittest.TestCase): def setUp(self): self.face = Part.makePlane(1, 1) @@ -198,6 +216,29 @@ class PartTestNormals(unittest.TestCase): def tearDown(self): pass +class PartTestShapeRotate(unittest.TestCase): + def testPlacement(self): + box = Part.makeBox(1, 1, 1) + box.Placement.Base = Base.Vector(10, 10, 10) + box.rotate((0, 0, 0), (0, 0, 1), 90) + + p1 = Base.Placement() + p1.Base = Base.Vector(10, 10, 10) + + p2 = Base.Placement() + p2.Rotation.Angle = math.radians(90) + self.assertTrue(box.Placement.isSame(p2 * p1)) + + p5 = p1.copy() + p5.rotate((0, 0, 0), (0, 0, 1), 90) + self.assertTrue(p5.isSame(p1 * p2)) + self.assertFalse(box.Placement.isSame(p5)) + + p5 = p1.copy() + p5.rotate((0, 0, 0), (0, 0, 1), 90, True) + self.assertTrue(p5.isSame(p2 * p1)) + self.assertTrue(box.Placement.isSame(p5)) + class PartTestCircle2D(unittest.TestCase): def testValidCircle(self): p1 = App.Base.Vector2d(0.01, 0.01) diff --git a/src/Mod/PartDesign/App/AppPartDesignPy.cpp b/src/Mod/PartDesign/App/AppPartDesignPy.cpp index e448dd58fe..9dfdc81f17 100644 --- a/src/Mod/PartDesign/App/AppPartDesignPy.cpp +++ b/src/Mod/PartDesign/App/AppPartDesignPy.cpp @@ -40,7 +40,7 @@ public: initialize("This module is the PartDesign module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object makeFilletArc(const Py::Tuple& args) diff --git a/src/Mod/PartDesign/App/Body.cpp b/src/Mod/PartDesign/App/Body.cpp index 25948d3fb0..3a27dc70ad 100644 --- a/src/Mod/PartDesign/App/Body.cpp +++ b/src/Mod/PartDesign/App/Body.cpp @@ -173,9 +173,9 @@ bool Body::isAfterInsertPoint(App::DocumentObject* feature) { } } -bool Body::isMemberOfMultiTransform(const App::DocumentObject* f) +bool Body::isMemberOfMultiTransform(const App::DocumentObject* obj) { - if (f == nullptr) + if (!obj) return false; // ORIGINAL COMMENT: @@ -189,38 +189,38 @@ bool Body::isMemberOfMultiTransform(const App::DocumentObject* f) // to auto set it when the originals are not null. See: // App::DocumentObjectExecReturn *Transformed::execute(void) // - return (f->getTypeId().isDerivedFrom(PartDesign::Transformed::getClassTypeId()) && - static_cast(f)->Originals.getValues().empty()); + return (obj->getTypeId().isDerivedFrom(PartDesign::Transformed::getClassTypeId()) && + static_cast(obj)->Originals.getValues().empty()); } -bool Body::isSolidFeature(const App::DocumentObject* f) +bool Body::isSolidFeature(const App::DocumentObject *obj) { - if (f == nullptr) + if (!obj) return false; - if (f->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) && - !PartDesign::Feature::isDatum(f)) { + if (obj->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) && + !PartDesign::Feature::isDatum(obj)) { // Transformed Features inside a MultiTransform are not solid features - return !isMemberOfMultiTransform(f); + return !isMemberOfMultiTransform(obj); } return false;//DeepSOIC: work-in-progress? } -bool Body::isAllowed(const App::DocumentObject* f) +bool Body::isAllowed(const App::DocumentObject *obj) { - if (f == nullptr) + if (!obj) return false; // TODO: Should we introduce a PartDesign::FeaturePython class? This should then also return true for isSolidFeature() - return (f->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) || - f->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId()) || + return (obj->getTypeId().isDerivedFrom(PartDesign::Feature::getClassTypeId()) || + obj->getTypeId().isDerivedFrom(Part::Datum::getClassTypeId()) || // TODO Shouldn't we replace it with Sketcher::SketchObject? (2015-08-13, Fat-Zer) - f->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId()) || - f->getTypeId().isDerivedFrom(PartDesign::ShapeBinder::getClassTypeId()) || - f->getTypeId().isDerivedFrom(PartDesign::SubShapeBinder::getClassTypeId()) + obj->getTypeId().isDerivedFrom(Part::Part2DObject::getClassTypeId()) || + obj->getTypeId().isDerivedFrom(PartDesign::ShapeBinder::getClassTypeId()) || + obj->getTypeId().isDerivedFrom(PartDesign::SubShapeBinder::getClassTypeId()) // TODO Why this lines was here? why should we allow anything of those? (2015-08-13, Fat-Zer) - //f->getTypeId().isDerivedFrom(Part::FeaturePython::getClassTypeId()) // trouble with this line on Windows!? Linker fails to find getClassTypeId() of the Part::FeaturePython... - //f->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()) + //obj->getTypeId().isDerivedFrom(Part::FeaturePython::getClassTypeId()) // trouble with this line on Windows!? Linker fails to find getClassTypeId() of the Part::FeaturePython... + //obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId()) ); } @@ -373,7 +373,7 @@ std::vector Body::removeObject(App::DocumentObject* featur } -App::DocumentObjectExecReturn *Body::execute(void) +App::DocumentObjectExecReturn *Body::execute() { /* Base::Console().Error("Body '%s':\n", getNameInDocument()); @@ -476,7 +476,7 @@ void Body::unsetupObject () { Part::BodyBase::unsetupObject (); } -PyObject *Body::getPyObject(void) +PyObject *Body::getPyObject() { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 diff --git a/src/Mod/PartDesign/App/Body.h b/src/Mod/PartDesign/App/Body.h index 33e83307e7..6964159fe0 100644 --- a/src/Mod/PartDesign/App/Body.h +++ b/src/Mod/PartDesign/App/Body.h @@ -50,11 +50,11 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderBody"; } //@} @@ -63,8 +63,8 @@ public: * Add the feature into the body at the current insert point. * The insertion poin is the before next solid after the Tip feature */ - virtual std::vector addObject(App::DocumentObject*) override; - virtual std::vector< DocumentObject* > addObjects(std::vector< DocumentObject* > obj) override; + std::vector addObject(App::DocumentObject*) override; + std::vector< DocumentObject* > addObjects(std::vector< DocumentObject* > obj) override; /** * Insert the feature into the body after the given feature. @@ -82,7 +82,7 @@ public: void setBaseProperty(App::DocumentObject* feature); /// Remove the feature from the body - virtual std::vector removeObject(DocumentObject* obj) override; + std::vector removeObject(DocumentObject* obj) override; /** * Checks if the given document object lays after the current insert point @@ -91,21 +91,23 @@ public: bool isAfterInsertPoint(App::DocumentObject* feature); /// Return true if the given feature is member of a MultiTransform feature - static bool isMemberOfMultiTransform(const App::DocumentObject* f); + static bool isMemberOfMultiTransform(const App::DocumentObject *obj); /** * Return true if the given feature is a solid feature allowed in a Body. Currently this is only valid * for features derived from PartDesign::Feature * Return false if the given feature is a Sketch or a Part::Datum feature */ - static bool isSolidFeature(const App::DocumentObject* f); + static bool isSolidFeature(const App::DocumentObject *obj); /** * Return true if the given feature is allowed in a Body. Currently allowed are * all features derived from PartDesign::Feature and Part::Datum and sketches */ - static bool isAllowed(const App::DocumentObject* f); - virtual bool allowObject(DocumentObject* f) override {return isAllowed(f);} + static bool isAllowed(const App::DocumentObject *obj); + bool allowObject(DocumentObject *obj) override { + return isAllowed(obj); + } /** * Return the body which this feature belongs too, or NULL @@ -113,10 +115,10 @@ public: */ static Body *findBodyOf(const App::DocumentObject* feature); - PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual std::vector getSubObjects(int reason=0) const override; - virtual App::DocumentObject *getSubObject(const char *subname, + std::vector getSubObjects(int reason=0) const override; + App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const override; void setShowTip(bool enable) { @@ -136,20 +138,20 @@ public: App::DocumentObject *getNextSolidFeature(App::DocumentObject* start = nullptr); // a body is solid if it has features that are solid according to member isSolidFeature. - bool isSolid(void); + bool isSolid(); protected: - virtual void onSettingDocument() override; + void onSettingDocument() override; /// Adjusts the first solid's feature's base on BaseFeature getting set - virtual void onChanged (const App::Property* prop) override; + void onChanged (const App::Property* prop) override; /// Creates the corresponding Origin object - virtual void setupObject () override; + void setupObject () override; /// Removes all planes and axis if they are still linked to the document - virtual void unsetupObject () override; + void unsetupObject () override; - virtual void onDocumentRestored() override; + void onDocumentRestored() override; private: boost::signals2::scoped_connection connection; diff --git a/src/Mod/PartDesign/App/BodyPy.xml b/src/Mod/PartDesign/App/BodyPy.xml index 8aadafec57..59e9bb5ef8 100644 --- a/src/Mod/PartDesign/App/BodyPy.xml +++ b/src/Mod/PartDesign/App/BodyPy.xml @@ -30,7 +30,7 @@
- Return the the visible feature of this body + Return the visible feature of this body diff --git a/src/Mod/PartDesign/App/BodyPyImp.cpp b/src/Mod/PartDesign/App/BodyPyImp.cpp index c1d342afc6..6f3bcf4e1e 100644 --- a/src/Mod/PartDesign/App/BodyPyImp.cpp +++ b/src/Mod/PartDesign/App/BodyPyImp.cpp @@ -33,7 +33,7 @@ using namespace PartDesign; // returns a string which represents the object e.g. when printed in python -std::string BodyPy::representation(void) const +std::string BodyPy::representation() const { return std::string(""); } diff --git a/src/Mod/PartDesign/App/CMakeLists.txt b/src/Mod/PartDesign/App/CMakeLists.txt index 182a3423be..d74a77c1d5 100644 --- a/src/Mod/PartDesign/App/CMakeLists.txt +++ b/src/Mod/PartDesign/App/CMakeLists.txt @@ -14,6 +14,7 @@ include_directories( ${QT_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${QT_INCLUDE_DIR} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/PartDesign/App/DatumCS.h b/src/Mod/PartDesign/App/DatumCS.h index 40742300ca..f21bb43837 100644 --- a/src/Mod/PartDesign/App/DatumCS.h +++ b/src/Mod/PartDesign/App/DatumCS.h @@ -36,9 +36,9 @@ class PartDesignExport CoordinateSystem : public Part::Datum public: CoordinateSystem(); - virtual ~CoordinateSystem(); + ~CoordinateSystem() override; - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderDatumCoordinateSystem"; } @@ -46,7 +46,7 @@ public: Base::Vector3d getYAxis(); Base::Vector3d getZAxis(); - virtual App::DocumentObject *getSubObject(const char *subname, + App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj, Base::Matrix4D *pmat, bool transform, int depth) const override; }; diff --git a/src/Mod/PartDesign/App/DatumLine.h b/src/Mod/PartDesign/App/DatumLine.h index 6a4497c6cc..8faa330fb9 100644 --- a/src/Mod/PartDesign/App/DatumLine.h +++ b/src/Mod/PartDesign/App/DatumLine.h @@ -34,17 +34,17 @@ namespace PartDesign class PartDesignExport Line : public Part::Datum { - PROPERTY_HEADER(PartDesign::Line); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Line); public: Line(); - virtual ~Line(); + ~Line() override; App::PropertyEnumeration ResizeMode; App::PropertyLength Length; - virtual void onChanged(const App::Property *prop); + void onChanged(const App::Property *prop) override; - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderDatumLine"; } diff --git a/src/Mod/PartDesign/App/DatumPlane.h b/src/Mod/PartDesign/App/DatumPlane.h index 8c2035be35..0b6e83f35f 100644 --- a/src/Mod/PartDesign/App/DatumPlane.h +++ b/src/Mod/PartDesign/App/DatumPlane.h @@ -34,25 +34,25 @@ namespace PartDesign class PartDesignExport Plane : public Part::Datum { - PROPERTY_HEADER(PartDesign::Plane); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Plane); public: Plane(); - virtual ~Plane(); + ~Plane() override; App::PropertyEnumeration ResizeMode; App::PropertyLength Length; App::PropertyLength Width; - virtual void onChanged(const App::Property *prop); - const char* getViewProviderName(void) const { + void onChanged(const App::Property *prop) override; + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderDatumPlane"; } Base::Vector3d getNormal(); protected: - virtual void Restore(Base::XMLReader& reader); + void Restore(Base::XMLReader& reader) override; private: static const char* ResizeModeEnums[]; diff --git a/src/Mod/PartDesign/App/DatumPoint.h b/src/Mod/PartDesign/App/DatumPoint.h index bf58b1fe5d..5f72f04c46 100644 --- a/src/Mod/PartDesign/App/DatumPoint.h +++ b/src/Mod/PartDesign/App/DatumPoint.h @@ -37,9 +37,9 @@ class PartDesignExport Point : public Part::Datum public: Point(); - virtual ~Point(); + ~Point() override; - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderDatumPoint"; } @@ -48,8 +48,8 @@ public: typedef Part::Datum Superclass; protected: - virtual void onChanged(const App::Property* prop) override; - virtual void onDocumentRestored() override; + void onChanged(const App::Property* prop) override; + void onDocumentRestored() override; private: void makeShape(); diff --git a/src/Mod/PartDesign/App/Feature.cpp b/src/Mod/PartDesign/App/Feature.cpp index 4801586d3a..9ac0fe8c8a 100644 --- a/src/Mod/PartDesign/App/Feature.cpp +++ b/src/Mod/PartDesign/App/Feature.cpp @@ -197,7 +197,7 @@ bool Feature::isDatum(const App::DocumentObject* feature) gp_Pln Feature::makePlnFromPlane(const App::DocumentObject* obj) { const App::GeoFeature* plane = static_cast(obj); - if (plane == nullptr) + if (!plane) throw Base::ValueError("Feature: Null object"); Base::Vector3d pos = plane->Placement.getValue().getPosition(); @@ -239,10 +239,10 @@ Body* Feature::getFeatureBody() const { namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(PartDesign::FeaturePython, PartDesign::Feature) -template<> const char* PartDesign::FeaturePython::getViewProviderName(void) const { +template<> const char* PartDesign::FeaturePython::getViewProviderName() const { return "PartDesignGui::ViewProviderPython"; } -template<> PyObject* PartDesign::FeaturePython::getPyObject(void) { +template<> PyObject* PartDesign::FeaturePython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new FeaturePythonPyT(this),true); diff --git a/src/Mod/PartDesign/App/Feature.h b/src/Mod/PartDesign/App/Feature.h index cb430ee80d..3c3df3075b 100644 --- a/src/Mod/PartDesign/App/Feature.h +++ b/src/Mod/PartDesign/App/Feature.h @@ -46,7 +46,7 @@ class Body; */ class PartDesignExport Feature : public Part::Feature { - PROPERTY_HEADER(PartDesign::Feature); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Feature); public: Feature(); @@ -55,7 +55,7 @@ public: App::PropertyLink BaseFeature; App::PropertyLinkHidden _Body; - short mustExecute() const; + short mustExecute() const override; /// Check whether the given feature is a datum feature static bool isDatum(const App::DocumentObject* feature); @@ -75,9 +75,9 @@ public: /// Returns the BaseFeature property's TopoShape (if any) Part::TopoShape getBaseTopoShape(bool silent=false) const; - virtual PyObject* getPyObject(void); + PyObject* getPyObject() override; - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProvider"; } diff --git a/src/Mod/PartDesign/App/FeatureAddSub.h b/src/Mod/PartDesign/App/FeatureAddSub.h index f7fea78e3b..d6c09aabab 100644 --- a/src/Mod/PartDesign/App/FeatureAddSub.h +++ b/src/Mod/PartDesign/App/FeatureAddSub.h @@ -44,7 +44,7 @@ public: Type getAddSubType(); - virtual short mustExecute() const override; + short mustExecute() const override; virtual void getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShape); @@ -61,20 +61,20 @@ typedef App::FeaturePythonT FeatureAddSubPython; class FeatureAdditivePython : public FeatureAddSubPython { - PROPERTY_HEADER(PartDesign::FeatureAdditivePython); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureAdditivePython); public: FeatureAdditivePython(); - ~FeatureAdditivePython(); + ~FeatureAdditivePython() override; }; class FeatureSubtractivePython : public FeatureAddSubPython { - PROPERTY_HEADER(PartDesign::FeatureSubtractivePython); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureSubtractivePython); public: FeatureSubtractivePython(); - ~FeatureSubtractivePython(); + ~FeatureSubtractivePython() override; }; } //namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureBase.cpp b/src/Mod/PartDesign/App/FeatureBase.cpp index c80c0169b6..40aeebfb32 100644 --- a/src/Mod/PartDesign/App/FeatureBase.cpp +++ b/src/Mod/PartDesign/App/FeatureBase.cpp @@ -47,7 +47,7 @@ Part::Feature* FeatureBase::getBaseObject(bool) const { return nullptr; } -short int FeatureBase::mustExecute(void) const { +short int FeatureBase::mustExecute() const { if(BaseFeature.isTouched()) return 1; @@ -56,7 +56,7 @@ short int FeatureBase::mustExecute(void) const { } -App::DocumentObjectExecReturn* FeatureBase::execute(void) { +App::DocumentObjectExecReturn* FeatureBase::execute() { if(!BaseFeature.getValue()) return new App::DocumentObjectExecReturn("BaseFeature link is not set"); diff --git a/src/Mod/PartDesign/App/FeatureBase.h b/src/Mod/PartDesign/App/FeatureBase.h index 0324e6316f..d68559a8b0 100644 --- a/src/Mod/PartDesign/App/FeatureBase.h +++ b/src/Mod/PartDesign/App/FeatureBase.h @@ -32,22 +32,22 @@ namespace PartDesign class PartDesignExport FeatureBase : public PartDesign::Feature { - PROPERTY_HEADER(PartDesign::FeatureBase); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureBase); public: FeatureBase(); - virtual short int mustExecute(void) const; + short int mustExecute() const override; - virtual Part::Feature* getBaseObject(bool silent=false) const; + Part::Feature* getBaseObject(bool silent=false) const override; - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderBase"; } - virtual void onChanged(const App::Property* prop); - virtual App::DocumentObjectExecReturn* execute(void); - virtual void onDocumentRestored(); + void onChanged(const App::Property* prop) override; + App::DocumentObjectExecReturn* execute() override; + void onDocumentRestored() override; }; } //namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureBoolean.cpp b/src/Mod/PartDesign/App/FeatureBoolean.cpp index 59aaead73f..c9da6922bb 100644 --- a/src/Mod/PartDesign/App/FeatureBoolean.cpp +++ b/src/Mod/PartDesign/App/FeatureBoolean.cpp @@ -66,7 +66,7 @@ short Boolean::mustExecute() const return PartDesign::Feature::mustExecute(); } -App::DocumentObjectExecReturn *Boolean::execute(void) +App::DocumentObjectExecReturn *Boolean::execute() { // Get the operation type std::string type = Type.getValueAsString(); diff --git a/src/Mod/PartDesign/App/FeatureBoolean.h b/src/Mod/PartDesign/App/FeatureBoolean.h index 537a81dcb3..b3ad810340 100644 --- a/src/Mod/PartDesign/App/FeatureBoolean.h +++ b/src/Mod/PartDesign/App/FeatureBoolean.h @@ -51,13 +51,13 @@ public: /** @name methods override feature */ //@{ /// Recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderBoolean"; } - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; //@} protected: diff --git a/src/Mod/PartDesign/App/FeatureChamfer.cpp b/src/Mod/PartDesign/App/FeatureChamfer.cpp index 9b3e4c02c2..f595e34a06 100644 --- a/src/Mod/PartDesign/App/FeatureChamfer.cpp +++ b/src/Mod/PartDesign/App/FeatureChamfer.cpp @@ -102,7 +102,7 @@ short Chamfer::mustExecute() const return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Chamfer::execute(void) +App::DocumentObjectExecReturn *Chamfer::execute() { // NOTE: Normally the Base property and the BaseFeature property should point to the same object. // The only difference is that the Base property also stores the edges that are to be chamfered @@ -130,7 +130,7 @@ App::DocumentObjectExecReturn *Chamfer::execute(void) getContinuousEdges(TopShape, SubNames, FaceNames); - if (SubNames.size() == 0) + if (SubNames.empty()) return new App::DocumentObjectExecReturn("No edges specified"); const int chamferType = ChamferType.getValue(); diff --git a/src/Mod/PartDesign/App/FeatureChamfer.h b/src/Mod/PartDesign/App/FeatureChamfer.h index 8d846509b6..2a6aada3ed 100644 --- a/src/Mod/PartDesign/App/FeatureChamfer.h +++ b/src/Mod/PartDesign/App/FeatureChamfer.h @@ -48,15 +48,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderChamfer"; } //@} - virtual void onChanged(const App::Property* /*prop*/) override; + void onChanged(const App::Property* /*prop*/) override; void updateProperties(); diff --git a/src/Mod/PartDesign/App/FeatureDraft.cpp b/src/Mod/PartDesign/App/FeatureDraft.cpp index c8d2b935a9..6a031b131c 100644 --- a/src/Mod/PartDesign/App/FeatureDraft.cpp +++ b/src/Mod/PartDesign/App/FeatureDraft.cpp @@ -95,7 +95,7 @@ short Draft::mustExecute() const return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Draft::execute(void) +App::DocumentObjectExecReturn *Draft::execute() { // Get parameters // Base shape @@ -109,7 +109,7 @@ App::DocumentObjectExecReturn *Draft::execute(void) // Faces where draft should be applied // Note: Cannot be const reference currently because of BRepOffsetAPI_DraftAngle::Remove() bug, see below std::vector SubVals = Base.getSubValuesStartsWith("Face"); - if (SubVals.size() == 0) + if (SubVals.empty()) return new App::DocumentObjectExecReturn("No faces specified"); // Draft angle @@ -118,7 +118,7 @@ App::DocumentObjectExecReturn *Draft::execute(void) // Pull direction gp_Dir pullDirection; App::DocumentObject* refDirection = PullDirection.getValue(); - if (refDirection != nullptr) { + if (refDirection) { if (refDirection->getTypeId().isDerivedFrom(PartDesign::Line::getClassTypeId())) { PartDesign::Line* line = static_cast(refDirection); Base::Vector3d d = line->getDirection(); @@ -155,7 +155,7 @@ App::DocumentObjectExecReturn *Draft::execute(void) // Neutral plane gp_Pln neutralPlane; App::DocumentObject* refPlane = NeutralPlane.getValue(); - if (refPlane == nullptr) { + if (!refPlane) { // Try to guess a neutral plane from the first selected face // Get edges of first selected face TopoDS_Shape face = TopShape.getSubShape(SubVals[0].c_str()); @@ -229,7 +229,7 @@ App::DocumentObjectExecReturn *Draft::execute(void) neutralPlane = adapt.Plane(); } else if (ref.ShapeType() == TopAbs_EDGE) { - if (refDirection != nullptr) { + if (refDirection) { // Create neutral plane through edge normal to pull direction TopoDS_Edge refEdge = TopoDS::Edge(ref); if (refEdge.IsNull()) @@ -255,7 +255,7 @@ App::DocumentObjectExecReturn *Draft::execute(void) neutralPlane.Transform(invObjLoc.Transformation()); } - if (refDirection == nullptr) { + if (!refDirection) { // Choose pull direction normal to neutral plane pullDirection = neutralPlane.Axis().Direction(); } diff --git a/src/Mod/PartDesign/App/FeatureDraft.h b/src/Mod/PartDesign/App/FeatureDraft.h index 9b7b92510d..d55a420e91 100644 --- a/src/Mod/PartDesign/App/FeatureDraft.h +++ b/src/Mod/PartDesign/App/FeatureDraft.h @@ -35,7 +35,7 @@ namespace PartDesign class PartDesignExport Draft : public DressUp { - PROPERTY_HEADER(PartDesign::Draft); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Draft); public: Draft(); @@ -48,16 +48,16 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderDraft"; } //@} private: - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; static const App::PropertyAngle::Constraints floatAngle; }; diff --git a/src/Mod/PartDesign/App/FeatureDressUp.cpp b/src/Mod/PartDesign/App/FeatureDressUp.cpp index 86828c2aee..a718b9dcc8 100644 --- a/src/Mod/PartDesign/App/FeatureDressUp.cpp +++ b/src/Mod/PartDesign/App/FeatureDressUp.cpp @@ -60,10 +60,10 @@ short DressUp::mustExecute() const { if (Base.getValue() && Base.getValue()->isTouched()) return 1; - return PartDesign::Feature::mustExecute(); + return PartDesign::FeatureAddSub::mustExecute(); } -void DressUp::positionByBaseFeature(void) +void DressUp::positionByBaseFeature() { Part::Feature *base = static_cast(BaseFeature.getValue()); if (base && base->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) @@ -159,7 +159,7 @@ void DressUp::getContinuousEdges(Part::TopoShape TopShape, std::vector< std::str } - FaceNames.push_back(aSubName.c_str()); + FaceNames.emplace_back(aSubName.c_str()); SubNames.erase(SubNames.begin()+i); } // empty name or any other sub-element @@ -231,7 +231,7 @@ void DressUp::getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShap baseShape.move(base->getLocation().Inverted()); if (base->getAddSubType() == Additive) { if(!baseShape.isNull() && baseShape.hasSubShape(TopAbs_SOLID)) - shapes.push_back(shape.cut(baseShape.getShape())); + shapes.emplace_back(shape.cut(baseShape.getShape())); else shapes.push_back(shape); } else { @@ -241,15 +241,15 @@ void DressUp::getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShap // push an empty compound to indicate null additive shape shapes.emplace_back(comp); if(!baseShape.isNull() && baseShape.hasSubShape(TopAbs_SOLID)) - shapes.push_back(baseShape.cut(shape.getShape())); + shapes.emplace_back(baseShape.cut(shape.getShape())); else shapes.push_back(shape); } } else { baseShape = getBaseTopoShape(); baseShape.move(getLocation().Inverted()); - shapes.push_back(shape.cut(baseShape.getShape())); - shapes.push_back(baseShape.cut(shape.getShape())); + shapes.emplace_back(shape.cut(baseShape.getShape())); + shapes.emplace_back(baseShape.cut(shape.getShape())); } // Make a compound to contain both additive and subtractive shape, diff --git a/src/Mod/PartDesign/App/FeatureDressUp.h b/src/Mod/PartDesign/App/FeatureDressUp.h index 2b1e2e77d0..c01f1fadb2 100644 --- a/src/Mod/PartDesign/App/FeatureDressUp.h +++ b/src/Mod/PartDesign/App/FeatureDressUp.h @@ -31,7 +31,7 @@ namespace PartDesign class PartDesignExport DressUp : public PartDesign::FeatureAddSub { - PROPERTY_HEADER(PartDesign::DressUp); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::DressUp); public: DressUp(); @@ -44,9 +44,9 @@ public: App::PropertyLinkSub Base; App::PropertyBool SupportTransform; - short mustExecute() const; + short mustExecute() const override; /// updates the Placement property from the Placement of the BaseFeature - void positionByBaseFeature(void); + void positionByBaseFeature(); /** * Returns the BaseFeature property's object if it's set otherwise returns Base's * feature property object otherwise feature property's object (if any) @@ -54,17 +54,17 @@ public: * silently return a nullptr, otherwise throw Base::Exception. * Default is false. */ - virtual Part::Feature* getBaseObject(bool silent=false) const; + Part::Feature* getBaseObject(bool silent=false) const override; /// extracts all edges from the subshapes (including face edges) and furthermore adds /// all C0 continuous edges to the vector void getContinuousEdges(Part::TopoShape, std::vector< std::string >&); // add argument to return the selected face that edges were derived from void getContinuousEdges(Part::TopoShape, std::vector< std::string >&, std::vector< std::string >&); - virtual void getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShape); + void getAddSubShape(Part::TopoShape &addShape, Part::TopoShape &subShape) override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } //namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureExtrude.cpp b/src/Mod/PartDesign/App/FeatureExtrude.cpp index 65a8b50b7c..cf4843009a 100644 --- a/src/Mod/PartDesign/App/FeatureExtrude.cpp +++ b/src/Mod/PartDesign/App/FeatureExtrude.cpp @@ -144,12 +144,9 @@ void FeatureExtrude::generatePrism(TopoDS_Shape& prism, if (method == "TwoLengths") { - // midplane makes no sense here Ltotal += L2; if (reversed) Loffset = -L; - else if (midplane) - Loffset = -0.5 * (L2 + L); else Loffset = -L2; } @@ -273,3 +270,57 @@ void FeatureExtrude::generateTaperedPrism(TopoDS_Shape& prism, prism = comp; } } + +void FeatureExtrude::updateProperties(const std::string &method) +{ + // disable settings that are not valid on the current method + // disable everything unless we are sure we need it + bool isLengthEnabled = false; + bool isLength2Enabled = false; + bool isOffsetEnabled = false; + bool isMidplaneEnabled = false; + bool isReversedEnabled = false; + bool isUpToFaceEnabled = false; + bool isTaperVisible = false; + bool isTaper2Visible = false; + if (method == "Length") { + isLengthEnabled = true; + isTaperVisible = true; + isMidplaneEnabled = true; + isReversedEnabled = !Midplane.getValue(); + } + else if (method == "UpToLast") { + isOffsetEnabled = true; + isReversedEnabled = true; + } + else if (method == "ThroughAll") { + isMidplaneEnabled = true; + isReversedEnabled = !Midplane.getValue(); + } + else if (method == "UpToFirst") { + isOffsetEnabled = true; + isReversedEnabled = true; + } + else if (method == "UpToFace") { + isOffsetEnabled = true; + isReversedEnabled = true; + isUpToFaceEnabled = true; + } + else if (method == "TwoLengths") { + isLengthEnabled = true; + isLength2Enabled = true; + isTaperVisible = true; + isTaper2Visible = true; + isReversedEnabled = true; + } + + Length.setReadOnly(!isLengthEnabled); + AlongSketchNormal.setReadOnly(!isLengthEnabled); + Length2.setReadOnly(!isLength2Enabled); + Offset.setReadOnly(!isOffsetEnabled); + TaperAngle.setReadOnly(!isTaperVisible); + TaperAngle2.setReadOnly(!isTaper2Visible); + Midplane.setReadOnly(!isMidplaneEnabled); + Reversed.setReadOnly(!isReversedEnabled); + UpToFace.setReadOnly(!isUpToFaceEnabled); +} diff --git a/src/Mod/PartDesign/App/FeatureExtrude.h b/src/Mod/PartDesign/App/FeatureExtrude.h index ba349c11e6..0cfd0acc7a 100644 --- a/src/Mod/PartDesign/App/FeatureExtrude.h +++ b/src/Mod/PartDesign/App/FeatureExtrude.h @@ -37,7 +37,7 @@ namespace PartDesign class PartDesignExport FeatureExtrude : public ProfileBased { - PROPERTY_HEADER(PartDesign::FeatureExtrude); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureExtrude); public: FeatureExtrude(); @@ -59,7 +59,7 @@ public: /** @name methods override feature */ //@{ - short mustExecute() const; + short mustExecute() const override; //@} protected: @@ -111,6 +111,11 @@ protected: const double angle, const double angle2, const bool midplane); + + /** + * Disables settings that are not valid for the current method + */ + void updateProperties(const std::string &method); }; } //namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureFillet.cpp b/src/Mod/PartDesign/App/FeatureFillet.cpp index 8187242f76..22f3f595f5 100644 --- a/src/Mod/PartDesign/App/FeatureFillet.cpp +++ b/src/Mod/PartDesign/App/FeatureFillet.cpp @@ -63,7 +63,7 @@ short Fillet::mustExecute() const return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Fillet::execute(void) +App::DocumentObjectExecReturn *Fillet::execute() { Part::TopoShape TopShape; try { @@ -86,7 +86,7 @@ App::DocumentObjectExecReturn *Fillet::execute(void) getContinuousEdges(TopShape, SubNames); - if (SubNames.size() == 0) + if (SubNames.empty()) return new App::DocumentObjectExecReturn("Fillet not possible on selected shapes"); double radius = Radius.getValue(); diff --git a/src/Mod/PartDesign/App/FeatureFillet.h b/src/Mod/PartDesign/App/FeatureFillet.h index e7a252de34..a1f37d0eea 100644 --- a/src/Mod/PartDesign/App/FeatureFillet.h +++ b/src/Mod/PartDesign/App/FeatureFillet.h @@ -33,7 +33,7 @@ namespace PartDesign class PartDesignExport Fillet : public DressUp { - PROPERTY_HEADER(PartDesign::Fillet); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Fillet); public: Fillet(); @@ -44,17 +44,17 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute(void) override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "PartDesignGui::ViewProviderFillet"; } //@} protected: - void Restore(Base::XMLReader &reader); - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); + void Restore(Base::XMLReader &reader) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; }; } //namespace Part diff --git a/src/Mod/PartDesign/App/FeatureGroove.cpp b/src/Mod/PartDesign/App/FeatureGroove.cpp index 810c55e952..835a3aaa5f 100644 --- a/src/Mod/PartDesign/App/FeatureGroove.cpp +++ b/src/Mod/PartDesign/App/FeatureGroove.cpp @@ -70,7 +70,7 @@ short Groove::mustExecute() const return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn *Groove::execute(void) +App::DocumentObjectExecReturn *Groove::execute() { // Validate parameters double angle = Angle.getValue(); @@ -187,13 +187,13 @@ App::DocumentObjectExecReturn *Groove::execute(void) } } -bool Groove::suggestReversed(void) +bool Groove::suggestReversed() { updateAxis(); return ProfileBased::getReversedAngle(Base.getValue(), Axis.getValue()) > 0.0; } -void Groove::updateAxis(void) +void Groove::updateAxis() { App::DocumentObject *pcReferenceAxis = ReferenceAxis.getValue(); const std::vector &subReferenceAxis = ReferenceAxis.getSubValues(); diff --git a/src/Mod/PartDesign/App/FeatureGroove.h b/src/Mod/PartDesign/App/FeatureGroove.h index e60f791c73..0ddd3f4960 100644 --- a/src/Mod/PartDesign/App/FeatureGroove.h +++ b/src/Mod/PartDesign/App/FeatureGroove.h @@ -32,7 +32,7 @@ namespace PartDesign class PartDesignExport Groove : public ProfileBased { - PROPERTY_HEADER(PartDesign::Groove); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Groove); public: Groove(); @@ -55,19 +55,19 @@ public: * If Reversed is true then the direction of revolution will be reversed. * The created material will be cut out of the sketch support */ - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderGroove"; } //@} /// suggests a value for Reversed flag so that material is always removed from the support - bool suggestReversed(void); + bool suggestReversed(); protected: /// updates Axis from ReferenceAxis - void updateAxis(void); + void updateAxis(); static const App::PropertyAngle::Constraints floatAngle; }; diff --git a/src/Mod/PartDesign/App/FeatureHelix.cpp b/src/Mod/PartDesign/App/FeatureHelix.cpp index e083472758..3586537a32 100644 --- a/src/Mod/PartDesign/App/FeatureHelix.cpp +++ b/src/Mod/PartDesign/App/FeatureHelix.cpp @@ -118,7 +118,7 @@ short Helix::mustExecute() const return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn* Helix::execute(void) +App::DocumentObjectExecReturn* Helix::execute() { // Validate and normalize parameters HelixMode mode = static_cast(Mode.getValue()); @@ -379,7 +379,7 @@ App::DocumentObjectExecReturn* Helix::execute(void) } } -void Helix::updateAxis(void) +void Helix::updateAxis() { App::DocumentObject* pcReferenceAxis = ReferenceAxis.getValue(); const std::vector& subReferenceAxis = ReferenceAxis.getSubValues(); diff --git a/src/Mod/PartDesign/App/FeatureHelix.h b/src/Mod/PartDesign/App/FeatureHelix.h index 02b0735eb6..531ded92d6 100644 --- a/src/Mod/PartDesign/App/FeatureHelix.h +++ b/src/Mod/PartDesign/App/FeatureHelix.h @@ -40,7 +40,7 @@ enum class HelixMode { class PartDesignExport Helix : public ProfileBased { - PROPERTY_HEADER(PartDesign::Helix); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Helix); public: Helix(); @@ -64,20 +64,20 @@ public: /** @name methods override feature */ //@{ - App::DocumentObjectExecReturn* execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn* execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderHelix"; } //@} void proposeParameters(bool force = false); - double safePitch(void); + double safePitch(); protected: /// updates Axis from ReferenceAxis - void updateAxis(void); + void updateAxis(); /// generate helix and move it to the right location. TopoDS_Shape generateHelixPath(double startOffset0 = 0.0); @@ -89,9 +89,9 @@ protected: Base::Vector3d getProfileCenterPoint(); // handle changed property types for backward compatibility - virtual void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop); + void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; static const App::PropertyFloatConstraint::Constraints floatTurns; static const App::PropertyAngle::Constraints floatAngle; @@ -106,7 +106,7 @@ private: class PartDesignExport AdditiveHelix : public Helix { - PROPERTY_HEADER(PartDesign::AdditiveHelix); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveHelix); public: AdditiveHelix(); }; @@ -114,7 +114,7 @@ public: class PartDesignExport SubtractiveHelix : public Helix { - PROPERTY_HEADER(PartDesign::SubtractiveHelix); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveHelix); public: SubtractiveHelix(); }; diff --git a/src/Mod/PartDesign/App/FeatureHole.cpp b/src/Mod/PartDesign/App/FeatureHole.cpp index 6a2e41e385..f7430c0fc1 100644 --- a/src/Mod/PartDesign/App/FeatureHole.cpp +++ b/src/Mod/PartDesign/App/FeatureHole.cpp @@ -48,6 +48,7 @@ #include #include #include +#include #include #include @@ -1630,7 +1631,7 @@ static gp_Pnt toPnt(gp_Vec dir) return gp_Pnt(dir.X(), dir.Y(), dir.Z()); } -App::DocumentObjectExecReturn* Hole::execute(void) +App::DocumentObjectExecReturn* Hole::execute() { TopoDS_Shape profileshape; try { @@ -2295,7 +2296,7 @@ void Hole::readCutDefinitions() for (const auto& f : files) { if (f.extension() == "json") { try { - std::ifstream input(f.filePath()); + Base::ifstream input(f); nlohmann::json j; input >> j; CutDimensionSet screwtype = j.get(); diff --git a/src/Mod/PartDesign/App/FeatureHole.h b/src/Mod/PartDesign/App/FeatureHole.h index 3400470aab..acf56a7e31 100644 --- a/src/Mod/PartDesign/App/FeatureHole.h +++ b/src/Mod/PartDesign/App/FeatureHole.h @@ -43,7 +43,7 @@ static constexpr size_t ThreadRunout_size = 24; class PartDesignExport Hole : public ProfileBased { - PROPERTY_HEADER(PartDesign::Hole); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Hole); public: Hole(); @@ -77,14 +77,14 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderHole"; } //@} - short mustExecute() const; + short mustExecute() const override; typedef struct { const char * designation; @@ -104,12 +104,12 @@ public: } UTSClearanceDefinition; static const UTSClearanceDefinition UTSHoleDiameters[22]; - virtual void Restore(Base::XMLReader & reader); + void Restore(Base::XMLReader & reader) override; virtual void updateProps(); protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; static const App::PropertyAngle::Constraints floatAngle; private: diff --git a/src/Mod/PartDesign/App/FeatureLinearPattern.cpp b/src/Mod/PartDesign/App/FeatureLinearPattern.cpp index fc1d1e192f..a98c5fe7cd 100644 --- a/src/Mod/PartDesign/App/FeatureLinearPattern.cpp +++ b/src/Mod/PartDesign/App/FeatureLinearPattern.cpp @@ -81,7 +81,7 @@ const std::list LinearPattern::getTransformations(const std::vector subStrings = Direction.getSubValues(); diff --git a/src/Mod/PartDesign/App/FeatureLinearPattern.h b/src/Mod/PartDesign/App/FeatureLinearPattern.h index bd4189ecc7..19e6d860be 100644 --- a/src/Mod/PartDesign/App/FeatureLinearPattern.h +++ b/src/Mod/PartDesign/App/FeatureLinearPattern.h @@ -32,7 +32,7 @@ namespace PartDesign class PartDesignExport LinearPattern : public PartDesign::Transformed { - PROPERTY_HEADER(PartDesign::LinearPattern); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::LinearPattern); public: LinearPattern(); @@ -44,10 +44,10 @@ public: /** @name methods override feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderLinearPattern"; } //@} @@ -61,10 +61,10 @@ public: * transformation direction will be parallel to the given edge, which must be linear * If Reversed is true, the direction of transformation will be opposite */ - const std::list getTransformations(const std::vector ); + const std::list getTransformations(const std::vector ) override; protected: - virtual void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop); + void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; static const App::PropertyIntegerConstraint::Constraints intOccurrences; }; diff --git a/src/Mod/PartDesign/App/FeatureLoft.cpp b/src/Mod/PartDesign/App/FeatureLoft.cpp index 4e7f861816..af4779044b 100644 --- a/src/Mod/PartDesign/App/FeatureLoft.cpp +++ b/src/Mod/PartDesign/App/FeatureLoft.cpp @@ -68,7 +68,7 @@ short Loft::mustExecute() const return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn *Loft::execute(void) +App::DocumentObjectExecReturn *Loft::execute() { auto getSectionShape = [](App::DocumentObject* feature, const std::vector &subs) -> TopoDS_Shape { diff --git a/src/Mod/PartDesign/App/FeatureLoft.h b/src/Mod/PartDesign/App/FeatureLoft.h index 70fc16a8af..dc6fd321f8 100644 --- a/src/Mod/PartDesign/App/FeatureLoft.h +++ b/src/Mod/PartDesign/App/FeatureLoft.h @@ -31,7 +31,7 @@ namespace PartDesign class PartDesignExport Loft : public ProfileBased { - PROPERTY_HEADER(PartDesign::Loft); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Loft); public: Loft(); @@ -42,17 +42,17 @@ public: /** @name methods override feature */ //@{ - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderLoft"; } //@} protected: // handle changed property - virtual void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop); + void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; private: //static const char* TypeEnums[]; @@ -61,14 +61,14 @@ private: class PartDesignExport AdditiveLoft : public Loft { - PROPERTY_HEADER(PartDesign::AdditiveLoft); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveLoft); public: AdditiveLoft(); }; class PartDesignExport SubtractiveLoft : public Loft { - PROPERTY_HEADER(PartDesign::SubtractiveLoft); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveLoft); public: SubtractiveLoft(); }; diff --git a/src/Mod/PartDesign/App/FeatureMirrored.cpp b/src/Mod/PartDesign/App/FeatureMirrored.cpp index 5e72f04f66..0379b1d36c 100644 --- a/src/Mod/PartDesign/App/FeatureMirrored.cpp +++ b/src/Mod/PartDesign/App/FeatureMirrored.cpp @@ -60,7 +60,7 @@ short Mirrored::mustExecute() const const std::list Mirrored::getTransformations(const std::vector) { App::DocumentObject* refObject = MirrorPlane.getValue(); - if (refObject == nullptr) + if (!refObject) throw Base::ValueError("No mirror plane reference specified"); std::vector subStrings = MirrorPlane.getSubValues(); if (subStrings.empty()) @@ -75,7 +75,7 @@ const std::list Mirrored::getTransformations(const std::vectorgetAxis(Part::Part2DObject::V_Axis); else if (subStrings[0] == "V_Axis") axis = refSketch->getAxis(Part::Part2DObject::H_Axis); - else if (subStrings[0] == "") + else if (subStrings[0].empty()) axis = refSketch->getAxis(Part::Part2DObject::N_Axis); else if (subStrings[0].compare(0, 4, "Axis") == 0) { int AxId = std::atoi(subStrings[0].substr(4,4000).c_str()); diff --git a/src/Mod/PartDesign/App/FeatureMirrored.h b/src/Mod/PartDesign/App/FeatureMirrored.h index 643f32f8be..3e1d66a306 100644 --- a/src/Mod/PartDesign/App/FeatureMirrored.h +++ b/src/Mod/PartDesign/App/FeatureMirrored.h @@ -44,7 +44,7 @@ public: short mustExecute() const; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const { return "PartDesignGui::ViewProviderMirrored"; } //@} diff --git a/src/Mod/PartDesign/App/FeatureMultiTransform.cpp b/src/Mod/PartDesign/App/FeatureMultiTransform.cpp index d506916819..66feeda17a 100644 --- a/src/Mod/PartDesign/App/FeatureMultiTransform.cpp +++ b/src/Mod/PartDesign/App/FeatureMultiTransform.cpp @@ -46,7 +46,7 @@ MultiTransform::MultiTransform() Transformations.setSize(0); } -void MultiTransform::positionBySupport(void) +void MultiTransform::positionBySupport() { PartDesign::Transformed::positionBySupport(); std::vector transFeatures = Transformations.getValues(); diff --git a/src/Mod/PartDesign/App/FeatureMultiTransform.h b/src/Mod/PartDesign/App/FeatureMultiTransform.h index dca8054d7e..b2ceb85693 100644 --- a/src/Mod/PartDesign/App/FeatureMultiTransform.h +++ b/src/Mod/PartDesign/App/FeatureMultiTransform.h @@ -32,7 +32,7 @@ namespace PartDesign class PartDesignExport MultiTransform : public PartDesign::Transformed { - PROPERTY_HEADER(PartDesign::MultiTransform); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::MultiTransform); public: MultiTransform(); @@ -41,10 +41,10 @@ public: /** @name methods override feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderMultiTransform"; } //@} @@ -56,10 +56,10 @@ public: * by the Transformations property. Subfeatures can be Mirrored, LinearPattern, PolarPattern and * Scaled. */ - const std::list getTransformations(const std::vector originals); + const std::list getTransformations(const std::vector originals) override; protected: - virtual void positionBySupport(void); + void positionBySupport() override; }; } //namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeaturePad.cpp b/src/Mod/PartDesign/App/FeaturePad.cpp index e8cc92f7f5..f801683a51 100644 --- a/src/Mod/PartDesign/App/FeaturePad.cpp +++ b/src/Mod/PartDesign/App/FeaturePad.cpp @@ -238,6 +238,9 @@ App::DocumentObjectExecReturn *Pad::execute() this->Shape.setValue(getSolid(prism)); } + // eventually disable some settings that are not valid for the current method + updateProperties(method); + return App::DocumentObject::StdReturn; } catch (Standard_Failure& e) { @@ -250,4 +253,5 @@ App::DocumentObjectExecReturn *Pad::execute() catch (Base::Exception& e) { return new App::DocumentObjectExecReturn(e.what()); } + } diff --git a/src/Mod/PartDesign/App/FeaturePad.h b/src/Mod/PartDesign/App/FeaturePad.h index 381571e4f5..f9933c1621 100644 --- a/src/Mod/PartDesign/App/FeaturePad.h +++ b/src/Mod/PartDesign/App/FeaturePad.h @@ -31,7 +31,7 @@ namespace PartDesign class PartDesignExport Pad : public FeatureExtrude { - PROPERTY_HEADER(PartDesign::Pad); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Pad); public: Pad(); @@ -51,9 +51,9 @@ public: * If Reversed is true then the direction of revolution will be reversed. * The created material will be fused with the sketch support (if there is one) */ - App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderPad"; } //@} diff --git a/src/Mod/PartDesign/App/FeaturePipe.cpp b/src/Mod/PartDesign/App/FeaturePipe.cpp index 5fc5dbfb42..55e53d7aac 100644 --- a/src/Mod/PartDesign/App/FeaturePipe.cpp +++ b/src/Mod/PartDesign/App/FeaturePipe.cpp @@ -96,7 +96,7 @@ short Pipe::mustExecute() const return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn *Pipe::execute(void) +App::DocumentObjectExecReturn *Pipe::execute() { auto getSectionShape = [](App::DocumentObject* feature, const std::vector &subs) -> TopoDS_Shape { diff --git a/src/Mod/PartDesign/App/FeaturePipe.h b/src/Mod/PartDesign/App/FeaturePipe.h index fd752ca3a4..b71890eabb 100644 --- a/src/Mod/PartDesign/App/FeaturePipe.h +++ b/src/Mod/PartDesign/App/FeaturePipe.h @@ -32,7 +32,7 @@ namespace PartDesign class PartDesignExport Pipe : public ProfileBased { - PROPERTY_HEADER(PartDesign::Pipe); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Pipe); public: Pipe(); @@ -48,10 +48,10 @@ public: App::PropertyEnumeration Transformation; App::PropertyLinkSubList Sections; - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderPipe"; } @@ -61,7 +61,7 @@ protected: void buildPipePath(const Part::TopoShape& input, const std::vector& edges, TopoDS_Shape& result); void setupAlgorithm(BRepOffsetAPI_MakePipeShell& mkPipeShell, TopoDS_Shape& auxshape); /// handle changed property - virtual void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop); + void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; private: static const char* TypeEnums[]; @@ -72,14 +72,14 @@ private: class PartDesignExport AdditivePipe : public Pipe { - PROPERTY_HEADER(PartDesign::AdditivePipe); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditivePipe); public: AdditivePipe(); }; class PartDesignExport SubtractivePipe : public Pipe { - PROPERTY_HEADER(PartDesign::SubtractivePipe); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractivePipe); public: SubtractivePipe(); }; diff --git a/src/Mod/PartDesign/App/FeaturePocket.cpp b/src/Mod/PartDesign/App/FeaturePocket.cpp index ce56376098..ef209b0e56 100644 --- a/src/Mod/PartDesign/App/FeaturePocket.cpp +++ b/src/Mod/PartDesign/App/FeaturePocket.cpp @@ -39,7 +39,7 @@ using namespace PartDesign; /* TRANSLATOR PartDesign::Pocket */ -const char* Pocket::TypeEnums[]= {"Length","ThroughAll","UpToFirst","UpToFace","TwoLengths",nullptr}; +const char* Pocket::TypeEnums[]= {"Length", "ThroughAll", "UpToFirst", "UpToFace", "TwoLengths", nullptr}; PROPERTY_SOURCE(PartDesign::Pocket, PartDesign::FeatureExtrude) @@ -73,7 +73,7 @@ App::DocumentObjectExecReturn *Pocket::execute() // Handle legacy features, these typically have Type set to 3 (previously NULL, now UpToFace), // empty FaceName (because it didn't exist) and a value for Length if (std::string(Type.getValueAsString()) == "UpToFace" && - (UpToFace.getValue() == nullptr && Length.getValue() > Precision::Confusion())) + (!UpToFace.getValue() && Length.getValue() > Precision::Confusion())) Type.setValue("Length"); // Validate parameters @@ -237,6 +237,9 @@ App::DocumentObjectExecReturn *Pocket::execute() this->Shape.setValue(getSolid(solRes)); } + // eventually disable some settings that are not valid for the current method + updateProperties(method); + return App::DocumentObject::StdReturn; } catch (Standard_Failure& e) { diff --git a/src/Mod/PartDesign/App/FeaturePocket.h b/src/Mod/PartDesign/App/FeaturePocket.h index 3c83e7becf..8d5f1e6102 100644 --- a/src/Mod/PartDesign/App/FeaturePocket.h +++ b/src/Mod/PartDesign/App/FeaturePocket.h @@ -31,7 +31,7 @@ namespace PartDesign class PartDesignExport Pocket : public FeatureExtrude { - PROPERTY_HEADER(PartDesign::Pocket); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Pocket); public: Pocket(); @@ -48,9 +48,9 @@ public: * If Midplane is true, then the extrusion will extend for half of the length on both sides of the sketch plane * The created material will be cut out of the sketch support */ - App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderPocket"; } //@} diff --git a/src/Mod/PartDesign/App/FeaturePolarPattern.cpp b/src/Mod/PartDesign/App/FeaturePolarPattern.cpp index dfce427225..c2d6c0e13f 100644 --- a/src/Mod/PartDesign/App/FeaturePolarPattern.cpp +++ b/src/Mod/PartDesign/App/FeaturePolarPattern.cpp @@ -98,7 +98,7 @@ const std::list PolarPattern::getTransformations(const std::vector subStrings = Axis.getSubValues(); if (subStrings.empty()) diff --git a/src/Mod/PartDesign/App/FeaturePolarPattern.h b/src/Mod/PartDesign/App/FeaturePolarPattern.h index 0ade352ee0..7362f311a5 100644 --- a/src/Mod/PartDesign/App/FeaturePolarPattern.h +++ b/src/Mod/PartDesign/App/FeaturePolarPattern.h @@ -34,7 +34,7 @@ namespace PartDesign class PartDesignExport PolarPattern : public PartDesign::Transformed { - PROPERTY_HEADER(PartDesign::PolarPattern); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::PolarPattern); public: PolarPattern(); @@ -46,10 +46,10 @@ public: /** @name methods override feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderPolarPattern"; } //@} @@ -64,10 +64,10 @@ public: * the given edge, which must be linear. * If Reversed is true, the direction of rotation will be opposite. */ - const std::list getTransformations(const std::vector); + const std::list getTransformations(const std::vector) override; protected: - virtual void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop); + void handleChangedPropertyType(Base::XMLReader& reader, const char* TypeName, App::Property* prop) override; static const App::PropertyIntegerConstraint::Constraints intOccurrences; static const App::PropertyAngle::Constraints floatAngle; }; diff --git a/src/Mod/PartDesign/App/FeaturePrimitive.cpp b/src/Mod/PartDesign/App/FeaturePrimitive.cpp index 6ed15a88c9..59318f1f53 100644 --- a/src/Mod/PartDesign/App/FeaturePrimitive.cpp +++ b/src/Mod/PartDesign/App/FeaturePrimitive.cpp @@ -159,7 +159,7 @@ void FeaturePrimitive::handleChangedPropertyName(Base::XMLReader &reader, const # pragma clang diagnostic ignored "-Wmissing-field-initializers" #endif -PYTHON_TYPE_DEF(PrimitivePy, PartDesign::FeaturePy) +PYTHON_TYPE_DEF(PrimitivePy, PartDesign::FeaturePy)//explicit bombs PYTHON_TYPE_IMP(PrimitivePy, PartDesign::FeaturePy) #if defined(__clang__) @@ -189,7 +189,7 @@ Box::Box() primitiveType = FeaturePrimitive::Box; } -App::DocumentObjectExecReturn* Box::execute(void) +App::DocumentObjectExecReturn* Box::execute() { double L = Length.getValue(); double W = Width.getValue(); @@ -242,7 +242,7 @@ Cylinder::Cylinder() primitiveType = FeaturePrimitive::Cylinder; } -App::DocumentObjectExecReturn* Cylinder::execute(void) +App::DocumentObjectExecReturn* Cylinder::execute() { // Build a cylinder if (Radius.getValue() < Precision::Confusion()) @@ -299,7 +299,7 @@ Sphere::Sphere() primitiveType = FeaturePrimitive::Sphere; } -App::DocumentObjectExecReturn* Sphere::execute(void) +App::DocumentObjectExecReturn* Sphere::execute() { // Build a sphere if (Radius.getValue() < Precision::Confusion()) @@ -349,7 +349,7 @@ Cone::Cone() primitiveType = FeaturePrimitive::Cone; } -App::DocumentObjectExecReturn* Cone::execute(void) +App::DocumentObjectExecReturn* Cone::execute() { if (Radius1.getValue() < 0.0) return new App::DocumentObjectExecReturn("Radius of cone cannot be negative"); @@ -411,7 +411,7 @@ Ellipsoid::Ellipsoid() primitiveType = FeaturePrimitive::Ellipsoid; } -App::DocumentObjectExecReturn* Ellipsoid::execute(void) +App::DocumentObjectExecReturn* Ellipsoid::execute() { // Build a sphere if (Radius1.getValue() < Precision::Confusion()) @@ -496,7 +496,7 @@ Torus::Torus() primitiveType = FeaturePrimitive::Torus; } -App::DocumentObjectExecReturn* Torus::execute(void) +App::DocumentObjectExecReturn* Torus::execute() { if (Radius1.getValue() < Precision::Confusion()) return new App::DocumentObjectExecReturn("Radius of torus too small"); @@ -560,7 +560,7 @@ Prism::Prism() primitiveType = FeaturePrimitive::Prism; } -App::DocumentObjectExecReturn* Prism::execute(void) +App::DocumentObjectExecReturn* Prism::execute() { // Build a prism if (Polygon.getValue() < 3) @@ -629,7 +629,7 @@ Wedge::Wedge() primitiveType = FeaturePrimitive::Wedge; } -App::DocumentObjectExecReturn* Wedge::execute(void) +App::DocumentObjectExecReturn* Wedge::execute() { double xmin = Xmin.getValue(); double ymin = Ymin.getValue(); diff --git a/src/Mod/PartDesign/App/FeaturePrimitive.h b/src/Mod/PartDesign/App/FeaturePrimitive.h index 91edae7825..e656912c6e 100644 --- a/src/Mod/PartDesign/App/FeaturePrimitive.h +++ b/src/Mod/PartDesign/App/FeaturePrimitive.h @@ -49,15 +49,15 @@ public: FeaturePrimitive(); - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderPrimitive"; } Type getPrimitiveType() {return primitiveType;} - virtual void onChanged(const App::Property* prop) override; - virtual PyObject* getPyObject() override; + void onChanged(const App::Property* prop) override; + PyObject* getPyObject() override; /// Do nothing, just to suppress warning, must be redefined in derived classes - virtual App::DocumentObjectExecReturn* execute() override { + App::DocumentObjectExecReturn* execute() override { return PartDesign::FeatureAddSub::execute(); } protected: @@ -69,7 +69,7 @@ protected: class PartDesignExport Box : public PartDesign::FeaturePrimitive { - PROPERTY_HEADER(PartDesign::Box); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Box); public: @@ -80,15 +80,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; protected: }; class PartDesignExport AdditiveBox : public Box { - PROPERTY_HEADER(PartDesign::AdditiveBox); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveBox); AdditiveBox() { addSubType = FeatureAddSub::Additive; @@ -96,7 +96,7 @@ class PartDesignExport AdditiveBox : public Box { }; class PartDesignExport SubtractiveBox : public Box { - PROPERTY_HEADER(PartDesign::SubtractiveBox); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveBox); SubtractiveBox() { addSubType = FeatureAddSub::Subtractive; @@ -106,7 +106,7 @@ class PartDesignExport SubtractiveBox : public Box { class PartDesignExport Cylinder : public PartDesign::FeaturePrimitive, public Part::PrismExtension { - PROPERTY_HEADER(PartDesign::Cylinder); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Cylinder); public: @@ -119,12 +119,12 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; }; class PartDesignExport AdditiveCylinder : public Cylinder { - PROPERTY_HEADER(PartDesign::AdditiveCylinder); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveCylinder); AdditiveCylinder() { addSubType = FeatureAddSub::Additive; @@ -132,7 +132,7 @@ class PartDesignExport AdditiveCylinder : public Cylinder { }; class PartDesignExport SubtractiveCylinder : public Cylinder { - PROPERTY_HEADER(PartDesign::SubtractiveCylinder); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveCylinder); SubtractiveCylinder() { addSubType = FeatureAddSub::Subtractive; @@ -142,7 +142,7 @@ class PartDesignExport SubtractiveCylinder : public Cylinder { class PartDesignExport Sphere : public PartDesign::FeaturePrimitive { - PROPERTY_HEADER(PartDesign::Sphere); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Sphere); public: @@ -156,15 +156,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; protected: }; class PartDesignExport AdditiveSphere : public Sphere { - PROPERTY_HEADER(PartDesign::AdditiveSphere); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveSphere); AdditiveSphere() { addSubType = FeatureAddSub::Additive; @@ -172,7 +172,7 @@ class PartDesignExport AdditiveSphere : public Sphere { }; class PartDesignExport SubtractiveSphere : public Sphere { - PROPERTY_HEADER(PartDesign::SubtractiveSphere); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveSphere); SubtractiveSphere() { addSubType = FeatureAddSub::Subtractive; @@ -181,7 +181,7 @@ class PartDesignExport SubtractiveSphere : public Sphere { class PartDesignExport Cone : public PartDesign::FeaturePrimitive { - PROPERTY_HEADER(PartDesign::Cone); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Cone); public: @@ -195,15 +195,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; protected: }; class PartDesignExport AdditiveCone : public Cone { - PROPERTY_HEADER(PartDesign::AdditiveCone); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveCone); AdditiveCone() { addSubType = FeatureAddSub::Additive; @@ -211,7 +211,7 @@ class PartDesignExport AdditiveCone : public Cone { }; class PartDesignExport SubtractiveCone : public Cone { - PROPERTY_HEADER(PartDesign::SubtractiveCone); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveCone); SubtractiveCone() { addSubType = FeatureAddSub::Subtractive; @@ -221,7 +221,7 @@ class PartDesignExport SubtractiveCone : public Cone { class PartDesignExport Ellipsoid : public PartDesign::FeaturePrimitive { - PROPERTY_HEADER(PartDesign::Ellipsoid); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Ellipsoid); public: @@ -237,15 +237,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; protected: }; class PartDesignExport AdditiveEllipsoid : public Ellipsoid { - PROPERTY_HEADER(PartDesign::AdditiveEllipsoid); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveEllipsoid); AdditiveEllipsoid() { addSubType = FeatureAddSub::Additive; @@ -253,7 +253,7 @@ class PartDesignExport AdditiveEllipsoid : public Ellipsoid { }; class PartDesignExport SubtractiveEllipsoid : public Ellipsoid { - PROPERTY_HEADER(PartDesign::SubtractiveEllipsoid); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveEllipsoid); SubtractiveEllipsoid() { addSubType = FeatureAddSub::Subtractive; @@ -263,7 +263,7 @@ class PartDesignExport SubtractiveEllipsoid : public Ellipsoid { class PartDesignExport Torus : public PartDesign::FeaturePrimitive { - PROPERTY_HEADER(PartDesign::Torus); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Torus); public: @@ -278,15 +278,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; protected: }; class PartDesignExport AdditiveTorus : public Torus { - PROPERTY_HEADER(PartDesign::AdditiveTorus); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveTorus); AdditiveTorus() { addSubType = FeatureAddSub::Additive; @@ -294,7 +294,7 @@ class PartDesignExport AdditiveTorus : public Torus { }; class PartDesignExport SubtractiveTorus : public Torus { - PROPERTY_HEADER(PartDesign::SubtractiveTorus); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveTorus); SubtractiveTorus() { addSubType = FeatureAddSub::Subtractive; @@ -304,7 +304,7 @@ class PartDesignExport SubtractiveTorus : public Torus { class PartDesignExport Prism : public PartDesign::FeaturePrimitive, public Part::PrismExtension { - PROPERTY_HEADER(PartDesign::Prism); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Prism); public: Prism(); @@ -316,12 +316,12 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; }; class PartDesignExport AdditivePrism : public Prism { - PROPERTY_HEADER(PartDesign::AdditivePrism); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditivePrism); AdditivePrism() { addSubType = FeatureAddSub::Additive; @@ -329,7 +329,7 @@ class PartDesignExport AdditivePrism : public Prism { }; class PartDesignExport SubtractivePrism : public Prism { - PROPERTY_HEADER(PartDesign::SubtractivePrism); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractivePrism); SubtractivePrism() { addSubType = FeatureAddSub::Subtractive; @@ -339,7 +339,7 @@ class PartDesignExport SubtractivePrism : public Prism { class PartDesignExport Wedge : public PartDesign::FeaturePrimitive { - PROPERTY_HEADER(PartDesign::Wedge); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Wedge); public: @@ -359,15 +359,15 @@ public: /** @name methods override feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; protected: }; class PartDesignExport AdditiveWedge : public Wedge { - PROPERTY_HEADER(PartDesign::AdditiveWedge); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::AdditiveWedge); AdditiveWedge() { addSubType = FeatureAddSub::Additive; @@ -375,7 +375,7 @@ class PartDesignExport AdditiveWedge : public Wedge { }; class PartDesignExport SubtractiveWedge : public Wedge { - PROPERTY_HEADER(PartDesign::SubtractiveWedge); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SubtractiveWedge); SubtractiveWedge() { addSubType = FeatureAddSub::Subtractive; diff --git a/src/Mod/PartDesign/App/FeatureRevolution.cpp b/src/Mod/PartDesign/App/FeatureRevolution.cpp index fbdd9571c7..dc1431a3c8 100644 --- a/src/Mod/PartDesign/App/FeatureRevolution.cpp +++ b/src/Mod/PartDesign/App/FeatureRevolution.cpp @@ -69,7 +69,7 @@ short Revolution::mustExecute() const return ProfileBased::mustExecute(); } -App::DocumentObjectExecReturn *Revolution::execute(void) +App::DocumentObjectExecReturn *Revolution::execute() { // Validate parameters double angle = Angle.getValue(); @@ -179,7 +179,7 @@ App::DocumentObjectExecReturn *Revolution::execute(void) } } -bool Revolution::suggestReversed(void) +bool Revolution::suggestReversed() { try { updateAxis(); @@ -190,7 +190,7 @@ bool Revolution::suggestReversed(void) return ProfileBased::getReversedAngle(Base.getValue(), Axis.getValue()) < 0.0; } -void Revolution::updateAxis(void) +void Revolution::updateAxis() { App::DocumentObject *pcReferenceAxis = ReferenceAxis.getValue(); const std::vector &subReferenceAxis = ReferenceAxis.getSubValues(); diff --git a/src/Mod/PartDesign/App/FeatureRevolution.h b/src/Mod/PartDesign/App/FeatureRevolution.h index 5689843774..23478f46c2 100644 --- a/src/Mod/PartDesign/App/FeatureRevolution.h +++ b/src/Mod/PartDesign/App/FeatureRevolution.h @@ -32,7 +32,7 @@ namespace PartDesign class PartDesignExport Revolution : public ProfileBased { - PROPERTY_HEADER(PartDesign::Revolution); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Revolution); public: Revolution(); @@ -55,19 +55,19 @@ public: * If Reversed is true then the direction of revolution will be reversed. * The created material will be fused with the sketch support (if there is one) */ - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderRevolution"; } //@} /// suggests a value for Reversed flag so that material is always added to the support - bool suggestReversed(void); + bool suggestReversed(); protected: /// updates Axis from ReferenceAxis - void updateAxis(void); + void updateAxis(); static const App::PropertyAngle::Constraints floatAngle; }; diff --git a/src/Mod/PartDesign/App/FeatureScaled.h b/src/Mod/PartDesign/App/FeatureScaled.h index b6ef13b3f4..90123fad79 100644 --- a/src/Mod/PartDesign/App/FeatureScaled.h +++ b/src/Mod/PartDesign/App/FeatureScaled.h @@ -33,7 +33,7 @@ namespace PartDesign class PartDesignExport Scaled : public PartDesign::Transformed { - PROPERTY_HEADER(PartDesign::Scaled); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Scaled); public: Scaled(); @@ -43,10 +43,10 @@ public: /** @name methods override feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderScaled"; } //@} @@ -60,7 +60,7 @@ public: */ // Note: We can't just use the Originals property because this will fail if the Scaled feature // is being used inside a MultiTransform feature - const std::list getTransformations(const std::vector originals); + const std::list getTransformations(const std::vector originals) override; }; } //namespace PartDesign diff --git a/src/Mod/PartDesign/App/FeatureSketchBased.cpp b/src/Mod/PartDesign/App/FeatureSketchBased.cpp index e33bb1d131..98f2dc1c77 100644 --- a/src/Mod/PartDesign/App/FeatureSketchBased.cpp +++ b/src/Mod/PartDesign/App/FeatureSketchBased.cpp @@ -91,7 +91,7 @@ void ProfileBased::setupObject() AllowMultiFace.setValue(true); } -void ProfileBased::positionByPrevious(void) +void ProfileBased::positionByPrevious() { Part::Feature* feat = getBaseObject(/* silent = */ true); if (feat) { @@ -317,7 +317,7 @@ TopoDS_Face ProfileBased::getSupportFace(const Part::Part2DObject* sketch) const const std::vector& sub = Support.getSubValues(); assert(sub.size() == 1); - if (sub.at(0) == "") { + if (sub.at(0).empty()) { // This seems to happen when sketch is on a datum plane return TopoDS::Face(Feature::makeShapeFromPlane(sketch)); } @@ -357,7 +357,7 @@ TopoDS_Face ProfileBased::getSupportFace(const App::PropertyLinkSub& link) const return face; } -int ProfileBased::getSketchAxisCount(void) const +int ProfileBased::getSketchAxisCount() const { Part::Part2DObject* sketch = static_cast(Profile.getValue()); if (!sketch) @@ -422,7 +422,7 @@ void ProfileBased::getFaceFromLinkSub(TopoDS_Face& upToFace, const App::Property App::DocumentObject* ref = refFace.getValue(); std::vector subStrings = refFace.getSubValues(); - if (ref == nullptr) + if (!ref) throw Base::ValueError("SketchBased: No face selected"); if (ref->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) { @@ -1150,7 +1150,7 @@ void ProfileBased::handleChangedPropertyName(Base::XMLReader & reader, const cha // get the value of my attribute std::string name = reader.getAttribute("value"); - if (name != "") { + if (!name.empty()) { App::Document* document = getDocument(); DocumentObject* object = document ? document->getObject(name.c_str()) : nullptr; Profile.setValue(object, vec); diff --git a/src/Mod/PartDesign/App/FeatureSketchBased.h b/src/Mod/PartDesign/App/FeatureSketchBased.h index 62629e288b..3a729dc49b 100644 --- a/src/Mod/PartDesign/App/FeatureSketchBased.h +++ b/src/Mod/PartDesign/App/FeatureSketchBased.h @@ -38,7 +38,7 @@ namespace PartDesign class PartDesignExport ProfileBased : public PartDesign::FeatureAddSub { - PROPERTY_HEADER(PartDesign::SketchBased); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::SketchBased); public: enum class ForbiddenAxis { @@ -60,20 +60,20 @@ public: App::PropertyBool AllowMultiFace; - short mustExecute() const; + short mustExecute() const override; - void setupObject(); + void setupObject() override; /** calculates and updates the Placement property based on the features * this one is made from: either from Base, if there is one, or from sketch, * if there is no base. */ - void positionByPrevious(void); + void positionByPrevious(); /** applies a transform on the Placement of the Sketch or its * support if it has one */ - virtual void transformPlacement(const Base::Placement &transform); + void transformPlacement(const Base::Placement &transform) override; /** * Verifies the linked Profile and returns it if it is a valid 2D object @@ -110,13 +110,13 @@ public: Part::TopoShape getProfileShape() const; /// retrieves the number of axes in the linked sketch (defined as construction lines) - int getSketchAxisCount(void) const; + int getSketchAxisCount() const; - virtual Part::Feature* getBaseObject(bool silent=false) const; + Part::Feature* getBaseObject(bool silent=false) const override; //backwards compatibility: profile property was renamed and has different type now - virtual void Restore(Base::XMLReader& reader); - virtual void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName); + void Restore(Base::XMLReader& reader) override; + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; // calculate the through all length double getThroughAllLength() const; @@ -159,7 +159,7 @@ protected: void getAxis(const App::DocumentObject* pcReferenceAxis, const std::vector& subReferenceAxis, Base::Vector3d& base, Base::Vector3d& dir, ForbiddenAxis checkAxis) const; - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: bool isParallelPlane(const TopoDS_Shape&, const TopoDS_Shape&) const; bool isEqualGeometry(const TopoDS_Shape&, const TopoDS_Shape&) const; diff --git a/src/Mod/PartDesign/App/FeatureSolid.h b/src/Mod/PartDesign/App/FeatureSolid.h index 2ca4aac5ec..020a3c300e 100644 --- a/src/Mod/PartDesign/App/FeatureSolid.h +++ b/src/Mod/PartDesign/App/FeatureSolid.h @@ -37,7 +37,7 @@ namespace PartDesign */ class PartDesignExport Solid : public Feature { - PROPERTY_HEADER(PartDesign::FeatureSolid); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::FeatureSolid); public: Solid(); diff --git a/src/Mod/PartDesign/App/FeatureThickness.cpp b/src/Mod/PartDesign/App/FeatureThickness.cpp index 65a1807ecd..2c3c2c4b64 100644 --- a/src/Mod/PartDesign/App/FeatureThickness.cpp +++ b/src/Mod/PartDesign/App/FeatureThickness.cpp @@ -59,7 +59,7 @@ short Thickness::mustExecute() const return DressUp::mustExecute(); } -App::DocumentObjectExecReturn *Thickness::execute(void) +App::DocumentObjectExecReturn *Thickness::execute() { // Base shape Part::TopoShape TopShape; diff --git a/src/Mod/PartDesign/App/FeatureThickness.h b/src/Mod/PartDesign/App/FeatureThickness.h index 2a1078a4da..0ac89fbf9a 100644 --- a/src/Mod/PartDesign/App/FeatureThickness.h +++ b/src/Mod/PartDesign/App/FeatureThickness.h @@ -33,7 +33,7 @@ namespace PartDesign class PartDesignExport Thickness : public DressUp { - PROPERTY_HEADER(PartDesign::Thickness); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Thickness); public: Thickness(); @@ -47,10 +47,10 @@ public: /** @name methods override feature */ //@{ /// recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderThickness"; } //@} diff --git a/src/Mod/PartDesign/App/FeatureTransformed.cpp b/src/Mod/PartDesign/App/FeatureTransformed.cpp index 5e11a7f3fa..0167939037 100644 --- a/src/Mod/PartDesign/App/FeatureTransformed.cpp +++ b/src/Mod/PartDesign/App/FeatureTransformed.cpp @@ -69,7 +69,7 @@ Transformed::Transformed() this->Refine.setValue(hGrp->GetBool("RefineModel", false)); } -void Transformed::positionBySupport(void) +void Transformed::positionBySupport() { // TODO May be here better to throw exception (silent=false) (2015-07-27, Fat-Zer) Part::Feature *support = getBaseObject(/* silent =*/ true); @@ -163,7 +163,7 @@ short Transformed::mustExecute() const return PartDesign::Feature::mustExecute(); } -App::DocumentObjectExecReturn *Transformed::execute(void) +App::DocumentObjectExecReturn *Transformed::execute() { std::vector originals = Originals.getValues(); if (originals.empty()) // typically InsideMultiTransform @@ -236,7 +236,7 @@ App::DocumentObjectExecReturn *Transformed::execute(void) shapes.emplace_back(shape); } - for (auto shape : shapes) + for (const auto& shape : shapes) shapeTools.Append(shape); return shapeTools; diff --git a/src/Mod/PartDesign/App/FeatureTransformed.h b/src/Mod/PartDesign/App/FeatureTransformed.h index edd7d59dbb..3e8e50104a 100644 --- a/src/Mod/PartDesign/App/FeatureTransformed.h +++ b/src/Mod/PartDesign/App/FeatureTransformed.h @@ -39,7 +39,7 @@ namespace PartDesign */ class PartDesignExport Transformed : public PartDesign::Feature { - PROPERTY_HEADER(PartDesign::Transformed); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesign::Transformed); public: Transformed(); @@ -58,7 +58,7 @@ public: * silently return a nullptr, otherwise throw Base::Exception. * Default is false. */ - virtual Part::Feature* getBaseObject(bool silent=false) const; + Part::Feature* getBaseObject(bool silent=false) const override; /// Return the sketch of the first original App::DocumentObject* getSketchObject() const; @@ -78,8 +78,8 @@ public: * If Originals is empty, execute() returns immediately without doing anything as * the actual processing will happen in the MultiTransform feature */ - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; //@} /** returns the compound of the shapes that were rejected during the last execute @@ -88,9 +88,9 @@ public: TopoDS_Shape rejected; protected: - void Restore(Base::XMLReader &reader); - void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop); - virtual void positionBySupport(void); + void Restore(Base::XMLReader &reader) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + virtual void positionBySupport(); TopoDS_Shape refineShapeIfActive(const TopoDS_Shape&) const; void divideTools(const std::vector &toolsIn, std::vector &individualsOut, TopoDS_Compound &compoundOut) const; diff --git a/src/Mod/PartDesign/App/ShapeBinder.cpp b/src/Mod/PartDesign/App/ShapeBinder.cpp index aff1c4e746..33adbcaec6 100644 --- a/src/Mod/PartDesign/App/ShapeBinder.cpp +++ b/src/Mod/PartDesign/App/ShapeBinder.cpp @@ -73,7 +73,7 @@ void ShapeBinder::onChanged(const App::Property* prop) Feature::onChanged(prop); } -short int ShapeBinder::mustExecute(void) const { +short int ShapeBinder::mustExecute() const { if (Support.isTouched()) return 1; @@ -117,7 +117,7 @@ bool ShapeBinder::hasPlacementChanged() const return this->Placement.getValue() != placement; } -App::DocumentObjectExecReturn* ShapeBinder::execute(void) { +App::DocumentObjectExecReturn* ShapeBinder::execute() { if (!this->isRestoring()) { Part::TopoShape shape(updatedShape()); @@ -204,7 +204,7 @@ Part::TopoShape ShapeBinder::buildShapeFromReferences(App::GeoFeature* obj, std: return part->Shape.getValue(); std::vector shapes; - for (std::string sub : subs) { + for (const std::string& sub : subs) { shapes.push_back(part->Shape.getShape().getSubShape(sub.c_str())); } @@ -444,12 +444,12 @@ void SubShapeBinder::setupCopyOnChange() { hasCopyOnChange = App::LinkBaseExtension::setupCopyOnChange(this, linked, BindCopyOnChange.getValue() == 1 ? ©OnChangeConns : nullptr, hasCopyOnChange); if (hasCopyOnChange) { - copyOnChangeConns.push_back(linked->signalChanged.connect( + copyOnChangeConns.emplace_back(linked->signalChanged.connect( [this](const App::DocumentObject&, const App::Property& prop) { if (!prop.testStatus(App::Property::Output) && !prop.testStatus(App::Property::PropOutput)) { - if (this->_CopiedObjs.size()) { + if (!this->_CopiedObjs.empty()) { FC_LOG("Clear binder " << getFullName() << " cache on change of " << prop.getFullName()); this->clearCopiedObjects(); @@ -560,7 +560,7 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { App::DocumentObject* copied = nullptr; if (BindCopyOnChange.getValue() == 2 && Support.getSubListValues().size() == 1) { - if (_CopiedObjs.size()) + if (!_CopiedObjs.empty()) copied = _CopiedObjs.front().getObject(); bool recomputeCopy = false; @@ -618,7 +618,7 @@ void SubShapeBinder::update(SubShapeBinder::UpdateOption options) { const auto& subvals = copied ? _CopiedLink.getSubValues() : l.getSubValues(); std::set subs(subvals.begin(), subvals.end()); - static std::string none(""); + static std::string none; if (subs.empty()) subs.insert(none); else if (subs.size() > 1) @@ -805,7 +805,7 @@ void SubShapeBinder::slotRecomputedObject(const App::DocumentObject& Obj) { } } -App::DocumentObjectExecReturn* SubShapeBinder::execute(void) { +App::DocumentObjectExecReturn* SubShapeBinder::execute() { setupCopyOnChange(); @@ -907,7 +907,7 @@ void SubShapeBinder::setLinks(std::mapgetFullName()); if (v.second.empty()) { - v.second.push_back(""); + v.second.emplace_back(""); continue; } @@ -988,7 +988,7 @@ void SubShapeBinder::handleChangedPropertyType( namespace App { PROPERTY_SOURCE_TEMPLATE(PartDesign::SubShapeBinderPython, PartDesign::SubShapeBinder) - template<> const char* PartDesign::SubShapeBinderPython::getViewProviderName(void) const { + template<> const char* PartDesign::SubShapeBinderPython::getViewProviderName() const { return "PartDesignGui::ViewProviderSubShapeBinderPython"; } template class PartDesignExport FeaturePythonT; diff --git a/src/Mod/PartDesign/App/ShapeBinder.h b/src/Mod/PartDesign/App/ShapeBinder.h index 75c5b13d90..03f9e6aca2 100644 --- a/src/Mod/PartDesign/App/ShapeBinder.h +++ b/src/Mod/PartDesign/App/ShapeBinder.h @@ -47,7 +47,7 @@ class PartDesignExport ShapeBinder : public Part::Feature public: ShapeBinder(); - virtual ~ShapeBinder(); + ~ShapeBinder() override; App::PropertyLinkSubListGlobal Support; App::PropertyBool TraceSupport; @@ -55,21 +55,21 @@ public: static void getFilteredReferences(const App::PropertyLinkSubList* prop, App::GeoFeature*& object, std::vector< std::string >& subobjects); static Part::TopoShape buildShapeFromReferences(App::GeoFeature* obj, std::vector< std::string > subs); - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderShapeBinder"; } protected: Part::TopoShape updatedShape() const; bool hasPlacementChanged() const; - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; - virtual short int mustExecute(void) const override; - virtual App::DocumentObjectExecReturn* execute(void) override; - virtual void onChanged(const App::Property* prop) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; + short int mustExecute() const override; + App::DocumentObjectExecReturn* execute() override; + void onChanged(const App::Property* prop) override; private: void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); - virtual void onSettingDocument() override; + void onSettingDocument() override; typedef boost::signals2::connection Connection; Connection connectDocumentChangedObject; @@ -81,9 +81,9 @@ public: typedef Part::Feature inherited; SubShapeBinder(); - ~SubShapeBinder(); + ~SubShapeBinder() override; - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "PartDesignGui::ViewProviderSubShapeBinder"; } @@ -113,24 +113,24 @@ public: }; void update(UpdateOption options = UpdateNone); - virtual int canLoadPartial() const override { + int canLoadPartial() const override { return PartialLoad.getValue()?1:0; } - virtual bool canLinkProperties() const override {return false;} + bool canLinkProperties() const override {return false;} - virtual App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj=nullptr, + App::DocumentObject *getSubObject(const char *subname, PyObject **pyObj=nullptr, Base::Matrix4D *mat=nullptr, bool transform=true, int depth=0) const override; protected: - virtual App::DocumentObjectExecReturn* execute(void) override; - virtual void onChanged(const App::Property *prop) override; + App::DocumentObjectExecReturn* execute() override; + void onChanged(const App::Property *prop) override; - virtual void handleChangedPropertyType( + void handleChangedPropertyType( Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; - virtual void onDocumentRestored() override; - virtual void setupObject() override; + void onDocumentRestored() override; + void setupObject() override; void setupCopyOnChange(); void checkCopyOnChange(const App::Property &prop); diff --git a/src/Mod/PartDesign/FeatureHole/FeatureHole.py b/src/Mod/PartDesign/FeatureHole/FeatureHole.py index da4d520d8f..f4345aac07 100644 --- a/src/Mod/PartDesign/FeatureHole/FeatureHole.py +++ b/src/Mod/PartDesign/FeatureHole/FeatureHole.py @@ -32,7 +32,7 @@ def makeVector(point): class Hole(): "Hole feature" App = FreeCAD - Gui = FreeCADGui + Gui = FreeCADGui def __init__(self, feature): self.feature = feature @@ -50,13 +50,13 @@ class Hole(): self.feature.addProperty("App::PropertyLength","Depth","Hole","Depth of hole").Depth=8.0 self.feature.addProperty("App::PropertyLength","CounterboreDiameter","Hole","Diameter of counterbore").CounterboreDiameter=10.0 self.feature.addProperty("App::PropertyLength","CounterboreDepth","Hole","Depth of counterbore").CounterboreDepth=4.0 - self.feature.addProperty("App::PropertyLength","CountersinkAngle","Hole","Angle of countersink").CountersinkAngle=45.0; - self.feature.addProperty("App::PropertyLength","ThreadLength","Hole","Length of thread").ThreadLength=5.0; + self.feature.addProperty("App::PropertyLength","CountersinkAngle","Hole","Angle of countersink").CountersinkAngle=45.0 + self.feature.addProperty("App::PropertyLength","ThreadLength","Hole","Length of thread").ThreadLength=5.0 self.feature.addProperty("App::PropertyString","PositionType","Hole","Type of position references").PositionType="Linear" self.feature.addProperty("App::PropertyLinkSub","Support","Hole","Support of hole feature").Support=None self.feature.addProperty("App::PropertyLink","HoleGroove","Hole","Revolution feature creating the hole").HoleGroove=None # Create new HoleGroove feature - body = FreeCADGui.activeView().getActiveObject("pdbody"); + body = FreeCADGui.activeView().getActiveObject("pdbody") self.sketchaxis = self.feature.Document.addObject("PartDesign::Line", "HoleSketchAxis") body.addFeature(self.sketchaxis) self.Gui.ActiveDocument.hide(self.sketchaxis.Name) @@ -78,14 +78,14 @@ class Hole(): self.oldCountersink = False def execute(self, feature): - if feature.Support != None: + if feature.Support is not None: (support, element) = feature.Support feature.Placement = feature.HoleGroove.Placement shape = feature.HoleGroove.Shape.copy() shape.Placement = FreeCAD.Placement() feature.Shape = shape - - self.Gui.ActiveDocument.hide(support.Name) + + self.Gui.ActiveDocument.hide(support.Name) # Copy display properties from support featview = feature.ViewObject suppview = support.ViewObject @@ -125,7 +125,7 @@ class Hole(): refs = plane.References if len(refs) == 0: return - + axis = plane.References[0][0] firstTime = (len(axis.References) == 0) if firstTime: @@ -156,7 +156,7 @@ class Hole(): except Exception: # Unknown curvetype GeomAbs_OtherCurve continue - axis.References = [(support, elementList[0]), (support, "Edge" + str(firstLineIndex+1)), (support, "Edge" + str(secondLineIndex+1))] + axis.References = [(support, elementList[0]), (support, "Edge" + str(firstLineIndex+1)), (support, "Edge" + str(secondLineIndex+1))] axis.Offset = 1.0 axis.Offset2 = 1.0 self.feature.PositionType = "Linear" @@ -166,7 +166,7 @@ class Hole(): #l2 = Part.LineSegment(e.Curve) #axis.Offset = p.distanceToLine(l1.StartPoint, l1.EndPoint - l1.StartPoint) #axis.Offset2 = p.distanceToLine(l1.StartPoint, l2.EndPoint - l2.StartPoint) - # TODO: Ensure that the hole is inside the face! + # TODO: Ensure that the hole is inside the face! break elif type(e.Curve) == Part.Circle: allEdges = support.Shape.Edges @@ -195,12 +195,12 @@ class Hole(): break except: continue - break - + break + # Grab a point from the wire of the support face axisbase = axis.Shape.Curve.StartPoint axisdir = axis.Shape.Curve.EndPoint - axisbase - found = False + found = False if not firstTime and len(refs) > 1: # Try to keep the old point, to avoid the sketch plane jumping around (obj, sub) = refs[1] @@ -215,12 +215,12 @@ class Hole(): break if not found: point = face.OuterWire.Vertexes[0] # Better this than nothing... and it can't actually happen, can it? - + # Find the index of the point in the support shape allVertexes = support.Shape.Vertexes for v in range(len(allVertexes)): - if allVertexes[v].Point == point.Point: - # Use this point and the axis to define the sketch plane + if allVertexes[v].Point == point.Point: + # Use this point and the axis to define the sketch plane if len(refs) < 2: refs.append((support, "Vertex" + str(v+1))) else: @@ -234,7 +234,7 @@ class Hole(): else: self.executeSketchChanged(fp) # Update the sketch of the hole self.setHoleDirection(fp) - + def setHoleDirection(self, feature): # Make sure the hole goes into the material, not out of it sketch = feature.HoleGroove.Sketch @@ -244,7 +244,7 @@ class Hole(): p1 = None p2 = None for v in sketch.Shape.Vertexes: - # Find the two sketch vertices that are on the sketch axis + # Find the two sketch vertices that are on the sketch axis if v.Point.distanceToLine(axisbase, axisdir) < 1E-10: # TODO: use Precision::Confusion() if p1 is None: p1 = v.Point @@ -263,7 +263,7 @@ class Hole(): dir = p2 - p1 else: top = p2 - dir = p1 - p2 + dir = p1 - p2 if not support.Shape.isInside(top + dir.multiply(1E-8), 1E-10, False): # Toggle the angle angle = sketch.Constraints[12].Value @@ -291,17 +291,17 @@ class Hole(): self.createOrUpdateStandardSketch(fp, length, radius) def createOrUpdateStandardSketch(self, fp, depth, radius): - (support, elements) = fp.Support + (support, elements) = fp.Support if fp.HoleGroove.Sketch.GeometryCount == 0: #FreeCAD.Console.PrintMessage("Standard sketch\n") - # New sketch + # New sketch sketch = fp.HoleGroove.Sketch axis = sketch.Support[0].References[0][0] # Geo -1,1 is the origin (Point) # Geo -1 is the X-axis # Geo -2 is the Y-axis # First external geometry is -3 - sketch.addExternal(axis.Name,"LineSegment") # Geo -3: Datum axis + sketch.addExternal(axis.Name,"LineSegment") # Geo -3: Datum axis sketch.addExternal(support.Name, elements[0]) # Geo -4: Support face # Note: Creating the sketch first with depth = 100.0 and then changing the constraint later seems to be more stable tempDepth = 100.0 @@ -314,8 +314,8 @@ class Hole(): sketch.addGeometry(Part.LineSegment(self.App.Vector(10.0,-10.0,0),self.App.Vector(20.0,-10.0,0))) # Geo2: Top of hole sketch.addConstraint(Sketcher.Constraint('Coincident',1,1,2,1)) # Datum2 sketch.addConstraint(Sketcher.Constraint('Perpendicular',2, 1)) # Datum3 - sketch.addGeometry(Part.LineSegment(self.App.Vector(20.0,-10.0,0),self.App.Vector(20.0,-25.0,0))) # Geo3: Vertical mantle of hole - sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) # temporary + sketch.addGeometry(Part.LineSegment(self.App.Vector(20.0,-10.0,0),self.App.Vector(20.0,-25.0,0))) # Geo3: Vertical mantle of hole + sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) # temporary sketch.addConstraint(Sketcher.Constraint('Parallel',3, 1)) # Datum4 sketch.addConstraint(Sketcher.Constraint('Distance',3,2,1, 10.0)) # Datum5: Radius sketch.addConstraint(Sketcher.Constraint('Distance',3,2,2, 15.0)) # Datum6: Depth @@ -323,7 +323,7 @@ class Hole(): sketch.addConstraint(Sketcher.Constraint('Coincident',4,1,1,2)) # Datum7 sketch.addConstraint(Sketcher.Constraint('Coincident',4,2,3,2)) # Datum8 # TODO: The tip angle of 118 degrees is for steel only. It should be taken from Part material data - # (as soon as that is implemented) + # (as soon as that is implemented) sketch.addConstraint(Sketcher.Constraint('Angle',4,1,1,2, 118.0/2.0 * math.pi / 180.0)) # Datum9 # Locate at the intersection of the two external geometries sketch.addConstraint(Sketcher.Constraint('PointOnObject',1,1,-3))# Datum10 @@ -332,7 +332,7 @@ class Hole(): # This datum is specific for this holetype, so move it to the last position sketch.delConstraint(4) sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) # Datum13 - fp.HoleGroove.ReferenceAxis = (sketch,['Axis0']) + fp.HoleGroove.ReferenceAxis = (sketch,['Axis0']) if self.oldCounterbore == True: # Remove counterbore from existing sketch #FreeCAD.Console.PrintMessage("Counter to Standard sketch\n") @@ -345,7 +345,7 @@ class Hole(): sketch.delConstraint(14) sketch.delConstraint(13) sketch.delGeometry(6) - sketch.delGeometry(5) + sketch.delGeometry(5) sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) # Datum13 elif self.oldCountersink == True: # Remove countersink from existing sketch @@ -355,7 +355,7 @@ class Hole(): sketch.delConstraint(15) sketch.delConstraint(14) sketch.delConstraint(13) - sketch.delGeometry(5) + sketch.delGeometry(5) sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) # Datum13 else: # Update existing standard sketch @@ -369,12 +369,12 @@ class Hole(): sketch.delConstraint(13) sketch.delConstraint(12) sketch.delConstraint(11) - sketch.delExternal(1) + sketch.delExternal(1) sketch.addExternal(support.Name, elements[0]) # Geo -4: Support face sketch.addConstraint(Sketcher.Constraint('PointOnObject',1,1,-4))# Datum11 sketch.addConstraint(Sketcher.Constraint('Angle',0,1,-3, 1, angle))# Datum12 sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,3,1)) # Datum13 - + self.setHoleDirection(fp) self.oldCounterbore = False self.oldCountersink = False @@ -404,17 +404,17 @@ class Hole(): sketch.delConstraint(13) sketch.delConstraint(12) sketch.delConstraint(11) - sketch.delExternal(1) + sketch.delExternal(1) sketch.addExternal(support.Name, elements[0]) # Geo -4: Support face sketch.addConstraint(Sketcher.Constraint('PointOnObject',1,1,-4))# Datum11 sketch.addConstraint(Sketcher.Constraint('Angle',0,1,-3, 1, angle))# Datum12 sketch.addConstraint(Sketcher.Constraint('Distance',2, cradius)) # Datum13 sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,5,1)) # Datum14 sketch.addConstraint(Sketcher.Constraint('Distance',3, 1, 2, cdepth)) # Datum15 - sketch.addConstraint(Sketcher.Constraint('Parallel',5, 1)) # Datum16 + sketch.addConstraint(Sketcher.Constraint('Parallel',5, 1)) # Datum16 sketch.addConstraint(Sketcher.Constraint('Coincident',5,2,6,1)) # Datum17 sketch.addConstraint(Sketcher.Constraint('Perpendicular',6, -3)) # Datum18 - sketch.addConstraint(Sketcher.Constraint('Coincident',6,2,3,1)) # Datum19 + sketch.addConstraint(Sketcher.Constraint('Coincident',6,2,3,1)) # Datum19 else: # Change standard to counterbore in existing sketch #FreeCAD.Console.PrintMessage("Standard to Counterbore sketch\n") @@ -430,7 +430,7 @@ class Hole(): sketch.addGeometry(Part.LineSegment(self.App.Vector(p2.x,p2.y-20.0, 0),p3)) # Geo6: bottom of counterbore sketch.addConstraint(Sketcher.Constraint('Coincident',5,2,6,1)) # Datum17 sketch.addConstraint(Sketcher.Constraint('Perpendicular',6, -3)) # Datum18 - sketch.addConstraint(Sketcher.Constraint('Coincident',6,2,3,1)) # Datum19 + sketch.addConstraint(Sketcher.Constraint('Coincident',6,2,3,1)) # Datum19 self.setHoleDirection(fp) self.oldCounterbore = True @@ -441,7 +441,7 @@ class Hole(): sangle = fp.CountersinkAngle * math.pi / 180.0 (support, elements) = fp.Support - if self.oldCountersink == True: + if self.oldCountersink == True: # Update properties of existing countersink sketch #FreeCAD.Console.PrintMessage("Update to Countersink sketch\n") sketch = fp.HoleGroove.Sketch @@ -458,13 +458,13 @@ class Hole(): sketch.delConstraint(13) sketch.delConstraint(12) sketch.delConstraint(11) - sketch.delExternal(1) + sketch.delExternal(1) sketch.addExternal(support.Name, elements[0]) # Geo -4: Support face sketch.addConstraint(Sketcher.Constraint('PointOnObject',1,1,-4))# Datum11 sketch.addConstraint(Sketcher.Constraint('Angle',0,1,-3, 1, angle))# Datum12 sketch.addConstraint(Sketcher.Constraint('Distance',2, sradius)) # Datum13 sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,5,1)) # Datum14 - sketch.addConstraint(Sketcher.Constraint('Angle',5,2, 1,2, sangle)) # Datum15 + sketch.addConstraint(Sketcher.Constraint('Angle',5,2, 1,2, sangle)) # Datum15 sketch.addConstraint(Sketcher.Constraint('Coincident',3,1,5,2)) # Datum16 else: # Change standard to countersink in existing sketch @@ -475,8 +475,8 @@ class Hole(): p2 = sketch.Geometry[2].EndPoint sketch.addGeometry(Part.LineSegment(p2,self.App.Vector(p2.x,p2.y-20.0,0))) # Geo5: Chamfer of countersink sketch.addConstraint(Sketcher.Constraint('Coincident',2,2,5,1)) # Datum14 - sketch.addConstraint(Sketcher.Constraint('Angle',5,2, 1,2, sangle)) # Datum15 - sketch.addConstraint(Sketcher.Constraint('Coincident',3,1,5,2)) # Datum16 + sketch.addConstraint(Sketcher.Constraint('Angle',5,2, 1,2, sangle)) # Datum15 + sketch.addConstraint(Sketcher.Constraint('Coincident',3,1,5,2)) # Datum16 self.setHoleDirection(fp) self.oldCounterbore = False diff --git a/src/Mod/PartDesign/FeatureHole/TaskHole.py b/src/Mod/PartDesign/FeatureHole/TaskHole.py index 6805cb27bd..63aa82de5d 100644 --- a/src/Mod/PartDesign/FeatureHole/TaskHole.py +++ b/src/Mod/PartDesign/FeatureHole/TaskHole.py @@ -46,37 +46,37 @@ class TaskHole: return True def reject(self): - if (self.feature != None): + if (self.feature is not None): self.hideFeature() # Show the support again document = self.feature.Document body = FreeCADGui.activeView().getActiveObject("pdbody"); groove = self.feature.HoleGroove sketch = groove.Sketch plane = sketch.Support[0] - axis = plane.References[0][0] + axis = plane.References[0][0] body.removeObject(self.feature) - document.removeObject(self.feature.Name) + document.removeObject(self.feature.Name) body.removeObject(groove) document.removeObject(groove.Name) body.removeObject(sketch) try: - document.removeObject(sketch.Name) + document.removeObject(sketch.Name) except Exception: pass # This always throws an exception: "Sketch support has been deleted" from SketchObject::execute() body.removeObject(plane) document.removeObject(plane.Name) body.removeObject(axis) - document.removeObject(axis.Name) + document.removeObject(axis.Name) FreeCADGui.ActiveDocument.resetEdit() FreeCADGui.Control.closeDialog(self) return True - + def isAllowedAlterDocument(self): return False - + def isAllowedAlterView(self): return False - + def isAllowedAlterSelection(self): return True @@ -100,9 +100,9 @@ class TaskHole: # Type form.tabType = form.tabWidget.findChild(QtGui.QWidget, "tab_type") form.buttonThru = form.tabType.findChild(QtGui.QRadioButton, "buttonThru") - form.buttonDepth = form.tabType.findChild(QtGui.QRadioButton, "buttonDepth") - form.checkThreaded = form.tabType.findChild(QtGui.QCheckBox, "checkThreaded") - form.checkCounterbore = form.tabType.findChild(QtGui.QCheckBox, "checkCounterbore") + form.buttonDepth = form.tabType.findChild(QtGui.QRadioButton, "buttonDepth") + form.checkThreaded = form.tabType.findChild(QtGui.QCheckBox, "checkThreaded") + form.checkCounterbore = form.tabType.findChild(QtGui.QCheckBox, "checkCounterbore") form.checkCountersink = form.tabType.findChild(QtGui.QCheckBox, "checkCountersink") # Norm form.tabNorm = form.tabWidget.findChild(QtGui.QWidget, "tab_norm") @@ -114,7 +114,7 @@ class TaskHole: for tol in Standards.standards_tolerance: form.comboTolerance.addItem(tol) form.comboNormDia = form.tabNorm.findChild(QtGui.QComboBox, "comboNormDia") - form.comboNormBoltWasher = form.tabNorm.findChild(QtGui.QComboBox, "comboNormBoltWasher") + form.comboNormBoltWasher = form.tabNorm.findChild(QtGui.QComboBox, "comboNormBoltWasher") # Thread form.tabThread = form.tabWidget.findChild(QtGui.QWidget, "tab_thread") form.comboThreadNorm = form.tabThread.findChild(QtGui.QComboBox, "comboThreadNorm") @@ -127,8 +127,8 @@ class TaskHole: form.comboFinishNorm.addItem(std) # Data form.tabData = form.tabWidget.findChild(QtGui.QWidget, "tab_data") - form.spinDiameter = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinDiameter") - form.spinDepth = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinDepth") + form.spinDiameter = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinDiameter") + form.spinDepth = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinDepth") form.spinCounterboreDiameter = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinCounterboreDiameter") form.spinCounterboreDepth = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinCounterboreDepth") form.spinCountersinkAngle = form.tabData.findChild(QtGui.QDoubleSpinBox, "spinCountersinkAngle") @@ -186,7 +186,7 @@ class TaskHole: # Update the UI self.updateUI() return True - + def getRefText(self, ref): (obj, element) = ref if isinstance(element, basestring): @@ -226,7 +226,7 @@ class TaskHole: self.form.comboNormBoltWasher.setEnabled(True) else: self.form.comboNormBoltWasher.setEnabled(False) - # comboNorm + # comboNorm standards = Standards.getStandards(holetype) self.form.comboNorm.blockSignals(True) self.form.comboNorm.clear() @@ -266,7 +266,7 @@ class TaskHole: elif holetype == "counterbore": throughStandard = Standards.getThroughHoleStandard(self.feature.Norm) self.feature.Diameter = Standards.getThroughHoleDia(throughStandard, self.feature.NormDiameter, self.feature.NormTolerance) - self.feature.CounterboreDiameter = Standards.getCounterboreDia(self.feature.Norm, self.feature.NormDiameter, self.feature.ExtraNorm) + self.feature.CounterboreDiameter = Standards.getCounterboreDia(self.feature.Norm, self.feature.NormDiameter, self.feature.ExtraNorm) # TODO: Calculate counter bore depth from standard for bolt and washer(s) # Requires accessing all the norms for bolts # self.feature.CounterboreDepth = calcCounterboreDepth(...) @@ -282,7 +282,7 @@ class TaskHole: else: self.form.tabNorm.setEnabled(True) self.form.comboTolerance.setEnabled(False) - self.form.tabThread.setEnabled(True) + self.form.tabThread.setEnabled(True) self.form.comboThreadNorm.blockSignals(True) standards = Standards.getStandards("thread") if not self.feature.NormThread in standards: @@ -341,7 +341,7 @@ class TaskHole: elif self.feature.Countersink == True: self.form.spinCounterboreDiameter.setEnabled(True) self.form.spinCounterboreDiameter.setValue(self.feature.CounterboreDiameter) - self.form.spinCounterboreDepth.setEnabled(False) + self.form.spinCounterboreDepth.setEnabled(False) self.form.spinCountersinkAngle.setEnabled(True) self.form.spinCountersinkAngle.setValue(self.feature.CountersinkAngle) else: @@ -362,7 +362,7 @@ class TaskHole: self.form.spinCountersinkAngle.setEnabled(False) if self.feature.Threaded == True: self.form.spinDiameter.setEnabled(False) - if self.feature.NormThreadFinish != "Custom": + if self.feature.NormThreadFinish != "Custom": self.form.spinThreadLength.setEnabled(False) self.form.spinThreadLength.setValue(self.feature.ThreadLength) # Position @@ -373,7 +373,7 @@ class TaskHole: self.feature.Support = (selection[0].Object, selection[0].SubElementNames) self.form.lineSupport.setText(self.getRefText(self.feature.Support)) if self.feature.PositionType == self.types[0]: - # Linear + # Linear self.form.buttonRef1.setText("Line/Plane") self.form.buttonRef1.setEnabled(True) self.form.buttonRef2.setText("Line/Plane") @@ -383,7 +383,7 @@ class TaskHole: self.form.labelRef1.setEnabled(True) self.form.labelRef1.setText("Distance") axis = self.feature.HoleGroove.Sketch.Support[0].References[0][0] - if len(axis.References) > 0 and axis.References[0] != None: + if len(axis.References) > 0 and axis.References[0] is not None: if (len(axis.References) == 3): self.form.lineRef1.setText(self.getRefText(axis.References[1])) else: @@ -392,7 +392,7 @@ class TaskHole: self.form.spinRef1.setValue(axis.Offset) self.form.labelRef2.setEnabled(True) self.form.labelRef2.setText("Distance") - if len(axis.References) > 1 and axis.References[1] != None: + if len(axis.References) > 1 and axis.References[1] is not None: if (len(axis.References) == 3): self.form.lineRef2.setText(self.getRefText(axis.References[2])) else: @@ -406,7 +406,7 @@ class TaskHole: self.form.buttonRef2.setEnabled(False) self.form.lineRef1.setEnabled(True) axis = self.feature.HoleGroove.Sketch.Support[0].References[0][0] - if len(axis.References) > 0 and axis.References[0] != None: + if len(axis.References) > 0 and axis.References[0] is not None: self.form.lineRef1.setText(self.getRefText(axis.References[0])) self.form.lineRef2.setEnabled(False) self.form.labelRef1.setEnabled(False) @@ -470,23 +470,23 @@ class TaskHole: def comboNormBoltWasher(self, index): self.feature.ExtraNorm = str(self.form.comboNormBoltWasher.itemText(index)) self.updateUI() - + def comboThreadNorm(self, index): - self.feature.NormThread = str(self.form.comboThreadNorm.itemText(index)) + self.feature.NormThread = str(self.form.comboThreadNorm.itemText(index)) self.updateUI() - + def comboThreadDia(self, index): diameter = str(self.form.comboThreadDia.itemText(index)) self.feature.NormDiameter = float(diameter[1:]) self.updateUI() - + def checkCustomThreadLength(self, checked): if checked == True: self.feature.NormThreadFinish = "Custom" else: self.feature.NormThreadFinish = str(self.form.comboFinishNorm.currentText()) self.updateUI() - + def comboFinishNorm(self, index): self.feature.NormThreadFinish = str(self.form.comboFinishNorm.itemText(index)) self.updateUI() @@ -515,7 +515,7 @@ class TaskHole: def spinThreadLength(self, val): if (val > 0.0): self.feature.ThreadLength = val - + def comboType(self, index): self.feature.PositionType = self.types[index] self.updateUI() @@ -532,12 +532,12 @@ class TaskHole: if shape.Surface.__class__ != Part.Plane: FreeCAD.Console.PrintMessage("Selected face must be planar\n") return - if self.feature.PositionType == self.types[0]: + if self.feature.PositionType == self.types[0]: # The Hole support is also the first reference of the sketch axis in Linear mode with edges selected if len(refs) == 3: refs[0] = (feature, element) axis.References = refs - self.feature.Support = (feature, [element]) + self.feature.Support = (feature, [element]) elif self.selectionMode == "LinearReference": if shape.ShapeType == "Edge": if shape.Curve.__class__ != Part.LineSegment: @@ -560,7 +560,7 @@ class TaskHole: refs = [(feature, element)] else: FreeCAD.Console.PrintMessage("Wrong shape type selected\n") - return + return axis.References = refs axis.Document.recompute() elif self.selectionMode == "LinearReference2": @@ -584,7 +584,7 @@ class TaskHole: refs.append((feature, element)) else: FreeCAD.Console.PrintMessage("Wrong shape type selected\n") - return + return axis.References = refs axis.Document.recompute() elif self.selectionMode == "CircularReference": @@ -598,7 +598,7 @@ class TaskHole: return else: FreeCAD.Console.PrintMessage("Wrong shape type selected\n") - return + return refs = [(feature, element)] axis.References = refs axis.Document.recompute() @@ -616,13 +616,13 @@ class TaskHole: def hideFeature(self): # Make sure selection takes place on support, not on hole feature - if self.feature.Support != None: + if self.feature.Support is not None: FreeCADGui.ActiveDocument.hide(self.feature.Name) (support, elements) = self.feature.Support FreeCADGui.ActiveDocument.show(support.Name) def showFeature(self): - if self.feature.Support != None: + if self.feature.Support is not None: FreeCADGui.ActiveDocument.show(self.feature.Name) (support, elements) = self.feature.Support FreeCADGui.ActiveDocument.hide(support.Name) diff --git a/src/Mod/PartDesign/FeatureHole/ViewProviderHole.py b/src/Mod/PartDesign/FeatureHole/ViewProviderHole.py index b3ac7602f3..2c6b83fd7b 100644 --- a/src/Mod/PartDesign/FeatureHole/ViewProviderHole.py +++ b/src/Mod/PartDesign/FeatureHole/ViewProviderHole.py @@ -40,8 +40,8 @@ class ViewProviderHole: # : PyCXX: Error creating object of type N2Py7SeqBaseINS_6ObjectEEE from None if not hasattr(self, "Object"): return - - if self.Object != None: + + if self.Object is not None: return [self.Object.HoleGroove, # the groove feature self.Object.HoleGroove.Sketch.Support[0], # the groove sketchplane (datum plane) feature self.Object.HoleGroove.Sketch.Support[0].References[0][0]] # the sketchplane first reference (datum line) @@ -63,9 +63,9 @@ class ViewProviderHole: ''' Print the name of the property that has changed ''' #FreeCAD.Console.PrintMessage("Change property: " + str(prop) + "\n") pass - + def setEdit(self,vp,mode): - panel = TaskHole(self.Object) + panel = TaskHole(self.Object) FreeCADGui.Control.showDialog(panel) if not panel.setupUi(): diff --git a/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp b/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp index 8c0546aed9..97257d74e8 100644 --- a/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp +++ b/src/Mod/PartDesign/Gui/AppPartDesignGui.cpp @@ -32,35 +32,35 @@ #include #include "Workbench.h" -#include "ViewProviderPocket.h" -#include "ViewProviderHole.h" +#include "ViewProviderBase.h" #include "ViewProviderBody.h" -#include "ViewProviderSketchBased.h" -#include "ViewProviderPad.h" +#include "ViewProviderBoolean.h" #include "ViewProviderChamfer.h" -#include "ViewProviderFillet.h" -#include "ViewProviderDraft.h" -#include "ViewProviderDressUp.h" -#include "ViewProviderRevolution.h" -#include "ViewProviderGroove.h" -#include "ViewProviderMirrored.h" -#include "ViewProviderLinearPattern.h" -#include "ViewProviderPolarPattern.h" -#include "ViewProviderScaled.h" -#include "ViewProviderMultiTransform.h" -#include "ViewProviderTransformed.h" -#include "ViewProviderDatumPoint.h" +#include "ViewProviderDatumCS.h" #include "ViewProviderDatumLine.h" #include "ViewProviderDatumPlane.h" -#include "ViewProviderBoolean.h" -#include "ViewProviderPrimitive.h" -#include "ViewProviderDatumCS.h" -#include "ViewProviderThickness.h" -#include "ViewProviderPipe.h" -#include "ViewProviderLoft.h" +#include "ViewProviderDatumPoint.h" +#include "ViewProviderDraft.h" +#include "ViewProviderDressUp.h" +#include "ViewProviderFillet.h" +#include "ViewProviderGroove.h" #include "ViewProviderHelix.h" +#include "ViewProviderHole.h" +#include "ViewProviderLinearPattern.h" +#include "ViewProviderLoft.h" +#include "ViewProviderMirrored.h" +#include "ViewProviderMultiTransform.h" +#include "ViewProviderPad.h" +#include "ViewProviderPipe.h" +#include "ViewProviderPocket.h" +#include "ViewProviderPolarPattern.h" +#include "ViewProviderPrimitive.h" +#include "ViewProviderRevolution.h" +#include "ViewProviderScaled.h" #include "ViewProviderShapeBinder.h" -#include "ViewProviderBase.h" +#include "ViewProviderSketchBased.h" +#include "ViewProviderThickness.h" +#include "ViewProviderTransformed.h" // use a different name to CreateCommand() @@ -84,7 +84,7 @@ public: initialize("This module is the PartDesignGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/PartDesign/Gui/CMakeLists.txt b/src/Mod/PartDesign/Gui/CMakeLists.txt index e7f9d5bf43..2ef6ad7882 100644 --- a/src/Mod/PartDesign/Gui/CMakeLists.txt +++ b/src/Mod/PartDesign/Gui/CMakeLists.txt @@ -13,6 +13,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/PartDesign/Gui/Command.cpp b/src/Mod/PartDesign/Gui/Command.cpp index 8bf0b727c3..b3fcda7f22 100644 --- a/src/Mod/PartDesign/Gui/Command.cpp +++ b/src/Mod/PartDesign/Gui/Command.cpp @@ -172,7 +172,7 @@ void CmdPartDesignPlane::activated(int iMsg) UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Plane"),"DatumPlane"); } -bool CmdPartDesignPlane::isActive(void) +bool CmdPartDesignPlane::isActive() { if (getActiveGuiDocument()) return true; @@ -200,7 +200,7 @@ void CmdPartDesignLine::activated(int iMsg) UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Line"),"DatumLine"); } -bool CmdPartDesignLine::isActive(void) +bool CmdPartDesignLine::isActive() { if (getActiveGuiDocument()) return true; @@ -228,7 +228,7 @@ void CmdPartDesignPoint::activated(int iMsg) UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::Point"),"DatumPoint"); } -bool CmdPartDesignPoint::isActive(void) +bool CmdPartDesignPoint::isActive() { if (getActiveGuiDocument()) return true; @@ -256,7 +256,7 @@ void CmdPartDesignCS::activated(int iMsg) UnifiedDatumCommand(*this, Base::Type::fromName("PartDesign::CoordinateSystem"),"Local_CS"); } -bool CmdPartDesignCS::isActive(void) +bool CmdPartDesignCS::isActive() { if (getActiveGuiDocument()) return true; @@ -299,7 +299,7 @@ void CmdPartDesignShapeBinder::activated(int iMsg) PartDesignGui::setEdit(support.getValue()); } else { PartDesign::Body *pcActiveBody = PartDesignGui::getBody(/*messageIfNot = */true); - if (pcActiveBody == nullptr) + if (!pcActiveBody) return; std::string FeatName = getUniqueObjectName("ShapeBinder",pcActiveBody); @@ -325,7 +325,7 @@ void CmdPartDesignShapeBinder::activated(int iMsg) // TODO do a proper error processing (2015-09-11, Fat-Zer) } -bool CmdPartDesignShapeBinder::isActive(void) +bool CmdPartDesignShapeBinder::isActive() { return hasActiveDocument (); } @@ -410,7 +410,7 @@ void CmdPartDesignSubShapeBinder::activated(int iMsg) } } -bool CmdPartDesignSubShapeBinder::isActive(void) { +bool CmdPartDesignSubShapeBinder::isActive() { return hasActiveDocument(); } @@ -466,7 +466,7 @@ void CmdPartDesignClone::activated(int iMsg) } } -bool CmdPartDesignClone::isActive(void) +bool CmdPartDesignClone::isActive() { return getSelection().countObjectsOfType(Part::Feature::getClassTypeId()) == 1; } @@ -830,7 +830,7 @@ void CmdPartDesignNewSketch::activated(int iMsg) } } -bool CmdPartDesignNewSketch::isActive(void) +bool CmdPartDesignNewSketch::isActive() { if (getActiveGuiDocument()) return true; @@ -939,7 +939,7 @@ unsigned validateSketches(std::vector& sketches, else ++o; } - if (inList.size() > 0) { + if (!inList.empty()) { status.push_back(PartDesignGui::TaskFeaturePick::isUsed); continue; } @@ -1320,7 +1320,7 @@ void CmdPartDesignPad::activated(int iMsg) prepareProfileBased(this, "Pad", 10.0); } -bool CmdPartDesignPad::isActive(void) +bool CmdPartDesignPad::isActive() { return hasActiveDocument(); } @@ -1352,7 +1352,7 @@ void CmdPartDesignPocket::activated(int iMsg) prepareProfileBased(this, "Pocket", 5.0); } -bool CmdPartDesignPocket::isActive(void) +bool CmdPartDesignPocket::isActive() { return hasActiveDocument(); } @@ -1399,7 +1399,7 @@ void CmdPartDesignHole::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "Hole", worker); } -bool CmdPartDesignHole::isActive(void) +bool CmdPartDesignHole::isActive() { return hasActiveDocument(); } @@ -1458,7 +1458,7 @@ void CmdPartDesignRevolution::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "Revolution", worker); } -bool CmdPartDesignRevolution::isActive(void) +bool CmdPartDesignRevolution::isActive() { return hasActiveDocument(); } @@ -1525,7 +1525,7 @@ void CmdPartDesignGroove::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "Groove", worker); } -bool CmdPartDesignGroove::isActive(void) +bool CmdPartDesignGroove::isActive() { return hasActiveDocument(); } @@ -1575,7 +1575,7 @@ void CmdPartDesignAdditivePipe::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "AdditivePipe", worker); } -bool CmdPartDesignAdditivePipe::isActive(void) +bool CmdPartDesignAdditivePipe::isActive() { return hasActiveDocument(); } @@ -1626,7 +1626,7 @@ void CmdPartDesignSubtractivePipe::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "SubtractivePipe", worker); } -bool CmdPartDesignSubtractivePipe::isActive(void) +bool CmdPartDesignSubtractivePipe::isActive() { return hasActiveDocument(); } @@ -1677,7 +1677,7 @@ void CmdPartDesignAdditiveLoft::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "AdditiveLoft", worker); } -bool CmdPartDesignAdditiveLoft::isActive(void) +bool CmdPartDesignAdditiveLoft::isActive() { return hasActiveDocument(); } @@ -1728,7 +1728,7 @@ void CmdPartDesignSubtractiveLoft::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "SubtractiveLoft", worker); } -bool CmdPartDesignSubtractiveLoft::isActive(void) +bool CmdPartDesignSubtractiveLoft::isActive() { return hasActiveDocument(); } @@ -1804,7 +1804,7 @@ void CmdPartDesignAdditiveHelix::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "AdditiveHelix", worker); } -bool CmdPartDesignAdditiveHelix::isActive(void) +bool CmdPartDesignAdditiveHelix::isActive() { return hasActiveDocument(); } @@ -1862,7 +1862,7 @@ void CmdPartDesignSubtractiveHelix::activated(int iMsg) prepareProfileBased(pcActiveBody, this, "SubtractiveHelix", worker); } -bool CmdPartDesignSubtractiveHelix::isActive(void) +bool CmdPartDesignSubtractiveHelix::isActive() { return hasActiveDocument(); } @@ -1886,7 +1886,7 @@ bool dressupGetSelected(Gui::Command* cmd, const std::string& which, std::vector selection = cmd->getSelection().getSelectionEx(); - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select an edge, face, or body.")); return false; @@ -1924,7 +1924,7 @@ bool dressupGetSelected(Gui::Command* cmd, const std::string& which, // if 1 Part::Feature object selected, but no subobjects, select all edges for the user // but only for fillet and chamfer (not for draft or thickness) - if (selection[0].getSubNames().size() == 0 && (which.compare("Fillet") == 0 || which.compare("Chamfer") == 0)){ + if (selection[0].getSubNames().empty() && (which.compare("Fillet") == 0 || which.compare("Chamfer") == 0)){ useAllEdges = true; std::string edgeTypeName = Part::TopoShape::shapeName(TopAbs_EDGE); //"Edge" int count = TopShape.countSubElements(edgeTypeName.c_str()); @@ -1946,7 +1946,7 @@ bool dressupGetSelected(Gui::Command* cmd, const std::string& which, void finishDressupFeature(const Gui::Command* cmd, const std::string& which, Part::Feature *base, const std::vector & SubNames, const bool useAllEdges) { - if (SubNames.size() == 0) { + if (SubNames.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QString::fromStdString(which) + QObject::tr(" not possible on selected faces/edges.")); return; @@ -2021,7 +2021,7 @@ void CmdPartDesignFillet::activated(int iMsg) makeChamferOrFillet(this, "Fillet"); } -bool CmdPartDesignFillet::isActive(void) +bool CmdPartDesignFillet::isActive() { return hasActiveDocument(); } @@ -2050,7 +2050,7 @@ void CmdPartDesignChamfer::activated(int iMsg) doCommand(Gui,"Gui.Selection.clearSelection()"); } -bool CmdPartDesignChamfer::isActive(void) +bool CmdPartDesignChamfer::isActive() { return hasActiveDocument(); } @@ -2107,7 +2107,7 @@ void CmdPartDesignDraft::activated(int iMsg) finishDressupFeature (this, "Draft", base, SubNames, useAllEdges); } -bool CmdPartDesignDraft::isActive(void) +bool CmdPartDesignDraft::isActive() { return hasActiveDocument(); } @@ -2157,7 +2157,7 @@ void CmdPartDesignThickness::activated(int iMsg) finishDressupFeature (this, "Thickness", base, SubNames, useAllEdges); } -bool CmdPartDesignThickness::isActive(void) +bool CmdPartDesignThickness::isActive() { return hasActiveDocument(); } @@ -2210,7 +2210,7 @@ void prepareTransformed(PartDesign::Body *pcActiveBody, Gui::Command* cmd, const // First check selections std::vector features = cmd->getSelection().getObjectsOfType(PartDesign::Feature::getClassTypeId()); // Next create a list of all eligible objects - if (features.size() == 0) { + if (features.empty()) { features = cmd->getDocument()->getObjectsOfType(PartDesign::Feature::getClassTypeId()); // If there is more than one selected or eligible object, show dialog and let user pick one if (features.size() > 1) { @@ -2319,7 +2319,7 @@ void CmdPartDesignMirrored::activated(int iMsg) prepareTransformed(pcActiveBody, this, "Mirrored", worker); } -bool CmdPartDesignMirrored::isActive(void) +bool CmdPartDesignMirrored::isActive() { return hasActiveDocument(); } @@ -2383,7 +2383,7 @@ void CmdPartDesignLinearPattern::activated(int iMsg) prepareTransformed(pcActiveBody, this, "LinearPattern", worker); } -bool CmdPartDesignLinearPattern::isActive(void) +bool CmdPartDesignLinearPattern::isActive() { return hasActiveDocument(); } @@ -2448,7 +2448,7 @@ void CmdPartDesignPolarPattern::activated(int iMsg) prepareTransformed(pcActiveBody, this, "PolarPattern", worker); } -bool CmdPartDesignPolarPattern::isActive(void) +bool CmdPartDesignPolarPattern::isActive() { return hasActiveDocument(); } @@ -2497,7 +2497,7 @@ void CmdPartDesignScaled::activated(int iMsg) prepareTransformed(pcActiveBody, this, "Scaled", worker); } -bool CmdPartDesignScaled::isActive(void) +bool CmdPartDesignScaled::isActive() { return hasActiveDocument(); } @@ -2558,7 +2558,7 @@ void CmdPartDesignMultiTransform::activated(int iMsg) prevFeature = pcActiveBody->getPrevSolidFeature(trFeat); } Gui::Selection().clearSelection(); - if (prevFeature != nullptr) + if (prevFeature) Gui::Selection().addSelection(prevFeature->getDocument()->getName(), prevFeature->getNameInDocument()); openCommand(QT_TRANSLATE_NOOP("Command", "Convert to MultiTransform feature")); @@ -2608,7 +2608,7 @@ void CmdPartDesignMultiTransform::activated(int iMsg) // Make sure the user isn't presented with an empty screen because no transformations are defined yet... App::DocumentObject* prevSolid = pcActiveBody->Tip.getValue(); - if (prevSolid != nullptr) { + if (prevSolid) { Part::Feature* feat = static_cast(prevSolid); FCMD_OBJ_CMD(Feat,"Shape = "<commandManager(); diff --git a/src/Mod/PartDesign/Gui/CommandBody.cpp b/src/Mod/PartDesign/Gui/CommandBody.cpp index 4a24405f56..f41814444c 100644 --- a/src/Mod/PartDesign/Gui/CommandBody.cpp +++ b/src/Mod/PartDesign/Gui/CommandBody.cpp @@ -128,7 +128,7 @@ void CmdPartDesignBody::activated(int iMsg) } else { partOfBaseFeature = App::Part::getPartOfObject(baseFeature); - if (partOfBaseFeature != nullptr && partOfBaseFeature != actPart){ + if (partOfBaseFeature && partOfBaseFeature != actPart){ //prevent cross-part mess QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Bad base feature"), QObject::tr("Base feature (%1) belongs to other part.") @@ -290,7 +290,7 @@ void CmdPartDesignBody::activated(int iMsg) updateActive(); } -bool CmdPartDesignBody::isActive(void) +bool CmdPartDesignBody::isActive() { return hasActiveDocument() && !PartDesignGui::isLegacyWorkflow ( getDocument () ); } @@ -506,7 +506,7 @@ void CmdPartDesignMigrate::activated(int iMsg) updateActive(); } -bool CmdPartDesignMigrate::isActive(void) +bool CmdPartDesignMigrate::isActive() { return hasActiveDocument(); } @@ -584,7 +584,7 @@ void CmdPartDesignMoveTip::activated(int iMsg) updateActive(); } -bool CmdPartDesignMoveTip::isActive(void) +bool CmdPartDesignMoveTip::isActive() { return hasActiveDocument(); } @@ -640,7 +640,7 @@ void CmdPartDesignDuplicateSelection::activated(int iMsg) updateActive(); } -bool CmdPartDesignDuplicateSelection::isActive(void) +bool CmdPartDesignDuplicateSelection::isActive() { return hasActiveDocument(); } @@ -811,7 +811,7 @@ void CmdPartDesignMoveFeature::activated(int iMsg) updateActive(); } -bool CmdPartDesignMoveFeature::isActive(void) +bool CmdPartDesignMoveFeature::isActive() { return hasActiveDocument () && !PartDesignGui::isLegacyWorkflow ( getDocument () ); } @@ -963,7 +963,7 @@ void CmdPartDesignMoveFeatureInTree::activated(int iMsg) updateActive(); } -bool CmdPartDesignMoveFeatureInTree::isActive(void) +bool CmdPartDesignMoveFeatureInTree::isActive() { return hasActiveDocument () && !PartDesignGui::isLegacyWorkflow ( getDocument () ); } @@ -973,7 +973,7 @@ bool CmdPartDesignMoveFeatureInTree::isActive(void) // Initialization //=========================================================================== -void CreatePartDesignBodyCommands(void) +void CreatePartDesignBodyCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/PartDesign/Gui/DlgActiveBody.h b/src/Mod/PartDesign/Gui/DlgActiveBody.h index d0ccf61139..111aa29c3e 100644 --- a/src/Mod/PartDesign/Gui/DlgActiveBody.h +++ b/src/Mod/PartDesign/Gui/DlgActiveBody.h @@ -46,7 +46,7 @@ class PartDesignGuiExport DlgActiveBody : public QDialog public: DlgActiveBody(QWidget* parent, App::Document*& doc, const QString& infoText=QString()); - ~DlgActiveBody(); + ~DlgActiveBody() override; void accept() override; PartDesign::Body* getActiveBody() const { return activeBody; } diff --git a/src/Mod/PartDesign/Gui/ReferenceSelection.cpp b/src/Mod/PartDesign/Gui/ReferenceSelection.cpp index 0d9672d7a8..4dbdc84d03 100644 --- a/src/Mod/PartDesign/Gui/ReferenceSelection.cpp +++ b/src/Mod/PartDesign/Gui/ReferenceSelection.cpp @@ -340,12 +340,12 @@ bool getReferencedSelection(const App::DocumentObject* thisObj, const Gui::Selec QString getRefStr(const App::DocumentObject* obj, const std::vector& sub) { - if (obj == nullptr) + if (!obj) return QString::fromLatin1(""); if (PartDesign::Feature::isDatum(obj)) return QString::fromLatin1(obj->getNameInDocument()); - else if (sub.size()>0) + else if (!sub.empty()) return QString::fromLatin1(obj->getNameInDocument()) + QString::fromLatin1(":") + QString::fromLatin1(sub.front().c_str()); else @@ -354,7 +354,7 @@ QString getRefStr(const App::DocumentObject* obj, const std::vector std::string buildLinkSubPythonStr(const App::DocumentObject* obj, const std::vector& subs) { - if ( obj == nullptr) + if (!obj) return "None"; std::string result("["); @@ -369,7 +369,7 @@ std::string buildLinkSubPythonStr(const App::DocumentObject* obj, const std::vec std::string buildLinkSingleSubPythonStr(const App::DocumentObject* obj, const std::vector& subs) { - if (obj == nullptr) + if (!obj) return "None"; if (PartDesign::Feature::isDatum(obj)) diff --git a/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp b/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp index 2259c1577a..3d2dbc050c 100644 --- a/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskBooleanParameters.cpp @@ -107,13 +107,13 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) if (body.empty()) return; App::DocumentObject* pcBody = pcBoolean->getDocument()->getObject(body.c_str()); - if (pcBody == nullptr) + if (!pcBody) return; // if the selected object is not a body then get the body it is part of if (!pcBody->getTypeId().isDerivedFrom(PartDesign::Body::getClassTypeId())) { pcBody = PartDesign::Body::findBodyOf(pcBody); - if (pcBody == nullptr) + if (!pcBody) return; body = pcBody->getNameInDocument(); } @@ -139,18 +139,18 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) // Hide base body and added body Gui::ViewProviderDocumentObject* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue())); - if (vp != nullptr) + if (vp) vp->hide(); vp = dynamic_cast( Gui::Application::Instance->getViewProvider(bodies.front())); - if (vp != nullptr) + if (vp) vp->hide(); BooleanView->show(); } else { // Hide newly added body Gui::ViewProviderDocumentObject* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(bodies.back())); - if (vp != nullptr) + if (vp) vp->hide(); } } @@ -179,12 +179,12 @@ void TaskBooleanParameters::onSelectionChanged(const Gui::SelectionChanges& msg) // Make bodies visible again Gui::ViewProviderDocumentObject* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(pcBody)); - if (vp != nullptr) + if (vp) vp->show(); - if (bodies.size() == 0) { + if (bodies.empty()) { Gui::ViewProviderDocumentObject* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue())); - if (vp != nullptr) + if (vp) vp->show(); BooleanView->hide(); } @@ -212,7 +212,7 @@ void TaskBooleanParameters::onButtonBodyRemove(bool checked) { if (checked) { Gui::Document* doc = Gui::Application::Instance->activeDocument(); - if (doc != nullptr) + if (doc) BooleanView->show(); selectionMode = bodyRemove; Gui::Selection().clearSelection(); @@ -273,12 +273,12 @@ void TaskBooleanParameters::onBodyDeleted(void) // Make bodies visible again Gui::ViewProviderDocumentObject* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(body)); - if (vp != nullptr) + if (vp) vp->show(); if (bodies.empty()) { Gui::ViewProviderDocumentObject* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(pcBoolean->BaseFeature.getValue())); - if (vp != nullptr) + if (vp) vp->show(); BooleanView->hide(); } @@ -303,7 +303,7 @@ void TaskBooleanParameters::exitSelectionMode() { selectionMode = none; Gui::Document* doc = Gui::Application::Instance->activeDocument(); - if (doc != nullptr) + if (doc) doc->setShow(BooleanView->getObject()->getNameInDocument()); } @@ -378,8 +378,8 @@ bool TaskDlgBooleanParameters::reject() // Show the bodies again PartDesign::Boolean* obj = static_cast(BooleanView->getObject()); Gui::Document* doc = Gui::Application::Instance->activeDocument(); - if (doc != nullptr) { - if (obj->BaseFeature.getValue() != nullptr) { + if (doc) { + if (obj->BaseFeature.getValue()) { doc->setShow(obj->BaseFeature.getValue()->getNameInDocument()); std::vector bodies = obj->Group.getValues(); for (std::vector::const_iterator b = bodies.begin(); b != bodies.end(); b++) diff --git a/src/Mod/PartDesign/Gui/TaskBooleanParameters.h b/src/Mod/PartDesign/Gui/TaskBooleanParameters.h index d9023eae9a..85d4b04378 100644 --- a/src/Mod/PartDesign/Gui/TaskBooleanParameters.h +++ b/src/Mod/PartDesign/Gui/TaskBooleanParameters.h @@ -48,24 +48,24 @@ class TaskBooleanParameters : public Gui::TaskView::TaskBox, public Gui::Selecti Q_OBJECT public: - TaskBooleanParameters(ViewProviderBoolean *BooleanView, QWidget *parent=nullptr); - ~TaskBooleanParameters(); + explicit TaskBooleanParameters(ViewProviderBoolean *BooleanView, QWidget *parent=nullptr); + ~TaskBooleanParameters() override; - const std::vector getBodies(void) const; - int getType(void) const; + const std::vector getBodies() const; + int getType() const; private Q_SLOTS: void onButtonBodyAdd(const bool checked); void onButtonBodyRemove(const bool checked); - void onBodyDeleted(void); + void onBodyDeleted(); void onTypeChanged(int index); protected: void exitSelectionMode(); protected: - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: QWidget* proxy; @@ -83,8 +83,8 @@ class TaskDlgBooleanParameters : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgBooleanParameters(ViewProviderBoolean *BooleanView); - ~TaskDlgBooleanParameters(); + explicit TaskDlgBooleanParameters(ViewProviderBoolean *BooleanView); + ~TaskDlgBooleanParameters() override; ViewProviderBoolean* getBooleanView() const { return BooleanView; } @@ -92,19 +92,19 @@ public: public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return false; } /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } protected: diff --git a/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp b/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp index c6b683f6e1..ad09973d74 100644 --- a/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskChamferParameters.cpp @@ -208,7 +208,7 @@ void TaskChamferParameters::clearButtons(const selectionModes notThis) DressUpView->highlightReferences(false); } -void TaskChamferParameters::onRefDeleted(void) +void TaskChamferParameters::onRefDeleted() { // assure we we are not in selection mode exitSelectionMode(); @@ -260,7 +260,7 @@ void TaskChamferParameters::onRefDeleted(void) } } -void TaskChamferParameters::onAddAllEdges(void) +void TaskChamferParameters::onAddAllEdges() { TaskDressUpParameters::addAllEdges(ui->listWidgetReferences); ui->buttonRefRemove->setEnabled(true); @@ -317,27 +317,27 @@ void TaskChamferParameters::onFlipDirection(bool flip) hideOnError(); } -int TaskChamferParameters::getType(void) const +int TaskChamferParameters::getType() const { return ui->chamferType->currentIndex(); } -double TaskChamferParameters::getSize(void) const +double TaskChamferParameters::getSize() const { return ui->chamferSize->value().getValue(); } -double TaskChamferParameters::getSize2(void) const +double TaskChamferParameters::getSize2() const { return ui->chamferSize2->value().getValue(); } -double TaskChamferParameters::getAngle(void) const +double TaskChamferParameters::getAngle() const { return ui->chamferAngle->value().getValue(); } -bool TaskChamferParameters::getFlipDirection(void) const +bool TaskChamferParameters::getFlipDirection() const { return ui->flipDirection->isChecked(); } diff --git a/src/Mod/PartDesign/Gui/TaskChamferParameters.h b/src/Mod/PartDesign/Gui/TaskChamferParameters.h index d767c29291..442401da80 100644 --- a/src/Mod/PartDesign/Gui/TaskChamferParameters.h +++ b/src/Mod/PartDesign/Gui/TaskChamferParameters.h @@ -39,10 +39,10 @@ class TaskChamferParameters : public TaskDressUpParameters Q_OBJECT public: - TaskChamferParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); - ~TaskChamferParameters(); + explicit TaskChamferParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + ~TaskChamferParameters() override; - virtual void apply(); + void apply() override; private Q_SLOTS: void onTypeChanged(int); @@ -50,15 +50,15 @@ private Q_SLOTS: void onSize2Changed(double); void onAngleChanged(double); void onFlipDirection(bool); - void onRefDeleted(void); + void onRefDeleted(void) override; void onAddAllEdges(void); void onCheckBoxUseAllEdgesToggled(bool checked); protected: - virtual void clearButtons(const selectionModes notThis); - bool event(QEvent *e); - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void clearButtons(const selectionModes notThis) override; + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; int getType(void) const; double getSize(void) const; @@ -78,12 +78,12 @@ class TaskDlgChamferParameters : public TaskDlgDressUpParameters Q_OBJECT public: - TaskDlgChamferParameters(ViewProviderChamfer *DressUpView); - ~TaskDlgChamferParameters(); + explicit TaskDlgChamferParameters(ViewProviderChamfer *DressUpView); + ~TaskDlgChamferParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp b/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp index 0b3eaf284c..3060a2d44e 100644 --- a/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDatumParameters.cpp @@ -144,7 +144,7 @@ bool TaskDlgDatumParameters::accept() { if (copy) { copyObjects.push_back(copy); copies.push_back(copyObjects.back()); - copySubValues.push_back(std::string()); + copySubValues.emplace_back(); } } else { diff --git a/src/Mod/PartDesign/Gui/TaskDatumParameters.h b/src/Mod/PartDesign/Gui/TaskDatumParameters.h index 8c4ed9ff19..ed25ca1fe7 100644 --- a/src/Mod/PartDesign/Gui/TaskDatumParameters.h +++ b/src/Mod/PartDesign/Gui/TaskDatumParameters.h @@ -50,8 +50,8 @@ class TaskDatumParameters : public PartGui::TaskAttacher Q_OBJECT public: - TaskDatumParameters(ViewProviderDatum *DatumView,QWidget *parent = nullptr); - ~TaskDatumParameters(); + explicit TaskDatumParameters(ViewProviderDatum *DatumView,QWidget *parent = nullptr); + ~TaskDatumParameters() override; }; /// simulation dialog for the TaskView @@ -60,11 +60,11 @@ class TaskDlgDatumParameters : public PartGui::TaskDlgAttacher Q_OBJECT public: - TaskDlgDatumParameters(ViewProviderDatum *DatumView); - ~TaskDlgDatumParameters(); + explicit TaskDlgDatumParameters(ViewProviderDatum *DatumView); + ~TaskDlgDatumParameters() override; - virtual bool accept(); - virtual bool reject(); + bool accept() override; + bool reject() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskDraftParameters.h b/src/Mod/PartDesign/Gui/TaskDraftParameters.h index 6aa4ed66f0..b2024e9376 100644 --- a/src/Mod/PartDesign/Gui/TaskDraftParameters.h +++ b/src/Mod/PartDesign/Gui/TaskDraftParameters.h @@ -37,12 +37,12 @@ class TaskDraftParameters : public TaskDressUpParameters Q_OBJECT public: - TaskDraftParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); - ~TaskDraftParameters(); + explicit TaskDraftParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + ~TaskDraftParameters() override; - double getAngle(void) const; - bool getReversed(void) const; - const std::vector getFaces(void) const; + double getAngle() const; + bool getReversed() const; + const std::vector getFaces() const; void getPlane(App::DocumentObject*& obj, std::vector& sub) const; void getLine(App::DocumentObject*& obj, std::vector& sub) const; @@ -51,13 +51,13 @@ private Q_SLOTS: void onReversedChanged(bool reversed); void onButtonPlane(const bool checked); void onButtonLine(const bool checked); - void onRefDeleted(void); + void onRefDeleted() override; protected: - virtual void clearButtons(const selectionModes notThis); - bool event(QEvent *e); - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void clearButtons(const selectionModes notThis) override; + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: std::unique_ptr ui; @@ -69,12 +69,12 @@ class TaskDlgDraftParameters : public TaskDlgDressUpParameters Q_OBJECT public: - TaskDlgDraftParameters(ViewProviderDraft *DraftView); - ~TaskDlgDraftParameters(); + explicit TaskDlgDraftParameters(ViewProviderDraft *DraftView); + ~TaskDlgDraftParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp b/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp index 1e934532be..f3fc3c478b 100644 --- a/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskDressUpParameters.cpp @@ -258,7 +258,7 @@ void TaskDressUpParameters::setSelection(QListWidgetItem* current) { DressUpView->highlightReferences(true); // clear existing selection because only the current item is highlighted, not all selected ones to keep the overview Gui::Selection().clearSelection(); - // highligh the selected item + // highlight the selected item Gui::Selection().addSelection(docName.c_str(), objName.c_str(), subName.c_str(), 0, 0, 0); } } @@ -351,7 +351,7 @@ void TaskDressUpParameters::removeItemFromListWidget(QListWidget* widget, const { QList items = widget->findItems(QString::fromLatin1(itemstr), Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator i = items.begin(); i != items.end(); i++) { + for (QList::const_iterator i = items.cbegin(); i != items.cend(); i++) { QListWidgetItem* it = widget->takeItem(widget->row(*i)); delete it; } diff --git a/src/Mod/PartDesign/Gui/TaskDressUpParameters.h b/src/Mod/PartDesign/Gui/TaskDressUpParameters.h index 6686b9ede5..f3a011cc73 100644 --- a/src/Mod/PartDesign/Gui/TaskDressUpParameters.h +++ b/src/Mod/PartDesign/Gui/TaskDressUpParameters.h @@ -46,7 +46,7 @@ class TaskDressUpParameters : public Gui::TaskView::TaskBox, public Gui::Selecti public: TaskDressUpParameters(ViewProviderDressUp *DressUpView, bool selectEdges, bool selectFaces, QWidget* parent = nullptr); - virtual ~TaskDressUpParameters(); + ~TaskDressUpParameters() override; const std::vector getReferences(void) const; Part::Feature *getBase(void) const; @@ -105,16 +105,16 @@ class TaskDlgDressUpParameters : public TaskDlgFeatureParameters Q_OBJECT public: - TaskDlgDressUpParameters(ViewProviderDressUp *DressUpView); - virtual ~TaskDlgDressUpParameters(); + explicit TaskDlgDressUpParameters(ViewProviderDressUp *DressUpView); + ~TaskDlgDressUpParameters() override; ViewProviderDressUp* getDressUpView() const { return static_cast(vp); } public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); - virtual bool reject(); + bool accept() override; + bool reject() override; protected: TaskDressUpParameters *parameter; diff --git a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp index 035d3f65d6..7880c04668 100644 --- a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.cpp @@ -50,7 +50,7 @@ TaskExtrudeParameters::TaskExtrudeParameters(ViewProviderSketchBased *SketchBase // we need a separate container widget to add all controls to proxy = new QWidget(this); ui->setupUi(proxy); - ui->lineFaceName->setPlaceholderText(tr("No face selected")); + handleLineFaceNameNo(); Gui::ButtonGroup* group = new Gui::ButtonGroup(this); group->addButton(ui->checkBoxMidplane); @@ -152,9 +152,9 @@ void TaskExtrudeParameters::setupDialog() } else if (obj && faceId >= 0) { ui->lineFaceName->setText(QString::fromLatin1("%1:%2%3") - .arg(QString::fromUtf8(obj->Label.getValue())) - .arg(tr("Face")) - .arg(faceId)); + .arg(QString::fromUtf8(obj->Label.getValue()), + tr("Face"), + QString::number(faceId))); ui->lineFaceName->setProperty("FeatureName", QByteArray(obj->getNameInDocument())); } else { @@ -220,7 +220,7 @@ void TaskExtrudeParameters::connectSlots() this, &TaskExtrudeParameters::onReversedChanged); connect(ui->changeMode, qOverload(&QComboBox::currentIndexChanged), this, &TaskExtrudeParameters::onModeChanged); - connect(ui->buttonFace, &QPushButton::clicked, + connect(ui->buttonFace, &QPushButton::toggled, this, &TaskExtrudeParameters::onButtonFace); connect(ui->lineFaceName, &QLineEdit::textEdited, this, &TaskExtrudeParameters::onFaceName); @@ -255,7 +255,7 @@ void TaskExtrudeParameters::onSelectionChanged(const Gui::SelectionChanges& msg) ui->lineFaceName->setProperty("FeatureName", QByteArray(msg.pObjectName)); ui->lineFaceName->setProperty("FaceName", QByteArray(msg.pSubName)); // Turn off reference selection mode - onButtonFace(false); + ui->buttonFace->setChecked(false); } else { clearFaceName(); @@ -468,7 +468,7 @@ void TaskExtrudeParameters::setCheckboxes(Modes mode, Type type) QMetaObject::invokeMethod(ui->lineFaceName, "setFocus", Qt::QueuedConnection); // Go into reference selection mode if no face has been selected yet if (ui->lineFaceName->property("FeatureName").isNull()) - onButtonFace(true); + ui->buttonFace->setChecked(true); } else if (mode == Modes::TwoDimensions) { isLengthEditVisible = true; @@ -507,7 +507,7 @@ void TaskExtrudeParameters::setCheckboxes(Modes mode, Type type) ui->buttonFace->setEnabled(isFaceEditEnabled); ui->lineFaceName->setEnabled(isFaceEditEnabled); if (!isFaceEditEnabled) { - onButtonFace(false); + ui->buttonFace->setChecked(false); } } @@ -681,16 +681,18 @@ void TaskExtrudeParameters::getReferenceAxis(App::DocumentObject*& obj, std::vec } } -void TaskExtrudeParameters::onButtonFace(const bool pressed) +void TaskExtrudeParameters::onButtonFace(const bool checked) { + if (!checked) + handleLineFaceNameNo(); + else + handleLineFaceNameClick(); // sets placeholder text + // to distinguish that this is the direction selection selectionFace = true; // only faces are allowed - TaskSketchBasedParameters::onSelectReference(pressed ? AllowSelection::FACE : AllowSelection::NONE); - - // Update button if onButtonFace() is called explicitly - ui->buttonFace->setChecked(pressed); + TaskSketchBasedParameters::onSelectReference(checked ? AllowSelection::FACE : AllowSelection::NONE); } void TaskExtrudeParameters::onFaceName(const QString& text) @@ -720,7 +722,7 @@ void TaskExtrudeParameters::onFaceName(const QString& text) void TaskExtrudeParameters::translateFaceName() { - ui->lineFaceName->setPlaceholderText(tr("No face selected")); + handleLineFaceNameNo(); QVariant featureName = ui->lineFaceName->property("FeatureName"); if (featureName.isValid()) { QStringList parts = ui->lineFaceName->text().split(QChar::fromLatin1(':')); @@ -733,9 +735,9 @@ void TaskExtrudeParameters::translateFaceName() if (ok) { ui->lineFaceName->setText(QString::fromLatin1("%1:%2%3") - .arg(parts[0]) - .arg(tr("Face")) - .arg(faceId)); + .arg(parts[0], + tr("Face"), + QString(faceId))); } else { ui->lineFaceName->setText(parts[0]); @@ -743,22 +745,22 @@ void TaskExtrudeParameters::translateFaceName() } } -double TaskExtrudeParameters::getOffset(void) const +double TaskExtrudeParameters::getOffset() const { return ui->offsetEdit->value().getValue(); } -bool TaskExtrudeParameters::getAlongSketchNormal(void) const +bool TaskExtrudeParameters::getAlongSketchNormal() const { return ui->checkBoxAlongDirection->isChecked(); } -bool TaskExtrudeParameters::getCustom(void) const +bool TaskExtrudeParameters::getCustom() const { return (ui->directionCB->currentIndex() == DirectionModes::Custom); } -std::string TaskExtrudeParameters::getReferenceAxis(void) const +std::string TaskExtrudeParameters::getReferenceAxis() const { std::vector sub; App::DocumentObject* obj; @@ -766,37 +768,37 @@ std::string TaskExtrudeParameters::getReferenceAxis(void) const return buildLinkSingleSubPythonStr(obj, sub); } -double TaskExtrudeParameters::getXDirection(void) const +double TaskExtrudeParameters::getXDirection() const { return ui->XDirectionEdit->value(); } -double TaskExtrudeParameters::getYDirection(void) const +double TaskExtrudeParameters::getYDirection() const { return ui->YDirectionEdit->value(); } -double TaskExtrudeParameters::getZDirection(void) const +double TaskExtrudeParameters::getZDirection() const { return ui->ZDirectionEdit->value(); } -bool TaskExtrudeParameters::getReversed(void) const +bool TaskExtrudeParameters::getReversed() const { return ui->checkBoxReversed->isChecked(); } -bool TaskExtrudeParameters::getMidplane(void) const +bool TaskExtrudeParameters::getMidplane() const { return ui->checkBoxMidplane->isChecked(); } -int TaskExtrudeParameters::getMode(void) const +int TaskExtrudeParameters::getMode() const { return ui->changeMode->currentIndex(); } -QString TaskExtrudeParameters::getFaceName(void) const +QString TaskExtrudeParameters::getFaceName() const { QVariant featureName = ui->lineFaceName->property("FeatureName"); if (featureName.isValid()) { @@ -845,7 +847,7 @@ void TaskExtrudeParameters::changeEvent(QEvent *e) } } -void TaskExtrudeParameters::saveHistory(void) +void TaskExtrudeParameters::saveHistory() { // save the user values to history ui->lengthEdit->pushToHistory(); @@ -890,4 +892,14 @@ void TaskExtrudeParameters::translateModeList(int) // implement in sub-class } +void TaskExtrudeParameters::handleLineFaceNameClick() +{ + ui->lineFaceName->setPlaceholderText(tr("Click on a face in the model")); +} + +void TaskExtrudeParameters::handleLineFaceNameNo() +{ + ui->lineFaceName->setPlaceholderText(tr("No face selected")); +} + #include "moc_TaskExtrudeParameters.cpp" diff --git a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h index d3ca39e3ef..80baa86212 100644 --- a/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h +++ b/src/Mod/PartDesign/Gui/TaskExtrudeParameters.h @@ -54,9 +54,9 @@ class TaskExtrudeParameters : public TaskSketchBasedParameters public: TaskExtrudeParameters(ViewProviderSketchBased *SketchBasedView, QWidget *parent, const std::string& pixmapname, const QString& parname); - ~TaskExtrudeParameters(); + ~TaskExtrudeParameters() override; - virtual void saveHistory() override; + void saveHistory() override; void fillDirectionCombo(); void addAxisToCombo(App::DocumentObject* linkObj, std::string linkSubname, QString itemText, @@ -90,7 +90,7 @@ protected Q_SLOTS: void onZDirectionEditChanged(double); void onMidplaneChanged(bool); void onReversedChanged(bool); - void onButtonFace(const bool pressed = true); + void onButtonFace(const bool checked = true); void onFaceName(const QString& text); virtual void onModeChanged(int); @@ -118,6 +118,8 @@ protected: virtual void updateUI(int index); void updateDirectionEdits(void); void setDirectionMode(int index); + void handleLineFaceNameClick(void); + void handleLineFaceNameNo(void); private: void tryRecomputeFeature(); diff --git a/src/Mod/PartDesign/Gui/TaskFeatureParameters.h b/src/Mod/PartDesign/Gui/TaskFeatureParameters.h index 144211c7ef..83345ac6e9 100644 --- a/src/Mod/PartDesign/Gui/TaskFeatureParameters.h +++ b/src/Mod/PartDesign/Gui/TaskFeatureParameters.h @@ -41,10 +41,10 @@ class TaskFeatureParameters : public Gui::TaskView::TaskBox, public: TaskFeatureParameters(PartDesignGui::ViewProvider* vp, QWidget *parent, const std::string& pixmapname, const QString& parname); - virtual ~TaskFeatureParameters() {} + ~TaskFeatureParameters() override {} /// save field history - virtual void saveHistory(void) {} + virtual void saveHistory() {} /// apply changes made in the parameters input to the model via commands virtual void apply() {} @@ -56,7 +56,7 @@ protected Q_SLOTS: private: /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; protected: PartDesignGui::ViewProvider *vp; @@ -70,14 +70,14 @@ class TaskDlgFeatureParameters : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgFeatureParameters(PartDesignGui::ViewProvider *vp); - virtual ~TaskDlgFeatureParameters(); + explicit TaskDlgFeatureParameters(PartDesignGui::ViewProvider *vp); + ~TaskDlgFeatureParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// Returns the view provider dialog is runed for PartDesignGui::ViewProvider *viewProvider() const { return vp; } diff --git a/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp b/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp index 35cbeda9f3..bb30b2973c 100644 --- a/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp +++ b/src/Mod/PartDesign/Gui/TaskFeaturePick.cpp @@ -112,8 +112,8 @@ TaskFeaturePick::TaskFeaturePick(std::vector& objects, for (; statusIt != status.end(); ++statusIt, ++objIt) { QListWidgetItem* item = new QListWidgetItem( QString::fromLatin1("%1 (%2)") - .arg(QString::fromUtf8((*objIt)->Label.getValue())) - .arg(getFeatureStatusString(*statusIt) + .arg(QString::fromUtf8((*objIt)->Label.getValue()), + getFeatureStatusString(*statusIt) ) ); item->setData(Qt::UserRole, QString::fromLatin1((*objIt)->getNameInDocument())); diff --git a/src/Mod/PartDesign/Gui/TaskFeaturePick.h b/src/Mod/PartDesign/Gui/TaskFeaturePick.h index afb24c0b55..4f3e991c22 100644 --- a/src/Mod/PartDesign/Gui/TaskFeaturePick.h +++ b/src/Mod/PartDesign/Gui/TaskFeaturePick.h @@ -61,7 +61,7 @@ public: bool singleFeatureSelect, QWidget *parent = nullptr); - ~TaskFeaturePick(); + ~TaskFeaturePick() override; std::vector getFeatures(); std::vector buildFeatures(); @@ -72,17 +72,17 @@ public: protected Q_SLOTS: void onUpdate(bool); - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void onItemSelectionChanged(); void onDoubleClick(QListWidgetItem *item); protected: /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; /** Notifies on undo */ - virtual void slotUndoDocument(const Gui::Document& Doc); + void slotUndoDocument(const Gui::Document& Doc) override; /** Notifies on document deletion */ - virtual void slotDeleteDocument(const Gui::Document& Doc); + void slotDeleteDocument(const Gui::Document& Doc) override; private: std::unique_ptr ui; @@ -111,25 +111,25 @@ public: std::function)> workfunc, bool singleFeatureSelect, std::function abortfunc = 0); - ~TaskDlgFeaturePick(); + ~TaskDlgFeaturePick() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument(void) const override { return false; } void showExternal(bool val); /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons(void) const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } diff --git a/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp b/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp index 5b79e664e2..2a75621bed 100644 --- a/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskFilletParameters.cpp @@ -162,7 +162,7 @@ void TaskFilletParameters::clearButtons(const selectionModes notThis) DressUpView->highlightReferences(false); } -void TaskFilletParameters::onRefDeleted(void) +void TaskFilletParameters::onRefDeleted() { // assure we we are not in selection mode exitSelectionMode(); @@ -214,7 +214,7 @@ void TaskFilletParameters::onRefDeleted(void) } } -void TaskFilletParameters::onAddAllEdges(void) +void TaskFilletParameters::onAddAllEdges() { TaskDressUpParameters::addAllEdges(ui->listWidgetReferences); ui->buttonRefRemove->setEnabled(true); @@ -231,7 +231,7 @@ void TaskFilletParameters::onLengthChanged(double len) hideOnError(); } -double TaskFilletParameters::getLength(void) const +double TaskFilletParameters::getLength() const { return ui->filletRadius->value().getValue(); } diff --git a/src/Mod/PartDesign/Gui/TaskFilletParameters.h b/src/Mod/PartDesign/Gui/TaskFilletParameters.h index e8ada661bc..37a1ffb977 100644 --- a/src/Mod/PartDesign/Gui/TaskFilletParameters.h +++ b/src/Mod/PartDesign/Gui/TaskFilletParameters.h @@ -36,23 +36,23 @@ class TaskFilletParameters : public TaskDressUpParameters Q_OBJECT public: - TaskFilletParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); - ~TaskFilletParameters(); + explicit TaskFilletParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + ~TaskFilletParameters() override; - virtual void apply(); + void apply() override; private Q_SLOTS: void onLengthChanged(double); - void onRefDeleted(void); - void onAddAllEdges(void); + void onRefDeleted() override; + void onAddAllEdges(); void onCheckBoxUseAllEdgesToggled(bool checked); protected: - double getLength(void) const; - virtual void clearButtons(const selectionModes notThis); - bool event(QEvent *e); - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + double getLength() const; + void clearButtons(const selectionModes notThis) override; + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: std::unique_ptr ui; @@ -64,12 +64,12 @@ class TaskDlgFilletParameters : public TaskDlgDressUpParameters Q_OBJECT public: - TaskDlgFilletParameters(ViewProviderFillet *DressUpView); - ~TaskDlgFilletParameters(); + explicit TaskDlgFilletParameters(ViewProviderFillet *DressUpView); + ~TaskDlgFilletParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp b/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp index dd8defbca9..a8340781de 100644 --- a/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskHelixParameters.cpp @@ -460,7 +460,7 @@ void TaskHelixParameters::onAxisChanged(int num) oldRefName = oldSubRefAxis.front(); App::PropertyLinkSub& lnk = *(axesInList[num]); - if (lnk.getValue() == nullptr) { + if (!lnk.getValue()) { // enter reference selection mode TaskSketchBasedParameters::onSelectReference( AllowSelection::EDGE | @@ -587,7 +587,7 @@ void TaskHelixParameters::getReferenceAxis(App::DocumentObject*& obj, std::vecto int num = ui->axis->currentIndex(); const App::PropertyLinkSub& lnk = *(axesInList.at(num)); - if (lnk.getValue() == nullptr) { + if (!lnk.getValue()) { throw Base::RuntimeError("Still in reference selection mode; reference wasn't selected yet"); } else { diff --git a/src/Mod/PartDesign/Gui/TaskHelixParameters.h b/src/Mod/PartDesign/Gui/TaskHelixParameters.h index eb11753823..76dbb194bc 100644 --- a/src/Mod/PartDesign/Gui/TaskHelixParameters.h +++ b/src/Mod/PartDesign/Gui/TaskHelixParameters.h @@ -45,10 +45,10 @@ class TaskHelixParameters : public TaskSketchBasedParameters Q_OBJECT public: - TaskHelixParameters(ViewProviderHelix* HelixView, QWidget* parent = nullptr); - ~TaskHelixParameters(); + explicit TaskHelixParameters(ViewProviderHelix* HelixView, QWidget* parent = nullptr); + ~TaskHelixParameters() override; - virtual void apply() override; + void apply() override; static bool showPreview(PartDesign::Helix*); @@ -133,7 +133,7 @@ class TaskDlgHelixParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgHelixParameters(ViewProviderHelix* HelixView); + explicit TaskDlgHelixParameters(ViewProviderHelix* HelixView); ViewProviderHelix* getHelixView() const { return static_cast(vp); } diff --git a/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp b/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp index a5b48d5500..8c2c9873e5 100644 --- a/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskHoleParameters.cpp @@ -689,7 +689,7 @@ void TaskHoleParameters::changeEvent(QEvent* e) void TaskHoleParameters::changedObject(const App::Document&, const App::Property& Prop) { // happens when aborting the command - if (vp == nullptr) + if (!vp) return; PartDesign::Hole* pcHole = static_cast(vp->getObject()); diff --git a/src/Mod/PartDesign/Gui/TaskHoleParameters.h b/src/Mod/PartDesign/Gui/TaskHoleParameters.h index 2c48239c17..b06583b878 100644 --- a/src/Mod/PartDesign/Gui/TaskHoleParameters.h +++ b/src/Mod/PartDesign/Gui/TaskHoleParameters.h @@ -50,8 +50,8 @@ class TaskHoleParameters : public TaskSketchBasedParameters Q_OBJECT public: - TaskHoleParameters(ViewProviderHole *HoleView, QWidget *parent = nullptr); - ~TaskHoleParameters(); + explicit TaskHoleParameters(ViewProviderHole *HoleView, QWidget *parent = nullptr); + ~TaskHoleParameters() override; void apply() override; @@ -114,7 +114,7 @@ private: public: Observer(TaskHoleParameters * _owner, PartDesign::Hole * _hole); private: - virtual void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); + void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) override; TaskHoleParameters * owner; PartDesign::Hole * hole; }; @@ -143,8 +143,8 @@ class TaskDlgHoleParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgHoleParameters(ViewProviderHole *HoleView); - ~TaskDlgHoleParameters(); + explicit TaskDlgHoleParameters(ViewProviderHole *HoleView); + ~TaskDlgHoleParameters() override; ViewProviderHole* getHoleView() const { return static_cast(vp); } diff --git a/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp b/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp index 2a465d4752..4509d36576 100644 --- a/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.cpp @@ -141,7 +141,7 @@ void TaskLinearPatternParameters::setupUI() // Fill data into dialog elements for (std::vector::const_iterator i = originals.begin(); i != originals.end(); ++i) { const App::DocumentObject* obj = *i; - if (obj != nullptr) { + if (obj) { QListWidgetItem* item = new QListWidgetItem(); item->setText(QString::fromUtf8(obj->Label.getValue())); item->setData(Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); @@ -318,7 +318,7 @@ void TaskLinearPatternParameters::onDirectionChanged(int /*num*/) return; PartDesign::LinearPattern* pcLinearPattern = static_cast(getObject()); try{ - if(dirLinks.getCurrentLink().getValue() == nullptr){ + if (!dirLinks.getCurrentLink().getValue()) { // enter reference selection mode hideObject(); showBase(); diff --git a/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.h b/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.h index 782b73067d..ba64fce804 100644 --- a/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.h +++ b/src/Mod/PartDesign/Gui/TaskLinearPatternParameters.h @@ -48,12 +48,12 @@ class TaskLinearPatternParameters : public TaskTransformedParameters public: /// Constructor for task with ViewProvider - TaskLinearPatternParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); + explicit TaskLinearPatternParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskLinearPatternParameters(TaskMultiTransformParameters *parentTask, QLayout *layout); - virtual ~TaskLinearPatternParameters(); + ~TaskLinearPatternParameters() override; - virtual void apply(); + void apply() override; private Q_SLOTS: void onUpdateViewTimer(); @@ -62,18 +62,18 @@ private Q_SLOTS: void onLength(const double l); void onOccurrences(const uint n); virtual void onUpdateView(bool); - virtual void onFeatureDeleted(void); + void onFeatureDeleted() override; protected: - virtual void addObject(App::DocumentObject*); - virtual void removeObject(App::DocumentObject*); - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); - virtual void clearButtons(); + void addObject(App::DocumentObject*) override; + void removeObject(App::DocumentObject*) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void clearButtons() override; void getDirection(App::DocumentObject*& obj, std::vector& sub) const; - bool getReverse(void) const; - double getLength(void) const; - unsigned getOccurrences(void) const; + bool getReverse() const; + double getLength() const; + unsigned getOccurrences() const; private: void connectSignals(); @@ -95,8 +95,8 @@ class TaskDlgLinearPatternParameters : public TaskDlgTransformedParameters Q_OBJECT public: - TaskDlgLinearPatternParameters(ViewProviderLinearPattern *LinearPatternView); - virtual ~TaskDlgLinearPatternParameters() {} + explicit TaskDlgLinearPatternParameters(ViewProviderLinearPattern *LinearPatternView); + ~TaskDlgLinearPatternParameters() override {} }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp b/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp index 46530013c9..4518461eda 100644 --- a/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskLoftParameters.cpp @@ -85,7 +85,8 @@ TaskLoftParameters::TaskLoftParameters(ViewProviderLoft *LoftView, bool /*newObj this->groupLayout()->addWidget(proxy); // Temporarily prevent unnecessary feature recomputes - for (QWidget* child : proxy->findChildren()) + const auto childs = proxy->findChildren(); + for (QWidget* child : childs) child->blockSignals(true); //add the profiles @@ -115,7 +116,7 @@ TaskLoftParameters::TaskLoftParameters(ViewProviderLoft *LoftView, bool /*newObj ui->checkBoxClosed->setChecked(loft->Closed.getValue()); // activate and de-activate dialog elements as appropriate - for (QWidget* child : proxy->findChildren()) + for (QWidget* child : childs) child->blockSignals(false); updateUI(); @@ -225,7 +226,7 @@ void TaskLoftParameters::removeFromListWidget(QListWidget* widget, QString name) QList items = widget->findItems(name, Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator it = items.begin(); it != items.end(); ++it) { + for (QList::const_iterator it = items.cbegin(); it != items.cend(); ++it) { QListWidgetItem* item = widget->takeItem(widget->row(*it)); delete item; } @@ -266,7 +267,6 @@ void TaskLoftParameters::indexesMoved() PartDesign::Loft* loft = static_cast(vp->getObject()); auto originals = loft->Sections.getSubListValues(); - QByteArray name; int rows = model->rowCount(); for (int i = 0; i < rows; i++) { QModelIndex index = model->index(i, 0); diff --git a/src/Mod/PartDesign/Gui/TaskLoftParameters.h b/src/Mod/PartDesign/Gui/TaskLoftParameters.h index c945eddbdd..3bd852f063 100644 --- a/src/Mod/PartDesign/Gui/TaskLoftParameters.h +++ b/src/Mod/PartDesign/Gui/TaskLoftParameters.h @@ -46,8 +46,8 @@ class TaskLoftParameters : public TaskSketchBasedParameters Q_OBJECT public: - TaskLoftParameters(ViewProviderLoft *LoftView, bool newObj=false, QWidget *parent = nullptr); - ~TaskLoftParameters(); + explicit TaskLoftParameters(ViewProviderLoft *LoftView, bool newObj=false, QWidget *parent = nullptr); + ~TaskLoftParameters() override; private Q_SLOTS: void onProfileButton(bool); @@ -61,10 +61,10 @@ private Q_SLOTS: protected: enum selectionModes { none, refAdd, refRemove, refProfile }; - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void updateUI(); bool referenceSelected(const Gui::SelectionChanges& msg) const; void removeFromListWidget(QListWidget*w, QString name); @@ -84,14 +84,14 @@ class TaskDlgLoftParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgLoftParameters(ViewProviderLoft *LoftView,bool newObj=false); - ~TaskDlgLoftParameters(); + explicit TaskDlgLoftParameters(ViewProviderLoft *LoftView,bool newObj=false); + ~TaskDlgLoftParameters() override; ViewProviderLoft* getLoftView() const { return static_cast(vp); } /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; protected: TaskLoftParameters *parameter; diff --git a/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp b/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp index aeb0ea2e8c..3eaeda48b4 100644 --- a/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskMirroredParameters.cpp @@ -122,7 +122,7 @@ void TaskMirroredParameters::setupUI() // Fill data into dialog elements for (std::vector::const_iterator i = originals.begin(); i != originals.end(); ++i) { const App::DocumentObject* obj = *i; - if (obj != nullptr) { + if (obj) { QListWidgetItem* item = new QListWidgetItem(); item->setText(QString::fromUtf8(obj->Label.getValue())); item->setData(Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); @@ -230,7 +230,7 @@ void TaskMirroredParameters::onPlaneChanged(int /*num*/) setupTransaction(); PartDesign::Mirrored* pcMirrored = static_cast(getObject()); try{ - if(planeLinks.getCurrentLink().getValue() == nullptr){ + if (!planeLinks.getCurrentLink().getValue()) { // enter reference selection mode hideObject(); showBase(); @@ -265,7 +265,7 @@ void TaskMirroredParameters::onUpdateView(bool on) } } -void TaskMirroredParameters::onFeatureDeleted(void) +void TaskMirroredParameters::onFeatureDeleted() { PartDesign::Transformed* pcTransformed = getObject(); std::vector originals = pcTransformed->Originals.getValues(); diff --git a/src/Mod/PartDesign/Gui/TaskMirroredParameters.h b/src/Mod/PartDesign/Gui/TaskMirroredParameters.h index 4087a91c83..b5782c7b29 100644 --- a/src/Mod/PartDesign/Gui/TaskMirroredParameters.h +++ b/src/Mod/PartDesign/Gui/TaskMirroredParameters.h @@ -47,27 +47,27 @@ class TaskMirroredParameters : public TaskTransformedParameters public: /// Constructor for task with ViewProvider - TaskMirroredParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); + explicit TaskMirroredParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskMirroredParameters(TaskMultiTransformParameters *parentTask, QLayout *layout); - virtual ~TaskMirroredParameters(); + ~TaskMirroredParameters() override; void getMirrorPlane(App::DocumentObject*& obj, std::vector& sub) const; - virtual void apply(); + void apply() override; private Q_SLOTS: void onPlaneChanged(int num); virtual void onUpdateView(bool); - virtual void onFeatureDeleted(void); + void onFeatureDeleted() override; protected: - virtual void addObject(App::DocumentObject*); - virtual void removeObject(App::DocumentObject*); - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); - virtual void clearButtons(); + void addObject(App::DocumentObject*) override; + void removeObject(App::DocumentObject*) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void clearButtons() override; private: void setupUI(); @@ -85,12 +85,12 @@ class TaskDlgMirroredParameters : public TaskDlgTransformedParameters Q_OBJECT public: - TaskDlgMirroredParameters(ViewProviderMirrored *MirroredView); - virtual ~TaskDlgMirroredParameters() {} + explicit TaskDlgMirroredParameters(ViewProviderMirrored *MirroredView); + ~TaskDlgMirroredParameters() override {} public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp index 07f40345da..ea624c1214 100644 --- a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.cpp @@ -134,7 +134,7 @@ TaskMultiTransformParameters::TaskMultiTransformParameters(ViewProviderTransform if (*i) ui->listTransformFeatures->addItem(QString::fromUtf8((*i)->Label.getValue())); } - if (transformFeatures.size() > 0) { + if (!transformFeatures.empty()) { ui->listTransformFeatures->setCurrentRow(0, QItemSelectionModel::ClearAndSelect); editHint = false; } else { @@ -188,7 +188,7 @@ void TaskMultiTransformParameters::clearButtons() ui->buttonRemoveFeature->setChecked(false); } -void TaskMultiTransformParameters::onFeatureDeleted(void) +void TaskMultiTransformParameters::onFeatureDeleted() { PartDesign::Transformed* pcTransformed = getObject(); std::vector originals = pcTransformed->Originals.getValues(); @@ -504,7 +504,7 @@ void TaskMultiTransformParameters::onUpdateView(bool on) } } -const std::vector TaskMultiTransformParameters::getTransformFeatures(void) const +const std::vector TaskMultiTransformParameters::getTransformFeatures() const { PartDesign::MultiTransform* pcMultiTransform = static_cast(TransformedView->getObject()); return pcMultiTransform->Transformations.getValues(); diff --git a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h index 8c7c54429b..fdd989f5ef 100644 --- a/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h +++ b/src/Mod/PartDesign/Gui/TaskMultiTransformParameters.h @@ -51,17 +51,17 @@ class TaskMultiTransformParameters : public TaskTransformedParameters Q_OBJECT public: - TaskMultiTransformParameters(ViewProviderTransformed *TransformedView,QWidget *parent = nullptr); - virtual ~TaskMultiTransformParameters(); + explicit TaskMultiTransformParameters(ViewProviderTransformed *TransformedView,QWidget *parent = nullptr); + ~TaskMultiTransformParameters() override; - const std::vector getTransformFeatures(void) const; + const std::vector getTransformFeatures() const; /// Return the currently active subFeature - PartDesign::Transformed* getSubFeature(void) { + PartDesign::Transformed* getSubFeature() { return subFeature; } - virtual void apply(); + void apply() override; private Q_SLOTS: void onTransformDelete(); @@ -74,20 +74,20 @@ private Q_SLOTS: void onMoveUp(); void onMoveDown(); /// User finished editing a subFeature - virtual void onSubTaskButtonOK(); + void onSubTaskButtonOK() override; // Note: There is no Cancel button because I couldn't work out how to save the state of // a subFeature so as to revert the changes of an edit operation virtual void onUpdateView(bool); - virtual void onFeatureDeleted(void); + void onFeatureDeleted() override; /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; protected: - virtual void addObject(App::DocumentObject*); - virtual void removeObject(App::DocumentObject*); - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); - virtual void clearButtons(); + void addObject(App::DocumentObject*) override; + void removeObject(App::DocumentObject*) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void clearButtons() override; private: void updateUI(); @@ -110,12 +110,12 @@ class TaskDlgMultiTransformParameters : public TaskDlgTransformedParameters Q_OBJECT public: - TaskDlgMultiTransformParameters(ViewProviderMultiTransform *MultiTransformView); - virtual ~TaskDlgMultiTransformParameters() {} + explicit TaskDlgMultiTransformParameters(ViewProviderMultiTransform *MultiTransformView); + ~TaskDlgMultiTransformParameters() override {} public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) // virtual bool reject(); }; diff --git a/src/Mod/PartDesign/Gui/TaskPadParameters.cpp b/src/Mod/PartDesign/Gui/TaskPadParameters.cpp index 437f8b411b..df39e51db7 100644 --- a/src/Mod/PartDesign/Gui/TaskPadParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPadParameters.cpp @@ -104,6 +104,10 @@ void TaskPadParameters::onModeChanged(int index) break; case Modes::ToFace: pcPad->Type.setValue("UpToFace"); + if (ui->lineFaceName->text().isEmpty()) { + ui->buttonFace->setChecked(true); + handleLineFaceNameClick(); // sets placeholder text + } break; case Modes::TwoDimensions: pcPad->Type.setValue("TwoLengths"); diff --git a/src/Mod/PartDesign/Gui/TaskPadParameters.h b/src/Mod/PartDesign/Gui/TaskPadParameters.h index e3be1b9096..0a353f410a 100644 --- a/src/Mod/PartDesign/Gui/TaskPadParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPadParameters.h @@ -43,10 +43,10 @@ class TaskPadParameters : public TaskExtrudeParameters Q_OBJECT public: - TaskPadParameters(ViewProviderPad *PadView, QWidget *parent = nullptr, bool newObj=false); - ~TaskPadParameters(); + explicit TaskPadParameters(ViewProviderPad *PadView, QWidget *parent = nullptr, bool newObj=false); + ~TaskPadParameters() override; - virtual void apply() override; + void apply() override; private: void onModeChanged(int index) override; @@ -60,7 +60,7 @@ class TaskDlgPadParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgPadParameters(ViewProviderPad *PadView, bool newObj=false); + explicit TaskDlgPadParameters(ViewProviderPad *PadView, bool newObj=false); ViewProviderPad* getPadView() const { return static_cast(vp); } diff --git a/src/Mod/PartDesign/Gui/TaskPadPocketParameters.ui b/src/Mod/PartDesign/Gui/TaskPadPocketParameters.ui index c66becbecd..b3ebfc164e 100644 --- a/src/Mod/PartDesign/Gui/TaskPadPocketParameters.ui +++ b/src/Mod/PartDesign/Gui/TaskPadPocketParameters.ui @@ -141,7 +141,7 @@ the sketch plane's normal vector will be used - + x-component of direction vector @@ -224,7 +224,7 @@ the sketch plane's normal vector will be used - + @@ -336,14 +336,27 @@ measured along the specified direction - + + + + 0 + 22 + + - Face + Select face + + + true - + + + true + + diff --git a/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp b/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp index 5db7ef33ca..ba68286861 100644 --- a/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPipeParameters.cpp @@ -258,7 +258,7 @@ void TaskPipeParameters::removeFromListWidget(QListWidget* widget, QString items { QList items = widget->findItems(itemstr, Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator i = items.begin(); i != items.end(); i++) { + for (QList::const_iterator i = items.cbegin(); i != items.cend(); i++) { QListWidgetItem* it = widget->takeItem(widget->row(*i)); delete it; } @@ -486,11 +486,10 @@ bool TaskPipeParameters::accept() for (auto &subSet : pcPipe->Sections.getSubListValues()) { if (!pcActiveBody->hasObject(subSet.first) && !pcActiveBody->getOrigin()->hasObject(subSet.first)) { - subSets.push_back( - std::make_pair( + subSets.emplace_back( PartDesignGui::TaskFeaturePick::makeCopy( subSet.first, "", dlg.radioIndependent->isChecked()), - subSet.second)); + subSet.second); copies.push_back(subSets.back().first); } else { @@ -758,7 +757,7 @@ void TaskPipeOrientation::removeFromListWidget(QListWidget* widget, QString name { QList items = widget->findItems(name, Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator i = items.begin(); i != items.end(); i++) { + for (QList::const_iterator i = items.cbegin(); i != items.cend(); i++) { QListWidgetItem* it = widget->takeItem(widget->row(*i)); delete it; } @@ -876,7 +875,6 @@ void TaskPipeScaling::indexesMoved() PartDesign::Pipe* pipe = static_cast(vp->getObject()); auto originals = pipe->Sections.getSubListValues(); - QByteArray name; int rows = model->rowCount(); for (int i = 0; i < rows; i++) { QModelIndex index = model->index(i, 0); @@ -988,7 +986,7 @@ void TaskPipeScaling::removeFromListWidget(QListWidget* widget, QString name) { QList items = widget->findItems(name, Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator i = items.begin(); i != items.end(); i++) { + for (QList::const_iterator i = items.cbegin(); i != items.cend(); i++) { QListWidgetItem* it = widget->takeItem(widget->row(*i)); delete it; } diff --git a/src/Mod/PartDesign/Gui/TaskPipeParameters.h b/src/Mod/PartDesign/Gui/TaskPipeParameters.h index ea77e0ceda..8839c86b1f 100644 --- a/src/Mod/PartDesign/Gui/TaskPipeParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPipeParameters.h @@ -79,8 +79,8 @@ class TaskPipeParameters : public TaskSketchBasedParameters Q_OBJECT public: - TaskPipeParameters(ViewProviderPipe *PipeView, bool newObj=false, QWidget *parent = nullptr); - ~TaskPipeParameters(); + explicit TaskPipeParameters(ViewProviderPipe *PipeView, bool newObj=false, QWidget *parent = nullptr); + ~TaskPipeParameters() override; bool accept(); @@ -95,7 +95,7 @@ protected: bool referenceSelected(const Gui::SelectionChanges& msg) const; private: - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void updateUI(); void clearButtons(); void exitSelectionMode(); @@ -120,8 +120,8 @@ class TaskPipeOrientation : public TaskSketchBasedParameters Q_OBJECT public: - TaskPipeOrientation(ViewProviderPipe *PipeView, bool newObj=false, QWidget *parent = nullptr); - virtual ~TaskPipeOrientation(); + explicit TaskPipeOrientation(ViewProviderPipe *PipeView, bool newObj=false, QWidget *parent = nullptr); + ~TaskPipeOrientation() override; private Q_SLOTS: @@ -137,7 +137,7 @@ protected: bool referenceSelected(const Gui::SelectionChanges& msg) const; private: - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void clearButtons(); void exitSelectionMode(); @@ -154,8 +154,8 @@ class TaskPipeScaling : public TaskSketchBasedParameters Q_OBJECT public: - TaskPipeScaling(ViewProviderPipe *PipeView,bool newObj=false,QWidget *parent = nullptr); - virtual ~TaskPipeScaling(); + explicit TaskPipeScaling(ViewProviderPipe *PipeView,bool newObj=false,QWidget *parent = nullptr); + ~TaskPipeScaling() override; private Q_SLOTS: void onScalingChanged(int); @@ -168,7 +168,7 @@ protected: bool referenceSelected(const Gui::SelectionChanges& msg) const; private: - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void clearButtons(); void exitSelectionMode(); @@ -185,12 +185,12 @@ class TaskDlgPipeParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgPipeParameters(ViewProviderPipe *PipeView,bool newObj=false); - ~TaskDlgPipeParameters(); + explicit TaskDlgPipeParameters(ViewProviderPipe *PipeView,bool newObj=false); + ~TaskDlgPipeParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) protected Q_SLOTS: diff --git a/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp b/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp index 069d258348..85a6b1d338 100644 --- a/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPocketParameters.cpp @@ -114,6 +114,10 @@ void TaskPocketParameters::onModeChanged(int index) pcPocket->Type.setValue("UpToFace"); pcPocket->Length.setValue(0.0); ui->lengthEdit->setValue(0.0); + if (ui->lineFaceName->text().isEmpty()) { + ui->buttonFace->setChecked(true); + handleLineFaceNameClick(); // sets placeholder text + } break; case Modes::TwoDimensions: oldLength = pcPocket->Length.getValue(); diff --git a/src/Mod/PartDesign/Gui/TaskPocketParameters.h b/src/Mod/PartDesign/Gui/TaskPocketParameters.h index 6eb918cca6..e7e27e7e2f 100644 --- a/src/Mod/PartDesign/Gui/TaskPocketParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPocketParameters.h @@ -43,10 +43,10 @@ class TaskPocketParameters : public TaskExtrudeParameters Q_OBJECT public: - TaskPocketParameters(ViewProviderPocket *PocketView, QWidget *parent = nullptr, bool newObj=false); - ~TaskPocketParameters(); + explicit TaskPocketParameters(ViewProviderPocket *PocketView, QWidget *parent = nullptr, bool newObj=false); + ~TaskPocketParameters() override; - virtual void apply() override; + void apply() override; private: void onModeChanged(int index) override; @@ -63,7 +63,7 @@ class TaskDlgPocketParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgPocketParameters(ViewProviderPocket *PocketView); + explicit TaskDlgPocketParameters(ViewProviderPocket *PocketView); ViewProviderPocket* getPocketView() const { return static_cast(vp); } diff --git a/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp b/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp index b40abaa4a0..8c75e55e3d 100644 --- a/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.cpp @@ -148,7 +148,7 @@ void TaskPolarPatternParameters::setupUI() // Fill data into dialog elements for (std::vector::const_iterator i = originals.begin(); i != originals.end(); ++i) { const App::DocumentObject* obj = *i; - if (obj != nullptr) { + if (obj) { QListWidgetItem* item = new QListWidgetItem(); item->setText(QString::fromUtf8(obj->Label.getValue())); item->setData(Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); @@ -318,7 +318,7 @@ void TaskPolarPatternParameters::onAxisChanged(int /*num*/) PartDesign::PolarPattern* pcPolarPattern = static_cast(getObject()); try{ - if(axesLinks.getCurrentLink().getValue() == nullptr){ + if (!axesLinks.getCurrentLink().getValue()) { // enter reference selection mode hideObject(); showBase(); diff --git a/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.h b/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.h index ae9609f940..ed799b3863 100644 --- a/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPolarPatternParameters.h @@ -48,12 +48,12 @@ class TaskPolarPatternParameters : public TaskTransformedParameters public: /// Constructor for task with ViewProvider - TaskPolarPatternParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); + explicit TaskPolarPatternParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskPolarPatternParameters(TaskMultiTransformParameters *parentTask, QLayout *layout); - virtual ~TaskPolarPatternParameters(); + ~TaskPolarPatternParameters() override; - void apply(); + void apply() override; private Q_SLOTS: void onUpdateViewTimer(); @@ -62,20 +62,20 @@ private Q_SLOTS: void onAngle(const double a); void onOccurrences(const uint n); virtual void onUpdateView(bool); - virtual void onFeatureDeleted(void); + void onFeatureDeleted() override; protected: - virtual void addObject(App::DocumentObject*); - virtual void removeObject(App::DocumentObject*); - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); - virtual void clearButtons(); + void addObject(App::DocumentObject*) override; + void removeObject(App::DocumentObject*) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void clearButtons() override; void getAxis(App::DocumentObject*& obj, std::vector& sub) const; - const std::string getStdAxis(void) const; - const std::string getAxis(void) const; - bool getReverse(void) const; - double getAngle(void) const; - unsigned getOccurrences(void) const; + const std::string getStdAxis() const; + const std::string getAxis() const; + bool getReverse() const; + double getAngle() const; + unsigned getOccurrences() const; private: void connectSignals(); @@ -97,8 +97,8 @@ class TaskDlgPolarPatternParameters : public TaskDlgTransformedParameters Q_OBJECT public: - TaskDlgPolarPatternParameters(ViewProviderPolarPattern *PolarPatternView); - virtual ~TaskDlgPolarPatternParameters() {} + explicit TaskDlgPolarPatternParameters(ViewProviderPolarPattern *PolarPatternView); + ~TaskDlgPolarPatternParameters() override {} }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp index 7c04e439e0..5801dc69de 100644 --- a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.cpp @@ -691,10 +691,10 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Length=%2\n" "%1.Width=%3\n" "%1.Height=%4\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->boxLength->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->boxWidth->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->boxHeight->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->boxLength->value(), format), + Base::UnitsApi::toNumber(ui->boxWidth->value(), format), + Base::UnitsApi::toNumber(ui->boxHeight->value(), format)); break; case 2: // cylinder @@ -704,12 +704,12 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Angle=%4\n" "%1.FirstAngle=%5\n" "%1.SecondAngle=%6\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->cylinderRadius->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->cylinderHeight->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->cylinderAngle->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->cylinderXSkew->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->cylinderYSkew->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->cylinderRadius->value(), format), + Base::UnitsApi::toNumber(ui->cylinderHeight->value(), format), + Base::UnitsApi::toNumber(ui->cylinderAngle->value(), format), + Base::UnitsApi::toNumber(ui->cylinderXSkew->value(), format), + Base::UnitsApi::toNumber(ui->cylinderYSkew->value(), format)); break; case 3: // cone @@ -724,11 +724,11 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Radius2=%3\n" "%1.Height=%4\n" "%1.Angle=%5\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->coneRadius1->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->coneRadius2->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->coneHeight->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->coneAngle->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->coneRadius1->value(), format), + Base::UnitsApi::toNumber(ui->coneRadius2->value(), format), + Base::UnitsApi::toNumber(ui->coneHeight->value(), format), + Base::UnitsApi::toNumber(ui->coneAngle->value(), format)); break; case 4: // sphere @@ -737,11 +737,11 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Angle1=%3\n" "%1.Angle2=%4\n" "%1.Angle3=%5\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->sphereRadius->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle1->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle2->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->sphereAngle3->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->sphereRadius->value(), format), + Base::UnitsApi::toNumber(ui->sphereAngle1->value(), format), + Base::UnitsApi::toNumber(ui->sphereAngle2->value(), format), + Base::UnitsApi::toNumber(ui->sphereAngle3->value(), format)); break; case 5: // ellipsoid cmd = QString::fromLatin1( @@ -751,13 +751,13 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Angle1=%5\n" "%1.Angle2=%6\n" "%1.Angle3=%7\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidRadius3->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle1->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle2->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->ellipsoidAngle3->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->ellipsoidRadius1->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidRadius2->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidRadius3->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidAngle1->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidAngle2->value(), format), + Base::UnitsApi::toNumber(ui->ellipsoidAngle3->value(), format)); break; case 6: // torus @@ -767,12 +767,12 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Angle1=%4\n" "%1.Angle2=%5\n" "%1.Angle3=%6\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->torusRadius1->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->torusRadius2->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->torusAngle1->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->torusAngle2->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->torusAngle3->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->torusRadius1->value(), format), + Base::UnitsApi::toNumber(ui->torusRadius2->value(), format), + Base::UnitsApi::toNumber(ui->torusAngle1->value(), format), + Base::UnitsApi::toNumber(ui->torusAngle2->value(), format), + Base::UnitsApi::toNumber(ui->torusAngle3->value(), format)); break; case 7: // prism cmd = QString::fromLatin1( @@ -781,12 +781,12 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Height=%4\n" "%1.FirstAngle=%5\n" "%1.SecondAngle=%6\n") - .arg(name) - .arg(ui->prismPolygon->value()) - .arg(Base::UnitsApi::toNumber(ui->prismCircumradius->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->prismHeight->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->prismXSkew->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->prismYSkew->value(), format)); + .arg(name, + QString::number(ui->prismPolygon->value()), + Base::UnitsApi::toNumber(ui->prismCircumradius->value(), format), + Base::UnitsApi::toNumber(ui->prismHeight->value(), format), + Base::UnitsApi::toNumber(ui->prismXSkew->value(), format), + Base::UnitsApi::toNumber(ui->prismYSkew->value(), format)); break; case 8: // wedge // Xmin/max, Ymin/max and Zmin/max must each not be equal @@ -816,17 +816,17 @@ bool TaskBoxPrimitives::setPrimitive(App::DocumentObject *obj) "%1.Zmax=%9\n" "%1.X2max=%10\n" "%1.Z2max=%11\n") - .arg(name) - .arg(Base::UnitsApi::toNumber(ui->wedgeXmin->value())) - .arg(Base::UnitsApi::toNumber(ui->wedgeYmin->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeZmin->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeX2min->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeZ2min->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeXmax->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeYmax->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeZmax->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeX2max->value(), format)) - .arg(Base::UnitsApi::toNumber(ui->wedgeZ2max->value(), format)); + .arg(name, + Base::UnitsApi::toNumber(ui->wedgeXmin->value()), + Base::UnitsApi::toNumber(ui->wedgeYmin->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZmin->value(), format), + Base::UnitsApi::toNumber(ui->wedgeX2min->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZ2min->value(), format), + Base::UnitsApi::toNumber(ui->wedgeXmax->value(), format), + Base::UnitsApi::toNumber(ui->wedgeYmax->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZmax->value(), format)) + .arg(Base::UnitsApi::toNumber(ui->wedgeX2max->value(), format), + Base::UnitsApi::toNumber(ui->wedgeZ2max->value(), format)); break; default: diff --git a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h index c3607bbf85..fe76273571 100644 --- a/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h +++ b/src/Mod/PartDesign/Gui/TaskPrimitiveParameters.h @@ -48,8 +48,8 @@ class TaskBoxPrimitives : public Gui::TaskView::TaskBox, Q_OBJECT public: - TaskBoxPrimitives(ViewProviderPrimitive* vp, QWidget* parent = nullptr); - ~TaskBoxPrimitives(); + explicit TaskBoxPrimitives(ViewProviderPrimitive* vp, QWidget* parent = nullptr); + ~TaskBoxPrimitives() override; bool setPrimitive(App::DocumentObject *); @@ -99,7 +99,7 @@ public Q_SLOTS: private: /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; private: QWidget* proxy; @@ -112,14 +112,14 @@ class TaskPrimitiveParameters : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskPrimitiveParameters(ViewProviderPrimitive *PrimitiveView); - ~TaskPrimitiveParameters(); + explicit TaskPrimitiveParameters(ViewProviderPrimitive *PrimitiveView); + ~TaskPrimitiveParameters() override; protected: - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const; + QDialogButtonBox::StandardButtons getStandardButtons() const override; - virtual bool accept(); - virtual bool reject(); + bool accept() override; + bool reject() override; private: TaskBoxPrimitives* primitive; diff --git a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp index f0f73d2a2f..8874da9480 100644 --- a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.cpp @@ -248,7 +248,7 @@ void TaskRevolutionParameters::onAxisChanged(int num) oldRefName = oldSubRefAxis.front(); App::PropertyLinkSub &lnk = *(axesInList[num]); - if (lnk.getValue() == nullptr) { + if (!lnk.getValue()) { // enter reference selection mode TaskSketchBasedParameters::onSelectReference(AllowSelection::EDGE | AllowSelection::PLANAR | @@ -305,7 +305,7 @@ void TaskRevolutionParameters::onReversed(bool on) recomputeFeature(); } -double TaskRevolutionParameters::getAngle(void) const +double TaskRevolutionParameters::getAngle() const { return ui->revolveAngle->value().getValue(); } @@ -317,7 +317,7 @@ void TaskRevolutionParameters::getReferenceAxis(App::DocumentObject*& obj, std:: int num = ui->axis->currentIndex(); const App::PropertyLinkSub &lnk = *(axesInList[num]); - if (lnk.getValue() == nullptr) { + if (!lnk.getValue()) { throw Base::RuntimeError("Still in reference selection mode; reference wasn't selected yet"); } else { PartDesign::ProfileBased* pcRevolution = static_cast(vp->getObject()); @@ -330,12 +330,12 @@ void TaskRevolutionParameters::getReferenceAxis(App::DocumentObject*& obj, std:: } } -bool TaskRevolutionParameters::getMidplane(void) const +bool TaskRevolutionParameters::getMidplane() const { return ui->checkBoxMidplane->isChecked(); } -bool TaskRevolutionParameters::getReversed(void) const +bool TaskRevolutionParameters::getReversed() const { return ui->checkBoxReversed->isChecked(); } diff --git a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h index 3a76ca7321..d4a02e227f 100644 --- a/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h +++ b/src/Mod/PartDesign/Gui/TaskRevolutionParameters.h @@ -46,10 +46,10 @@ class TaskRevolutionParameters : public TaskSketchBasedParameters Q_OBJECT public: - TaskRevolutionParameters(ViewProvider* RevolutionView,QWidget *parent = nullptr); - ~TaskRevolutionParameters(); + explicit TaskRevolutionParameters(ViewProvider* RevolutionView,QWidget *parent = nullptr); + ~TaskRevolutionParameters() override; - virtual void apply() override; + void apply() override; /** * @brief fillAxisCombo fills the combo and selects the item according to @@ -72,9 +72,9 @@ protected: void changeEvent(QEvent *e) override; bool updateView() const; void getReferenceAxis(App::DocumentObject *&obj, std::vector &sub) const; - double getAngle(void) const; - bool getMidplane(void) const; - bool getReversed(void) const; + double getAngle() const; + bool getMidplane() const; + bool getReversed() const; //mirrors of revolution's or groove's properties //should have been done by inheriting revolution and groove from common class... @@ -108,7 +108,7 @@ class TaskDlgRevolutionParameters : public TaskDlgSketchBasedParameters Q_OBJECT public: - TaskDlgRevolutionParameters(PartDesignGui::ViewProvider *RevolutionView); + explicit TaskDlgRevolutionParameters(PartDesignGui::ViewProvider *RevolutionView); ViewProvider* getRevolutionView() const { return vp; } diff --git a/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp b/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp index c2a15a97b9..bfe4f907f1 100644 --- a/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskScaledParameters.cpp @@ -113,7 +113,7 @@ void TaskScaledParameters::setupUI() // Fill data into dialog elements for (std::vector::const_iterator i = originals.begin(); i != originals.end(); ++i) { const App::DocumentObject* obj = *i; - if (obj != nullptr) { + if (obj) { QListWidgetItem* item = new QListWidgetItem(); item->setText(QString::fromUtf8(obj->Label.getValue())); item->setData(Qt::UserRole, QString::fromLatin1(obj->getNameInDocument())); diff --git a/src/Mod/PartDesign/Gui/TaskScaledParameters.h b/src/Mod/PartDesign/Gui/TaskScaledParameters.h index 2b45a05cc5..7a89055963 100644 --- a/src/Mod/PartDesign/Gui/TaskScaledParameters.h +++ b/src/Mod/PartDesign/Gui/TaskScaledParameters.h @@ -47,25 +47,25 @@ class TaskScaledParameters : public TaskTransformedParameters public: /// Constructor for task with ViewProvider - TaskScaledParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); + explicit TaskScaledParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) TaskScaledParameters(TaskMultiTransformParameters *parentTask, QLayout *layout); - virtual ~TaskScaledParameters(); + ~TaskScaledParameters() override; - virtual void apply(); + void apply() override; private Q_SLOTS: void onFactor(const double f); void onOccurrences(const uint n); virtual void onUpdateView(bool); - virtual void onFeatureDeleted(void); + void onFeatureDeleted() override; protected: - virtual void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); - virtual void clearButtons(); - double getFactor(void) const; - unsigned getOccurrences(void) const; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void clearButtons() override; + double getFactor() const; + unsigned getOccurrences() const; private: void setupUI(); @@ -82,12 +82,12 @@ class TaskDlgScaledParameters : public TaskDlgTransformedParameters Q_OBJECT public: - TaskDlgScaledParameters(ViewProviderScaled *ScaledView); - virtual ~TaskDlgScaledParameters() {} + explicit TaskDlgScaledParameters(ViewProviderScaled *ScaledView); + ~TaskDlgScaledParameters() override {} public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp b/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp index b78ef5e131..fb4bf64264 100644 --- a/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp +++ b/src/Mod/PartDesign/Gui/TaskShapeBinder.cpp @@ -99,7 +99,7 @@ void TaskShapeBinder::updateUI() connect(ui->baseEdit, &QLineEdit::textChanged, this, &TaskShapeBinder::supportChanged); - for (auto sub : subs) + for (const auto& sub : subs) ui->listWidgetReferences->addItem(QString::fromStdString(sub)); if (obj) { @@ -222,7 +222,7 @@ void TaskShapeBinder::removeFromListWidget(QListWidget* widget, QString itemstr) { QList items = widget->findItems(itemstr, Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator i = items.begin(); i != items.end(); i++) { + for (QList::const_iterator i = items.cbegin(); i != items.cend(); i++) { QListWidgetItem* it = widget->takeItem(widget->row(*i)); delete it; } diff --git a/src/Mod/PartDesign/Gui/TaskShapeBinder.h b/src/Mod/PartDesign/Gui/TaskShapeBinder.h index 3590e59a91..65727a13f5 100644 --- a/src/Mod/PartDesign/Gui/TaskShapeBinder.h +++ b/src/Mod/PartDesign/Gui/TaskShapeBinder.h @@ -51,14 +51,14 @@ class TaskShapeBinder : public Gui::TaskView::TaskBox, Gui::SelectionObserver Q_OBJECT public: - TaskShapeBinder(ViewProviderShapeBinder *view,bool newObj=false,QWidget *parent = nullptr); - ~TaskShapeBinder(); + explicit TaskShapeBinder(ViewProviderShapeBinder *view,bool newObj=false,QWidget *parent = nullptr); + ~TaskShapeBinder() override; void accept(); protected: enum selectionModes { none, refAdd, refRemove, refObjAdd }; - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; selectionModes selectionMode = none; void removeFromListWidget(QListWidget *w, QString name); @@ -67,7 +67,7 @@ protected: private: void setupButtonGroup(); void setupContextMenu(); - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void onButtonToggled(QAbstractButton *button, bool checked); void updateUI(); void supportChanged(const QString&); @@ -91,14 +91,14 @@ class TaskDlgShapeBinder : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgShapeBinder(ViewProviderShapeBinder *view,bool newObj=false); - ~TaskDlgShapeBinder(); + explicit TaskDlgShapeBinder(ViewProviderShapeBinder *view,bool newObj=false); + ~TaskDlgShapeBinder() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; protected: TaskShapeBinder *parameter; diff --git a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp index b5175cc3e5..cd1bc567fb 100644 --- a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.cpp @@ -142,7 +142,7 @@ QVariant TaskSketchBasedParameters::setUpToFace(const QString& text) // Check whether this is the name of an App::Plane or Part::Datum feature App::DocumentObject* obj = vp->getObject()->getDocument()->getObject(parts[0].toLatin1()); - if (obj == nullptr) + if (!obj) return QVariant(); if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId())) { diff --git a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h index 6e7f34daa5..e5979fc21f 100644 --- a/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h +++ b/src/Mod/PartDesign/Gui/TaskSketchBasedParameters.h @@ -47,10 +47,10 @@ class TaskSketchBasedParameters : public PartDesignGui::TaskFeatureParameters, public: TaskSketchBasedParameters(PartDesignGui::ViewProvider* vp, QWidget *parent, const std::string& pixmapname, const QString& parname); - ~TaskSketchBasedParameters(); + ~TaskSketchBasedParameters() override; protected: - void onSelectionChanged(const Gui::SelectionChanges& msg)=0; + void onSelectionChanged(const Gui::SelectionChanges& msg) override =0; const QString onAddSelection(const Gui::SelectionChanges& msg); virtual void startReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base); virtual void finishReferenceSelection(App::DocumentObject* profile, App::DocumentObject* base); @@ -79,14 +79,14 @@ class TaskDlgSketchBasedParameters : public PartDesignGui::TaskDlgFeatureParamet Q_OBJECT public: - TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp); - ~TaskDlgSketchBasedParameters(); + explicit TaskDlgSketchBasedParameters(PartDesignGui::ViewProvider *vp); + ~TaskDlgSketchBasedParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskThicknessParameters.h b/src/Mod/PartDesign/Gui/TaskThicknessParameters.h index 5d7f212de2..5513b2f47d 100644 --- a/src/Mod/PartDesign/Gui/TaskThicknessParameters.h +++ b/src/Mod/PartDesign/Gui/TaskThicknessParameters.h @@ -36,8 +36,8 @@ class TaskThicknessParameters : public TaskDressUpParameters Q_OBJECT public: - TaskThicknessParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); - ~TaskThicknessParameters(); + explicit TaskThicknessParameters(ViewProviderDressUp *DressUpView, QWidget *parent=nullptr); + ~TaskThicknessParameters() override; double getValue(void) const; bool getReversed(void) const; @@ -51,13 +51,13 @@ private Q_SLOTS: void onJoinTypeChanged(int join); void onReversedChanged(bool reversed); void onIntersectionChanged(bool intersection); - void onRefDeleted(void); + void onRefDeleted(void) override; protected: - virtual void clearButtons(const selectionModes notThis); - bool event(QEvent *e); - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void clearButtons(const selectionModes notThis) override; + bool event(QEvent *e) override; + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: std::unique_ptr ui; @@ -69,12 +69,12 @@ class TaskDlgThicknessParameters : public TaskDlgDressUpParameters Q_OBJECT public: - TaskDlgThicknessParameters(ViewProviderThickness *ThicknessView); - ~TaskDlgThicknessParameters(); + explicit TaskDlgThicknessParameters(ViewProviderThickness *ThicknessView); + ~TaskDlgThicknessParameters() override; public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; }; } //namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/TaskTransformedMessages.h b/src/Mod/PartDesign/Gui/TaskTransformedMessages.h index 44996230f7..a6f0c09c6d 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedMessages.h +++ b/src/Mod/PartDesign/Gui/TaskTransformedMessages.h @@ -42,8 +42,8 @@ class TaskTransformedMessages : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskTransformedMessages(ViewProviderTransformed *transformedView); - ~TaskTransformedMessages(); + explicit TaskTransformedMessages(ViewProviderTransformed *transformedView); + ~TaskTransformedMessages() override; void slotDiagnosis(QString msg); diff --git a/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp b/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp index bbaa4d4cd4..44704a87b2 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp +++ b/src/Mod/PartDesign/Gui/TaskTransformedParameters.cpp @@ -233,7 +233,7 @@ void TaskTransformedParameters::removeItemFromListWidget(QListWidget* widget, co { QList items = widget->findItems(itemstr, Qt::MatchExactly); if (!items.empty()) { - for (QList::const_iterator i = items.begin(); i != items.end(); i++) { + for (QList::const_iterator i = items.cbegin(); i != items.cend(); i++) { QListWidgetItem* it = widget->takeItem(widget->row(*i)); delete it; } @@ -498,7 +498,7 @@ int ComboLinks::addLink(const App::PropertyLinkSub &lnk, QString itemText) this->linksInList.push_back(new App::PropertyLinkSub()); App::PropertyLinkSub &newitem = *(linksInList[linksInList.size()-1]); newitem.Paste(lnk); - if (newitem.getValue() && this->doc == nullptr) + if (newitem.getValue() && !this->doc) this->doc = newitem.getValue()->getDocument(); return linksInList.size()-1; } @@ -511,7 +511,7 @@ int ComboLinks::addLink(App::DocumentObject *linkObj, std::string linkSubname, Q this->linksInList.push_back(new App::PropertyLinkSub()); App::PropertyLinkSub &newitem = *(linksInList[linksInList.size()-1]); newitem.setValue(linkObj,std::vector(1,linkSubname)); - if (newitem.getValue() && this->doc == nullptr) + if (newitem.getValue() && !this->doc) this->doc = newitem.getValue()->getDocument(); return linksInList.size()-1; } diff --git a/src/Mod/PartDesign/Gui/TaskTransformedParameters.h b/src/Mod/PartDesign/Gui/TaskTransformedParameters.h index d5f9d1ec07..3efb7bb7ef 100644 --- a/src/Mod/PartDesign/Gui/TaskTransformedParameters.h +++ b/src/Mod/PartDesign/Gui/TaskTransformedParameters.h @@ -64,9 +64,9 @@ public: * remove items from the combo directly, otherwise internal tracking list * will go out of sync, and crashes may result. */ - ComboLinks(QComboBox &combo); + explicit ComboLinks(QComboBox &combo); ComboLinks() {_combo = nullptr; doc = nullptr;} - void setCombo(QComboBox &combo) {assert(_combo == nullptr); this->_combo = &combo; _combo->clear();} + void setCombo(QComboBox &combo) {assert(!_combo); this->_combo = &combo; _combo->clear();} /** * @brief addLink adds an item to the combo. Doesn't check for duplicates. @@ -123,10 +123,10 @@ class TaskTransformedParameters : public Gui::TaskView::TaskBox, public: /// Constructor for task with ViewProvider - TaskTransformedParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); + explicit TaskTransformedParameters(ViewProviderTransformed *TransformedView, QWidget *parent = nullptr); /// Constructor for task with parent task (MultiTransform mode) - TaskTransformedParameters(TaskMultiTransformParameters *parentTask); - virtual ~TaskTransformedParameters(); + explicit TaskTransformedParameters(TaskMultiTransformParameters *parentTask); + ~TaskTransformedParameters() override; /// Returns the originals property of associated top feeature object const std::vector & getOriginals(void) const; @@ -156,7 +156,7 @@ public: return transactionID; } -protected Q_SLOTS: +protected: /** * Returns the base transformation view provider * For stand alone features it will be view provider associated with this object @@ -171,6 +171,7 @@ protected Q_SLOTS: */ PartDesign::Transformed *getTopTransformedObject () const; +protected Q_SLOTS: /// Connect the subTask OK button to the MultiTransform task virtual void onSubTaskButtonOK() {} void onButtonAddFeature(const bool checked); @@ -207,9 +208,9 @@ protected: virtual void addObject(App::DocumentObject*); virtual void removeObject(App::DocumentObject*); /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); - virtual void changeEvent(QEvent *e) = 0; - virtual void onSelectionChanged(const Gui::SelectionChanges& msg) = 0; + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; + void changeEvent(QEvent *e) override = 0; + void onSelectionChanged(const Gui::SelectionChanges& msg) override = 0; virtual void clearButtons()=0; static void removeItemFromListWidget(QListWidget* widget, const QString& itemstr); @@ -239,17 +240,17 @@ class TaskDlgTransformedParameters : public PartDesignGui::TaskDlgFeatureParamet Q_OBJECT public: - TaskDlgTransformedParameters(ViewProviderTransformed *TransformedView); - virtual ~TaskDlgTransformedParameters() {} + explicit TaskDlgTransformedParameters(ViewProviderTransformed *TransformedView); + ~TaskDlgTransformedParameters() override {} ViewProviderTransformed* getTransformedView() const { return static_cast(vp); } public: /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; protected: TaskTransformedParameters *parameter; TaskTransformedMessages *message; diff --git a/src/Mod/PartDesign/Gui/Utils.cpp b/src/Mod/PartDesign/Gui/Utils.cpp index 9fd9d45dc5..2018d680ae 100644 --- a/src/Mod/PartDesign/Gui/Utils.cpp +++ b/src/Mod/PartDesign/Gui/Utils.cpp @@ -56,27 +56,27 @@ using namespace Attacher; namespace PartDesignGui { bool setEdit(App::DocumentObject *obj, PartDesign::Body *body) { - if(!obj || !obj->getNameInDocument()) { + if (!obj || !obj->getNameInDocument()) { FC_ERR("invalid object"); return false; } - if(body == nullptr) { + if (!body) { body = getBodyFor(obj, false); - if(!body) { + if (!body) { FC_ERR("no body found"); return false; } } auto *activeView = Gui::Application::Instance->activeView(); - if(!activeView) + if (!activeView) return false; App::DocumentObject *parent = nullptr; std::string subname; auto activeBody = activeView->getActiveObject(PDBODYKEY,&parent,&subname); - if(activeBody != body) { + if (activeBody != body) { parent = obj; subname.clear(); - }else{ + } else { subname += obj->getNameInDocument(); subname += '.'; } diff --git a/src/Mod/PartDesign/Gui/Utils.h b/src/Mod/PartDesign/Gui/Utils.h index 3ebf9dda1e..3de0003515 100644 --- a/src/Mod/PartDesign/Gui/Utils.h +++ b/src/Mod/PartDesign/Gui/Utils.h @@ -67,7 +67,7 @@ PartDesign::Body * makeBodyActive(App::DocumentObject *body, App::Document *doc, std::string *subname=nullptr); /// Display error when there are existing Body objects, but none are active -void needActiveBodyError(void); +void needActiveBodyError(); /// Create a Body object in doc, set it active, and return pointer to it PartDesign::Body * makeBody(App::Document *doc); diff --git a/src/Mod/PartDesign/Gui/ViewProvider.cpp b/src/Mod/PartDesign/Gui/ViewProvider.cpp index 45e5a3630c..b896352488 100644 --- a/src/Mod/PartDesign/Gui/ViewProvider.cpp +++ b/src/Mod/PartDesign/Gui/ViewProvider.cpp @@ -50,7 +50,7 @@ using namespace PartDesignGui; PROPERTY_SOURCE_WITH_EXTENSIONS(PartDesignGui::ViewProvider, PartGui::ViewProviderPart) ViewProvider::ViewProvider() -:oldWb(""), oldTip(nullptr), isSetTipIcon(false) +: oldTip(nullptr), isSetTipIcon(false) { PartGui::ViewProviderAttachExtension::initExtension(this); } @@ -59,7 +59,7 @@ ViewProvider::~ViewProvider() { } -bool ViewProvider::doubleClicked(void) +bool ViewProvider::doubleClicked() { try { QString text = QObject::tr("Edit %1").arg(QString::fromUtf8(getObject()->Label.getValue())); @@ -248,7 +248,7 @@ bool ViewProvider::onDelete(const std::vector &) // find surrounding features in the tree Part::BodyBase* body = PartDesign::Body::findBodyOf(getObject()); - if (body != nullptr) { + if (body) { // Deletion from the tree of a feature is handled by Document.removeObject, which has no clue // about what a body is. Therefore, Bodies, although an "activable" container, know nothing // about what happens at Document level with the features they contain. diff --git a/src/Mod/PartDesign/Gui/ViewProvider.h b/src/Mod/PartDesign/Gui/ViewProvider.h index 1506f5eef2..aee7a80bc0 100644 --- a/src/Mod/PartDesign/Gui/ViewProvider.h +++ b/src/Mod/PartDesign/Gui/ViewProvider.h @@ -46,9 +46,9 @@ public: /// constructor ViewProvider(); /// destructor - virtual ~ViewProvider(); + ~ViewProvider() override; - virtual bool doubleClicked(void) override; + bool doubleClicked(void) override; void updateData(const App::Property*) override; void onChanged(const App::Property* prop) override; @@ -68,16 +68,16 @@ public: //Returns the ViewProvider of the body the feature belongs to, or NULL, if not in a body ViewProviderBody* getBodyViewProvider(); - virtual PyObject* getPyObject(void) override; + PyObject* getPyObject(void) override; - virtual QIcon mergeColorfulOverlayIcons (const QIcon & orig) const override; + QIcon mergeColorfulOverlayIcons (const QIcon & orig) const override; protected: - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; - virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; - virtual bool onDelete(const std::vector &) override; + bool onDelete(const std::vector &) override; /** * Returns a newly create dialog for the part to be placed in the task view diff --git a/src/Mod/PartDesign/Gui/ViewProviderAddSub.h b/src/Mod/PartDesign/Gui/ViewProviderAddSub.h index 4555113479..800180733f 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderAddSub.h +++ b/src/Mod/PartDesign/Gui/ViewProviderAddSub.h @@ -31,16 +31,16 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderAddSub : public ViewProvider { - PROPERTY_HEADER(PartDesignGui::ViewProviderAddSub); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderAddSub); public: /// constructor ViewProviderAddSub(); /// destructor - virtual ~ViewProviderAddSub(); + ~ViewProviderAddSub() override; - virtual void attach(App::DocumentObject*); - virtual void updateData(const App::Property*); + void attach(App::DocumentObject*) override; + void updateData(const App::Property*) override; protected: void updateAddSubShapeIndicator(); diff --git a/src/Mod/PartDesign/Gui/ViewProviderBase.cpp b/src/Mod/PartDesign/Gui/ViewProviderBase.cpp index 345656c151..7fa0087c3a 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBase.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBase.cpp @@ -44,7 +44,7 @@ ViewProviderBase::~ViewProviderBase() } -bool ViewProviderBase::doubleClicked(void) +bool ViewProviderBase::doubleClicked() { // If the Placement is mutable then open the transform panel. // If the Placement can't be modified then just do nothing on double-click. @@ -85,7 +85,7 @@ bool ViewProviderBase::setEdit(int ModNum) if (!base->Placement.testStatus(App::Property::Immutable) && !base->Placement.testStatus(App::Property::ReadOnly) && !base->Placement.testStatus(App::Property::Hidden)) { - return PartGui::ViewProviderPart::setEdit(ModNum); + return PartGui::ViewProviderPart::setEdit(ModNum); // clazy:exclude=skipped-base-method } return false; @@ -93,5 +93,5 @@ bool ViewProviderBase::setEdit(int ModNum) void ViewProviderBase::unsetEdit(int ModNum) { - PartGui::ViewProviderPart::unsetEdit(ModNum); + PartGui::ViewProviderPart::unsetEdit(ModNum); // clazy:exclude=skipped-base-method } diff --git a/src/Mod/PartDesign/Gui/ViewProviderBase.h b/src/Mod/PartDesign/Gui/ViewProviderBase.h index 6158fc99b0..e2b79c823c 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBase.h +++ b/src/Mod/PartDesign/Gui/ViewProviderBase.h @@ -30,20 +30,20 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderBase : public ViewProvider { - PROPERTY_HEADER(PartDesignGui::ViewProviderBase); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderBase); public: /// constructor ViewProviderBase(); /// destructor - virtual ~ViewProviderBase(); + ~ViewProviderBase() override; - virtual bool doubleClicked(void); - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member); + bool doubleClicked() override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/ViewProviderBody.cpp b/src/Mod/PartDesign/Gui/ViewProviderBody.cpp index ce5ac372cf..9c564aa1a5 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBody.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBody.cpp @@ -133,10 +133,10 @@ void ViewProviderBody::setupContextMenu(QMenu* menu, QObject* receiver, const ch QAction* act = menu->addAction(tr("Toggle active body")); func->trigger(act, std::bind(&ViewProviderBody::doubleClicked, this)); - Gui::ViewProviderGeometryObject::setupContextMenu(menu, receiver, member); + Gui::ViewProviderGeometryObject::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method } -bool ViewProviderBody::doubleClicked(void) +bool ViewProviderBody::doubleClicked() { //first, check if the body is already active. auto activeDoc = Gui::Application::Instance->activeDocument(); @@ -442,7 +442,7 @@ void ViewProviderBody::setVisualBodyMode(bool bodymode) { } } -std::vector< std::string > ViewProviderBody::getDisplayModes(void) const { +std::vector< std::string > ViewProviderBody::getDisplayModes() const { //we get all display modes and remove the "Group" mode, as this is what we use for "Through" //body display mode @@ -477,7 +477,7 @@ bool ViewProviderBody::canDropObject(App::DocumentObject* obj) const App::Part *actPart = PartDesignGui::getActivePart(); App::Part* partOfBaseFeature = App::Part::getPartOfObject(obj); - if (partOfBaseFeature != nullptr && partOfBaseFeature != actPart) + if (partOfBaseFeature && partOfBaseFeature != actPart) return false; return true; @@ -505,7 +505,7 @@ void ViewProviderBody::dropObject(App::DocumentObject* obj) e.ReportException(); } } - else if (body->BaseFeature.getValue() == nullptr) { + else if (!body->BaseFeature.getValue()) { body->BaseFeature.setValue(obj); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderBody.h b/src/Mod/PartDesign/Gui/ViewProviderBody.h index 3650857d2f..f677ea894c 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBody.h +++ b/src/Mod/PartDesign/Gui/ViewProviderBody.h @@ -50,25 +50,25 @@ public: /// constructor ViewProviderBody(); /// destructor - virtual ~ViewProviderBody(); + ~ViewProviderBody() override; App::PropertyEnumeration DisplayModeBody; - virtual void attach(App::DocumentObject *) override; + void attach(App::DocumentObject *) override; - virtual bool doubleClicked(void) override; - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool doubleClicked(void) override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; - virtual std::vector< std::string > getDisplayModes(void) const override; - virtual void setDisplayMode(const char* ModeName) override; - virtual void setOverrideMode(const std::string& mode) override; + std::vector< std::string > getDisplayModes(void) const override; + void setDisplayMode(const char* ModeName) override; + void setOverrideMode(const std::string& mode) override; - virtual bool onDelete(const std::vector &) override; + bool onDelete(const std::vector &) override; /// Update the children's highlighting when triggered - virtual void updateData(const App::Property* prop) override; + void updateData(const App::Property* prop) override; ///unify children visuals - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; /// Update the sizes of origin and datums void updateOriginDatumSize (); @@ -80,11 +80,11 @@ public: SbBox3f getBoundBox (); /** Check whether objects can be added to the view provider by drag and drop */ - virtual bool canDropObjects() const override; + bool canDropObjects() const override; /** Check whether the object can be dropped to the view provider by drag and drop */ - virtual bool canDropObject(App::DocumentObject*) const override; + bool canDropObject(App::DocumentObject*) const override; /** Add an object to the view provider by drag and drop */ - virtual void dropObject(App::DocumentObject*) override; + void dropObject(App::DocumentObject*) override; protected: void slotChangedObjectApp ( const App::DocumentObject& obj, const App::Property& prop ); diff --git a/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp b/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp index 34ee485969..e997424d36 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderBoolean.cpp @@ -103,7 +103,7 @@ bool ViewProviderBoolean::setEdit(int ModNum) return true; } else { - return PartGui::ViewProviderPart::setEdit(ModNum); + return PartGui::ViewProviderPart::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderBoolean.h b/src/Mod/PartDesign/Gui/ViewProviderBoolean.h index 37ab9516f8..854f22d677 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderBoolean.h +++ b/src/Mod/PartDesign/Gui/ViewProviderBoolean.h @@ -40,19 +40,19 @@ public: /// constructor ViewProviderBoolean(); /// destructor - virtual ~ViewProviderBoolean(); + ~ViewProviderBoolean() override; App::PropertyEnumeration Display; /// grouping handling void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual bool onDelete(const std::vector &) override; - virtual void attach(App::DocumentObject*) override; - virtual void onChanged(const App::Property* prop) override; + bool onDelete(const std::vector &) override; + void attach(App::DocumentObject*) override; + void onChanged(const App::Property* prop) override; protected: - virtual bool setEdit(int ModNum) override; + bool setEdit(int ModNum) override; static const char* DisplayEnum[]; diff --git a/src/Mod/PartDesign/Gui/ViewProviderChamfer.h b/src/Mod/PartDesign/Gui/ViewProviderChamfer.h index 680f2ea7a3..6abcd4cc9c 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderChamfer.h +++ b/src/Mod/PartDesign/Gui/ViewProviderChamfer.h @@ -32,7 +32,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderChamfer : public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderChamfer) - PROPERTY_HEADER(PartDesignGui::ViewProviderChamfer); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderChamfer); public: /// constructor @@ -41,11 +41,11 @@ public: menuName = tr("Chamfer parameters");} /// return "Chamfer" - virtual const std::string & featureName() const; + const std::string & featureName() const override; protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp b/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp index ff417cbd31..515c1825e4 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDatum.cpp @@ -107,7 +107,7 @@ void ViewProviderDatum::attach(App::DocumentObject *obj) App::DocumentObject* o = getObject(); if (o->getTypeId() == PartDesign::Plane::getClassTypeId()) { datumType = QString::fromLatin1("Plane"); - datumText = QObject::tr("Plane"); + datumText = QObject::tr("Plane"); datumMenuText = tr("Datum Plane parameters"); } else if (o->getTypeId() == PartDesign::Line::getClassTypeId()) { @@ -158,7 +158,7 @@ bool ViewProviderDatum::onDelete(const std::vector &) return true; } -std::vector ViewProviderDatum::getDisplayModes(void) const +std::vector ViewProviderDatum::getDisplayModes() const { return { "Base" }; } @@ -214,7 +214,7 @@ SoDetail* ViewProviderDatum::getDetail(const char* subelement) const return nullptr; } -bool ViewProviderDatum::isSelectable(void) const +bool ViewProviderDatum::isSelectable() const { return true; } @@ -272,7 +272,7 @@ bool ViewProviderDatum::setEdit(int ModNum) } } -bool ViewProviderDatum::doubleClicked(void) +bool ViewProviderDatum::doubleClicked() { auto activeDoc = Gui::Application::Instance->activeDocument(); if(!activeDoc) @@ -289,7 +289,7 @@ bool ViewProviderDatum::doubleClicked(void) PartDesign::Body* activeBody = activeView->getActiveObject(PDBODYKEY); auto datumBody = PartDesignGui::getBodyFor(pcDatum, false); - if (datumBody != nullptr) { + if (datumBody) { if (datumBody != activeBody) { Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.ActiveView.setActiveObject('%s',%s)", diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatum.h b/src/Mod/PartDesign/Gui/ViewProviderDatum.h index 8fe61fb1b0..76af19a279 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatum.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatum.h @@ -42,29 +42,29 @@ class PartDesignGuiExport ViewProviderDatum : public Gui::ViewProviderGeometryOb { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderDatum) PROPERTY_HEADER_WITH_EXTENSIONS(PartDesignGui::ViewProviderDatum); - + public: /// constructor ViewProviderDatum(); /// destructor - virtual ~ViewProviderDatum(); + ~ViewProviderDatum() override; /// grouping handling void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual void attach(App::DocumentObject *) override; - virtual bool onDelete(const std::vector &) override; - virtual bool doubleClicked(void) override; + void attach(App::DocumentObject *) override; + bool onDelete(const std::vector &) override; + bool doubleClicked(void) override; std::vector getDisplayModes(void) const override; void setDisplayMode(const char* ModeName) override; /// indicates if the ViewProvider use the new Selection model - virtual bool useNewSelectionModel(void) const override { return true; } + bool useNewSelectionModel(void) const override { return true; } /// indicates if the ViewProvider can be selected - virtual bool isSelectable(void) const override; + bool isSelectable(void) const override; /// return a hit element to the selection path or 0 - virtual std::string getElement(const SoDetail *) const override; - virtual SoDetail* getDetail(const char*) const override; + std::string getElement(const SoDetail *) const override; + SoDetail* getDetail(const char*) const override; /** * Enable/Disable the selectability of the datum @@ -91,7 +91,7 @@ public: /// The datum type (Plane, Line or Point) // TODO remove this attribute (2015-09-08, Fat-Zer) QString datumType; - QString datumText; + QString datumText; QString datumMenuText; /** @@ -114,8 +114,8 @@ public: static double marginFactor () { return 0.1; }; protected: - virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; /** * Guesses the context this datum belongs to and returns appropriate bounding box of all diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h b/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h index 8e8a385e2a..0441a9db9a 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumCS.h @@ -38,7 +38,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderDatumCoordinateSystem : public PartDesignGui::ViewProviderDatum { - PROPERTY_HEADER(PartDesignGui::ViewProviderDatumCoordinateSystem); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumCoordinateSystem); public: App::PropertyFloatConstraint Zoom; @@ -47,16 +47,16 @@ public: /// Constructor ViewProviderDatumCoordinateSystem(); - virtual ~ViewProviderDatumCoordinateSystem(); + ~ViewProviderDatumCoordinateSystem() override; - virtual void attach ( App::DocumentObject *obj ); - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property*); + void attach ( App::DocumentObject *obj ) override; + void updateData(const App::Property*) override; + void onChanged(const App::Property*) override; - virtual void setExtents (Base::BoundBox3d bbox); + void setExtents (Base::BoundBox3d bbox) override; - virtual SoDetail* getDetail(const char* subelement) const; - virtual std::string getElement(const SoDetail* detail) const; + SoDetail* getDetail(const char* subelement) const override; + std::string getElement(const SoDetail* detail) const override; private: void setupLabels(); diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h b/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h index fde0c63ae0..c43a428dbb 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumLine.h @@ -33,17 +33,17 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderDatumLine : public PartDesignGui::ViewProviderDatum { - PROPERTY_HEADER(PartDesignGui::ViewProviderDatumLine); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumLine); public: /// Constructor ViewProviderDatumLine(); - virtual ~ViewProviderDatumLine(); + ~ViewProviderDatumLine() override; - virtual void attach ( App::DocumentObject *obj ); - virtual void updateData(const App::Property*); + void attach ( App::DocumentObject *obj ) override; + void updateData(const App::Property*) override; - void setExtents (Base::BoundBox3d bbox); + void setExtents (Base::BoundBox3d bbox) override; void setExtents(double l); private: diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h b/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h index 3aa3ff28fc..2540ff8645 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumPlane.h @@ -31,17 +31,17 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderDatumPlane : public PartDesignGui::ViewProviderDatum { - PROPERTY_HEADER(PartDesignGui::ViewProviderDatumPlane); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumPlane); public: /// Constructor ViewProviderDatumPlane(); - virtual ~ViewProviderDatumPlane(); + ~ViewProviderDatumPlane() override; - virtual void attach ( App::DocumentObject *obj ); - virtual void updateData(const App::Property*); + void attach ( App::DocumentObject *obj ) override; + void updateData(const App::Property*) override; - void setExtents (Base::BoundBox3d bbox); + void setExtents (Base::BoundBox3d bbox) override; void setExtents(double l, double w); private: diff --git a/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h b/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h index 1df7d03981..910dc64b56 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDatumPoint.h @@ -31,19 +31,19 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderDatumPoint : public PartDesignGui::ViewProviderDatum { - PROPERTY_HEADER(PartDesignGui::ViewProviderDatumPoint); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDatumPoint); public: /// Constructor ViewProviderDatumPoint(); - virtual ~ViewProviderDatumPoint(); + ~ViewProviderDatumPoint() override; - virtual void attach ( App::DocumentObject *obj ); + void attach ( App::DocumentObject *obj ) override; // Note: don't overload setExtents () here because point doesn't really depends on it protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; } // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/ViewProviderDraft.h b/src/Mod/PartDesign/Gui/ViewProviderDraft.h index 472feab588..eacf1a4a07 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDraft.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDraft.h @@ -33,7 +33,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderDraft : public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderDraft) - PROPERTY_HEADER(PartDesignGui::ViewProviderDraft); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDraft); public: /// constructor @@ -42,11 +42,11 @@ public: menuName = tr("Draft parameters"); } /// return "Draft" - virtual const std::string & featureName() const; + const std::string & featureName() const override; protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; } // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp b/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp index 0b1643fe74..2dfc60755e 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderDressUp.cpp @@ -86,11 +86,11 @@ void ViewProviderDressUp::highlightReferences(const bool on) { PartDesign::DressUp* pcDressUp = static_cast(getObject()); Part::Feature* base = pcDressUp->getBaseObject (/*silent =*/ true); - if (base == nullptr) + if (!base) return; PartGui::ViewProviderPart* vp = dynamic_cast( Gui::Application::Instance->getViewProvider(base)); - if (vp == nullptr) + if (!vp) return; std::vector faces = pcDressUp->Base.getSubValuesStartsWith("Face"); diff --git a/src/Mod/PartDesign/Gui/ViewProviderDressUp.h b/src/Mod/PartDesign/Gui/ViewProviderDressUp.h index 3c5c404c9d..b004537874 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderDressUp.h +++ b/src/Mod/PartDesign/Gui/ViewProviderDressUp.h @@ -34,18 +34,18 @@ class TaskDlgDressUpParameters; class PartDesignGuiExport ViewProviderDressUp : public ViewProvider { - PROPERTY_HEADER(PartDesignGui::ViewProviderDressUp); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderDressUp); public: /// constructor ViewProviderDressUp() {} /// destructor - virtual ~ViewProviderDressUp() + ~ViewProviderDressUp() override {} /// grouping handling - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; /// Highlight the references that have been selected void highlightReferences(const bool on); @@ -58,7 +58,7 @@ public: QString menuName; protected: - virtual bool setEdit(int ModNum); + bool setEdit(int ModNum) override; private: std::vector originalFaceColors; diff --git a/src/Mod/PartDesign/Gui/ViewProviderFillet.h b/src/Mod/PartDesign/Gui/ViewProviderFillet.h index 25d380520c..1a8940ad6c 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderFillet.h +++ b/src/Mod/PartDesign/Gui/ViewProviderFillet.h @@ -32,7 +32,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderFillet : public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderFillet) - PROPERTY_HEADER(PartDesignGui::ViewProviderFillet); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderFillet); public: /// constructor @@ -41,11 +41,11 @@ public: menuName = tr("Fillet parameters"); } /// return "Fillet" - virtual const std::string & featureName() const; + const std::string & featureName() const override; protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; } // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/ViewProviderGroove.h b/src/Mod/PartDesign/Gui/ViewProviderGroove.h index 307d52a59c..3412b232f8 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderGroove.h +++ b/src/Mod/PartDesign/Gui/ViewProviderGroove.h @@ -31,22 +31,22 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderGroove : public ViewProviderSketchBased { - PROPERTY_HEADER(PartDesignGui::ViewProviderGroove); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderGroove); public: /// constructor ViewProviderGroove(); /// destructor - virtual ~ViewProviderGroove(); + ~ViewProviderGroove() override; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /** * Returns a newly created TaskDlgRevolutionParameters * NOTE: as for now groove and revolution share the dialog implementation */ - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp b/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp index 764fcdd519..79c2fbc6ed 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderHelix.cpp @@ -93,7 +93,7 @@ void ViewProviderHelix::unsetEdit(int ModNum) std::vector ViewProviderHelix::claimChildren(void) const { std::vector temp; App::DocumentObject* sketch = static_cast(getObject())->Profile.getValue(); - if (sketch != nullptr && sketch->isDerivedFrom(Part::Part2DObject::getClassTypeId())) + if (sketch && sketch->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(sketch); return temp; diff --git a/src/Mod/PartDesign/Gui/ViewProviderHelix.h b/src/Mod/PartDesign/Gui/ViewProviderHelix.h index 83dd7d6d55..716fdfc6ed 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHelix.h +++ b/src/Mod/PartDesign/Gui/ViewProviderHelix.h @@ -31,28 +31,28 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderHelix : public ViewProviderAddSub { - PROPERTY_HEADER(PartDesignGui::ViewProviderHelix); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderHelix); public: /// constructor ViewProviderHelix(); /// destructor - virtual ~ViewProviderHelix(); + ~ViewProviderHelix() override; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; /// grouping handling - std::vector claimChildren(void)const; + std::vector claimChildren(void)const override; - virtual bool onDelete(const std::vector &); + bool onDelete(const std::vector &) override; protected: - virtual QIcon getIcon(void) const; + QIcon getIcon(void) const override; /// Returns a newly created TaskDlgHelixParameters - virtual TaskDlgFeatureParameters *getEditDialog(); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + TaskDlgFeatureParameters *getEditDialog() override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderHole.cpp b/src/Mod/PartDesign/Gui/ViewProviderHole.cpp index cb13be44c9..f9e579d460 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHole.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderHole.cpp @@ -50,7 +50,7 @@ ViewProviderHole::~ViewProviderHole() { } -std::vector ViewProviderHole::claimChildren(void)const +std::vector ViewProviderHole::claimChildren()const { std::vector temp; temp.push_back(static_cast(getObject())->Profile.getValue()); @@ -61,7 +61,7 @@ std::vector ViewProviderHole::claimChildren(void)const void ViewProviderHole::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { addDefaultAction(menu, QObject::tr("Edit hole")); - PartGui::ViewProviderPart::setupContextMenu(menu, receiver, member); + PartGui::ViewProviderPart::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method } bool ViewProviderHole::setEdit(int ModNum) @@ -102,7 +102,7 @@ bool ViewProviderHole::setEdit(int ModNum) return true; } else { - return PartGui::ViewProviderPart::setEdit(ModNum); + return PartGui::ViewProviderPart::setEdit(ModNum); // clazy:exclude=skipped-base-method } } diff --git a/src/Mod/PartDesign/Gui/ViewProviderHole.h b/src/Mod/PartDesign/Gui/ViewProviderHole.h index 9a56cc6e19..c0c7c47086 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderHole.h +++ b/src/Mod/PartDesign/Gui/ViewProviderHole.h @@ -31,20 +31,20 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderHole : public ViewProvider { - PROPERTY_HEADER(PartDesignGui::ViewProviderHole); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderHole); public: /// constructor ViewProviderHole(); /// destructor - virtual ~ViewProviderHole(); + ~ViewProviderHole() override; /// grouping handling - std::vector claimChildren(void)const; - void setupContextMenu(QMenu *menu, QObject *receiver, const char *member); - bool onDelete(const std::vector &s); + std::vector claimChildren()const override; + void setupContextMenu(QMenu *menu, QObject *receiver, const char *member) override; + bool onDelete(const std::vector &s) override; protected: - bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h b/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h index 9380a0bdf6..2cc3537607 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h +++ b/src/Mod/PartDesign/Gui/ViewProviderLinearPattern.h @@ -31,7 +31,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderLinearPattern : public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderLinearPattern) - PROPERTY_HEADER(PartDesignGui::ViewProviderLinearPattern); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderLinearPattern); public: ViewProviderLinearPattern() { featureName = std::string("LinearPattern"); @@ -40,7 +40,7 @@ public: protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp b/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp index e1cc9732fe..27917d3eaf 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderLoft.cpp @@ -47,18 +47,18 @@ ViewProviderLoft::~ViewProviderLoft() { } -std::vector ViewProviderLoft::claimChildren(void)const +std::vector ViewProviderLoft::claimChildren()const { std::vector temp; PartDesign::Loft* pcLoft = static_cast(getObject()); App::DocumentObject* sketch = pcLoft->getVerifiedSketch(true); - if (sketch != nullptr) + if (sketch) temp.push_back(sketch); for(App::DocumentObject* obj : pcLoft->Sections.getValues()) { - if (obj != nullptr && obj->isDerivedFrom(Part::Part2DObject::getClassTypeId())) + if (obj && obj->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(obj); } @@ -118,7 +118,7 @@ void ViewProviderLoft::highlightSection(bool on) { PartDesign::Loft* pcLoft = static_cast(getObject()); auto sections = pcLoft->Sections.getSubListValues(); - for (auto it : sections) { + for (auto& it : sections) { // only take the entire shape when we have a sketch selected, but // not a point of the sketch auto subName = it.second.empty() ? "" : it.second.front(); @@ -173,7 +173,7 @@ void ViewProviderLoft::highlightReferences(Part::Feature* base, const std::vecto } } -QIcon ViewProviderLoft::getIcon(void) const { +QIcon ViewProviderLoft::getIcon() const { QString str = QString::fromLatin1("PartDesign_"); auto* prim = static_cast(getObject()); if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) diff --git a/src/Mod/PartDesign/Gui/ViewProviderLoft.h b/src/Mod/PartDesign/Gui/ViewProviderLoft.h index 7c4dd1ec33..910a485dfa 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderLoft.h +++ b/src/Mod/PartDesign/Gui/ViewProviderLoft.h @@ -30,7 +30,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderLoft : public ViewProviderAddSub { - PROPERTY_HEADER(PartDesignGui::ViewProviderLoft); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderLoft); public: enum Reference { @@ -42,22 +42,22 @@ public: /// constructor ViewProviderLoft(); /// destructor - virtual ~ViewProviderLoft(); + ~ViewProviderLoft() override; /// grouping handling - std::vector claimChildren(void)const; - void setupContextMenu(QMenu*, QObject*, const char*); + std::vector claimChildren(void)const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual bool onDelete(const std::vector &); + bool onDelete(const std::vector &) override; void highlightProfile(bool on); void highlightSection(bool on); void highlightReferences(Reference mode, bool on); protected: - virtual QIcon getIcon(void) const; - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual TaskDlgFeatureParameters* getEditDialog(); + QIcon getIcon(void) const override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; + TaskDlgFeatureParameters* getEditDialog() override; private: void highlightReferences(Part::Feature*, const std::vector&, bool); diff --git a/src/Mod/PartDesign/Gui/ViewProviderMirrored.h b/src/Mod/PartDesign/Gui/ViewProviderMirrored.h index 9460852feb..8657eb7f5d 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMirrored.h +++ b/src/Mod/PartDesign/Gui/ViewProviderMirrored.h @@ -31,7 +31,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderMirrored : public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGuii::ViewProviderMirrored) - PROPERTY_HEADER(PartDesignGui::ViewProviderMirrored); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderMirrored); public: ViewProviderMirrored() { featureName = std::string("Mirrored"); @@ -41,7 +41,7 @@ public: protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp index 884d28ca4c..2ee4d174a7 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.cpp @@ -40,13 +40,13 @@ TaskDlgFeatureParameters *ViewProviderMultiTransform::getEditDialog() { void ViewProviderMultiTransform::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { this->addDefaultAction(menu, QObject::tr("Edit %1").arg(QString::fromStdString(featureName))); - PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); + PartDesignGui::ViewProvider::setupContextMenu(menu, receiver, member); // clazy:exclude=skipped-base-method } -std::vector ViewProviderMultiTransform::claimChildren(void) const +std::vector ViewProviderMultiTransform::claimChildren() const { PartDesign::MultiTransform* pcMultiTransform = static_cast(getObject()); - if (pcMultiTransform == nullptr) + if (!pcMultiTransform) return std::vector(); // TODO: Show error? std::vector transformFeatures = pcMultiTransform->Transformations.getValues(); diff --git a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h index 64cf6d42a8..18fccfbe58 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h +++ b/src/Mod/PartDesign/Gui/ViewProviderMultiTransform.h @@ -31,7 +31,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderMultiTransform : public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderMultiTransform) - PROPERTY_HEADER(PartDesignGui::ViewProviderMultiTransform); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderMultiTransform); public: ViewProviderMultiTransform() { featureName = std::string("MultiTransform"); @@ -39,14 +39,14 @@ public: sPixmap = "PartDesign_MultiTransform.svg"; } - std::vector claimChildren(void) const; - void setupContextMenu(QMenu*, QObject*, const char*); + std::vector claimChildren() const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual bool onDelete(const std::vector &); + bool onDelete(const std::vector &) override; protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderPad.h b/src/Mod/PartDesign/Gui/ViewProviderPad.h index f4465015d1..cdc3a8a2b6 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPad.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPad.h @@ -30,19 +30,19 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderPad : public ViewProviderSketchBased { - PROPERTY_HEADER(PartDesignGui::ViewProviderPad); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPad); public: /// constructor ViewProviderPad(); /// destructor - virtual ~ViewProviderPad(); + ~ViewProviderPad() override; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly created TaskDlgPadParameters - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp b/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp index cf102a4fed..a13319096c 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPipe.cpp @@ -47,27 +47,27 @@ ViewProviderPipe::~ViewProviderPipe() { } -std::vector ViewProviderPipe::claimChildren(void)const +std::vector ViewProviderPipe::claimChildren()const { std::vector temp; PartDesign::Pipe* pcPipe = static_cast(getObject()); App::DocumentObject* sketch = pcPipe->getVerifiedSketch(true); - if (sketch != nullptr) + if (sketch) temp.push_back(sketch); for(App::DocumentObject* obj : pcPipe->Sections.getValues()) { - if (obj != nullptr && obj->isDerivedFrom(Part::Part2DObject::getClassTypeId())) + if (obj && obj->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(obj); } App::DocumentObject* spine = pcPipe->Spine.getValue(); - if (spine != nullptr && spine->isDerivedFrom(Part::Part2DObject::getClassTypeId())) + if (spine && spine->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(spine); App::DocumentObject* auxspine = pcPipe->AuxillerySpine.getValue(); - if (auxspine != nullptr && auxspine->isDerivedFrom(Part::Part2DObject::getClassTypeId())) + if (auxspine && auxspine->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(auxspine); return temp; @@ -174,7 +174,7 @@ void ViewProviderPipe::highlightReferences(Part::Feature* base, const std::vecto } } -QIcon ViewProviderPipe::getIcon(void) const { +QIcon ViewProviderPipe::getIcon() const { QString str = QString::fromLatin1("PartDesign_"); auto* prim = static_cast(getObject()); if(prim->getAddSubType() == PartDesign::FeatureAddSub::Additive) diff --git a/src/Mod/PartDesign/Gui/ViewProviderPipe.h b/src/Mod/PartDesign/Gui/ViewProviderPipe.h index 182cfcb109..70b69ba707 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPipe.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPipe.h @@ -30,7 +30,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderPipe : public ViewProviderAddSub { - PROPERTY_HEADER(PartDesignGui::ViewProviderPipe); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPipe); public: enum Reference { @@ -43,22 +43,22 @@ public: /// constructor ViewProviderPipe(); /// destructor - virtual ~ViewProviderPipe(); + ~ViewProviderPipe() override; /// grouping handling - std::vector claimChildren(void)const; - void setupContextMenu(QMenu*, QObject*, const char*); + std::vector claimChildren()const override; + void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual bool onDelete(const std::vector &); + bool onDelete(const std::vector &) override; void highlightReferences(Reference mode, bool on); protected: - virtual QIcon getIcon(void) const; - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + QIcon getIcon() const override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; /// Returns a newly created TaskDlgPipeParameters - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; private: void highlightReferences(Part::Feature*, const std::vector&, bool); diff --git a/src/Mod/PartDesign/Gui/ViewProviderPocket.h b/src/Mod/PartDesign/Gui/ViewProviderPocket.h index 9b22c2cc03..d51381e933 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPocket.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPocket.h @@ -31,19 +31,19 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderPocket : public ViewProviderSketchBased { - PROPERTY_HEADER(PartDesignGui::ViewProviderPocket); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPocket); public: /// constructor ViewProviderPocket(); /// destructor - virtual ~ViewProviderPocket(); + ~ViewProviderPocket() override; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly created TaskDlgPocketParameters - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h b/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h index dd8bb9b5b0..e00b4d32fb 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPolarPattern.h @@ -31,7 +31,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderPolarPattern : public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderPolarPattern) - PROPERTY_HEADER(PartDesignGui::ViewProviderPolarPattern); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPolarPattern); public: ViewProviderPolarPattern() { featureName = std::string("PolarPattern"); @@ -41,7 +41,7 @@ public: protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp index 27ebe48b3d..72d4cbecf1 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.cpp @@ -117,7 +117,7 @@ void ViewProviderPrimitive::updateData(const App::Property* p) { PartDesignGui::ViewProviderAddSub::updateData(p); } -QIcon ViewProviderPrimitive::getIcon(void) const { +QIcon ViewProviderPrimitive::getIcon() const { QString str = QString::fromLatin1("PartDesign_"); auto* prim = static_cast(getObject()); diff --git a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h index 37a1975cd2..f3fbb2944f 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h +++ b/src/Mod/PartDesign/Gui/ViewProviderPrimitive.h @@ -30,22 +30,22 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderPrimitive : public ViewProviderAddSub { - PROPERTY_HEADER(PartDesignGui::ViewProviderPrimitive); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderPrimitive); public: /// constructor ViewProviderPrimitive(); /// destructor - virtual ~ViewProviderPrimitive(); + ~ViewProviderPrimitive() override; - virtual void attach(App::DocumentObject*); - virtual void updateData(const App::Property*); + void attach(App::DocumentObject*) override; + void updateData(const App::Property*) override; protected: - virtual QIcon getIcon(void) const; - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + QIcon getIcon(void) const override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; void updateAddSubShapeIndicator(); diff --git a/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp b/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp index 0c01560189..5f3d0730ce 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderPyImp.cpp @@ -32,7 +32,7 @@ using namespace PartDesignGui; // returns a string which represent the object e.g. when printed in python -std::string ViewProviderPy::representation(void) const +std::string ViewProviderPy::representation() const { return std::string(""); } diff --git a/src/Mod/PartDesign/Gui/ViewProviderRevolution.h b/src/Mod/PartDesign/Gui/ViewProviderRevolution.h index dcafe4115c..23e2c2f548 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderRevolution.h +++ b/src/Mod/PartDesign/Gui/ViewProviderRevolution.h @@ -31,19 +31,19 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderRevolution : public ViewProviderSketchBased { - PROPERTY_HEADER(PartDesignGui::ViewProviderRevolution); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderRevolution); public: /// constructor ViewProviderRevolution(); /// destructor - virtual ~ViewProviderRevolution(); + ~ViewProviderRevolution() override; - void setupContextMenu(QMenu*, QObject*, const char*); + void setupContextMenu(QMenu*, QObject*, const char*) override; protected: /// Returns a newly created TaskDlgRevolutionParameters - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderScaled.h b/src/Mod/PartDesign/Gui/ViewProviderScaled.h index da3fcf53ff..b14d5f38a8 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderScaled.h +++ b/src/Mod/PartDesign/Gui/ViewProviderScaled.h @@ -31,7 +31,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderScaled : public ViewProviderTransformed { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderScaled) - PROPERTY_HEADER(PartDesignGui::ViewProviderScaled); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderScaled); public: ViewProviderScaled() { featureName = std::string("Scaled"); @@ -41,7 +41,7 @@ public: protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp index 36fdad51f6..3cef2ae9c4 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.cpp @@ -144,7 +144,7 @@ void ViewProviderShapeBinder::highlightReferences(bool on) PartGui::ViewProviderPart* svp = dynamic_cast( Gui::Application::Instance->getViewProvider(obj)); - if (svp == nullptr) + if (!svp) return; if (on) { @@ -160,7 +160,7 @@ void ViewProviderShapeBinder::highlightReferences(bool on) std::vector fcolors = originalFaceColors; fcolors.resize(eMap.Extent(), svp->ShapeColor.getValue()); - for (std::string e : subs) { + for (const std::string& e : subs) { // Note: stoi may throw, but it strictly shouldn't happen if (e.compare(0, 4, "Edge") == 0) { int idx = std::stoi(e.substr(4)) - 1; @@ -280,7 +280,7 @@ std::string ViewProviderSubShapeBinder::dropObjectEx(App::DocumentObject* obj, A values[owner ? owner : obj] = elements; else { std::vector subs; - if (elements.size()) { + if (!elements.empty()) { subs.reserve(elements.size()); for (auto& element : elements) subs.push_back(sub + element); @@ -330,7 +330,7 @@ bool ViewProviderSubShapeBinder::setEdit(int ModNum) { if (!obj || !obj->getNameInDocument()) continue; const auto& subs = link.getSubValues(); - if (subs.size()) + if (!subs.empty()) Gui::Selection().addSelections(obj->getDocument()->getName(), obj->getNameInDocument(), subs); else @@ -355,7 +355,7 @@ void ViewProviderSubShapeBinder::updatePlacement(bool transaction) { bool relative = self->Relative.getValue(); App::DocumentObject* parent = nullptr; std::string parentSub; - if (relative && self->getParents().size()) { + if (relative && !self->getParents().empty()) { const auto& sel = Gui::Selection().getSelection("", Gui::ResolveMode::NoResolve); if (sel.size() != 1 || !sel[0].pObject || sel[0].pObject->getSubObject(sel[0].SubName) != self) diff --git a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h index 6af3f70e8b..a4492b4de8 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h +++ b/src/Mod/PartDesign/Gui/ViewProviderShapeBinder.h @@ -36,14 +36,14 @@ class PartDesignGuiExport ViewProviderShapeBinder : public PartGui::ViewProvider public: /// Constructor ViewProviderShapeBinder(); - virtual ~ViewProviderShapeBinder(); + ~ViewProviderShapeBinder() override; void setupContextMenu(QMenu*, QObject*, const char*) override; void highlightReferences(bool on); protected: - virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; private: std::vector originalLineColors; @@ -67,13 +67,13 @@ public: const char *subname, const std::vector &elements) const override; std::string dropObjectEx(App::DocumentObject*, App::DocumentObject*, const char *, const std::vector &) override; - std::vector claimChildren(void) const override; + std::vector claimChildren() const override; - virtual bool doubleClicked() override; - virtual void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; - virtual bool setEdit(int ModNum) override; - virtual void attach(App::DocumentObject *obj) override; - virtual void onChanged(const App::Property *prop) override; + bool doubleClicked() override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; + bool setEdit(int ModNum) override; + void attach(App::DocumentObject *obj) override; + void onChanged(const App::Property *prop) override; private: enum { diff --git a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp index 341b22ae93..5a596c6caa 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp +++ b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.cpp @@ -45,10 +45,10 @@ ViewProviderSketchBased::~ViewProviderSketchBased() } -std::vector ViewProviderSketchBased::claimChildren(void) const { +std::vector ViewProviderSketchBased::claimChildren() const { std::vector temp; App::DocumentObject* sketch = static_cast(getObject())->Profile.getValue(); - if (sketch != nullptr && sketch->isDerivedFrom(Part::Part2DObject::getClassTypeId())) + if (sketch && sketch->isDerivedFrom(Part::Part2DObject::getClassTypeId())) temp.push_back(sketch); return temp; diff --git a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h index 5478d1a869..5f4fb54c01 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h +++ b/src/Mod/PartDesign/Gui/ViewProviderSketchBased.h @@ -32,18 +32,18 @@ namespace PartDesignGui { */ class PartDesignGuiExport ViewProviderSketchBased : public ViewProvider { - PROPERTY_HEADER(PartDesignGui::ViewProviderSketchBased); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderSketchBased); public: /// constructor ViewProviderSketchBased(); /// destructor - virtual ~ViewProviderSketchBased(); + ~ViewProviderSketchBased() override; /// grouping handling - std::vector claimChildren(void)const; + std::vector claimChildren()const override; - virtual bool onDelete(const std::vector &); + bool onDelete(const std::vector &) override; }; diff --git a/src/Mod/PartDesign/Gui/ViewProviderThickness.h b/src/Mod/PartDesign/Gui/ViewProviderThickness.h index 6ce2e9f00d..339f10c793 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderThickness.h +++ b/src/Mod/PartDesign/Gui/ViewProviderThickness.h @@ -32,7 +32,7 @@ namespace PartDesignGui { class PartDesignGuiExport ViewProviderThickness : public ViewProviderDressUp { Q_DECLARE_TR_FUNCTIONS(PartDesignGui::ViewProviderThickness) - PROPERTY_HEADER(PartDesignGui::ViewProviderThickness); + PROPERTY_HEADER_WITH_OVERRIDE(PartDesignGui::ViewProviderThickness); public: /// constructor @@ -41,11 +41,11 @@ public: menuName = tr("Thickness parameters"); } /// return "Thickness" - virtual const std::string & featureName() const; + const std::string & featureName() const override; protected: /// Returns a newly create dialog for the part to be placed in the task view - virtual TaskDlgFeatureParameters *getEditDialog(); + TaskDlgFeatureParameters *getEditDialog() override; }; } // namespace PartDesignGui diff --git a/src/Mod/PartDesign/Gui/ViewProviderTransformed.h b/src/Mod/PartDesign/Gui/ViewProviderTransformed.h index 9c262e54df..6afa144049 100644 --- a/src/Mod/PartDesign/Gui/ViewProviderTransformed.h +++ b/src/Mod/PartDesign/Gui/ViewProviderTransformed.h @@ -39,12 +39,12 @@ public: ViewProviderTransformed() : featureName("undefined"), pcRejectedRoot(nullptr) {} /// destructor - virtual ~ViewProviderTransformed() + ~ViewProviderTransformed() override {} void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual bool onDelete(const std::vector &) override; + bool onDelete(const std::vector &) override; /// signals if the transformation contains errors boost::signals2::signal signalDiagnosis; @@ -54,11 +54,11 @@ public: // Name of menu dialog QString menuName; - virtual Gui::ViewProvider *startEditing(int ModNum=0) override; + Gui::ViewProvider *startEditing(int ModNum=0) override; protected: - virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; bool checkDlgOpen(TaskDlgTransformedParameters* transformedDlg); diff --git a/src/Mod/PartDesign/Gui/Workbench.cpp b/src/Mod/PartDesign/Gui/Workbench.cpp index 5dc1392e94..183fa9d413 100644 --- a/src/Mod/PartDesign/Gui/Workbench.cpp +++ b/src/Mod/PartDesign/Gui/Workbench.cpp @@ -169,7 +169,7 @@ void Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) con { auto selection = Gui::Selection().getSelection(); // Add move Tip Command - if ( selection.size () >= 1 ) { + if ( !selection.empty() ) { App::DocumentObject *feature = selection.front().pObject; PartDesign::Body *body = nullptr; @@ -194,7 +194,7 @@ void Workbench::setupContextMenu(const char* recipient, Gui::MenuItem* item) con Gui::MDIView *activeView = Gui::Application::Instance->activeView(); - if ( selection.size () > 0 && activeView ) { + if ( !selection.empty() && activeView ) { bool docHaveBodies = activeView->getAppDocument()->countObjectsOfType ( PartDesign::Body::getClassTypeId () ) > 0; diff --git a/src/Mod/PartDesign/Gui/Workbench.h b/src/Mod/PartDesign/Gui/Workbench.h index 97975ea020..5138f78e02 100644 --- a/src/Mod/PartDesign/Gui/Workbench.h +++ b/src/Mod/PartDesign/Gui/Workbench.h @@ -42,24 +42,24 @@ namespace PartDesignGui { */ class PartDesignGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; /** Run some actions when the workbench gets activated. */ - virtual void activated(); + void activated() override; /** Run some actions when the workbench gets deactivated. */ - virtual void deactivated(); + void deactivated() override; /// Add custom entries to the context menu - virtual void setupContextMenu(const char* recipient, Gui::MenuItem*) const; + void setupContextMenu(const char* recipient, Gui::MenuItem*) const override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; private: /// Refresh the Body's highlighting when a document becomes active diff --git a/src/Mod/PartDesign/Scripts/Gear.py b/src/Mod/PartDesign/Scripts/Gear.py index 508bd6081f..8812757cf1 100644 --- a/src/Mod/PartDesign/Scripts/Gear.py +++ b/src/Mod/PartDesign/Scripts/Gear.py @@ -219,7 +219,7 @@ def compute(): App.ActiveDocument.recompute() - if c1.isChecked()==True: + if c1.isChecked(): gearMesh = App.ActiveDocument.addObject("Mesh::Feature", "Gear3D-mesh") faces = [] diff --git a/src/Mod/PartDesign/TestPartDesignGui.py b/src/Mod/PartDesign/TestPartDesignGui.py index 9174dcceea..f08e2cf297 100644 --- a/src/Mod/PartDesign/TestPartDesignGui.py +++ b/src/Mod/PartDesign/TestPartDesignGui.py @@ -40,7 +40,7 @@ class CallableCheckWorkflow: def __call__(self): diag = QApplication.activeModalWidget() self.test.assertIsNotNone(diag, "Dialog box could not be found") - if (diag != None): + if (diag is not None): cbuttons = diag.findChildren(QtGui.QPushButton) cbutton = cbuttons[1] dialogcheck = CallableCheckDialog(self.test) @@ -60,7 +60,7 @@ class CallableCheckWarning: def __call__(self): diag = QApplication.activeModalWidget() self.test.assertIsNotNone(diag, "Input dialog box could not be found") - if (diag != None): + if (diag is not None): QtCore.QTimer.singleShot(0, diag, QtCore.SLOT('accept()')) class CallableComboBox: @@ -69,10 +69,10 @@ class CallableComboBox: def __call__(self): diag = QApplication.activeModalWidget() self.test.assertIsNotNone(diag, "Warning dialog box could not be found") - if (diag != None): + if (diag is not None): cbox = diag.findChild(QtGui.QComboBox) self.test.assertIsNotNone(cbox, "ComboBox widget could not be found") - if (cbox != None): + if (cbox is not None): QtCore.QTimer.singleShot(0, diag, QtCore.SLOT('accept()')) App = FreeCAD @@ -155,7 +155,7 @@ class PartDesignGuiTestCases(unittest.TestCase): self.BodySource.addObject(self.Sketch) self.Sketch.Support = (self.BodySource.Origin.OriginFeatures[3], ['']) self.Sketch.MapMode = 'FlatFace' - + geoList = [] geoList.append(Part.LineSegment(App.Vector(-10.000000,10.000000,0),App.Vector(10.000000,10.000000,0))) @@ -195,8 +195,8 @@ class PartDesignGuiTestCases(unittest.TestCase): QtCore.QTimer.singleShot(500, cobj) Gui.runCommand('PartDesign_MoveFeature') #assert depenedencies of the Sketch - self.Doc.recompute() - + self.Doc.recompute() + self.assertFalse(self.Sketch.Support[0][0] in self.BodySource.Origin.OriginFeatures) self.assertTrue(self.Sketch.Support[0][0] in self.BodyTarget.Origin.OriginFeatures) self.assertEqual(len(self.BodySource.Group), 0, "Source body feature count is wrong") @@ -219,7 +219,7 @@ class PartDesignTransformed(unittest.TestCase): self.TempDoc = os.path.join(tempDir, 'PartDesignTransformed.FCStd') App.ActiveDocument.saveAs(self.TempDoc) App.closeDocument("PartDesignTransformed") - + def testMultiTransformCase(self): App.Console.PrintMessage('Testing applying MultiTransform to the Box outside the body\n') App.open(self.TempDoc) @@ -231,10 +231,10 @@ class PartDesignTransformed(unittest.TestCase): Gui.runCommand("PartDesign_MultiTransform") App.closeDocument("PartDesignTransformed") - + def tearDown(self): #closing doc - if (App.ActiveDocument != None and App.ActiveDocument.Name == PartDesignTransformed): + if (App.ActiveDocument is not None and App.ActiveDocument.Name == PartDesignTransformed): App.closeDocument("PartDesignTransformed") #print ("omit closing document for debugging") @@ -248,7 +248,7 @@ class PartDesignTransformed(unittest.TestCase): # self.Box.addGeometry(Part.LineSegment(App.Vector(69.432587,36.960674,0),App.Vector(69.432587,-53.196629,0))) # self.Box.addGeometry(Part.LineSegment(App.Vector(69.432587,-53.196629,0),App.Vector(-99.230339,-53.196629,0))) # self.Box.addGeometry(Part.LineSegment(App.Vector(-99.230339,-53.196629,0),App.Vector(-99.230339,36.960674,0))) -# +# # def tearDown(self): # #closing doc # FreeCAD.closeDocument("SketchGuiTest") diff --git a/src/Mod/PartDesign/WizardShaft/WizardShaft.py b/src/Mod/PartDesign/WizardShaft/WizardShaft.py index ae02afa5d7..13cc7ea033 100644 --- a/src/Mod/PartDesign/WizardShaft/WizardShaft.py +++ b/src/Mod/PartDesign/WizardShaft/WizardShaft.py @@ -189,7 +189,7 @@ class WizardShaftGui: 'ToolTip': ToolTip} def IsActive(self): - return FreeCAD.ActiveDocument != None + return FreeCAD.ActiveDocument is not None def __del__(self): global WizardShaftDlg @@ -198,7 +198,7 @@ class WizardShaftGui: class WizardShaftGuiCallback: def Activated(self): global WizardShaftDlg - if WizardShaftDlg != None and WizardShaftDlg.table != None: + if WizardShaftDlg is not None and WizardShaftDlg.table is not None: WizardShaftDlg.table.finishEditConstraint() def isActive(self): diff --git a/src/Mod/PartDesign/fcgear/involute.py b/src/Mod/PartDesign/fcgear/involute.py index d8349a972b..057ccfa9ed 100644 --- a/src/Mod/PartDesign/fcgear/involute.py +++ b/src/Mod/PartDesign/fcgear/involute.py @@ -24,9 +24,7 @@ from math import cos, sin, pi, acos, atan, sqrt -import sys -if sys.version_info.major >= 3: - xrange = range +xrange = range def CreateExternalGear(w, m, Z, phi, split=True): diff --git a/src/Mod/Path/App/AppPath.cpp b/src/Mod/Path/App/AppPath.cpp index f91649f11f..1e7a055943 100644 --- a/src/Mod/Path/App/AppPath.cpp +++ b/src/Mod/Path/App/AppPath.cpp @@ -53,7 +53,7 @@ namespace Path { -extern PyObject* initModule(); + extern PyObject* initModule(); } /* Python entry */ @@ -71,16 +71,20 @@ PyMOD_INIT_FUNC(Path) PyObject* pathModule = Path::initModule(); Base::Console().Log("Loading Path module... done\n"); + Py::Object module(pathModule); + // Add Types to module Base::Interpreter().addType(&Path::CommandPy ::Type, pathModule, "Command"); Base::Interpreter().addType(&Path::PathPy ::Type, pathModule, "Path"); Base::Interpreter().addType(&Path::ToolPy ::Type, pathModule, "Tool"); Base::Interpreter().addType(&Path::TooltablePy ::Type, pathModule, "Tooltable"); Base::Interpreter().addType(&Path::AreaPy ::Type, pathModule, "Area"); - Base::Interpreter().addType(&Path::VoronoiPy ::Type, pathModule, "Voronoi"); - Base::Interpreter().addType(&Path::VoronoiCellPy ::Type, pathModule, "VoronoiCell"); - Base::Interpreter().addType(&Path::VoronoiEdgePy ::Type, pathModule, "VoronoiEdge"); - Base::Interpreter().addType(&Path::VoronoiVertexPy ::Type, pathModule, "VoronoiVertex"); + + PyObject* voronoiModule(module.getAttr("Voronoi").ptr()); + Base::Interpreter().addType(&Path::VoronoiPy ::Type, voronoiModule, "Diagram"); + Base::Interpreter().addType(&Path::VoronoiCellPy ::Type, voronoiModule, "Cell"); + Base::Interpreter().addType(&Path::VoronoiEdgePy ::Type, voronoiModule, "Edge"); + Base::Interpreter().addType(&Path::VoronoiVertexPy ::Type, voronoiModule, "Vertex"); // 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/Path/App/AppPathPy.cpp b/src/Mod/Path/App/AppPathPy.cpp index 0f3505e3d5..ac33305e21 100644 --- a/src/Mod/Path/App/AppPathPy.cpp +++ b/src/Mod/Path/App/AppPathPy.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -90,344 +91,356 @@ } throw Py::Exception(); namespace Path { -class Module : public Py::ExtensionModule -{ + class VoronoiModule : public Py::ExtensionModule + { + public: + VoronoiModule() : Py::ExtensionModule("Voronoi") + { + initialize("Working with Voronoi diagrams and data structures"); + } + ~VoronoiModule() override {} + }; -public: + class Module : public Py::ExtensionModule + { + VoronoiModule voronoi; + public: - Module() : Py::ExtensionModule("Path") - { - add_varargs_method("write",&Module::write, - "write(object,filename): Exports a given path object to a GCode file" - ); - add_varargs_method("read",&Module::read, - "read(filename,[document]): Imports a GCode file into the given document" - ); - add_varargs_method("show",&Module::show, - "show(path,[string]): Add the path to the active document or create one if no document exists" - ); - add_varargs_method("fromShape",&Module::fromShape, - "fromShape(Shape): Returns a Path object from a Part Shape (deprecated - use fromShapes() instead)" - ); - add_keyword_method("fromShapes",&Module::fromShapes, - "fromShapes(shapes, start=Vector(), return_end=False" PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_PATH) ")\n" - "\nReturns a Path object from a list of shapes\n" - "\n* shapes: input list of shapes.\n" - "\n* start (Vector()): feed start position, and also serves as a hint of path entry.\n" - "\n* return_end (False): if True, returns tuple (path, endPosition).\n" - PARAM_PY_DOC(ARG, AREA_PARAMS_PATH) - ); - add_keyword_method("sortWires",&Module::sortWires, - "sortWires(shapes, start=Vector(), " - PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_ARC_PLANE) - PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_SORT) ")\n" - "\nReturns (wires,end), where 'wires' is sorted across Z value and with optimized travel distance,\n" - "and 'end' is the ending position of the whole wires. If arc_plane==1, it returns (wires,end,arc_plane),\n" - "where arc_plane is the found plane if any, or unchanged.\n" - "\n* shapes: input shape list\n" - "\n* start (Vector()): optional start position.\n" - PARAM_PY_DOC(ARG, AREA_PARAMS_ARC_PLANE) - PARAM_PY_DOC(ARG, AREA_PARAMS_SORT) - ); - initialize("This module is the Path module."); // register with Python - } + Module() : Py::ExtensionModule("Path") + { + add_varargs_method("write",&Module::write, + "write(object,filename): Exports a given path object to a GCode file" + ); + add_varargs_method("read",&Module::read, + "read(filename,[document]): Imports a GCode file into the given document" + ); + add_varargs_method("show",&Module::show, + "show(path,[string]): Add the path to the active document or create one if no document exists" + ); + add_varargs_method("fromShape",&Module::fromShape, + "fromShape(Shape): Returns a Path object from a Part Shape (deprecated - use fromShapes() instead)" + ); + add_keyword_method("fromShapes",&Module::fromShapes, + "fromShapes(shapes, start=Vector(), return_end=False" PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_PATH) ")\n" + "\nReturns a Path object from a list of shapes\n" + "\n* shapes: input list of shapes.\n" + "\n* start (Vector()): feed start position, and also serves as a hint of path entry.\n" + "\n* return_end (False): if True, returns tuple (path, endPosition).\n" + PARAM_PY_DOC(ARG, AREA_PARAMS_PATH) + ); + add_keyword_method("sortWires",&Module::sortWires, + "sortWires(shapes, start=Vector(), " + PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_ARC_PLANE) + PARAM_PY_ARGS_DOC(ARG,AREA_PARAMS_SORT) ")\n" + "\nReturns (wires,end), where 'wires' is sorted across Z value and with optimized travel distance,\n" + "and 'end' is the ending position of the whole wires. If arc_plane==1, it returns (wires,end,arc_plane),\n" + "where arc_plane is the found plane if any, or unchanged.\n" + "\n* shapes: input shape list\n" + "\n* start (Vector()): optional start position.\n" + PARAM_PY_DOC(ARG, AREA_PARAMS_ARC_PLANE) + PARAM_PY_DOC(ARG, AREA_PARAMS_SORT) + ); + initialize("This module is the Path module."); // register with Python - virtual ~Module() {} + PyModule_AddObject(m_module, "Voronoi", voronoi.module().ptr()); + } -private: + ~Module() override {} - Py::Object write(const Py::Tuple& args) - { - char* Name; - PyObject* pObj; - if (!PyArg_ParseTuple(args.ptr(), "Oet",&pObj,"utf-8",&Name)) - throw Py::Exception(); - std::string EncodedName = std::string(Name); - PyMem_Free(Name); - Base::FileInfo file(EncodedName.c_str()); + private: - if (PyObject_TypeCheck(pObj, &(App::DocumentObjectPy::Type))) { - App::DocumentObject* obj = static_cast(pObj)->getDocumentObjectPtr(); - if (obj->getTypeId().isDerivedFrom(Base::Type::fromName("Path::Feature"))) { - const Toolpath& path = static_cast(obj)->Path.getValue(); - std::string gcode = path.toGCode(); - std::ofstream ofile(EncodedName.c_str()); - ofile << gcode; - ofile.close(); - } - else { - throw Py::RuntimeError("The given file is not a path"); - } - } + Py::Object write(const Py::Tuple& args) + { + char* Name; + PyObject* pObj; + if (!PyArg_ParseTuple(args.ptr(), "Oet",&pObj,"utf-8",&Name)) + throw Py::Exception(); + std::string EncodedName = std::string(Name); + PyMem_Free(Name); + Base::FileInfo file(EncodedName.c_str()); - return Py::None(); - } + if (PyObject_TypeCheck(pObj, &(App::DocumentObjectPy::Type))) { + App::DocumentObject* obj = static_cast(pObj)->getDocumentObjectPtr(); + if (obj->getTypeId().isDerivedFrom(Base::Type::fromName("Path::Feature"))) { + const Toolpath& path = static_cast(obj)->Path.getValue(); + std::string gcode = path.toGCode(); + Base::ofstream ofile(file); + ofile << gcode; + ofile.close(); + } + else { + throw Py::RuntimeError("The given file is not a path"); + } + } + + return Py::None(); + } - Py::Object read(const Py::Tuple& args) - { - char* Name; - const char* DocName=nullptr; - if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName)) - throw Py::Exception(); - std::string EncodedName = std::string(Name); - PyMem_Free(Name); + Py::Object read(const Py::Tuple& args) + { + char* Name; + const char* DocName=nullptr; + if (!PyArg_ParseTuple(args.ptr(), "et|s","utf-8",&Name,&DocName)) + throw Py::Exception(); + std::string EncodedName = std::string(Name); + PyMem_Free(Name); - Base::FileInfo file(EncodedName.c_str()); - if (!file.exists()) - throw Py::RuntimeError("File doesn't exist"); + Base::FileInfo file(EncodedName.c_str()); + if (!file.exists()) + throw Py::RuntimeError("File doesn't exist"); - App::Document *pcDoc; - if (DocName) - pcDoc = App::GetApplication().getDocument(DocName); - else - pcDoc = App::GetApplication().getActiveDocument(); - if (!pcDoc) - pcDoc = App::GetApplication().newDocument(DocName); + App::Document *pcDoc; + if (DocName) + pcDoc = App::GetApplication().getDocument(DocName); + else + pcDoc = App::GetApplication().getActiveDocument(); + if (!pcDoc) + pcDoc = App::GetApplication().newDocument(DocName); - try { - // read the gcode file - std::ifstream filestr(file.filePath().c_str()); - std::stringstream buffer; - buffer << filestr.rdbuf(); - std::string gcode = buffer.str(); - Toolpath path; - path.setFromGCode(gcode); - Path::Feature *object = static_cast(pcDoc->addObject("Path::Feature",file.fileNamePure().c_str())); - object->Path.setValue(path); - pcDoc->recompute(); - } - catch (const Base::Exception& e) { - throw Py::RuntimeError(e.what()); - } + try { + // read the gcode file + Base::ifstream filestr(file); + std::stringstream buffer; + buffer << filestr.rdbuf(); + std::string gcode = buffer.str(); + Toolpath path; + path.setFromGCode(gcode); + Path::Feature *object = static_cast(pcDoc->addObject("Path::Feature",file.fileNamePure().c_str())); + object->Path.setValue(path); + pcDoc->recompute(); + } + catch (const Base::Exception& e) { + throw Py::RuntimeError(e.what()); + } - return Py::None(); - } + return Py::None(); + } - Py::Object show(const Py::Tuple& args) - { - PyObject *pcObj; - char *name = "Path"; - if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(PathPy::Type), &pcObj, &name)) - throw Py::Exception(); + Py::Object show(const Py::Tuple& args) + { + PyObject *pcObj; + char *name = "Path"; + if (!PyArg_ParseTuple(args.ptr(), "O!|s", &(PathPy::Type), &pcObj, &name)) + throw Py::Exception(); - try { - App::Document *pcDoc = App::GetApplication().getActiveDocument(); - if (!pcDoc) - pcDoc = App::GetApplication().newDocument(); - PathPy* pPath = static_cast(pcObj); - Path::Feature *pcFeature = static_cast(pcDoc->addObject("Path::Feature", name)); - Path::Toolpath* pa = pPath->getToolpathPtr(); - if (!pa) { - throw Py::Exception(PyExc_ReferenceError, "object doesn't reference a valid path"); - } + try { + App::Document *pcDoc = App::GetApplication().getActiveDocument(); + if (!pcDoc) + pcDoc = App::GetApplication().newDocument(); + PathPy* pPath = static_cast(pcObj); + Path::Feature *pcFeature = static_cast(pcDoc->addObject("Path::Feature", name)); + Path::Toolpath* pa = pPath->getToolpathPtr(); + if (!pa) { + throw Py::Exception(PyExc_ReferenceError, "object doesn't reference a valid path"); + } - // copy the data - pcFeature->Path.setValue(*pa); - } - catch (const Base::Exception& e) { - throw Py::RuntimeError(e.what()); - } + // copy the data + pcFeature->Path.setValue(*pa); + } + catch (const Base::Exception& e) { + throw Py::RuntimeError(e.what()); + } - return Py::None(); - } + return Py::None(); + } - Py::Object fromShape(const Py::Tuple& args) - { - PyObject *pcObj; - if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj)) - throw Py::Exception(); - TopoDS_Shape shape; - try { - if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) { - shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); - } else { - throw Py::TypeError("the given object is not a shape"); - } - if (!shape.IsNull()) { - if (shape.ShapeType() == TopAbs_WIRE) { - Path::Toolpath result; - bool first = true; - Base::Placement last; + Py::Object fromShape(const Py::Tuple& args) + { + PyObject *pcObj; + if (!PyArg_ParseTuple(args.ptr(), "O", &pcObj)) + throw Py::Exception(); + TopoDS_Shape shape; + try { + if (PyObject_TypeCheck(pcObj, &(Part::TopoShapePy::Type))) { + shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); + } else { + throw Py::TypeError("the given object is not a shape"); + } + if (!shape.IsNull()) { + if (shape.ShapeType() == TopAbs_WIRE) { + Path::Toolpath result; + bool first = true; + Base::Placement last; - TopExp_Explorer ExpEdges (shape,TopAbs_EDGE); - while (ExpEdges.More()) { - const TopoDS_Edge& edge = TopoDS::Edge(ExpEdges.Current()); - TopExp_Explorer ExpVerts(edge,TopAbs_VERTEX); - bool vfirst = true; - while (ExpVerts.More()) { - const TopoDS_Vertex& vert = TopoDS::Vertex(ExpVerts.Current()); - gp_Pnt pnt = BRep_Tool::Pnt(vert); - Base::Placement tpl; - tpl.setPosition(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z())); - if (first) { - // add first point as a G0 move - Path::Command cmd; - std::ostringstream ctxt; - ctxt << "G0 X" << tpl.getPosition().x << " Y" << tpl.getPosition().y << " Z" << tpl.getPosition().z; - cmd.setFromGCode(ctxt.str()); - result.addCommand(cmd); - first = false; - vfirst = false; - } else { - if (vfirst) - vfirst = false; - else { - Path::Command cmd; - cmd.setFromPlacement(tpl); + TopExp_Explorer ExpEdges (shape,TopAbs_EDGE); + while (ExpEdges.More()) { + const TopoDS_Edge& edge = TopoDS::Edge(ExpEdges.Current()); + TopExp_Explorer ExpVerts(edge,TopAbs_VERTEX); + bool vfirst = true; + while (ExpVerts.More()) { + const TopoDS_Vertex& vert = TopoDS::Vertex(ExpVerts.Current()); + gp_Pnt pnt = BRep_Tool::Pnt(vert); + Base::Placement tpl; + tpl.setPosition(Base::Vector3d(pnt.X(),pnt.Y(),pnt.Z())); + if (first) { + // add first point as a G0 move + Path::Command cmd; + std::ostringstream ctxt; + ctxt << "G0 X" << tpl.getPosition().x << " Y" << tpl.getPosition().y << " Z" << tpl.getPosition().z; + cmd.setFromGCode(ctxt.str()); + result.addCommand(cmd); + first = false; + vfirst = false; + } else { + if (vfirst) + vfirst = false; + else { + Path::Command cmd; + cmd.setFromPlacement(tpl); - // write arc data if needed - BRepAdaptor_Curve adapt(edge); - if (adapt.GetType() == GeomAbs_Circle) { - gp_Circ circ = adapt.Circle(); - gp_Pnt c = circ.Location(); - bool clockwise = false; - gp_Dir n = circ.Axis().Direction(); - if (n.Z() < 0) - clockwise = true; - Base::Vector3d center = Base::Vector3d(c.X(),c.Y(),c.Z()); - // center coords must be relative to last point - center -= last.getPosition(); - cmd.setCenter(center,clockwise); - } - result.addCommand(cmd); - } - } - ExpVerts.Next(); - last = tpl; - } - ExpEdges.Next(); - } - return Py::asObject(new PathPy(new Path::Toolpath(result))); - } else { - throw Py::TypeError("the given shape must be a wire"); - } - } else { - throw Py::TypeError("the given shape is empty"); - } - } - catch (const Base::Exception& e) { - throw Py::RuntimeError(e.what()); - } - } + // write arc data if needed + BRepAdaptor_Curve adapt(edge); + if (adapt.GetType() == GeomAbs_Circle) { + gp_Circ circ = adapt.Circle(); + gp_Pnt c = circ.Location(); + bool clockwise = false; + gp_Dir n = circ.Axis().Direction(); + if (n.Z() < 0) + clockwise = true; + Base::Vector3d center = Base::Vector3d(c.X(),c.Y(),c.Z()); + // center coords must be relative to last point + center -= last.getPosition(); + cmd.setCenter(center,clockwise); + } + result.addCommand(cmd); + } + } + ExpVerts.Next(); + last = tpl; + } + ExpEdges.Next(); + } + return Py::asObject(new PathPy(new Path::Toolpath(result))); + } else { + throw Py::TypeError("the given shape must be a wire"); + } + } else { + throw Py::TypeError("the given shape is empty"); + } + } + catch (const Base::Exception& e) { + throw Py::RuntimeError(e.what()); + } + } - Py::Object fromShapes(const Py::Tuple& args, const Py::Dict &kwds) - { - PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_PATH) - PyObject *pShapes=nullptr; - PyObject *start=nullptr; - PyObject *return_end=Py_False; - static char* kwd_list[] = {"shapes", "start", "return_end", - PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_PATH), nullptr}; - if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), - "O|O!O!" PARAM_PY_KWDS(AREA_PARAMS_PATH), - kwd_list, &pShapes, &(Base::VectorPy::Type), &start, &PyBool_Type, &return_end, - PARAM_REF(PARAM_FARG,AREA_PARAMS_PATH))) - throw Py::Exception(); + Py::Object fromShapes(const Py::Tuple& args, const Py::Dict &kwds) + { + PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_PATH) + PyObject *pShapes=nullptr; + PyObject *start=nullptr; + PyObject *return_end=Py_False; + static char* kwd_list[] = {"shapes", "start", "return_end", + PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_PATH), nullptr}; + if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), + "O|O!O!" PARAM_PY_KWDS(AREA_PARAMS_PATH), + kwd_list, &pShapes, &(Base::VectorPy::Type), &start, &PyBool_Type, &return_end, + PARAM_REF(PARAM_FARG,AREA_PARAMS_PATH))) + throw Py::Exception(); - std::list shapes; - if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type))) - shapes.push_back(static_cast(pShapes)->getTopoShapePtr()->getShape()); - else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) || - PyObject_TypeCheck(pShapes, &(PyTuple_Type))) - { - Py::Sequence shapeSeq(pShapes); - for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) { - PyObject* item = (*it).ptr(); - if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - PyErr_SetString(PyExc_TypeError, "non-shape object in sequence"); - throw Py::Exception(); - } - shapes.push_back(static_cast(item)->getTopoShapePtr()->getShape()); - } - } + std::list shapes; + if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type))) + shapes.push_back(static_cast(pShapes)->getTopoShapePtr()->getShape()); + else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) || + PyObject_TypeCheck(pShapes, &(PyTuple_Type))) + { + Py::Sequence shapeSeq(pShapes); + for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) { + PyObject* item = (*it).ptr(); + if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { + PyErr_SetString(PyExc_TypeError, "non-shape object in sequence"); + throw Py::Exception(); + } + shapes.push_back(static_cast(item)->getTopoShapePtr()->getShape()); + } + } - gp_Pnt pstart; - if(start) { - Base::Vector3d vec = static_cast(start)->value(); - pstart.SetCoord(vec.x, vec.y, vec.z); - } + gp_Pnt pstart; + if(start) { + Base::Vector3d vec = static_cast(start)->value(); + pstart.SetCoord(vec.x, vec.y, vec.z); + } - try { - gp_Pnt pend; - std::unique_ptr path(new Toolpath); - Area::toPath(*path,shapes,start?&pstart:nullptr, &pend, - PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_PATH)); - if (!Base::asBoolean(return_end)) - return Py::asObject(new PathPy(path.release())); - Py::Tuple tuple(2); - tuple.setItem(0, Py::asObject(new PathPy(path.release()))); - tuple.setItem(1, Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(),pend.Y(),pend.Z())))); - return tuple; - } PATH_CATCH - } + try { + gp_Pnt pend; + std::unique_ptr path(new Toolpath); + Area::toPath(*path,shapes,start?&pstart:nullptr, &pend, + PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_PATH)); + if (!Base::asBoolean(return_end)) + return Py::asObject(new PathPy(path.release())); + Py::Tuple tuple(2); + tuple.setItem(0, Py::asObject(new PathPy(path.release()))); + tuple.setItem(1, Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(),pend.Y(),pend.Z())))); + return tuple; + } PATH_CATCH + } - Py::Object sortWires(const Py::Tuple& args, const Py::Dict &kwds) - { - PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_ARC_PLANE) - PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_SORT) - PyObject *pShapes=nullptr; - PyObject *start=nullptr; - static char* kwd_list[] = {"shapes", "start", - PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_ARC_PLANE), - PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_SORT), nullptr}; - if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), - "O|O!" - PARAM_PY_KWDS(AREA_PARAMS_ARC_PLANE) - PARAM_PY_KWDS(AREA_PARAMS_SORT), - kwd_list, &pShapes, &(Base::VectorPy::Type), &start, - PARAM_REF(PARAM_FARG,AREA_PARAMS_ARC_PLANE), - PARAM_REF(PARAM_FARG,AREA_PARAMS_SORT))) - throw Py::Exception(); + Py::Object sortWires(const Py::Tuple& args, const Py::Dict &kwds) + { + PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_ARC_PLANE) + PARAM_PY_DECLARE_INIT(PARAM_FARG,AREA_PARAMS_SORT) + PyObject *pShapes=nullptr; + PyObject *start=nullptr; + static char* kwd_list[] = {"shapes", "start", + PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_ARC_PLANE), + PARAM_FIELD_STRINGS(ARG,AREA_PARAMS_SORT), nullptr}; + if (!PyArg_ParseTupleAndKeywords(args.ptr(), kwds.ptr(), + "O|O!" + PARAM_PY_KWDS(AREA_PARAMS_ARC_PLANE) + PARAM_PY_KWDS(AREA_PARAMS_SORT), + kwd_list, &pShapes, &(Base::VectorPy::Type), &start, + PARAM_REF(PARAM_FARG,AREA_PARAMS_ARC_PLANE), + PARAM_REF(PARAM_FARG,AREA_PARAMS_SORT))) + throw Py::Exception(); - std::list shapes; - if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type))) { - shapes.push_back(static_cast(pShapes)->getTopoShapePtr()->getShape()); - } - else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) || - PyObject_TypeCheck(pShapes, &(PyTuple_Type))) { - Py::Sequence shapeSeq(pShapes); - for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) { - PyObject* item = (*it).ptr(); - if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { - PyErr_SetString(PyExc_TypeError, "non-shape object in sequence"); - throw Py::Exception(); - } - shapes.push_back(static_cast(item)->getTopoShapePtr()->getShape()); - } - } + std::list shapes; + if (PyObject_TypeCheck(pShapes, &(Part::TopoShapePy::Type))) { + shapes.push_back(static_cast(pShapes)->getTopoShapePtr()->getShape()); + } + else if (PyObject_TypeCheck(pShapes, &(PyList_Type)) || + PyObject_TypeCheck(pShapes, &(PyTuple_Type))) { + Py::Sequence shapeSeq(pShapes); + for (Py::Sequence::iterator it = shapeSeq.begin(); it != shapeSeq.end(); ++it) { + PyObject* item = (*it).ptr(); + if(!PyObject_TypeCheck(item, &(Part::TopoShapePy::Type))) { + PyErr_SetString(PyExc_TypeError, "non-shape object in sequence"); + throw Py::Exception(); + } + shapes.push_back(static_cast(item)->getTopoShapePtr()->getShape()); + } + } - gp_Pnt pstart,pend; - if(start) { - Base::Vector3d vec = static_cast(start)->value(); - pstart.SetCoord(vec.x, vec.y, vec.z); - } + gp_Pnt pstart,pend; + if(start) { + Base::Vector3d vec = static_cast(start)->value(); + pstart.SetCoord(vec.x, vec.y, vec.z); + } - try { - bool need_arc_plane = arc_plane==Area::ArcPlaneAuto; - std::list wires = Area::sortWires(shapes,start!=nullptr,&pstart, - &pend, nullptr, &arc_plane, PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_SORT)); - Py::List list; - for(auto &wire : wires) { - list.append(Part::shape2pyshape(TopoDS::Wire(wire))); - } + try { + bool need_arc_plane = arc_plane==Area::ArcPlaneAuto; + std::list wires = Area::sortWires(shapes, start != nullptr, &pstart, + &pend, nullptr, &arc_plane, PARAM_PY_FIELDS(PARAM_FARG,AREA_PARAMS_SORT)); + Py::List list; + for(auto &wire : wires) { + list.append(Part::shape2pyshape(TopoDS::Wire(wire))); + } - Py::Tuple ret(need_arc_plane ? 3 : 2); - ret.setItem(0, list); - ret.setItem(1, Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(),pend.Y(),pend.Z())))); - if (need_arc_plane) - ret.setItem(2, Py::Long(arc_plane)); + Py::Tuple ret(need_arc_plane ? 3 : 2); + ret.setItem(0, list); + ret.setItem(1, Py::asObject(new Base::VectorPy(Base::Vector3d(pend.X(),pend.Y(),pend.Z())))); + if (need_arc_plane) + ret.setItem(2, Py::Long(arc_plane)); - return ret; - } PATH_CATCH - } -}; + return ret; + } PATH_CATCH + } + }; -PyObject* initModule() -{ - return Base::Interpreter().addModule(new Module); -} + PyObject* initModule() + { + return Base::Interpreter().addModule(new Module); + } } // namespace Path diff --git a/src/Mod/Path/App/Area.cpp b/src/Mod/Path/App/Area.cpp index 77e1884160..03e0b4eef9 100644 --- a/src/Mod/Path/App/Area.cpp +++ b/src/Mod/Path/App/Area.cpp @@ -210,7 +210,7 @@ Area::Area(const Area& other, bool deep_copy) myShape = other.myShape; myShapeDone = other.myShapeDone; mySections.reserve(other.mySections.size()); - for (shared_ptr area : other.mySections) + for (const shared_ptr& area : other.mySections) mySections.push_back(make_shared(*area, true)); } @@ -545,7 +545,7 @@ void Area::addToBuild(CArea& area, const TopoDS_Shape& shape) { } } - if (areaOpen.m_curves.size()) { + if (!areaOpen.m_curves.empty()) { if (&area == myArea.get() || myParams.OpenMode == OpenModeNone) myAreaOpen->m_curves.splice(myAreaOpen->m_curves.end(), areaOpen.m_curves); else @@ -706,7 +706,7 @@ struct WireJoiner { // void join(double tol) { tol = tol * tol; - while (edges.size()) { + while (!edges.empty()) { auto it = edges.begin(); BRepBuilderAPI_MakeWire mkWire; mkWire.Add(it->edge); @@ -715,7 +715,7 @@ struct WireJoiner { bool done = false; for (int idx = 0; !done && idx < 2; ++idx) { - while (edges.size()) { + while (!edges.empty()) { std::vector ret; ret.reserve(1); const gp_Pnt& pt = idx == 0 ? pstart : pend; @@ -913,12 +913,12 @@ struct WireJoiner { size_t iStart; size_t iEnd; size_t iCurrent; - StackInfo(size_t idx) :iStart(idx), iEnd(idx), iCurrent(idx) {} + explicit StackInfo(size_t idx) :iStart(idx), iEnd(idx), iCurrent(idx) {} }; std::vector stack; std::vector vertexStack; - for (int iteration = 1; edgesToVisit.size(); ++iteration) { + for (int iteration = 1; !edgesToVisit.empty(); ++iteration) { EdgeInfo* currentInfo = *edgesToVisit.begin(); int currentIdx = 1; // used to tell whether search connection from the start(0) or end(1) TopoDS_Edge& e = currentInfo->edge; @@ -1566,7 +1566,7 @@ std::vector > Area::makeSections( } } } - if (area->myShapes.size()) { + if (!area->myShapes.empty()) { sections.push_back(area); FC_TIME_LOG(t1, "makeSection " << z); showShape(area->getShape(), nullptr, "section_%u_final", i); @@ -1606,7 +1606,7 @@ TopoDS_Shape Area::getPlane(gp_Trsf* trsf) { } bool Area::isBuilt() const { - return (myArea || mySections.size()); + return (myArea || !mySections.empty()); } std::list Area::getProjectedShapes(const gp_Trsf& trsf, bool inverse) const @@ -1675,7 +1675,7 @@ void Area::build() { if (myParams.OpenMode != OpenModeNone) myArea->m_curves.splice(myArea->m_curves.end(), myAreaOpen->m_curves); pending = false; - if (areaClip.m_curves.size()) { + if (!areaClip.m_curves.empty()) { if (op == OperationCompound) myArea->m_curves.splice(myArea->m_curves.end(), areaClip.m_curves); else { @@ -3121,7 +3121,7 @@ std::list Area::sortWires(const std::list& shapes, auto current_it = shape_list.end(); double current_height = (pstart.*getter)(); double max_dist = sort_mode == SortModeGreedy ? threshold * threshold : 0; - while (shape_list.size()) { + while (!shape_list.empty()) { AREA_TRACE("sorting " << shape_list.size() << ' ' << AREA_XYZ(pstart)); double best_d = DBL_MAX; auto best_it = shape_list.begin(); @@ -3314,7 +3314,7 @@ void Area::toPath(Toolpath& path, const std::list& shapes, PARAM_REF(PARAM_FARG, AREA_PARAMS_ARC_PLANE), PARAM_FIELDS(PARAM_FARG, AREA_PARAMS_SORT)); - if (wires.size() == 0) + if (wires.empty()) return; short currentArcPlane = arc_plane; diff --git a/src/Mod/Path/App/Area.h b/src/Mod/Path/App/Area.h index 12da5df313..8994be0f55 100644 --- a/src/Mod/Path/App/Area.h +++ b/src/Mod/Path/App/Area.h @@ -95,7 +95,7 @@ struct PathExport CAreaConfig { * arc unfiting and fitting is lossy. And repeatedly perform these operation * may cause shape deformation. So it is best to delay arc fitting until the * final step*/ - CAreaConfig(const CAreaParams& p, bool noFitArcs = true); + explicit CAreaConfig(const CAreaParams& p, bool noFitArcs = true); /** The destructor restores the setting, and thus exception safe. */ ~CAreaConfig(); @@ -105,7 +105,7 @@ struct PathExport CAreaConfig { /** Base class for FreeCAD wrapping of libarea */ class PathExport Area: public Base::BaseClass { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: struct Shape { @@ -171,9 +171,9 @@ public: /** Declare all parameters defined in #AREA_PARAMS_ALL as member variable */ PARAM_ENUM_DECLARE(AREA_PARAMS_ALL) - Area(const AreaParams* params = nullptr); + explicit Area(const AreaParams* params = nullptr); Area(const Area& other, bool deep_copy = true); - virtual ~Area(); + ~Area() override; bool isBuilt() const; diff --git a/src/Mod/Path/App/AreaPyImp.cpp b/src/Mod/Path/App/AreaPyImp.cpp index 7832162193..a39776231a 100644 --- a/src/Mod/Path/App/AreaPyImp.cpp +++ b/src/Mod/Path/App/AreaPyImp.cpp @@ -149,7 +149,7 @@ static const PyMethodDef areaOverrides[] = { "of this Area is used if section mode is 'Workplane'.", }, { - "setDefaultParams",reinterpret_cast(reinterpret_cast(areaSetParams)), METH_VARARGS|METH_KEYWORDS|METH_STATIC, + "setDefaultParams",reinterpret_cast(reinterpret_cast(areaSetParams)), METH_VARARGS|METH_KEYWORDS|METH_STATIC, "setDefaultParams(key=value...):\n" "Static method to set the default parameters of all following Path.Area, plus the following\n" "additional parameters.\n" @@ -159,13 +159,13 @@ static const PyMethodDef areaOverrides[] = { "getDefaultParams(): Static method to return the current default parameters." }, { - "abort",reinterpret_cast(reinterpret_cast(areaAbort)), METH_VARARGS|METH_KEYWORDS|METH_STATIC, + "abort",reinterpret_cast(reinterpret_cast(areaAbort)), METH_VARARGS|METH_KEYWORDS|METH_STATIC, "abort(aborting=True): Static method to abort any ongoing operation\n" "\nTo ensure no stray abortion is left in the previous operation, it is advised to manually clear\n" "the aborting flag by calling abort(False) before starting a new operation.", }, { - "getParamsDesc",reinterpret_cast(reinterpret_cast(areaGetParamsDesc)), METH_VARARGS|METH_KEYWORDS|METH_STATIC, + "getParamsDesc",reinterpret_cast(reinterpret_cast(areaGetParamsDesc)), METH_VARARGS|METH_KEYWORDS|METH_STATIC, "getParamsDesc(as_string=False): Returns a list of supported parameters and their descriptions.\n" "\n* as_string: if False, then return a dictionary of documents of all supported parameters." }, @@ -195,7 +195,7 @@ static AreaPyModifier mod; using namespace Path; // returns a string which represents the object e.g. when printed in python -std::string AreaPy::representation(void) const +std::string AreaPy::representation() const { std::stringstream str; str << ""; @@ -445,7 +445,7 @@ PyObject* AreaPy::getParamsDesc(PyObject *, PyObject *) return nullptr; } -Py::List AreaPy::getSections(void) const { +Py::List AreaPy::getSections() const { Py::List ret; Area *area = getAreaPtr(); for(size_t i=0,count=area->getSectionCount(); i &shapes = area->getChildren(); @@ -462,7 +462,7 @@ Py::List AreaPy::getShapes(void) const { return ret; } -Py::Object AreaPy::getWorkplane(void) const { +Py::Object AreaPy::getWorkplane() const { return Part::shape2pyshape(getAreaPtr()->getPlane()); } diff --git a/src/Mod/Path/App/CMakeLists.txt b/src/Mod/Path/App/CMakeLists.txt index 1d1110350c..fa9a52c302 100644 --- a/src/Mod/Path/App/CMakeLists.txt +++ b/src/Mod/Path/App/CMakeLists.txt @@ -18,6 +18,7 @@ include_directories( ${EIGEN3_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Path/App/Command.cpp b/src/Mod/Path/App/Command.cpp index a81d3f010c..3f78109903 100644 --- a/src/Mod/Path/App/Command.cpp +++ b/src/Mod/Path/App/Command.cpp @@ -75,7 +75,7 @@ Placement Command::getPlacement (const Base::Vector3d pos) const return plac; } -Vector3d Command::getCenter (void) const +Vector3d Command::getCenter () const { static const std::string i = "I"; static const std::string j = "J"; @@ -301,7 +301,7 @@ void Command::scaleBy(double factor) // Reimplemented from base class -unsigned int Command::getMemSize (void) const +unsigned int Command::getMemSize () const { return toGCode().size(); } diff --git a/src/Mod/Path/App/CommandPyImp.cpp b/src/Mod/Path/App/CommandPyImp.cpp index 80c73059c2..ab3d366dc7 100644 --- a/src/Mod/Path/App/CommandPyImp.cpp +++ b/src/Mod/Path/App/CommandPyImp.cpp @@ -40,7 +40,7 @@ using namespace Path; // returns a string which represents the object e.g. when printed in python -std::string CommandPy::representation(void) const +std::string CommandPy::representation() const { std::stringstream str; str.precision(5); @@ -137,7 +137,7 @@ int CommandPy::PyInit(PyObject* args, PyObject* kwd) // Name attribute -Py::String CommandPy::getName(void) const +Py::String CommandPy::getName() const { return Py::String(getCommandPtr()->Name.c_str()); } @@ -151,7 +151,7 @@ void CommandPy::setName(Py::String arg) // Parameters attribute get/set -Py::Dict CommandPy::getParameters(void) const +Py::Dict CommandPy::getParameters() const { // dict now a class member , https://forum.freecadweb.org/viewtopic.php?f=15&t=50583 if (parameters_copy_dict.length()==0) { @@ -224,7 +224,7 @@ PyObject* CommandPy::setFromGCode(PyObject *args) // Placement attribute get/set -Py::Object CommandPy::getPlacement(void) const +Py::Object CommandPy::getPlacement() const { return Py::asObject(new Base::PlacementPy(new Base::Placement(getCommandPtr()->getPlacement()))); } diff --git a/src/Mod/Path/App/FeatureArea.cpp b/src/Mod/Path/App/FeatureArea.cpp index c5c48b5c53..26dd7cc07b 100644 --- a/src/Mod/Path/App/FeatureArea.cpp +++ b/src/Mod/Path/App/FeatureArea.cpp @@ -69,7 +69,7 @@ Area &FeatureArea::getArea() { return myArea; } -App::DocumentObjectExecReturn *FeatureArea::execute(void) +App::DocumentObjectExecReturn *FeatureArea::execute() { myInited = true; @@ -143,7 +143,7 @@ const std::vector &FeatureArea::getShapes() { return myShapes; } -short FeatureArea::mustExecute(void) const +short FeatureArea::mustExecute() const { if(myInited && !myArea.isBuilt()) return 1; @@ -206,7 +206,7 @@ std::list FeatureAreaView::getShapes() { return shapes; } -App::DocumentObjectExecReturn *FeatureAreaView::execute(void) +App::DocumentObjectExecReturn *FeatureAreaView::execute() { App::DocumentObject* pObj = Source.getValue(); if (!pObj) @@ -244,10 +244,10 @@ namespace App { PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaPython, Path::FeatureArea) PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaViewPython, Path::FeatureAreaView) -template<> const char* Path::FeatureAreaPython::getViewProviderName(void) const { +template<> const char* Path::FeatureAreaPython::getViewProviderName() const { return "PathGui::ViewProviderAreaPython"; } -template<> const char* Path::FeatureAreaViewPython::getViewProviderName(void) const { +template<> const char* Path::FeatureAreaViewPython::getViewProviderName() const { return "PathGui::ViewProviderAreaViewPython"; } /// @endcond diff --git a/src/Mod/Path/App/FeatureArea.h b/src/Mod/Path/App/FeatureArea.h index 8ff370217d..a4fd904f07 100644 --- a/src/Mod/Path/App/FeatureArea.h +++ b/src/Mod/Path/App/FeatureArea.h @@ -36,23 +36,23 @@ namespace Path class PathExport FeatureArea : public Part::Feature { - PROPERTY_HEADER(Path::FeatureArea); + PROPERTY_HEADER_WITH_OVERRIDE(Path::FeatureArea); public: /// Constructor - FeatureArea(void); - virtual ~FeatureArea(); + FeatureArea(); + ~FeatureArea() override; Area &getArea(); const std::vector &getShapes(); /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PathGui::ViewProviderArea"; } - virtual App::DocumentObjectExecReturn *execute(void); - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + PyObject *getPyObject() override; App::PropertyLinkList Sources; Part::PropertyPartShape WorkPlane; @@ -74,18 +74,18 @@ typedef App::FeaturePythonT FeatureAreaPython; class PathExport FeatureAreaView : public Part::Feature { - PROPERTY_HEADER(Path::FeatureAreaView); + PROPERTY_HEADER_WITH_OVERRIDE(Path::FeatureAreaView); public: /// Constructor - FeatureAreaView(void); + FeatureAreaView(); std::list getShapes(); - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "PathGui::ViewProviderAreaView"; } - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; App::PropertyLink Source; App::PropertyInteger SectionIndex; diff --git a/src/Mod/Path/App/FeatureAreaPyImp.cpp b/src/Mod/Path/App/FeatureAreaPyImp.cpp index 2d8824a322..cc975a8ca4 100644 --- a/src/Mod/Path/App/FeatureAreaPyImp.cpp +++ b/src/Mod/Path/App/FeatureAreaPyImp.cpp @@ -36,7 +36,7 @@ using namespace Path; // returns a string which represent the object e.g. when printed in python -std::string FeatureAreaPy::representation(void) const +std::string FeatureAreaPy::representation() const { return std::string(""); } @@ -81,7 +81,7 @@ PyObject* FeatureAreaPy::setParams(PyObject *args, PyObject *keywds) return Py_None; } -Py::Object FeatureAreaPy::getWorkPlane(void) const { +Py::Object FeatureAreaPy::getWorkPlane() const { return Part::shape2pyshape(getFeatureAreaPtr()->getArea().getPlane()); } diff --git a/src/Mod/Path/App/FeaturePath.cpp b/src/Mod/Path/App/FeaturePath.cpp index 55cdc02c96..ad41da82c7 100644 --- a/src/Mod/Path/App/FeaturePath.cpp +++ b/src/Mod/Path/App/FeaturePath.cpp @@ -44,7 +44,7 @@ Feature::~Feature() { } -short Feature::mustExecute(void) const +short Feature::mustExecute() const { return App::GeoFeature::mustExecute(); } @@ -68,7 +68,7 @@ void Feature::onChanged(const App::Property* prop) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Path::FeaturePython, Path::Feature) -template<> const char* Path::FeaturePython::getViewProviderName(void) const { +template<> const char* Path::FeaturePython::getViewProviderName() const { return "PathGui::ViewProviderPathPython"; } /// @endcond diff --git a/src/Mod/Path/App/FeaturePathCompound.cpp b/src/Mod/Path/App/FeaturePathCompound.cpp index 12719a738b..c29329c59f 100644 --- a/src/Mod/Path/App/FeaturePathCompound.cpp +++ b/src/Mod/Path/App/FeaturePathCompound.cpp @@ -48,7 +48,7 @@ FeatureCompound::~FeatureCompound() { } -App::DocumentObjectExecReturn *FeatureCompound::execute(void) +App::DocumentObjectExecReturn *FeatureCompound::execute() { const std::vector &Paths = Group.getValues(); Path::Toolpath result; @@ -121,7 +121,7 @@ PyObject *FeatureCompound::getPyObject() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Path::FeatureCompoundPython, Path::FeatureCompound) -template<> const char* Path::FeatureCompoundPython::getViewProviderName(void) const { +template<> const char* Path::FeatureCompoundPython::getViewProviderName() const { return "PathGui::ViewProviderPathCompoundPython"; } /// @endcond diff --git a/src/Mod/Path/App/FeaturePathCompoundPyImp.cpp b/src/Mod/Path/App/FeaturePathCompoundPyImp.cpp index 7982fa1fa2..82ba77bd63 100644 --- a/src/Mod/Path/App/FeaturePathCompoundPyImp.cpp +++ b/src/Mod/Path/App/FeaturePathCompoundPyImp.cpp @@ -34,7 +34,7 @@ using namespace Path; // returns a string which represents the object e.g. when printed in python -std::string FeaturePathCompoundPy::representation(void) const +std::string FeaturePathCompoundPy::representation() const { return std::string(""); } diff --git a/src/Mod/Path/App/FeaturePathShape.cpp b/src/Mod/Path/App/FeaturePathShape.cpp index ca7e2e68a7..5b2430398d 100644 --- a/src/Mod/Path/App/FeaturePathShape.cpp +++ b/src/Mod/Path/App/FeaturePathShape.cpp @@ -64,7 +64,7 @@ FeatureShape::~FeatureShape() { } -App::DocumentObjectExecReturn *FeatureShape::execute(void) +App::DocumentObjectExecReturn *FeatureShape::execute() { Toolpath path; std::vector links = Sources.getValues(); @@ -97,7 +97,7 @@ App::DocumentObjectExecReturn *FeatureShape::execute(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Path::FeatureShapePython, Path::FeatureShape) -template<> const char* Path::FeatureShapePython::getViewProviderName(void) const { +template<> const char* Path::FeatureShapePython::getViewProviderName() const { return "PathGui::ViewProviderPathShape"; } /// @endcond diff --git a/src/Mod/Path/App/FeaturePathShape.h b/src/Mod/Path/App/FeaturePathShape.h index 4ee41d607b..2480f9fcbb 100644 --- a/src/Mod/Path/App/FeaturePathShape.h +++ b/src/Mod/Path/App/FeaturePathShape.h @@ -47,7 +47,7 @@ class PathExport FeatureShape : public Path::Feature public: /// Constructor - FeatureShape(void); + FeatureShape(); virtual ~FeatureShape(); // Part::PropertyPartShape Shape; @@ -58,11 +58,11 @@ public: //@{ /// recalculate the feature - virtual App::DocumentObjectExecReturn *execute(void); + virtual App::DocumentObjectExecReturn *execute(); //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + virtual const char* getViewProviderName() const { return "PathGui::ViewProviderPathShape"; } diff --git a/src/Mod/Path/App/Path.cpp b/src/Mod/Path/App/Path.cpp index c47a03e9de..0d026c51c2 100644 --- a/src/Mod/Path/App/Path.cpp +++ b/src/Mod/Path/App/Path.cpp @@ -82,7 +82,7 @@ Toolpath &Toolpath::operator=(const Toolpath& otherPath) return *this; } -void Toolpath::clear(void) +void Toolpath::clear() { for(std::vector::iterator it = vpcCommands.begin();it!=vpcCommands.end();++it) delete ( *it ); @@ -125,7 +125,7 @@ void Toolpath::deleteCommand(int pos) double Toolpath::getLength() { - if(vpcCommands.size()==0) + if(vpcCommands.empty()) return 0; double l = 0; Vector3d last(0,0,0); @@ -168,7 +168,7 @@ double Toolpath::getCycleTime(double hFeed, double vFeed, double hRapid, double vRapid = vFeed; } - if (vpcCommands.size() == 0) { + if (vpcCommands.empty()) { return 0; } double l = 0; @@ -220,21 +220,21 @@ public: BoundBoxSegmentVisitor() { } - virtual void g0(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) + void g0(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) override { (void)id; processPt(last); processPts(pts); processPt(next); } - virtual void g1(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) + void g1(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) override { (void)id; processPt(last); processPts(pts); processPt(next); } - virtual void g23(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, const Base::Vector3d ¢er) + void g23(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, const Base::Vector3d ¢er) override { (void)id; (void)center; @@ -242,8 +242,8 @@ public: processPts(pts); processPt(next); } - virtual void g8x(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, - const std::deque &p, const std::deque &q) + void g8x(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, + const std::deque &p, const std::deque &q) override { (void)id; (void)q; // always within the bounds of p @@ -252,7 +252,7 @@ public: processPts(p); processPt(next); } - virtual void g38(int id, const Base::Vector3d &last, const Base::Vector3d &next) + void g38(int id, const Base::Vector3d &last, const Base::Vector3d &next) override { (void)id; processPt(last); @@ -357,7 +357,7 @@ void Toolpath::setFromGCode(const std::string instr) recalculate(); } -std::string Toolpath::toGCode(void) const +std::string Toolpath::toGCode() const { std::string result; for (std::vector::const_iterator it=vpcCommands.begin();it!=vpcCommands.end();++it) { @@ -367,10 +367,10 @@ std::string Toolpath::toGCode(void) const return result; } -void Toolpath::recalculate(void) // recalculates the path cache +void Toolpath::recalculate() // recalculates the path cache { - if(vpcCommands.size()==0) + if(vpcCommands.empty()) return; // TODO recalculate the KDL stuff. At the moment, this is unused. @@ -432,7 +432,7 @@ void Toolpath::recalculate(void) // recalculates the path cache // reimplemented from base class -unsigned int Toolpath::getMemSize (void) const +unsigned int Toolpath::getMemSize () const { return toGCode().size(); } diff --git a/src/Mod/Path/App/PathPyImp.cpp b/src/Mod/Path/App/PathPyImp.cpp index e84088e25f..cb6f2daca8 100644 --- a/src/Mod/Path/App/PathPyImp.cpp +++ b/src/Mod/Path/App/PathPyImp.cpp @@ -36,7 +36,7 @@ using namespace Path; // returns a string which represents the object e.g. when printed in python -std::string PathPy::representation(void) const +std::string PathPy::representation() const { std::stringstream str; str.precision(5); @@ -86,7 +86,7 @@ int PathPy::PyInit(PyObject* args, PyObject* /*kwd*/) // Commands get/set -Py::List PathPy::getCommands(void) const +Py::List PathPy::getCommands() const { Py::List list; for(unsigned int i = 0; i < getToolpathPtr()->getSize(); i++) @@ -107,7 +107,7 @@ void PathPy::setCommands(Py::List list) } } -Py::Object PathPy::getCenter(void) const +Py::Object PathPy::getCenter() const { return Py::Vector(getToolpathPtr()->getCenter()); } @@ -119,17 +119,17 @@ void PathPy::setCenter(Py::Object obj) // read-only attributes -Py::Float PathPy::getLength(void) const +Py::Float PathPy::getLength() const { return Py::Float(getToolpathPtr()->getLength()); } -Py::Long PathPy::getSize(void) const +Py::Long PathPy::getSize() const { return Py::Long((long)getToolpathPtr()->getSize()); } -Py::Object PathPy::getBoundBox(void) const +Py::Object PathPy::getBoundBox() const { return Py::BoundingBox(getToolpathPtr()->getBoundBox()); } diff --git a/src/Mod/Path/App/PropertyPath.cpp b/src/Mod/Path/App/PropertyPath.cpp index ef18ae1d2f..7281caeafc 100644 --- a/src/Mod/Path/App/PropertyPath.cpp +++ b/src/Mod/Path/App/PropertyPath.cpp @@ -60,12 +60,12 @@ void PropertyPath::setValue(const Toolpath& pa) } -const Toolpath &PropertyPath::getValue(void)const +const Toolpath &PropertyPath::getValue()const { return _Path; } -PyObject *PropertyPath::getPyObject(void) +PyObject *PropertyPath::getPyObject() { return new PathPy(new Toolpath(_Path)); } @@ -83,7 +83,7 @@ void PropertyPath::setPyObject(PyObject *value) } } -App::Property *PropertyPath::Copy(void) const +App::Property *PropertyPath::Copy() const { PropertyPath *prop = new PropertyPath(); prop->_Path = this->_Path; @@ -98,7 +98,7 @@ void PropertyPath::Paste(const App::Property &from) hasSetValue(); } -unsigned int PropertyPath::getMemSize (void) const +unsigned int PropertyPath::getMemSize () const { return _Path.getMemSize(); } diff --git a/src/Mod/Path/App/PropertyTool.cpp b/src/Mod/Path/App/PropertyTool.cpp index 1083866f14..43741c1d01 100644 --- a/src/Mod/Path/App/PropertyTool.cpp +++ b/src/Mod/Path/App/PropertyTool.cpp @@ -58,12 +58,12 @@ void PropertyTool::setValue(const Tool& tt) } -const Tool &PropertyTool::getValue(void)const +const Tool &PropertyTool::getValue()const { return _Tool; } -PyObject *PropertyTool::getPyObject(void) +PyObject *PropertyTool::getPyObject() { return new ToolPy(new Tool(_Tool)); } @@ -81,7 +81,7 @@ void PropertyTool::setPyObject(PyObject *value) } } -App::Property *PropertyTool::Copy(void) const +App::Property *PropertyTool::Copy() const { PropertyTool *prop = new PropertyTool(); prop->_Tool = this->_Tool; @@ -96,7 +96,7 @@ void PropertyTool::Paste(const App::Property &from) hasSetValue(); } -unsigned int PropertyTool::getMemSize (void) const +unsigned int PropertyTool::getMemSize () const { return _Tool.getMemSize(); } diff --git a/src/Mod/Path/App/PropertyTooltable.cpp b/src/Mod/Path/App/PropertyTooltable.cpp index 26d19d0016..7c4a3bc8f5 100644 --- a/src/Mod/Path/App/PropertyTooltable.cpp +++ b/src/Mod/Path/App/PropertyTooltable.cpp @@ -58,12 +58,12 @@ void PropertyTooltable::setValue(const Tooltable& tt) } -const Tooltable &PropertyTooltable::getValue(void)const +const Tooltable &PropertyTooltable::getValue()const { return _Tooltable; } -PyObject *PropertyTooltable::getPyObject(void) +PyObject *PropertyTooltable::getPyObject() { return new TooltablePy(new Tooltable(_Tooltable)); } @@ -81,7 +81,7 @@ void PropertyTooltable::setPyObject(PyObject *value) } } -App::Property *PropertyTooltable::Copy(void) const +App::Property *PropertyTooltable::Copy() const { PropertyTooltable *prop = new PropertyTooltable(); prop->_Tooltable = this->_Tooltable; @@ -96,7 +96,7 @@ void PropertyTooltable::Paste(const App::Property &from) hasSetValue(); } -unsigned int PropertyTooltable::getMemSize (void) const +unsigned int PropertyTooltable::getMemSize () const { return _Tooltable.getMemSize(); } diff --git a/src/Mod/Path/App/Tool.cpp b/src/Mod/Path/App/Tool.cpp index 7705c3780b..0e0afda51e 100644 --- a/src/Mod/Path/App/Tool.cpp +++ b/src/Mod/Path/App/Tool.cpp @@ -69,7 +69,7 @@ Tool::~Tool() } // Reimplemented from base class -unsigned int Tool::getMemSize (void) const +unsigned int Tool::getMemSize () const { return 0; } @@ -108,7 +108,7 @@ void Tool::Restore(XMLReader &reader) } -const std::vector Tool::ToolTypes(void) +const std::vector Tool::ToolTypes() { std::vector toolTypes(13); toolTypes[0] ="EndMill"; @@ -128,7 +128,7 @@ const std::vector Tool::ToolTypes(void) } -const std::vector Tool::ToolMaterials(void) +const std::vector Tool::ToolMaterials() { std::vector toolMat(7); toolMat[0] ="Carbide"; diff --git a/src/Mod/Path/App/ToolPyImp.cpp b/src/Mod/Path/App/ToolPyImp.cpp index 0d4299d27b..17cfe90d2c 100644 --- a/src/Mod/Path/App/ToolPyImp.cpp +++ b/src/Mod/Path/App/ToolPyImp.cpp @@ -39,7 +39,7 @@ using namespace Path; // returns a string which represents the object e.g. when printed in python -std::string ToolPy::representation(void) const +std::string ToolPy::representation() const { std::stringstream str; str.precision(5); @@ -111,7 +111,7 @@ int ToolPy::PyInit(PyObject* args, PyObject* kwd) // attributes get/setters -Py::String ToolPy::getName(void) const +Py::String ToolPy::getName() const { return Py::String(getToolPtr()->Name.c_str()); } @@ -122,7 +122,7 @@ void ToolPy::setName(Py::String arg) getToolPtr()->Name = name; } -Py::String ToolPy::getToolType(void) const +Py::String ToolPy::getToolType() const { return Py::String(Tool::TypeName(getToolPtr()->Type)); } @@ -134,7 +134,7 @@ void ToolPy::setToolType(Py::String arg) } -Py::String ToolPy::getMaterial(void) const +Py::String ToolPy::getMaterial() const { return Py::String(Tool::MaterialName(getToolPtr()->Material)); } @@ -145,7 +145,7 @@ void ToolPy::setMaterial(Py::String arg) getToolPtr()->Material = Tool::getToolMaterial(matStr); } -Py::Float ToolPy::getDiameter(void) const +Py::Float ToolPy::getDiameter() const { return Py::Float(getToolPtr()->Diameter); } @@ -155,7 +155,7 @@ void ToolPy::setDiameter(Py::Float arg) getToolPtr()->Diameter = arg.operator double(); } -Py::Float ToolPy::getLengthOffset(void) const +Py::Float ToolPy::getLengthOffset() const { return Py::Float(getToolPtr()->LengthOffset); } @@ -165,7 +165,7 @@ void ToolPy::setLengthOffset(Py::Float arg) getToolPtr()->LengthOffset = arg.operator double(); } -Py::Float ToolPy::getFlatRadius(void) const +Py::Float ToolPy::getFlatRadius() const { return Py::Float(getToolPtr()->FlatRadius); } @@ -175,7 +175,7 @@ void ToolPy::setFlatRadius(Py::Float arg) getToolPtr()->FlatRadius = arg.operator double(); } -Py::Float ToolPy::getCornerRadius(void) const +Py::Float ToolPy::getCornerRadius() const { return Py::Float(getToolPtr()->CornerRadius); } @@ -185,7 +185,7 @@ void ToolPy::setCornerRadius(Py::Float arg) getToolPtr()->CornerRadius = arg.operator double(); } -Py::Float ToolPy::getCuttingEdgeAngle(void) const +Py::Float ToolPy::getCuttingEdgeAngle() const { return Py::Float(getToolPtr()->CuttingEdgeAngle); } @@ -195,7 +195,7 @@ void ToolPy::setCuttingEdgeAngle(Py::Float arg) getToolPtr()->CuttingEdgeAngle = arg.operator double(); } -Py::Float ToolPy::getCuttingEdgeHeight(void) const +Py::Float ToolPy::getCuttingEdgeHeight() const { return Py::Float(getToolPtr()->CuttingEdgeHeight); } diff --git a/src/Mod/Path/App/Tooltable.cpp b/src/Mod/Path/App/Tooltable.cpp index 504a8c09ea..a7d10877dc 100644 --- a/src/Mod/Path/App/Tooltable.cpp +++ b/src/Mod/Path/App/Tooltable.cpp @@ -79,7 +79,7 @@ void Tooltable::deleteTool(int pos) } } -unsigned int Tooltable::getMemSize (void) const +unsigned int Tooltable::getMemSize () const { return 0; } diff --git a/src/Mod/Path/App/TooltablePyImp.cpp b/src/Mod/Path/App/TooltablePyImp.cpp index 5fb636d285..42b319e8ba 100644 --- a/src/Mod/Path/App/TooltablePyImp.cpp +++ b/src/Mod/Path/App/TooltablePyImp.cpp @@ -39,7 +39,7 @@ using namespace Path; #define PYINT_ASLONG(o) PyLong_AsLong(o) // returns a string which represents the object e.g. when printed in python -std::string TooltablePy::representation(void) const +std::string TooltablePy::representation() const { std::stringstream str; str.precision(5); @@ -94,7 +94,7 @@ int TooltablePy::PyInit(PyObject* args, PyObject* /*kwd*/) // Commands get/set -Py::Dict TooltablePy::getTools(void) const +Py::Dict TooltablePy::getTools() const { Py::Dict dict; for(std::map::iterator i = getTooltablePtr()->Tools.begin(); i != getTooltablePtr()->Tools.end(); ++i) { @@ -230,7 +230,7 @@ int TooltablePy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/) return 0; } -Py::Int TooltablePy::getVersion(void) const +Py::Int TooltablePy::getVersion() const { return Py::Int(getTooltablePtr()->Version); } @@ -239,7 +239,7 @@ void TooltablePy::setVersion(Py::Int version) { getTooltablePtr()->Version = version; } -Py::String TooltablePy::getName(void) const +Py::String TooltablePy::getName() const { return Py::String(getTooltablePtr()->Name.c_str()); } diff --git a/src/Mod/Path/App/Voronoi.cpp b/src/Mod/Path/App/Voronoi.cpp index e5c9f116db..4cdb8a5d0f 100644 --- a/src/Mod/Path/App/Voronoi.cpp +++ b/src/Mod/Path/App/Voronoi.cpp @@ -153,7 +153,7 @@ void Voronoi::addSegment(const Voronoi::segment_type &s) { pil.y(low(s).y() * vd->getScale()); pih.x(high(s).x() * vd->getScale()); pih.y(high(s).y() * vd->getScale()); - vd->segments.push_back(segment_type(pil, pih)); + vd->segments.emplace_back(pil, pih); } long Voronoi::numPoints() const { @@ -192,7 +192,7 @@ void Voronoi::colorExterior(const Voronoi::diagram_type::edge_type *edge, std::s edge->color(colorValue); edge->twin()->color(colorValue); auto v = edge->vertex1(); - if (v == nullptr || !edge->is_primary()) { + if (!v || !edge->is_primary()) { return; } v->color(colorValue); diff --git a/src/Mod/Path/App/VoronoiCell.cpp b/src/Mod/Path/App/VoronoiCell.cpp index 460bd612a9..2e7be77b28 100644 --- a/src/Mod/Path/App/VoronoiCell.cpp +++ b/src/Mod/Path/App/VoronoiCell.cpp @@ -54,8 +54,8 @@ VoronoiCell::VoronoiCell(Voronoi::diagram_type *d, const Voronoi::diagram_type:: VoronoiCell::~VoronoiCell() { } -bool VoronoiCell::isBound(void) const { - if (ptr != nullptr && dia.isValid() && index != Voronoi::InvalidIndex) { +bool VoronoiCell::isBound() const { + if (ptr && dia.isValid() && index != Voronoi::InvalidIndex) { if (&(dia->cells()[index]) == ptr) { return true; } diff --git a/src/Mod/Path/App/VoronoiCellPy.xml b/src/Mod/Path/App/VoronoiCellPy.xml index dd57e44332..49fcdf33f2 100644 --- a/src/Mod/Path/App/VoronoiCellPy.xml +++ b/src/Mod/Path/App/VoronoiCellPy.xml @@ -3,6 +3,7 @@ - Returns the index of the cell's source + Returns the cell's category as an integer + + + Returns the cell's category as a string + + + Incident edge of the cell - if exists diff --git a/src/Mod/Path/App/VoronoiCellPyImp.cpp b/src/Mod/Path/App/VoronoiCellPyImp.cpp index 319c084041..b1454e0b56 100644 --- a/src/Mod/Path/App/VoronoiCellPyImp.cpp +++ b/src/Mod/Path/App/VoronoiCellPyImp.cpp @@ -36,7 +36,7 @@ using namespace Path; // returns a string which represents the object e.g. when printed in python -std::string VoronoiCellPy::representation(void) const +std::string VoronoiCellPy::representation() const { std::stringstream ss; ss.precision(5); @@ -103,7 +103,7 @@ VoronoiCell* getVoronoiCellFromPy(const VoronoiCellPy *c, PyObject *args = nullp return self; } -Py::Long VoronoiCellPy::getIndex(void) const { +Py::Long VoronoiCellPy::getIndex() const { VoronoiCell *c = getVoronoiCellPtr(); if (c->isBound()) { return Py::Long(c->dia->index(c->ptr)); @@ -111,7 +111,7 @@ Py::Long VoronoiCellPy::getIndex(void) const { return Py::Long(-1); } -Py::Long VoronoiCellPy::getColor(void) const { +Py::Long VoronoiCellPy::getColor() const { VoronoiCell *c = getVoronoiCellPtr(); if (c->isBound()) { Voronoi::color_type color = c->ptr->color() & Voronoi::ColorMask; @@ -124,20 +124,35 @@ void VoronoiCellPy::setColor(Py::Long color) { getCellFromPy(this)->color(long(color) & Voronoi::ColorMask); } -Py::Long VoronoiCellPy::getSourceIndex(void) const +Py::Long VoronoiCellPy::getSourceIndex() const { VoronoiCell *c = getVoronoiCellFromPy(this); long index = c->ptr->source_index(); return Py::Long(index); } -Py::Int VoronoiCellPy::getSourceCategory(void) const +Py::Int VoronoiCellPy::getSourceCategory() const { VoronoiCell *c = getVoronoiCellFromPy(this); return Py::Int(c->ptr->source_category()); } -Py::Object VoronoiCellPy::getIncidentEdge(void) const +Py::String VoronoiCellPy::getSourceCategoryName() const +{ + VoronoiCell *c = getVoronoiCellFromPy(this); + switch (c->ptr->source_category()) { + case boost::polygon::SOURCE_CATEGORY_SINGLE_POINT: return Py::String("SINGLE_POINT"); + case boost::polygon::SOURCE_CATEGORY_SEGMENT_START_POINT: return Py::String("SEGMENT_START_POINT"); + case boost::polygon::SOURCE_CATEGORY_SEGMENT_END_POINT: return Py::String("SEGMENT_END_POINT"); + case boost::polygon::SOURCE_CATEGORY_INITIAL_SEGMENT: return Py::String("INITIAL_SEGMENT"); + case boost::polygon::SOURCE_CATEGORY_REVERSE_SEGMENT: return Py::String("REVERSE_SEGMENT"); + case boost::polygon::SOURCE_CATEGORY_GEOMETRY_SHIFT: return Py::String("GEOMETRY_SHIFT"); + case boost::polygon::SOURCE_CATEGORY_BITMASK: return Py::String("BITMASK"); + } + return Py::String(""); +} + +Py::Object VoronoiCellPy::getIncidentEdge() const { VoronoiCell *c = getVoronoiCellFromPy(this); return Py::asObject(new VoronoiEdgePy(new VoronoiEdge(c->dia, c->ptr->incident_edge()))); diff --git a/src/Mod/Path/App/VoronoiEdge.cpp b/src/Mod/Path/App/VoronoiEdge.cpp index 6d825c0706..02453e259c 100644 --- a/src/Mod/Path/App/VoronoiEdge.cpp +++ b/src/Mod/Path/App/VoronoiEdge.cpp @@ -55,8 +55,8 @@ VoronoiEdge::VoronoiEdge(Voronoi::diagram_type *d, const Voronoi::diagram_type:: VoronoiEdge::~VoronoiEdge() { } -bool VoronoiEdge::isBound(void) const { - if (ptr != nullptr && dia.isValid() && index != Voronoi::InvalidIndex) { +bool VoronoiEdge::isBound() const { + if (ptr && dia.isValid() && index != Voronoi::InvalidIndex) { if (&(dia->edges()[index]) == ptr) { return true; } diff --git a/src/Mod/Path/App/VoronoiEdgePy.xml b/src/Mod/Path/App/VoronoiEdgePy.xml index bce837524d..6137fc5a4a 100644 --- a/src/Mod/Path/App/VoronoiEdgePy.xml +++ b/src/Mod/Path/App/VoronoiEdgePy.xml @@ -3,6 +3,7 @@ Returns true if edge goes through endpoint of the segment site + + + Returns true if the point is on the segment + + Returns a shape for the edge diff --git a/src/Mod/Path/App/VoronoiEdgePyImp.cpp b/src/Mod/Path/App/VoronoiEdgePyImp.cpp index a99f53d152..7c941bdecb 100644 --- a/src/Mod/Path/App/VoronoiEdgePyImp.cpp +++ b/src/Mod/Path/App/VoronoiEdgePyImp.cpp @@ -39,7 +39,6 @@ #include "VoronoiVertex.h" #include "VoronoiVertexPy.h" - using namespace Path; namespace { @@ -164,6 +163,22 @@ namespace { return false; } + bool pointsMatch(const Voronoi::point_type &p0, const Voronoi::point_type &p1, double scale) { + return 1e-6 > distanceBetween(p0, p1, scale); + } + + bool isPointOnSegment(const Voronoi::point_type &point, const Voronoi::segment_type &segment, double scale) { + return pointsMatch(point, low(segment), scale) || pointsMatch(point, high(segment), scale); + } + + template + PyObject* makeLineSegment(const VoronoiEdge *e, const T &p0, double z0, const T &p1, double z1) { + Part::GeomLineSegment p; + p.setPoints(e->dia->scaledVector(p0, z0), e->dia->scaledVector(p1, z1)); + Handle(Geom_Curve) h = Handle(Geom_Curve)::DownCast(p.handle()); + BRepBuilderAPI_MakeEdge mkBuilder(h, h->FirstParameter(), h->LastParameter()); + return new Part::TopoShapeEdgePy(new Part::TopoShape(mkBuilder.Shape())); + } } std::ostream& operator<<(std::ostream& os, const Voronoi::vertex_type &v) { @@ -180,7 +195,7 @@ std::ostream& operator<<(std::ostream& os, const Voronoi::segment_type &s) { // returns a string which represents the object e.g. when printed in python -std::string VoronoiEdgePy::representation(void) const +std::string VoronoiEdgePy::representation() const { std::stringstream ss; ss.precision(5); @@ -259,7 +274,7 @@ VoronoiEdge* getVoronoiEdgeFromPy(const VoronoiEdgePy *e, PyObject *args = nullp return self; } -Py::Long VoronoiEdgePy::getIndex(void) const { +Py::Long VoronoiEdgePy::getIndex() const { VoronoiEdge *e = getVoronoiEdgePtr(); if (e->isBound()) { return Py::Long(e->dia->index(e->ptr)); @@ -267,7 +282,7 @@ Py::Long VoronoiEdgePy::getIndex(void) const { return Py::Long(-1); } -Py::Long VoronoiEdgePy::getColor(void) const { +Py::Long VoronoiEdgePy::getColor() const { VoronoiEdge *e = getVoronoiEdgePtr(); if (e->isBound()) { Voronoi::color_type color = e->ptr->color() & Voronoi::ColorMask; @@ -280,7 +295,7 @@ void VoronoiEdgePy::setColor(Py::Long color) { getEdgeFromPy(this)->color(long(color) & Voronoi::ColorMask); } -Py::List VoronoiEdgePy::getVertices(void) const +Py::List VoronoiEdgePy::getVertices() const { Py::List list; VoronoiEdge *e = getVoronoiEdgePtr(); @@ -303,37 +318,37 @@ Py::List VoronoiEdgePy::getVertices(void) const return list; } -Py::Object VoronoiEdgePy::getTwin(void) const +Py::Object VoronoiEdgePy::getTwin() const { VoronoiEdge *e = getVoronoiEdgeFromPy(this); return Py::asObject(new VoronoiEdgePy(new VoronoiEdge(e->dia, e->ptr->twin()))); } -Py::Object VoronoiEdgePy::getNext(void) const +Py::Object VoronoiEdgePy::getNext() const { VoronoiEdge *e = getVoronoiEdgeFromPy(this); return Py::asObject(new VoronoiEdgePy(new VoronoiEdge(e->dia, e->ptr->next()))); } -Py::Object VoronoiEdgePy::getPrev(void) const +Py::Object VoronoiEdgePy::getPrev() const { VoronoiEdge *e = getVoronoiEdgeFromPy(this); return Py::asObject(new VoronoiEdgePy(new VoronoiEdge(e->dia, e->ptr->prev()))); } -Py::Object VoronoiEdgePy::getRotNext(void) const +Py::Object VoronoiEdgePy::getRotNext() const { VoronoiEdge *e = getVoronoiEdgeFromPy(this); return Py::asObject(new VoronoiEdgePy(new VoronoiEdge(e->dia, e->ptr->rot_next()))); } -Py::Object VoronoiEdgePy::getRotPrev(void) const +Py::Object VoronoiEdgePy::getRotPrev() const { VoronoiEdge *e = getVoronoiEdgeFromPy(this); return Py::asObject(new VoronoiEdgePy(new VoronoiEdge(e->dia, e->ptr->rot_prev()))); } -Py::Object VoronoiEdgePy::getCell(void) const +Py::Object VoronoiEdgePy::getCell() const { VoronoiEdge *e = getVoronoiEdgeFromPy(this); return Py::asObject(new VoronoiCellPy(new VoronoiCell(e->dia, e->ptr->cell()))); @@ -388,6 +403,21 @@ PyObject* VoronoiEdgePy::isSecondary(PyObject *args) return chk; } +PyObject* VoronoiEdgePy::isBorderline(PyObject *args) +{ + VoronoiEdge *e = getVoronoiEdgeFromPy(this, args); + PyObject *chk = Py_False; + if (e->isBound() && !e->ptr->is_linear()) { + Voronoi::point_type point = e->ptr->cell()->contains_point() ? e->dia->retrievePoint(e->ptr->cell()) : e->dia->retrievePoint(e->ptr->twin()->cell()); + Voronoi::segment_type segment = e->ptr->cell()->contains_point() ? e->dia->retrieveSegment(e->ptr->twin()->cell()) : e->dia->retrieveSegment(e->ptr->cell()); + if (isPointOnSegment(point, segment, e->dia->getScale())) { + chk = Py_True; + } + } + Py_INCREF(chk); + return chk; +} + PyObject* VoronoiEdgePy::toShape(PyObject *args) { double z0 = 0.0; @@ -406,11 +436,7 @@ PyObject* VoronoiEdgePy::toShape(PyObject *args) auto v0 = e->ptr->vertex0(); auto v1 = e->ptr->vertex1(); if (v0 && v1) { - Part::GeomLineSegment p; - p.setPoints(e->dia->scaledVector(*v0, z0), e->dia->scaledVector(*v1, z1)); - Handle(Geom_Curve) h = Handle(Geom_Curve)::DownCast(p.handle()); - BRepBuilderAPI_MakeEdge mkBuilder(h, h->FirstParameter(), h->LastParameter()); - return new Part::TopoShapeEdgePy(new Part::TopoShape(mkBuilder.Shape())); + return makeLineSegment(e, *v0, z0, *v1, z1); } } else { // infinite linear, need to clip somehow @@ -455,11 +481,7 @@ PyObject* VoronoiEdgePy::toShape(PyObject *args) end.x(origin.x() + direction.x() * k); end.y(origin.y() + direction.y() * k); } - Part::GeomLineSegment p; - p.setPoints(e->dia->scaledVector(begin, z0), e->dia->scaledVector(end, z1)); - Handle(Geom_Curve) h = Handle(Geom_Curve)::DownCast(p.handle()); - BRepBuilderAPI_MakeEdge mkBuilder(h, h->FirstParameter(), h->LastParameter()); - return new Part::TopoShapeEdgePy(new Part::TopoShape(mkBuilder.Shape())); + return makeLineSegment(e, begin, z0, end, z1); } } else { // parabolic curve, which is always formed by a point and an edge @@ -467,6 +489,11 @@ PyObject* VoronoiEdgePy::toShape(PyObject *args) Voronoi::segment_type segment = e->ptr->cell()->contains_point() ? e->dia->retrieveSegment(e->ptr->twin()->cell()) : e->dia->retrieveSegment(e->ptr->cell()); // the location is the mid point between the normal on the segment through point // this is only the mid point of the segment if the parabola is symmetric + + if (isPointOnSegment(point, segment, e->dia->getScale())) { + return makeLineSegment(e, low(segment), z0, high(segment), z1); + } + Voronoi::point_type loc; { Voronoi::point_type proj = orthognalProjection(point, segment); @@ -495,7 +522,7 @@ PyObject* VoronoiEdgePy::toShape(PyObject *args) double dist1 = distanceBetween(pt1, pt1x, e->dia->getScale()) * sideOf(pt1, xaxis); if (dist1 < dist0) { // if the parabola is traversed in the revere direction we need to use the points - // on the other side of the parabola - beauty of symmetric geometries + // on the other side of the parabola - 'beauty of symmetric geometries dist0 = -dist0; dist1 = -dist1; } @@ -521,6 +548,9 @@ PyObject* VoronoiEdgePy::toShape(PyObject *args) // focal length if parabola in the xy-plane is simply half the distance between the // point and segment - aka the distance between point and location, aka the length of axis focal = length(axis) / e->dia->getScale(); + if (dbg) { + std::cerr << "focal = " << length(axis) << "/" << e->dia->getScale() << "\n"; + } } else { // if the parabola is not in the xy-plane we need to find the // (x,y) coordinates of a point on the parabola in the parabola's @@ -555,6 +585,7 @@ PyObject* VoronoiEdgePy::toShape(PyObject *args) std::cerr << " loc" << loc << ", axis" << axis << std::endl; std::cerr << " dist0(" << dist0 << " : " << flenX0 << ", dist1(" << dist1 << " : " << flenX1 << ")" << std::endl; std::cerr << " z(" << z0 << ", " << zx << ", " << z1 << ")" << std::endl; + std::cerr << " focal = (" << flenX << " * " << flenX << ") / (4 * fabs(" << flenY << "))\n"; } // use new X values to set the parameters dist0 = dist0 >= 0 ? flenX0 : -flenX0; diff --git a/src/Mod/Path/App/VoronoiPy.xml b/src/Mod/Path/App/VoronoiPy.xml index d330d6ccca..1ca39c9065 100644 --- a/src/Mod/Path/App/VoronoiPy.xml +++ b/src/Mod/Path/App/VoronoiPy.xml @@ -3,6 +3,7 @@ numSegments() << ", " << getVoronoiPtr()->numPoints() << "}" << " -> " << "{" << getVoronoiPtr()->numCells() << ", " << getVoronoiPtr()->numEdges() << ", " << getVoronoiPtr()->numVertices() << "}" @@ -143,7 +143,7 @@ PyObject* VoronoiPy::numVertices(PyObject *args) return PyLong_FromLong(getVoronoiPtr()->numVertices()); } -Py::List VoronoiPy::getVertices(void) const { +Py::List VoronoiPy::getVertices() const { Py::List list; for (int i=0; inumVertices(); ++i) { list.append(Py::asObject(new VoronoiVertexPy(getVoronoiPtr()->create(i)))); @@ -151,7 +151,7 @@ Py::List VoronoiPy::getVertices(void) const { return list; } -Py::List VoronoiPy::getEdges(void) const { +Py::List VoronoiPy::getEdges() const { Py::List list; for (int i=0; inumEdges(); ++i) { list.append(Py::asObject(new VoronoiEdgePy(getVoronoiPtr()->create(i)))); @@ -159,7 +159,7 @@ Py::List VoronoiPy::getEdges(void) const { return list; } -Py::List VoronoiPy::getCells(void) const { +Py::List VoronoiPy::getCells() const { Py::List list; for (int i=0; inumCells(); ++i) { list.append(Py::asObject(new VoronoiCellPy(getVoronoiPtr()->create(i)))); @@ -188,7 +188,7 @@ static bool callbackWithVertex(Voronoi::diagram_type *dia, PyObject *callback, c #endif Py_DECREF(arglist); Py_DECREF(vx); - if (result == nullptr) { + if (!result) { bail = true; } else { rc = result == Py_True; diff --git a/src/Mod/Path/App/VoronoiVertex.cpp b/src/Mod/Path/App/VoronoiVertex.cpp index 64379fe99b..bd3893af9a 100644 --- a/src/Mod/Path/App/VoronoiVertex.cpp +++ b/src/Mod/Path/App/VoronoiVertex.cpp @@ -55,8 +55,8 @@ VoronoiVertex::VoronoiVertex(Voronoi::diagram_type *d, const Voronoi::diagram_ty VoronoiVertex::~VoronoiVertex() { } -bool VoronoiVertex::isBound(void) const { - if (ptr != nullptr && dia.isValid() && index != Voronoi::InvalidIndex) { +bool VoronoiVertex::isBound() const { + if (ptr && dia.isValid() && index != Voronoi::InvalidIndex) { if (&(dia->vertices()[index]) == ptr) { return true; } diff --git a/src/Mod/Path/App/VoronoiVertexPy.xml b/src/Mod/Path/App/VoronoiVertexPy.xml index b4e647b746..b5262808ad 100644 --- a/src/Mod/Path/App/VoronoiVertexPy.xml +++ b/src/Mod/Path/App/VoronoiVertexPy.xml @@ -3,6 +3,7 @@ isBound()) { return Py::Long(v->dia->index(v->ptr)); @@ -112,7 +112,7 @@ Py::Long VoronoiVertexPy::getIndex(void) const { return Py::Long(-1); } -Py::Long VoronoiVertexPy::getColor(void) const { +Py::Long VoronoiVertexPy::getColor() const { VoronoiVertex *v = getVoronoiVertexPtr(); if (v->isBound()) { Voronoi::color_type color = v->ptr->color() & Voronoi::ColorMask; @@ -125,13 +125,13 @@ void VoronoiVertexPy::setColor(Py::Long color) { getVertexFromPy(this)->color(long(color) & Voronoi::ColorMask); } -Py::Float VoronoiVertexPy::getX(void) const +Py::Float VoronoiVertexPy::getX() const { VoronoiVertex *v = getVoronoiVertexFromPy(this); return Py::Float(v->ptr->x() / v->dia->getScale()); } -Py::Float VoronoiVertexPy::getY(void) const +Py::Float VoronoiVertexPy::getY() const { VoronoiVertex *v = getVoronoiVertexFromPy(this); return Py::Float(v->ptr->y() / v->dia->getScale()); diff --git a/src/Mod/Path/Gui/AppPathGui.cpp b/src/Mod/Path/Gui/AppPathGui.cpp index f2a1592683..e73817a263 100644 --- a/src/Mod/Path/Gui/AppPathGui.cpp +++ b/src/Mod/Path/Gui/AppPathGui.cpp @@ -36,7 +36,7 @@ // use a different name to CreateCommand() -void CreatePathCommands(void); +void CreatePathCommands(); void loadPathResource() { diff --git a/src/Mod/Path/Gui/AppPathGuiPy.cpp b/src/Mod/Path/Gui/AppPathGuiPy.cpp index b9f8c4a8cf..54ee0e7bb5 100644 --- a/src/Mod/Path/Gui/AppPathGuiPy.cpp +++ b/src/Mod/Path/Gui/AppPathGuiPy.cpp @@ -63,7 +63,7 @@ public: initialize("This module is the PathGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object open(const Py::Tuple& args) diff --git a/src/Mod/Path/Gui/CMakeLists.txt b/src/Mod/Path/Gui/CMakeLists.txt index 89d6e72ae1..e0c8d919f9 100644 --- a/src/Mod/Path/Gui/CMakeLists.txt +++ b/src/Mod/Path/Gui/CMakeLists.txt @@ -14,6 +14,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Path/Gui/Command.cpp b/src/Mod/Path/Gui/Command.cpp index b116ce8a2c..3b5aaa8fef 100644 --- a/src/Mod/Path/Gui/Command.cpp +++ b/src/Mod/Path/Gui/Command.cpp @@ -73,7 +73,7 @@ void CmdPathArea::activated(int iMsg) { const Part::Feature *pcObj = static_cast(selObj.getObject()); const std::vector &subnames = selObj.getSubNames(); - if(addView && areaName.size()) addView = false; + if(addView && !areaName.empty()) addView = false; if(subnames.empty()) { if(addView && pcObj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId())) @@ -102,7 +102,7 @@ void CmdPathArea::activated(int iMsg) sources << "FreeCAD.activeDocument()." << sub_fname << ","; } } - if(addView && areaName.size()) { + if(addView && !areaName.empty()) { std::string FeatName = getUniqueObjectName("FeatureAreaView"); openCommand(QT_TRANSLATE_NOOP("Command", "Create Path Area View")); doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureAreaView','%s')",FeatName.c_str()); @@ -123,7 +123,7 @@ void CmdPathArea::activated(int iMsg) updateActive(); } -bool CmdPathArea::isActive(void) +bool CmdPathArea::isActive() { return hasActiveDocument(); } @@ -162,7 +162,7 @@ void CmdPathAreaWorkplane::activated(int iMsg) const Part::Feature *pcObj = static_cast(selObj.getObject()); if(subnames.empty()) { if(pcObj->getTypeId().isDerivedFrom(Path::FeatureArea::getClassTypeId())) { - if(areaName.size()){ + if(!areaName.empty()){ Base::Console().Error("Please select one FeatureArea only\n"); return; } @@ -174,7 +174,7 @@ void CmdPathAreaWorkplane::activated(int iMsg) return; } } - if(planeName.size()){ + if(!planeName.empty()){ Base::Console().Error("Please select one shape object for plane only\n"); return; }else{ @@ -210,7 +210,7 @@ void CmdPathAreaWorkplane::activated(int iMsg) updateActive(); } -bool CmdPathAreaWorkplane::isActive(void) +bool CmdPathAreaWorkplane::isActive() { return !getSelection().getSelectionEx(nullptr, Path::FeatureArea::getClassTypeId()).empty(); } @@ -237,7 +237,7 @@ void CmdPathCompound::activated(int iMsg) { Q_UNUSED(iMsg); std::vector Sel = getSelection().getSelection(); - if (Sel.size() > 0) { + if (!Sel.empty()) { std::ostringstream cmd; cmd << "["; Path::Feature *pcPathObject; @@ -263,7 +263,7 @@ void CmdPathCompound::activated(int iMsg) } } -bool CmdPathCompound::isActive(void) +bool CmdPathCompound::isActive() { return hasActiveDocument(); } @@ -332,14 +332,14 @@ void CmdPathShape::activated(int iMsg) updateActive(); } -bool CmdPathShape::isActive(void) +bool CmdPathShape::isActive() { return hasActiveDocument(); } -void CreatePathCommands(void) +void CreatePathCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommand(new CmdPathCompound()); diff --git a/src/Mod/Path/Gui/DlgProcessorChooser.h b/src/Mod/Path/Gui/DlgProcessorChooser.h index 7ba234350c..dd07b69db9 100644 --- a/src/Mod/Path/Gui/DlgProcessorChooser.h +++ b/src/Mod/Path/Gui/DlgProcessorChooser.h @@ -36,13 +36,13 @@ class DlgProcessorChooser : public QDialog Q_OBJECT public: - DlgProcessorChooser(std::vector &scriptnames, bool withArguments = false); - ~DlgProcessorChooser(); + explicit DlgProcessorChooser(std::vector &scriptnames, bool withArguments = false); + ~DlgProcessorChooser() override; std::string getProcessor(); std::string getArguments(); - void accept(); + void accept() override; protected Q_SLOTS: diff --git a/src/Mod/Path/Gui/DlgSettingsPathColor.h b/src/Mod/Path/Gui/DlgSettingsPathColor.h index 81484e3b5d..797f29d102 100644 --- a/src/Mod/Path/Gui/DlgSettingsPathColor.h +++ b/src/Mod/Path/Gui/DlgSettingsPathColor.h @@ -35,14 +35,14 @@ class DlgSettingsPathColor : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsPathColor(QWidget* parent = nullptr); - ~DlgSettingsPathColor(); + explicit DlgSettingsPathColor(QWidget* parent = nullptr); + ~DlgSettingsPathColor() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Path/Gui/Resources/panels/DressupPathBoundary.ui b/src/Mod/Path/Gui/Resources/panels/DressupPathBoundary.ui index 841a720bd4..90ccfe95b4 100644 --- a/src/Mod/Path/Gui/Resources/panels/DressupPathBoundary.ui +++ b/src/Mod/Path/Gui/Resources/panels/DressupPathBoundary.ui @@ -254,7 +254,7 @@ - <html><head/><body><p>I checked the path is constrained by the solid. Otherwise the the volume of the solid describes a &quot;keep out&quot; zone.</p></body></html> + <html><head/><body><p>I checked the path is constrained by the solid. Otherwise the volume of the solid describes a &quot;keep out&quot; zone.</p></body></html> Constrained to Inside diff --git a/src/Mod/Path/Gui/Resources/preferences/PathDressupHoldingTags.ui b/src/Mod/Path/Gui/Resources/preferences/PathDressupHoldingTags.ui index ef03bbaf29..22e9362017 100644 --- a/src/Mod/Path/Gui/Resources/preferences/PathDressupHoldingTags.ui +++ b/src/Mod/Path/Gui/Resources/preferences/PathDressupHoldingTags.ui @@ -84,7 +84,7 @@ - <html><head/><body><p>Radius of the fillet on the tag's top edge.</p><p>If the radius is bigger than that which the the tag shape itself supports, the resulting shape will be that of a dome.</p></body></html> + <html><head/><body><p>Radius of the fillet on the tag's top edge.</p><p>If the radius is bigger than that which the tag shape itself supports, the resulting shape will be that of a dome.</p></body></html> diff --git a/src/Mod/Path/Gui/TaskDlgPathCompound.cpp b/src/Mod/Path/Gui/TaskDlgPathCompound.cpp index b8e48cc13c..66d1dc282b 100644 --- a/src/Mod/Path/Gui/TaskDlgPathCompound.cpp +++ b/src/Mod/Path/Gui/TaskDlgPathCompound.cpp @@ -79,7 +79,7 @@ TaskWidgetPathCompound::~TaskWidgetPathCompound() delete ui; } -std::vector TaskWidgetPathCompound::getList(void) const { +std::vector TaskWidgetPathCompound::getList() const { std::vector names; for(int i = 0; i < ui->PathsList->count(); i++) { diff --git a/src/Mod/Path/Gui/TaskDlgPathCompound.h b/src/Mod/Path/Gui/TaskDlgPathCompound.h index 92e85b2ece..bd736c3c96 100644 --- a/src/Mod/Path/Gui/TaskDlgPathCompound.h +++ b/src/Mod/Path/Gui/TaskDlgPathCompound.h @@ -41,13 +41,13 @@ class TaskWidgetPathCompound : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskWidgetPathCompound(ViewProviderPathCompound *CompoundView, QWidget *parent=nullptr); - ~TaskWidgetPathCompound(); + explicit TaskWidgetPathCompound(ViewProviderPathCompound *CompoundView, QWidget *parent=nullptr); + ~TaskWidgetPathCompound() override; - std::vector getList(void) const; + std::vector getList() const; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: QWidget* proxy; diff --git a/src/Mod/Path/Gui/ViewProviderArea.cpp b/src/Mod/Path/Gui/ViewProviderArea.cpp index cb5c9e9a07..1e8f28a8e2 100644 --- a/src/Mod/Path/Gui/ViewProviderArea.cpp +++ b/src/Mod/Path/Gui/ViewProviderArea.cpp @@ -42,7 +42,7 @@ ViewProviderArea::~ViewProviderArea() { } -std::vector ViewProviderArea::claimChildren(void) const +std::vector ViewProviderArea::claimChildren() const { return std::vector( static_cast(getObject())->Sources.getValues()); @@ -126,7 +126,7 @@ ViewProviderAreaView::~ViewProviderAreaView() { } -std::vector ViewProviderAreaView::claimChildren(void) const +std::vector ViewProviderAreaView::claimChildren() const { std::vector ret; Path::FeatureAreaView* feature = static_cast(getObject()); diff --git a/src/Mod/Path/Gui/ViewProviderPath.cpp b/src/Mod/Path/Gui/ViewProviderPath.cpp index dbb449b4d1..0d8a10e6d4 100644 --- a/src/Mod/Path/Gui/ViewProviderPath.cpp +++ b/src/Mod/Path/Gui/ViewProviderPath.cpp @@ -90,7 +90,7 @@ public: } } - void onSelectionChanged(const Gui::SelectionChanges& msg) { + void onSelectionChanged(const Gui::SelectionChanges& msg) override { if(msg.Type == Gui::SelectionChanges::RmvPreselect) { setArrow(); return; @@ -280,7 +280,7 @@ void ViewProviderPath::attach(App::DocumentObject *pcObj) addDisplayMaskMode(pcPathRoot, "Waypoints"); } -bool ViewProviderPath::useNewSelectionModel(void) const { +bool ViewProviderPath::useNewSelectionModel() const { return SelectionStyle.getValue()!=2; } @@ -291,10 +291,10 @@ void ViewProviderPath::setDisplayMode(const char* ModeName) inherited::setDisplayMode( ModeName ); } -std::vector ViewProviderPath::getDisplayModes(void) const +std::vector ViewProviderPath::getDisplayModes() const { std::vector StrList; - StrList.push_back("Waypoints"); + StrList.emplace_back("Waypoints"); return StrList; } @@ -344,7 +344,7 @@ void ViewProviderPath::onChanged(const App::Property* prop) if (prop == &LineWidth) { pcDrawStyle->lineWidth = LineWidth.getValue(); } else if (prop == &NormalColor) { - if (colorindex.size() > 0 && coordStart>=0 && coordStart<(int)colorindex.size()) { + if (!colorindex.empty() && coordStart>=0 && coordStart<(int)colorindex.size()) { const App::Color& c = NormalColor.getValue(); ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Path"); unsigned long rcol = hGrp->GetUnsigned("DefaultRapidPathColor",2852126975UL); // dark red (170,0,0) @@ -492,33 +492,33 @@ public: command2Edge.resize(tp.getSize(),-1); } - virtual void setup(const Base::Vector3d &last) + void setup(const Base::Vector3d &last) override { points.push_back(last); markers.push_back(last); } - virtual void g0(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) + void g0(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) override { (void)last; gx(id, &next, pts, 0); } - virtual void g1(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) + void g1(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts) override { (void)last; gx(id, &next, pts, 1); } - virtual void g23(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, const Base::Vector3d ¢er) + void g23(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, const Base::Vector3d ¢er) override { (void)last; gx(id, &next, pts, 1); markers.push_back(center); } - virtual void g8x(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, - const std::deque &p, const std::deque &q) + void g8x(int id, const Base::Vector3d &last, const Base::Vector3d &next, const std::deque &pts, + const std::deque &p, const std::deque &q) override { (void)last; @@ -547,7 +547,7 @@ public: pushCommand(id); } - virtual void g38(int id, const Base::Vector3d &last, const Base::Vector3d &next) + void g38(int id, const Base::Vector3d &last, const Base::Vector3d &next) override { #if 0 Base::Vector3d p1(next.x,next.y,last.z); @@ -588,7 +588,7 @@ private: colorindex.push_back(color); } - if (next != nullptr) { + if (next) { points.push_back(*next); markers.push_back(*next); colorindex.push_back(color); diff --git a/src/Mod/Path/Gui/ViewProviderPathCompound.cpp b/src/Mod/Path/Gui/ViewProviderPathCompound.cpp index ee908a97cd..bf25db0cce 100644 --- a/src/Mod/Path/Gui/ViewProviderPathCompound.cpp +++ b/src/Mod/Path/Gui/ViewProviderPathCompound.cpp @@ -55,7 +55,7 @@ void ViewProviderPathCompound::unsetEdit(int ModNum) Gui::Control().closeDialog(); } -std::vector ViewProviderPathCompound::claimChildren(void)const +std::vector ViewProviderPathCompound::claimChildren()const { return std::vector(static_cast(getObject())->Group.getValues()); } diff --git a/src/Mod/Path/Gui/ViewProviderPathShape.cpp b/src/Mod/Path/Gui/ViewProviderPathShape.cpp index c0cbecf4b1..bbb9b88e8a 100644 --- a/src/Mod/Path/Gui/ViewProviderPathShape.cpp +++ b/src/Mod/Path/Gui/ViewProviderPathShape.cpp @@ -42,7 +42,7 @@ QIcon ViewProviderPathShape::getIcon() const return Gui::BitmapFactory().pixmap("Path_Shape"); } -std::vector ViewProviderPathShape::claimChildren(void) const +std::vector ViewProviderPathShape::claimChildren() const { return std::vector( static_cast(getObject())->Sources.getValues()); diff --git a/src/Mod/Path/PathScripts/PathCamoticsGui.py b/src/Mod/Path/PathScripts/PathCamoticsGui.py index c75f6e6a0d..f68948a9d7 100644 --- a/src/Mod/Path/PathScripts/PathCamoticsGui.py +++ b/src/Mod/Path/PathScripts/PathCamoticsGui.py @@ -32,7 +32,6 @@ import PathScripts.PathPost as PathPost import camotics import io import json -import os import queue import subprocess @@ -245,7 +244,6 @@ class CamoticsSimulation(QtCore.QObject): def cancel(self): pass - def buildproject(self): # , files=[]): PathLog.track() diff --git a/src/Mod/Path/PathScripts/PathDressupHoldingTags.py b/src/Mod/Path/PathScripts/PathDressupHoldingTags.py index db6426c2d6..57a38c6285 100644 --- a/src/Mod/Path/PathScripts/PathDressupHoldingTags.py +++ b/src/Mod/Path/PathScripts/PathDressupHoldingTags.py @@ -609,10 +609,6 @@ class MapWireToTag: "Exception during processing tag @(%.2f, %.2f) (%s) - disabling the tag" % (self.tag.x, self.tag.y, e.args[0]) ) - # if sys.version_info.major < 3: - # traceback.print_exc(e) - # else: - # traceback.print_exc() self.tag.enabled = False commands = [] for e in self.edges: @@ -705,10 +701,6 @@ class PathData: if wire.isClosed(): return wire except Exception: - # if sys.version_info.major < 3: - # traceback.print_exc(e) - # else: - # traceback.print_exc() return None def supportsTagGeneration(self): @@ -1275,10 +1267,6 @@ class ObjectTagDressup: PathLog.error( "processing tags failed clearing all tags ... '%s'" % (e.args[0]) ) - # if sys.version_info.major < 3: - # traceback.print_exc(e) - # else: - # traceback.print_exc() obj.Path = obj.Base.Path # update disabled in case there are some additional ones @@ -1323,10 +1311,6 @@ class ObjectTagDressup: ) + "\n" ) - # if sys.version_info.major < 3: - # traceback.print_exc(e) - # else: - # traceback.print_exc() return None self.toolRadius = float(PathDressup.toolController(obj.Base).Tool.Diameter) / 2 diff --git a/src/Mod/Path/PathScripts/PathDressupPathBoundary.py b/src/Mod/Path/PathScripts/PathDressupPathBoundary.py index 01eff7a407..5a45f60965 100644 --- a/src/Mod/Path/PathScripts/PathDressupPathBoundary.py +++ b/src/Mod/Path/PathScripts/PathDressupPathBoundary.py @@ -174,7 +174,7 @@ class PathBoundary: lastExit = None for cmd in self.baseOp.Path.Commands[1:]: if cmd.Name in PathGeom.CmdMoveAll: - if bogusX == True: + if bogusX: bogusX = "X" not in cmd.Parameters if bogusY: bogusY = "Y" not in cmd.Parameters diff --git a/src/Mod/Path/PathScripts/PathEngrave.py b/src/Mod/Path/PathScripts/PathEngrave.py index 6496658aaf..ca79b735d6 100644 --- a/src/Mod/Path/PathScripts/PathEngrave.py +++ b/src/Mod/Path/PathScripts/PathEngrave.py @@ -51,7 +51,7 @@ class ObjectEngrave(PathEngraveBase.ObjectOp): self.wires = [] def opFeatures(self, obj): - """opFeatures(obj) ... return all standard features and edges based geomtries""" + """opFeatures(obj) ... return all standard features and edges based geometries""" return ( PathOp.FeatureTool | PathOp.FeatureDepths diff --git a/src/Mod/Path/PathScripts/PathOp.py b/src/Mod/Path/PathScripts/PathOp.py index b39cc3dbe5..dc8e61c5eb 100644 --- a/src/Mod/Path/PathScripts/PathOp.py +++ b/src/Mod/Path/PathScripts/PathOp.py @@ -29,6 +29,7 @@ import PathScripts.PathLog as PathLog import PathScripts.PathPreferences as PathPreferences import PathScripts.PathUtil as PathUtil import PathScripts.PathUtils as PathUtils +import math import time @@ -867,7 +868,7 @@ class ObjectOp(object): # Get the cycle time in seconds seconds = obj.Path.getCycleTime(hFeedrate, vFeedrate, hRapidrate, vRapidrate) - if not seconds: + if not seconds or math.isnan(seconds): return translate("Path", "Cycletime Error") # Convert the cycle time to a HH:MM:SS format diff --git a/src/Mod/Path/PathScripts/PathPost.py b/src/Mod/Path/PathScripts/PathPost.py index f185678151..0799573a14 100644 --- a/src/Mod/Path/PathScripts/PathPost.py +++ b/src/Mod/Path/PathScripts/PathPost.py @@ -115,7 +115,7 @@ def processFileNameSubstitutions( j = job.Label filename = filename.replace("%j", j) - # Use the sequnce number if explicitly called + # Use the sequence number if explicitly called if "%S" in filename: j = job.Label filename = filename.replace("%S", str(sequencenumber)) diff --git a/src/Mod/Path/PathScripts/PathSelection.py b/src/Mod/Path/PathScripts/PathSelection.py index 4cdf61bef9..8e89cf95a2 100644 --- a/src/Mod/Path/PathScripts/PathSelection.py +++ b/src/Mod/Path/PathScripts/PathSelection.py @@ -124,7 +124,7 @@ class CHAMFERGate(PathBaseGate): class DRILLGate(PathBaseGate): def allow(self, doc, obj, sub): PathLog.debug("obj: {} sub: {}".format(obj, sub)) - if not hasattr(obj, "Shape") and sub: + if not hasattr(obj, "Shape"): return False shape = obj.Shape subobj = shape.getElement(sub) diff --git a/src/Mod/Path/PathScripts/PathThreadMilling.py b/src/Mod/Path/PathScripts/PathThreadMilling.py index 7ce1ead63e..6aa1a67de7 100644 --- a/src/Mod/Path/PathScripts/PathThreadMilling.py +++ b/src/Mod/Path/PathScripts/PathThreadMilling.py @@ -48,10 +48,108 @@ else: translate = FreeCAD.Qt.translate +# Constants +LeftHand = "LeftHand" +RightHand = "RightHand" +ThreadTypeCustomExternal = "CustomExternal" +ThreadTypeCustomInternal = "CustomInternal" +ThreadTypeImperialExternal2A = "ImperialExternal2A" +ThreadTypeImperialExternal3A = "ImperialExternal3A" +ThreadTypeImperialInternal2B = "ImperialInternal2B" +ThreadTypeImperialInternal3B = "ImperialInternal3B" +ThreadTypeMetricExternal4G6G = "MetricExternal4G6G" +ThreadTypeMetricExternal6G = "MetricExternal6G" +ThreadTypeMetricInternal6H = "MetricInternal6H" +DirectionClimb = "Climb" +DirectionConventional = "Conventional" + +ThreadOrientations = [LeftHand, RightHand] + +ThreadTypeData = { + ThreadTypeImperialExternal2A: "imperial-external-2A.csv", + ThreadTypeImperialExternal3A: "imperial-external-3A.csv", + ThreadTypeImperialInternal2B: "imperial-internal-2B.csv", + ThreadTypeImperialInternal3B: "imperial-internal-3B.csv", + ThreadTypeMetricExternal4G6G: "metric-external-4G6G.csv", + ThreadTypeMetricExternal6G: "metric-external-6G.csv", + ThreadTypeMetricInternal6H: "metric-internal-6H.csv", +} + +ThreadTypesExternal = [ + ThreadTypeCustomExternal, + ThreadTypeImperialExternal2A, + ThreadTypeImperialExternal3A, + ThreadTypeMetricExternal4G6G, + ThreadTypeMetricExternal6G, +] +ThreadTypesInternal = [ + ThreadTypeCustomInternal, + ThreadTypeImperialInternal2B, + ThreadTypeImperialInternal3B, + ThreadTypeMetricInternal6H, +] +ThreadTypesImperial = [ + ThreadTypeImperialExternal2A, + ThreadTypeImperialExternal3A, + ThreadTypeImperialInternal2B, + ThreadTypeImperialInternal3B, +] +ThreadTypesMetric = [ + ThreadTypeMetricExternal4G6G, + ThreadTypeMetricExternal6G, + ThreadTypeMetricInternal6H, +] +ThreadTypes = ThreadTypesInternal + ThreadTypesExternal +Directions = [DirectionClimb, DirectionConventional] + +def _isThreadInternal(obj): + return obj.ThreadType in ThreadTypesInternal + +def threadSetupInternal(obj, zTop, zBottom): + PathLog.track() + if obj.ThreadOrientation == RightHand: + # Right hand thread, G2, top down -> conventional milling + if obj.Direction == DirectionConventional: + return ("G2", zTop, zBottom) + # For climb milling we need to cut the thread from the bottom up + # in the opposite direction -> G3 + return ("G3", zBottom, zTop) + # Left hand thread, G3, top down -> climb milling + if obj.Direction == DirectionClimb: + return ("G3", zTop, zBottom) + # for conventional milling, cut bottom up with G2 + return ("G2", zBottom, zTop) + +def threadSetupExternal(obj, zTop, zBottom): + PathLog.track() + if obj.ThreadOrientation == RightHand: + # right hand thread, G2, top down -> climb milling + if obj.Direction == DirectionClimb: + return ("G2", zTop, zBottom) + # for conventional, mill bottom up the other way around + return ("G3", zBottom, zTop) + # left hand thread, G3, top down -> conventional milling + if obj.Direction == DirectionConventional: + return ("G3", zTop, zBottom) + # for climb milling need to go bottom up and the other way + return ("G2", zBottom, zTop) + +def threadSetup(obj): + """Return (cmd, zbegin, zend) of thread milling operation""" + PathLog.track() + + zTop = obj.StartDepth.Value + zBottom = obj.FinalDepth.Value + + if _isThreadInternal(obj): + return threadSetupInternal(obj, zTop, zBottom) + else: + return threadSetupExternal(obj, zTop, zBottom) + def threadRadii(internal, majorDia, minorDia, toolDia, toolCrest): """threadRadii(majorDia, minorDia, toolDia, toolCrest) ... returns the minimum and maximum radius for thread.""" - PathLog.track(majorDia, minorDia, toolDia, toolCrest) + PathLog.track(internal, majorDia, minorDia, toolDia, toolCrest) if toolCrest is None: toolCrest = 0.0 # As it turns out metric and imperial standard threads follow the same rules. @@ -66,12 +164,15 @@ def threadRadii(internal, majorDia, minorDia, toolDia, toolCrest): outerTip = majorDia / 2.0 + H / 8.0 # Compensate for the crest of the tool toolTip = outerTip - toolCrest * SQRT_3_DIVIDED_BY_2 - return ((minorDia - toolDia) / 2.0, toolTip - toolDia / 2.0) - # mill outside in - innerTip = minorDia / 2.0 - H / 4.0 - # Compensate for the crest of the tool - toolTip = innerTip - toolCrest * SQRT_3_DIVIDED_BY_2 - return ((majorDia + toolDia) / 2.0, toolTip + toolDia / 2.0) + radii = ((minorDia - toolDia) / 2.0, toolTip - toolDia / 2.0) + else: + # mill outside in + innerTip = minorDia / 2.0 - H / 4.0 + # Compensate for the crest of the tool + toolTip = innerTip - toolCrest * SQRT_3_DIVIDED_BY_2 + radii = ((majorDia + toolDia) / 2.0, toolTip + toolDia / 2.0) + PathLog.track(radii) + return radii def threadPasses(count, radii, internal, majorDia, minorDia, toolDia, toolCrest): @@ -92,11 +193,14 @@ def threadPasses(count, radii, internal, majorDia, minorDia, toolDia, toolCrest) minor, major = radii(internal, majorDia, minorDia, toolDia, toolCrest) H = float(major - minor) Hi = [H * math.sqrt((i + 1) / count) for i in range(count)] - PathLog.debug("threadPasses({}, {}) -> H={} : {}".format(minor, major, H, Hi)) - if internal: - return [minor + h for h in Hi] - return [major - h for h in Hi] + # For external threads threadRadii returns the radii in reverse order because that's + # the order in which they have to get milled. As a result H ends up being negative + # and the math for internal and external threads is identical. + passes = [minor + h for h in Hi] + PathLog.debug(f"threadPasses({minor}, {major}) -> H={H} : {Hi} --> {passes}") + + return passes def elevatorRadius(obj, center, internal, tool): @@ -121,59 +225,6 @@ def elevatorRadius(obj, center, internal, tool): class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): """Proxy object for thread milling operation.""" - LeftHand = "LeftHand" - RightHand = "RightHand" - ThreadTypeCustomExternal = "CustomExternal" - ThreadTypeCustomInternal = "CustomInternal" - ThreadTypeImperialExternal2A = "ImperialExternal2A" - ThreadTypeImperialExternal3A = "ImperialExternal3A" - ThreadTypeImperialInternal2B = "ImperialInternal2B" - ThreadTypeImperialInternal3B = "ImperialInternal3B" - ThreadTypeMetricExternal4G6G = "MetricExternal4G6G" - ThreadTypeMetricExternal6G = "MetricExternal6G" - ThreadTypeMetricInternal6H = "MetricInternal6H" - DirectionClimb = "Climb" - DirectionConventional = "Conventional" - - ThreadOrientations = [LeftHand, RightHand] - - ThreadTypeData = { - ThreadTypeImperialExternal2A: "imperial-external-2A.csv", - ThreadTypeImperialExternal3A: "imperial-external-3A.csv", - ThreadTypeImperialInternal2B: "imperial-internal-2B.csv", - ThreadTypeImperialInternal3B: "imperial-internal-3B.csv", - ThreadTypeMetricExternal4G6G: "metric-external-4G6G.csv", - ThreadTypeMetricExternal6G: "metric-external-6G.csv", - ThreadTypeMetricInternal6H: "metric-internal-6H.csv", - } - - ThreadTypesExternal = [ - ThreadTypeCustomExternal, - ThreadTypeImperialExternal2A, - ThreadTypeImperialExternal3A, - ThreadTypeMetricExternal4G6G, - ThreadTypeMetricExternal6G, - ] - ThreadTypesInternal = [ - ThreadTypeCustomInternal, - ThreadTypeImperialInternal2B, - ThreadTypeImperialInternal3B, - ThreadTypeMetricInternal6H, - ] - ThreadTypesImperial = [ - ThreadTypeImperialExternal2A, - ThreadTypeImperialExternal3A, - ThreadTypeImperialInternal2B, - ThreadTypeImperialInternal3B, - ] - ThreadTypesMetric = [ - ThreadTypeMetricExternal4G6G, - ThreadTypeMetricExternal6G, - ThreadTypeMetricInternal6H, - ] - ThreadTypes = ThreadTypesInternal + ThreadTypesExternal - Directions = [DirectionClimb, DirectionConventional] - @classmethod def propertyEnumerations(self, dataType="data"): """helixOpPropertyEnumerations(dataType="data")... return property enumeration lists of specified dataType. @@ -191,59 +242,59 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): "ThreadType": [ ( translate("Path_ThreadMilling", "Custom External"), - ObjectThreadMilling.ThreadTypeCustomExternal, + ThreadTypeCustomExternal, ), ( translate("Path_ThreadMilling", "Custom Internal"), - ObjectThreadMilling.ThreadTypeCustomInternal, + ThreadTypeCustomInternal, ), ( translate("Path_ThreadMilling", "Imperial External (2A)"), - ObjectThreadMilling.ThreadTypeImperialExternal2A, + ThreadTypeImperialExternal2A, ), ( translate("Path_ThreadMilling", "Imperial External (3A)"), - ObjectThreadMilling.ThreadTypeImperialExternal3A, + ThreadTypeImperialExternal3A, ), ( translate("Path_ThreadMilling", "Imperial Internal (2B)"), - ObjectThreadMilling.ThreadTypeImperialInternal2B, + ThreadTypeImperialInternal2B, ), ( translate("Path_ThreadMilling", "Imperial Internal (3B)"), - ObjectThreadMilling.ThreadTypeImperialInternal3B, + ThreadTypeImperialInternal3B, ), ( translate("Path_ThreadMilling", "Metric External (4G6G)"), - ObjectThreadMilling.ThreadTypeMetricExternal4G6G, + ThreadTypeMetricExternal4G6G, ), ( translate("Path_ThreadMilling", "Metric External (6G)"), - ObjectThreadMilling.ThreadTypeMetricExternal6G, + ThreadTypeMetricExternal6G, ), ( translate("Path_ThreadMilling", "Metric Internal (6H)"), - ObjectThreadMilling.ThreadTypeMetricInternal6H, + ThreadTypeMetricInternal6H, ), ], "ThreadOrientation": [ ( translate("Path_ThreadMilling", "LeftHand"), - ObjectThreadMilling.LeftHand, + LeftHand, ), ( translate("Path_ThreadMilling", "RightHand"), - ObjectThreadMilling.RightHand, + RightHand, ), ], "Direction": [ ( translate("Path_ThreadMilling", "Climb"), - ObjectThreadMilling.DirectionClimb, + DirectionClimb, ), ( translate("Path_ThreadMilling", "Conventional"), - ObjectThreadMilling.DirectionConventional, + DirectionConventional, ), ], } @@ -274,14 +325,14 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): "Thread", QT_TRANSLATE_NOOP("App::Property", "Set thread orientation"), ) - # obj.ThreadOrientation = self.ThreadOrientations + # obj.ThreadOrientation = ThreadOrientations obj.addProperty( "App::PropertyEnumeration", "ThreadType", "Thread", QT_TRANSLATE_NOOP("App::Property", "Currently only internal"), ) - # obj.ThreadType = self.ThreadTypes + # obj.ThreadType = ThreadTypes obj.addProperty( "App::PropertyString", "ThreadName", @@ -362,32 +413,6 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): for n in self.propertyEnumerations(): setattr(obj, n[0], n[1]) - def _isThreadInternal(self, obj): - return obj.ThreadType in self.ThreadTypesInternal - - def _threadSetupInternal(self, obj): - PathLog.track() - # the thing to remember is that Climb, for an internal thread must always be G3 - if obj.Direction == self.DirectionClimb: - if obj.ThreadOrientation == self.RightHand: - return ("G3", obj.FinalDepth.Value, obj.StartDepth.Value) - return ("G3", obj.StartDepth.Value, obj.FinalDepth.Value) - if obj.ThreadOrientation == self.RightHand: - return ("G2", obj.StartDepth.Value, obj.FinalDepth.Value) - return ("G2", obj.FinalDepth.Value, obj.StartDepth.Value) - - def threadSetup(self, obj): - PathLog.track() - cmd, zbegin, zend = self._threadSetupInternal(obj) - - if obj.ThreadType in self.ThreadTypesInternal: - return (cmd, zbegin, zend) - - # need to reverse direction for external threads - if cmd == "G2": - return ("G3", zbegin, zend) - return ("G2", zbegin, zend) - def threadPassRadii(self, obj): PathLog.track(obj.Label) rMajor = (obj.MajorDiameter.Value - self.tool.Diameter) / 2.0 @@ -402,7 +427,7 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): def executeThreadMill(self, obj, loc, gcode, zStart, zFinal, pitch): PathLog.track(obj.Label, loc, gcode, zStart, zFinal, pitch) - elevator = elevatorRadius(obj, loc, self._isThreadInternal(obj), self.tool) + elevator = elevatorRadius(obj, loc, _isThreadInternal(obj), self.tool) move2clearance = Path.Command( "G0", {"Z": obj.ClearanceHeight.Value, "F": self.vertRapid} @@ -413,7 +438,7 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): for radius in threadPasses( obj.Passes, threadRadii, - self._isThreadInternal(obj), + _isThreadInternal(obj), obj.MajorDiameter.Value, obj.MinorDiameter.Value, float(self.tool.Diameter), @@ -421,7 +446,7 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): ): if ( not start is None - and not self._isThreadInternal(obj) + and not _isThreadInternal(obj) and not obj.LeadInOut ): # external thread without lead in/out have to go up and over @@ -459,7 +484,7 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): if self.isToolSupported(obj, self.tool): self.commandlist.append(Path.Command("(Begin Thread Milling)")) - (cmd, zStart, zFinal) = self.threadSetup(obj) + (cmd, zStart, zFinal) = threadSetup(obj) pitch = obj.Pitch.Value if obj.TPI > 0: pitch = 25.4 / obj.TPI @@ -482,13 +507,13 @@ class ObjectThreadMilling(PathCircularHoleBase.ObjectOp): def opSetDefaultValues(self, obj, job): PathLog.track() - obj.ThreadOrientation = self.RightHand - obj.ThreadType = self.ThreadTypeMetricInternal6H + obj.ThreadOrientation = RightHand + obj.ThreadType = ThreadTypeMetricInternal6H obj.ThreadFit = 50 obj.Pitch = 1 obj.TPI = 0 obj.Passes = 1 - obj.Direction = self.DirectionClimb + obj.Direction = DirectionClimb obj.LeadInOut = False def isToolSupported(self, obj, tool): diff --git a/src/Mod/Path/PathScripts/PathThreadMillingGui.py b/src/Mod/Path/PathScripts/PathThreadMillingGui.py index 7b98ebe34e..54ae450a15 100644 --- a/src/Mod/Path/PathScripts/PathThreadMillingGui.py +++ b/src/Mod/Path/PathScripts/PathThreadMillingGui.py @@ -140,32 +140,32 @@ class TaskPanelOpPage(PathCircularHoleBaseGui.TaskPanelOpPage): def _isThreadCustom(self): return self.form.threadType.currentData() in [ - PathThreadMilling.ObjectThreadMilling.ThreadTypeCustomInternal, - PathThreadMilling.ObjectThreadMilling.ThreadTypeCustomExternal, + PathThreadMilling.ThreadTypeCustomInternal, + PathThreadMilling.ThreadTypeCustomExternal, ] def _isThreadImperial(self): return ( self.form.threadType.currentData() - in PathThreadMilling.ObjectThreadMilling.ThreadTypesImperial + in PathThreadMilling.ThreadTypesImperial ) def _isThreadMetric(self): return ( self.form.threadType.currentData() - in PathThreadMilling.ObjectThreadMilling.ThreadTypesMetric + in PathThreadMilling.ThreadTypesMetric ) def _isThreadInternal(self): return ( self.form.threadType.currentData() - in PathThreadMilling.ObjectThreadMilling.ThreadTypesInternal + in PathThreadMilling.ThreadTypesInternal ) def _isThreadExternal(self): return ( self.form.threadType.currentData() - in PathThreadMilling.ObjectThreadMilling.ThreadTypesExternal + in PathThreadMilling.ThreadTypesExternal ) def _updateFromThreadType(self): @@ -195,7 +195,7 @@ class TaskPanelOpPage(PathCircularHoleBaseGui.TaskPanelOpPage): self.pitch.updateSpinBox(0) fillThreads( self.form, - PathThreadMilling.ObjectThreadMilling.ThreadTypeData[ + PathThreadMilling.ThreadTypeData[ self.form.threadType.currentData() ], self.obj.ThreadName, diff --git a/src/Mod/Path/PathScripts/PathToolBit.py b/src/Mod/Path/PathScripts/PathToolBit.py index e657b7e315..8067d9f9ca 100644 --- a/src/Mod/Path/PathScripts/PathToolBit.py +++ b/src/Mod/Path/PathScripts/PathToolBit.py @@ -286,6 +286,9 @@ class ToolBit(object): break if doc is None: p = findToolShape(p, path if path else obj.File) + if p is None: + raise FileNotFoundError + if not path and p != obj.BitShape: obj.BitShape = p PathLog.debug("ToolBit {} using shape file: {}".format(obj.Label, p)) @@ -482,6 +485,9 @@ class ToolBitFactory(object): def CreateFrom(self, path, name="ToolBit"): PathLog.track(name, path) + + if not os.path.isfile(path): + raise FileNotFoundError(f"{path} not found") try: data = Declaration(path) bit = Factory.CreateFromAttrs(data, name, path) diff --git a/src/Mod/Path/PathScripts/PathToolBitLibraryGui.py b/src/Mod/Path/PathScripts/PathToolBitLibraryGui.py index 902f6a7411..a4db74a907 100644 --- a/src/Mod/Path/PathScripts/PathToolBitLibraryGui.py +++ b/src/Mod/Path/PathScripts/PathToolBitLibraryGui.py @@ -73,7 +73,10 @@ def checkWorkingDir(): qm = PySide.QtGui.QMessageBox ret = qm.question( - None, "", translate("Path_ToolBit","Toolbit working directory not set up. Do that now?"), qm.Yes | qm.No + None, + "", + translate("Path_ToolBit", "Toolbit working directory not set up. Do that now?"), + qm.Yes | qm.No, ) if ret == qm.No: @@ -117,9 +120,10 @@ def checkWorkingDir(): ret = qm.question( None, "", - translate("Path_ToolBit","Toolbit Working directory {} needs these sudirectories:\n {} \n Create them?").format( - workingdir, needed - ), + translate( + "Path_ToolBit", + "Toolbit Working directory {} needs these sudirectories:\n {} \n Create them?", + ).format(workingdir, needed), qm.Yes | qm.No, ) @@ -136,7 +140,9 @@ def checkWorkingDir(): ret = qm.question( None, "", - translate("Path_ToolBit","Copy example files to new {} directory?").format(dir), + translate( + "Path_ToolBit", "Copy example files to new {} directory?" + ).format(dir), qm.Yes | qm.No, ) if ret == qm.Yes: @@ -788,12 +794,15 @@ class ToolBitLibrary(object): TooltableTypeJSON = translate("Path_ToolBit", "Tooltable JSON (*.fctl)") TooltableTypeLinuxCNC = translate("Path_ToolBit", "LinuxCNC tooltable (*.tbl)") + TooltableTypeCamotics = translate("Path_ToolBit", "Camotics tooltable (*.json)") filename = PySide.QtGui.QFileDialog.getSaveFileName( self.form, translate("Path_ToolBit", "Save toolbit library"), PathPreferences.lastPathToolLibrary(), - "{};;{}".format(TooltableTypeJSON, TooltableTypeLinuxCNC), + "{};;{};;{}".format( + TooltableTypeJSON, TooltableTypeLinuxCNC, TooltableTypeCamotics + ), ) if filename and filename[0]: if filename[1] == TooltableTypeLinuxCNC: @@ -803,6 +812,13 @@ class ToolBitLibrary(object): else "{}.tbl".format(filename[0]) ) self.libararySaveLinuxCNC(path) + elif filename[1] == TooltableTypeCamotics: + path = ( + filename[0] + if filename[0].endswith(".json") + else "{}.json".format(filename[0]) + ) + self.libararySaveCamotics(path) else: path = ( filename[0] @@ -878,3 +894,73 @@ class ToolBitLibrary(object): else: PathLog.error("Could not find tool #{} ".format(toolNr)) + + def libararySaveCamotics(self, path): + + SHAPEMAP = { + "ballend": "Ballnose", + "endmill": "Cylindrical", + "v-bit": "Conical", + "chamfer": "Snubnose", + } + + tooltemplate = { + "units": "metric", + "shape": "cylindrical", + "length": 10, + "diameter": 3.125, + "description": "", + } + toollist = {} + + unitstring = ( + "imperial" if FreeCAD.Units.getSchema() in [2, 3, 5, 7] else "metric" + ) + + for row in range(self.toolModel.rowCount()): + toolNr = self.toolModel.data( + self.toolModel.index(row, 0), PySide.QtCore.Qt.EditRole + ) + + toolPath = self.toolModel.data(self.toolModel.index(row, 0), _PathRole) + PathLog.debug(toolPath) + try: + bit = PathToolBit.Factory.CreateFrom(toolPath) + except FileNotFoundError as e: + FreeCAD.Console.PrintError(e) + continue + except Exception as e: + raise e + + if not bit: + continue + + PathLog.track(bit) + + toolitem = tooltemplate.copy() + + toolitem["diameter"] = ( + float(bit.Diameter.getUserPreferred()[0].split()[0]) + if hasattr(bit, "Diameter") + else 2 + ) + toolitem["description"] = bit.Label + toolitem["length"] = ( + float(bit.Length.getUserPreferred()[0].split()[0]) + if hasattr(bit, "Length") + else 10 + ) + + if hasattr(bit, "Camotics"): + toolitem["shape"] = bit.Camotics + else: + toolitem["shape"] = SHAPEMAP.get(bit.ShapeName, "Cylindrical") + + toolitem["units"] = unitstring + FreeCAD.ActiveDocument.removeObject(bit.Name) + + toollist[toolNr] = toolitem + + if len(toollist) > 0: + with open(path, "w") as fp: + fp.write(json.dumps(toollist, indent=2)) diff --git a/src/Mod/Path/PathScripts/PathVcarve.py b/src/Mod/Path/PathScripts/PathVcarve.py index 4e1fe227e0..31b5377ced 100644 --- a/src/Mod/Path/PathScripts/PathVcarve.py +++ b/src/Mod/Path/PathScripts/PathVcarve.py @@ -43,6 +43,7 @@ EXTERIOR1 = 2 EXTERIOR2 = 3 COLINEAR = 4 TWIN = 5 +BORDERLINE = 6 if False: PathLog.setLevel(PathLog.Level.DEBUG, PathLog.thisModule()) @@ -196,7 +197,7 @@ class ObjectVcarve(PathEngraveBase.ObjectOp): """Proxy class for Vcarve operation.""" def opFeatures(self, obj): - """opFeatures(obj) ... return all standard features and edges based geomtries""" + """opFeatures(obj) ... return all standard features and edges based geometries""" return ( PathOp.FeatureTool | PathOp.FeatureHeights @@ -291,13 +292,19 @@ class ObjectVcarve(PathEngraveBase.ObjectOp): voronoiWires = [] for f in faces: - vd = Path.Voronoi() + vd = Path.Voronoi.Diagram() insert_many_wires(vd, f.Wires) vd.construct() for e in vd.Edges: - e.Color = PRIMARY if e.isPrimary() else SECONDARY + if e.isPrimary(): + if e.isBorderline(): + e.Color = BORDERLINE + else: + e.Color = PRIMARY + else: + e.Color = SECONDARY vd.colorExterior(EXTERIOR1) vd.colorExterior( EXTERIOR2, diff --git a/src/Mod/Path/PathScripts/post/heidenhain_post.py b/src/Mod/Path/PathScripts/post/heidenhain_post.py index 9d94d002f5..a1880a0605 100644 --- a/src/Mod/Path/PathScripts/post/heidenhain_post.py +++ b/src/Mod/Path/PathScripts/post/heidenhain_post.py @@ -465,7 +465,7 @@ def export(objectslist, filename, argstring): parsedElem = HEIDEN_Line( c.Parameters, Compensation, Feed, True, Spindle_Status, Cmd_Count ) - if parsedElem != None: + if parsedElem is not None: POSTGCODE.append(parsedElem) # Linear movement @@ -473,7 +473,7 @@ def export(objectslist, filename, argstring): parsedElem = HEIDEN_Line( c.Parameters, Compensation, Feed, False, "", Cmd_Count ) - if parsedElem != None: + if parsedElem is not None: POSTGCODE.append(parsedElem) # Arc movement @@ -481,7 +481,7 @@ def export(objectslist, filename, argstring): parsedElem = HEIDEN_Arc( c.Parameters, command, Compensation, Feed, False, "", Cmd_Count ) - if parsedElem != None: + if parsedElem is not None: POSTGCODE.extend(parsedElem) if command == "G80": # Reset Canned Cycles @@ -492,13 +492,13 @@ def export(objectslist, filename, argstring): # Drilling, Dwell Drilling, Peck Drilling if command == "G81" or command == "G82" or command == "G83": parsedElem = HEIDEN_Drill(obj, c.Parameters, command, Feed) - if parsedElem != None: + if parsedElem is not None: POSTGCODE.extend(parsedElem) # Tool change if command == "M6": parsedElem = HEIDEN_ToolCall(obj) - if parsedElem != None: + if parsedElem is not None: POSTGCODE.append(parsedElem) if COMPENSATION_DIFF_STATUS[0]: # Restore the compensation if removed @@ -666,9 +666,9 @@ def HEIDEN_Line( H_Line += " " + H_Line_Params[1][0] # F parameter (check rapid o feed) - if line_rapid == True: + if line_rapid: H_Line_Params[1][1] = FEED_MAX_SPEED - if MACHINE_USE_FMAX == True and line_rapid == True: + if MACHINE_USE_FMAX and line_rapid: H_Line += " FMAX" else: if ( @@ -837,9 +837,9 @@ def HEIDEN_Arc( H_ArcPoint += " " + H_Arc_Params[1][0] # F parameter - if arc_rapid == True: + if arc_rapid: H_Arc_Params[1][1] = FEED_MAX_SPEED - if MACHINE_USE_FMAX == True and arc_rapid == True: + if MACHINE_USE_FMAX and arc_rapid: H_ArcPoint += " FMAX" else: if ( @@ -961,7 +961,7 @@ def HEIDEN_Drill( else: drill_SafePoint = drill_Params["R"] # Surface equals to theoric start point of drilling - if drill_Surface != None and drill_SafePoint > drill_Surface: + if drill_Surface is not None and drill_SafePoint > drill_Surface: drill_Defs["DIST"] = drill_Surface - drill_SafePoint drill_StartPoint = drill_Surface else: @@ -1108,7 +1108,7 @@ def HEIDEN_LBL_Get(GetPoint=None, GetLevel=None, GetAddit=0): global STORED_LBL global LBLIZE_PATH_LEVEL - if GetPoint != None: + if GetPoint is not None: if LBLIZE_PATH_LEVEL != GetLevel: LBLIZE_PATH_LEVEL = GetLevel if len(STORED_LBL) != 0 and len(STORED_LBL[-1][-1]) == 0: diff --git a/src/Mod/Path/PathScripts/post/philips_post.py b/src/Mod/Path/PathScripts/post/philips_post.py index edc2d82c67..74bc2612e0 100644 --- a/src/Mod/Path/PathScripts/post/philips_post.py +++ b/src/Mod/Path/PathScripts/post/philips_post.py @@ -431,7 +431,7 @@ def export(objectslist, filename, argstring): if not MODAL or command != lastcommand: outstring.append(mappedCommand) - # if MODAL == True: + # if MODAL: # #\better: append iff MODAL == False # if command == lastcommand: # outstring.pop(0) diff --git a/src/Mod/Path/PathSimulator/App/AppPathSimulator.cpp b/src/Mod/Path/PathSimulator/App/AppPathSimulator.cpp index 9079e8aef0..1d19fb21a2 100644 --- a/src/Mod/Path/PathSimulator/App/AppPathSimulator.cpp +++ b/src/Mod/Path/PathSimulator/App/AppPathSimulator.cpp @@ -46,7 +46,7 @@ public: initialize("This module is the PathSimulator module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Path/PathSimulator/App/PathSim.cpp b/src/Mod/Path/PathSimulator/App/PathSim.cpp index 5feb2c849a..c3e66e7af8 100644 --- a/src/Mod/Path/PathSimulator/App/PathSim.cpp +++ b/src/Mod/Path/PathSimulator/App/PathSim.cpp @@ -46,9 +46,9 @@ PathSim::PathSim() PathSim::~PathSim() { - if (m_stock != nullptr) + if (m_stock) delete m_stock; - if (m_tool != nullptr) + if (m_tool) delete m_tool; } @@ -68,7 +68,7 @@ Base::Placement * PathSim::ApplyCommand(Base::Placement * pos, Command * cmd) Point3D fromPos(*pos); Point3D toPos(*pos); toPos.UpdateCmd(*cmd); - if (m_tool != nullptr) + if (m_tool) { if (cmd->Name == "G0" || cmd->Name == "G1") { diff --git a/src/Mod/Path/PathSimulator/App/PathSimPyImp.cpp b/src/Mod/Path/PathSimulator/App/PathSimPyImp.cpp index d657a9fb17..5809ffe250 100644 --- a/src/Mod/Path/PathSimulator/App/PathSimPyImp.cpp +++ b/src/Mod/Path/PathSimulator/App/PathSimPyImp.cpp @@ -37,7 +37,7 @@ using namespace PathSimulator; // returns a string which represents the object e.g. when printed in python -std::string PathSimPy::representation(void) const +std::string PathSimPy::representation() const { return std::string(""); } @@ -87,7 +87,7 @@ PyObject* PathSimPy::GetResultMesh(PyObject * args) if (!PyArg_ParseTuple(args, "")) return nullptr; cStock *stock = getPathSimPtr()->m_stock; - if (stock == nullptr) + if (!stock) { PyErr_SetString(PyExc_RuntimeError, "Simulation has stock object"); return nullptr; @@ -122,7 +122,7 @@ PyObject* PathSimPy::ApplyCommand(PyObject * args, PyObject * kwds) return newposPy; } -Py::Object PathSimPy::getTool(void) const +Py::Object PathSimPy::getTool() const { //return Py::Object(); throw Py::AttributeError("Not yet implemented"); diff --git a/src/Mod/Path/PathSimulator/App/VolSim.h b/src/Mod/Path/PathSimulator/App/VolSim.h index fbf37ee59f..1d983ac534 100644 --- a/src/Mod/Path/PathSimulator/App/VolSim.h +++ b/src/Mod/Path/PathSimulator/App/VolSim.h @@ -50,8 +50,8 @@ struct Point3D { Point3D() : x(0), y(0), z(0), sina(0), cosa(0) {} Point3D(float x, float y, float z) : x(x), y(y), z(z), sina(0), cosa(0) {} - Point3D(Base::Vector3d & vec) : x(vec[0]), y(vec[1]), z(vec[2]), sina(0), cosa(0) {} - Point3D(Base::Placement & pl) : x(pl.getPosition()[0]), y(pl.getPosition()[1]), z(pl.getPosition()[2]), sina(0), cosa(0) {} + explicit Point3D(Base::Vector3d & vec) : x(vec[0]), y(vec[1]), z(vec[2]), sina(0), cosa(0) {} + explicit Point3D(Base::Placement & pl) : x(pl.getPosition()[0]), y(pl.getPosition()[1]), z(pl.getPosition()[2]), sina(0), cosa(0) {} inline void set(float px, float py, float pz) { x = px; y = py; z = pz; } inline void Add(Point3D & p) { x += p.x; y += p.y; z += p.z; } inline void Rotate() { float tx = x; x = x * cosa - y * sina; y = tx * sina + y * cosa; } @@ -119,7 +119,7 @@ public: ~Array2D() { - if (data != nullptr) + if (data) delete[] data; } diff --git a/src/Mod/Path/PathTests/TestPathSetupSheet.py b/src/Mod/Path/PathTests/TestPathSetupSheet.py index 9b74a12301..5d226ddeb6 100644 --- a/src/Mod/Path/PathTests/TestPathSetupSheet.py +++ b/src/Mod/Path/PathTests/TestPathSetupSheet.py @@ -31,8 +31,6 @@ from PathTests.PathTestUtils import PathTestBase def refstring(string): - if sys.version_info.major < 3: - return string return string.replace(" u'", " '") diff --git a/src/Mod/Path/PathTests/TestPathThreadMilling.py b/src/Mod/Path/PathTests/TestPathThreadMilling.py index fcfb49f1c1..dac113a77b 100644 --- a/src/Mod/Path/PathTests/TestPathThreadMilling.py +++ b/src/Mod/Path/PathTests/TestPathThreadMilling.py @@ -28,9 +28,19 @@ import math from PathTests.PathTestUtils import PathTestBase +class TestObject(object): + + def __init__(self, orientation, direction, zTop, zBottom): + self.ThreadOrientation = orientation + self.Direction = direction + self.StartDepth = FreeCAD.Units.Quantity(zTop, FreeCAD.Units.Length) + self.FinalDepth = FreeCAD.Units.Quantity(zBottom, FreeCAD.Units.Length) + def radii(internal, major, minor, toolDia, toolCrest): """test radii function for simple testing""" - return (minor, major) + if internal: + return (minor, major) + return (major, minor) class TestPathThreadMilling(PathTestBase): @@ -45,6 +55,18 @@ class TestPathThreadMilling(PathTestBase): for i in range(len(have)): self.assertRoughly(have[i], want[i]) + def assertSetupInternal(self, obj, c, begin, end): + cmd, zBegin, zEnd = PathThreadMilling.threadSetupInternal(obj, obj.StartDepth.Value, obj.FinalDepth.Value) + self.assertEqual(cmd, c) + self.assertEqual(zBegin, begin) + self.assertEqual(zEnd, end) + + def assertSetupExternal(self, obj, c, begin, end): + cmd, zBegin, zEnd = PathThreadMilling.threadSetupExternal(obj, obj.StartDepth.Value, obj.FinalDepth.Value) + self.assertEqual(cmd, c) + self.assertEqual(zBegin, begin) + self.assertEqual(zEnd, end) + def test00(self): """Verify internal radii.""" self.assertRadii(PathThreadMilling.threadRadii(True, 20, 18, 2, 0), (8, 9.2)) @@ -92,3 +114,36 @@ class TestPathThreadMilling(PathTestBase): PathThreadMilling.threadPasses(5, radii, False, 10, 9, 0, 0), [9.552786, 9.367544, 9.225403, 9.105573, 9], ) + + def test40(self): + """Verify internal right hand thread setup.""" + + hand = PathThreadMilling.RightHand + + self.assertSetupInternal(TestObject(hand, PathThreadMilling.DirectionConventional, 1, 0), "G2", 1, 0) + self.assertSetupInternal(TestObject(hand, PathThreadMilling.DirectionClimb, 1, 0), "G3", 0, 1) + + def test41(self): + """Verify internal left hand thread setup.""" + + hand = PathThreadMilling.LeftHand + + self.assertSetupInternal(TestObject(hand, PathThreadMilling.DirectionConventional, 1, 0), "G2", 0, 1) + self.assertSetupInternal(TestObject(hand, PathThreadMilling.DirectionClimb, 1, 0), "G3", 1, 0) + + def test50(self): + """Verify exteranl right hand thread setup.""" + + hand = PathThreadMilling.RightHand + + self.assertSetupExternal(TestObject(hand, PathThreadMilling.DirectionClimb, 1, 0), "G2", 1, 0) + self.assertSetupExternal(TestObject(hand, PathThreadMilling.DirectionConventional, 1, 0), "G3", 0, 1) + + def test51(self): + """Verify exteranl left hand thread setup.""" + + hand = PathThreadMilling.LeftHand + + self.assertSetupExternal(TestObject(hand, PathThreadMilling.DirectionClimb, 1, 0), "G2", 0, 1) + self.assertSetupExternal(TestObject(hand, PathThreadMilling.DirectionConventional, 1, 0), "G3", 1, 0) + diff --git a/src/Mod/Path/PathTests/TestPathVoronoi.py b/src/Mod/Path/PathTests/TestPathVoronoi.py index 90125677ca..a6a91bf725 100644 --- a/src/Mod/Path/PathTests/TestPathVoronoi.py +++ b/src/Mod/Path/PathTests/TestPathVoronoi.py @@ -25,7 +25,6 @@ import Part import Path import PathScripts.PathGeom as PathGeom import PathTests.PathTestUtils as PathTestUtils -import sys vd = None @@ -50,17 +49,14 @@ def initVD(): ptv = [FreeCAD.Vector(p[0], p[1]) for p in pts] ptv.append(ptv[0]) - vd = Path.Voronoi() + vd = Path.Voronoi.Diagram() for i in range(len(pts)): vd.addSegment(ptv[i], ptv[i + 1]) vd.construct() for e in vd.Edges: - if sys.version_info.major > 2: - e.Color = 0 if e.isPrimary() else 1 - else: - e.Color = long(0) if e.isPrimary() else long(1) + e.Color = 0 if e.isPrimary() else 1 vd.colorExterior(2) vd.colorColinear(3) diff --git a/src/Mod/Path/Tools/README.md b/src/Mod/Path/Tools/README.md index 7b869494ca..2c99e3e7c6 100644 --- a/src/Mod/Path/Tools/README.md +++ b/src/Mod/Path/Tools/README.md @@ -10,7 +10,7 @@ practically impossible for `*.fcstd` files. When a tool is instantiated in a job the PDN body is created from the shape and the attributes and constraints are set according to the values from the JSON file. All additional parameters are created as properties on the object. This -provides the the correct shape and dimensions which can be used to generate a point cloud or mesh for advanced +provides the correct shape and dimensions which can be used to generate a point cloud or mesh for advanced algorithms (and potentially simulation). # Tool Libraries diff --git a/src/Mod/Path/libarea/Adaptive.cpp b/src/Mod/Path/libarea/Adaptive.cpp index b46284572f..5c9f194a19 100644 --- a/src/Mod/Path/libarea/Adaptive.cpp +++ b/src/Mod/Path/libarea/Adaptive.cpp @@ -68,7 +68,7 @@ inline bool HasAnyPath(const Paths &paths) { for (Paths::size_type i = 0; i < paths.size(); i++) { - if (paths[i].size() > 0) + if (!paths[i].empty()) return true; } return false; @@ -251,7 +251,7 @@ int getPathNestingLevel(const Path &path, const Paths &paths) int nesting = 0; for (const auto &other : paths) { - if (path.size() > 0 && PointInPolygon(path.front(), other) != 0) + if (!path.empty() && PointInPolygon(path.front(), other) != 0) nesting++; } return nesting; @@ -262,7 +262,7 @@ void appendDirectChildPaths(Paths &outPaths, const Path &path, const Paths &path int nesting = getPathNestingLevel(path, paths); for (const auto &other : paths) { - if (path.size() > 0 && other.size() > 0 && PointInPolygon(other.front(), path) != 0) + if (!path.empty() && !other.empty() && PointInPolygon(other.front(), path) != 0) { if (getPathNestingLevel(other, paths) == nesting + 1) outPaths.push_back(other); @@ -480,7 +480,7 @@ bool Line2CircleIntersect(const IntPoint &c, double radius, const IntPoint &p1, result.emplace_back(p1.X + t2 * dx, p1.Y + t2 * dy); result.emplace_back(p1.X + t2 * dx, p1.Y + t2 * dy); } - return result.size() > 0; + return !result.empty(); } // calculate center point of polygon @@ -703,7 +703,7 @@ bool PopPathWithClosestPoint(Paths &paths /*closest path is removed from collect IntPoint p1, Path &result) { - if (paths.size() == 0) + if (paths.empty()) return false; double minDistSqrd = __DBL_MAX__; @@ -773,7 +773,7 @@ void DeduplicatePaths(const Paths &inputs, Paths &outputs) } } - if (!duplicate && new_pth.size() > 0) + if (!duplicate && !new_pth.empty()) { outputs.push_back(new_pth); } @@ -785,11 +785,11 @@ void ConnectPaths(Paths input, Paths &output) output.clear(); bool newPath = true; Path joined; - while (input.size() > 0) + while (!input.empty()) { if (newPath) { - if (joined.size() > 0) + if (!joined.empty()) output.push_back(joined); joined.clear(); for (auto pt : input.front()) @@ -841,7 +841,7 @@ void ConnectPaths(Paths input, Paths &output) if (!anyMatch) newPath = true; } - if (joined.size() > 0) + if (!joined.empty()) output.push_back(joined); } @@ -1200,7 +1200,7 @@ class EngagePoint while (PopPathWithClosestPoint(toChain, current, result)) { toolBoundPaths.push_back(result); - if (result.size() > 0) + if (!result.empty()) current = result.back(); } @@ -1794,7 +1794,7 @@ std::list Adaptive2d::Execute(const DPaths &stockPaths, const DP if (opType == OperationType::otClearingOutside) { // add stock paths, with overshooting - for (auto p : stockOvershoot) + for (const auto& p : stockOvershoot) inputPaths.push_back(p); } else if (opType == OperationType::otClearingInside) @@ -1916,16 +1916,16 @@ bool Adaptive2d::FindEntryPoint(TPaths &progressPaths, const Paths &toolBoundPat double step = RESOLUTION_FACTOR; double currentDelta = -1; clipof.Execute(incOffset, currentDelta); - while (incOffset.size() > 0) + while (!incOffset.empty()) { clipof.Execute(incOffset, currentDelta); - if (incOffset.size() > 0) + if (!incOffset.empty()) lastValidOffset = incOffset; currentDelta -= step; } for (size_t i = 0; i < lastValidOffset.size(); i++) { - if (lastValidOffset[i].size() > 0) + if (!lastValidOffset[i].empty()) { entryPoint = Compute2DPolygonCentroid(lastValidOffset[i]); found = true; @@ -1960,7 +1960,7 @@ bool Adaptive2d::FindEntryPoint(TPaths &progressPaths, const Paths &toolBoundPat clip.AddPaths(boundPaths, PolyType::ptClip, true); Paths crossing; clip.Execute(ClipType::ctDifference, crossing); - if (crossing.size() > 0) + if (!crossing.empty()) { // helix does not fit to the cutting area found = false; @@ -2345,7 +2345,7 @@ void Adaptive2d::AppendToolPath(TPaths &progressPaths, AdaptiveOutput &output, IntPoint endPoint(passToolPath[0]); // if there is a previous path - need to resolve linking move to new path - if (output.AdaptivePaths.size() > 0 && output.AdaptivePaths.back().second.size() > 1) + if (!output.AdaptivePaths.empty() && output.AdaptivePaths.back().second.size() > 1) { auto &lastTPath = output.AdaptivePaths.back(); @@ -2544,7 +2544,7 @@ void Adaptive2d::AppendToolPath(TPaths &progressPaths, AdaptiveOutput &output, cutPath.second.push_back(nextT); } - if (cutPath.second.size() > 0) + if (!cutPath.second.empty()) output.AdaptivePaths.push_back(cutPath); Perf_AppendToolPath.Stop(); } @@ -2554,20 +2554,20 @@ void Adaptive2d::CheckReportProgress(TPaths &progressPaths, bool force) if (!force && (clock() - lastProgressTime < PROGRESS_TICKS)) return; // not yet lastProgressTime = clock(); - if (progressPaths.size() == 0) + if (progressPaths.empty()) return; if (progressCallback) if ((*progressCallback)(progressPaths)) stopProcessing = true; // call python function, if returns true signal stop processing // clean the paths - keep the last point - if (progressPaths.back().second.size() == 0) + if (progressPaths.back().second.empty()) return; TPath *lastPath = &progressPaths.back(); DPoint *lastPoint = &lastPath->second.back(); DPoint next(lastPoint->first, lastPoint->second); while (progressPaths.size() > 1) progressPaths.pop_back(); - while (progressPaths.front().second.size() > 0) + while (!progressPaths.front().second.empty()) progressPaths.front().second.pop_back(); progressPaths.front().first = MotionType::mtCutting; progressPaths.front().second.push_back(next); @@ -2577,7 +2577,7 @@ void Adaptive2d::AddPathsToProgress(TPaths &progressPaths, Paths paths, MotionTy { for (const auto &pth : paths) { - if (pth.size() > 0) + if (!pth.empty()) { progressPaths.push_back(TPath()); progressPaths.back().first = mt; @@ -2590,7 +2590,7 @@ void Adaptive2d::AddPathsToProgress(TPaths &progressPaths, Paths paths, MotionTy void Adaptive2d::AddPathToProgress(TPaths &progressPaths, const Path pth, MotionType mt) { - if (pth.size() > 0) + if (!pth.empty()) { progressPaths.push_back(TPath()); progressPaths.back().first = mt; @@ -2639,7 +2639,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) clipof.Execute(outsideEngage, toolRadiusScaled - stepOverFactor * toolRadiusScaled); CleanPolygons(outsideEngage); ReversePaths(outsideEngage); - for (auto p : outsideEngage) + for (const auto& p : outsideEngage) engageBounds.push_back(p); outsideEntry = true; } @@ -2719,14 +2719,14 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) angleHistory.clear(); // append a new path to progress info paths - if (progressPaths.size() == 0) + if (progressPaths.empty()) { progressPaths.push_back(TPath()); } else { // append new path if previous not empty - if (progressPaths.back().second.size() > 0) + if (!progressPaths.back().second.empty()) progressPaths.push_back(TPath()); } @@ -2896,18 +2896,18 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) if (area > 0.5 * MIN_CUT_AREA_FACTOR * optimalCutAreaPD * RESOLUTION_FACTOR) { // cut is ok - record it noCutDistance=0; - if (toClearPath.size() == 0) + if (toClearPath.empty()) toClearPath.push_back(toolPos); toClearPath.push_back(newToolPos); cumulativeCutArea += area; // append to toolpaths - if (passToolPath.size() == 0) + if (passToolPath.empty()) { // in outside entry first successful cut defines the "helix center" and start point // in this case helix diameter is 0 (straight line downwards) - if (output.AdaptivePaths.size() == 0 && outsideEntry) + if (output.AdaptivePaths.empty() && outsideEntry) { entryPoint = toolPos; output.HelixCenterPoint.first = double(entryPoint.X) / scaleFactor; @@ -2922,7 +2922,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) toolPos = newToolPos; // append to progress info paths - if (progressPaths.size() == 0) + if (progressPaths.empty()) progressPaths.push_back(TPath()); progressPaths.back().second.emplace_back(double(newToolPos.X) / scaleFactor, double(newToolPos.Y) / scaleFactor); @@ -2945,7 +2945,7 @@ void Adaptive2d::ProcessPolyNode(Paths boundPaths, Paths toolBoundPaths) } } /* end of points loop*/ - if (toClearPath.size() > 0) + if (!toClearPath.empty()) { cleared.ExpandCleared(toClearPath); toClearPath.clear(); diff --git a/src/Mod/Path/libarea/AreaOrderer.cpp b/src/Mod/Path/libarea/AreaOrderer.cpp index 46ac425606..8d1d47e6e7 100644 --- a/src/Mod/Path/libarea/AreaOrderer.cpp +++ b/src/Mod/Path/libarea/AreaOrderer.cpp @@ -77,14 +77,14 @@ void CInnerCurves::Insert(shared_ptr pcurve) shared_ptr new_item(new CInnerCurves(shared_from_this(), pcurve)); this->m_inner_curves.insert(new_item); - for(shared_ptr c : outside_of_these) { + for(const shared_ptr& c : outside_of_these) { // move items c->m_pOuter = new_item; new_item->m_inner_curves.insert(c); this->m_inner_curves.erase(c); } - for(shared_ptr c : crossing_these) { + for(const shared_ptr& c : crossing_these) { // unite these new_item->Unite(c); this->m_inner_curves.erase(c); diff --git a/src/Mod/Path/libarea/clipper.cpp b/src/Mod/Path/libarea/clipper.cpp index 89799588ab..0af5d2443e 100644 --- a/src/Mod/Path/libarea/clipper.cpp +++ b/src/Mod/Path/libarea/clipper.cpp @@ -1923,7 +1923,7 @@ void Clipper::InsertLocalMinimaIntoAEL(const cInt botY) //if any output polygons share an edge, they'll need joining later ... if (Op1 && IsHorizontal(*rb) && - m_GhostJoins.size() > 0 && (rb->WindDelta != 0)) + !m_GhostJoins.empty() && (rb->WindDelta != 0)) { for (JoinList::size_type i = 0; i < m_GhostJoins.size(); ++i) { @@ -3798,7 +3798,7 @@ void ClipperOffset::Execute(Paths& solution, double delta) clpr.AddPath(outer, ptSubject, true); clpr.ReverseSolution(true); clpr.Execute(ctUnion, solution, pftNegative, pftNegative); - if (solution.size() > 0) solution.erase(solution.begin()); + if (!solution.empty()) solution.erase(solution.begin()); } } //------------------------------------------------------------------------------ diff --git a/src/Mod/Points/App/AppPointsPy.cpp b/src/Mod/Points/App/AppPointsPy.cpp index 22fa85c128..aba6213f94 100644 --- a/src/Mod/Points/App/AppPointsPy.cpp +++ b/src/Mod/Points/App/AppPointsPy.cpp @@ -64,7 +64,7 @@ public: initialize("This module is the Points module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: std::tuple readE57Settings() const diff --git a/src/Mod/Points/App/CMakeLists.txt b/src/Mod/Points/App/CMakeLists.txt index 3a32b8eb84..3529caa5e9 100644 --- a/src/Mod/Points/App/CMakeLists.txt +++ b/src/Mod/Points/App/CMakeLists.txt @@ -8,6 +8,7 @@ include_directories( ${Boost_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${CMAKE_BINARY_DIR}/src/3rdParty/libE57Format ${CMAKE_SOURCE_DIR}/src/3rdParty/libE57Format/include diff --git a/src/Mod/Points/App/Points.h b/src/Mod/Points/App/Points.h index 6c23b39196..0776e1f4e7 100644 --- a/src/Mod/Points/App/Points.h +++ b/src/Mod/Points/App/Points.h @@ -45,7 +45,7 @@ namespace Points */ class PointsExport PointKernel : public Data::ComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: typedef float float_type; @@ -56,12 +56,12 @@ public: PointKernel() { } - PointKernel(size_type size) + explicit PointKernel(size_type size) { resize(size); } PointKernel(const PointKernel&); - virtual ~PointKernel() + ~PointKernel() override { } @@ -73,14 +73,14 @@ public: * List of different subelement types * its NOT a list of the subelements itself */ - virtual std::vector getElementTypes() const; - virtual unsigned long countSubElements(const char* Type) const; + std::vector getElementTypes() const override; + unsigned long countSubElements(const char* Type) const override; /// get the subelement by type and number - virtual Data::Segment* getSubElement(const char* Type, unsigned long) const; + Data::Segment* getSubElement(const char* Type, unsigned long) const override; //@} - inline void setTransform(const Base::Matrix4D& rclTrf){_Mtrx = rclTrf;} - inline Base::Matrix4D getTransform() const{return _Mtrx;} + inline void setTransform(const Base::Matrix4D& rclTrf) override{_Mtrx = rclTrf;} + inline Base::Matrix4D getTransform() const override{return _Mtrx;} std::vector& getBasicPoints() { return this->_Points; } const std::vector& getBasicPoints() const @@ -90,20 +90,20 @@ public: void swap(std::vector& pts) { this->_Points.swap(pts); } - virtual void getPoints(std::vector &Points, + void getPoints(std::vector &Points, std::vector &Normals, - float Accuracy, uint16_t flags=0) const; - virtual void transformGeometry(const Base::Matrix4D &rclMat); - virtual Base::BoundBox3d getBoundBox()const; + float Accuracy, uint16_t flags=0) const override; + void transformGeometry(const Base::Matrix4D &rclMat) override; + Base::BoundBox3d getBoundBox()const override; /** @name I/O */ //@{ // Implemented from Persistence - unsigned int getMemSize () const; - void Save (Base::Writer &writer) const; - void SaveDocFile (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); - void RestoreDocFile(Base::Reader &reader); + unsigned int getMemSize () const override; + void Save (Base::Writer &writer) const override; + void SaveDocFile (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; + void RestoreDocFile(Base::Reader &reader) override; void save(const char* file) const; void save(std::ostream&) const; void load(const char* file); @@ -130,15 +130,15 @@ public: /// get the points inline const Base::Vector3d getPoint(const int idx) const { - return transformToOutside(_Points[idx]); + return transformPointToOutside(_Points[idx]); } /// set the points inline void setPoint(const int idx,const Base::Vector3d& point) { - _Points[idx] = transformToInside(point); + _Points[idx] = transformPointToInside(point); } /// insert the points inline void push_back(const Base::Vector3d& point) { - _Points.push_back(transformToInside(point)); + _Points.push_back(transformPointToInside(point)); } class PointsExport const_point_iterator diff --git a/src/Mod/Points/App/PointsAlgos.cpp b/src/Mod/Points/App/PointsAlgos.cpp index 79932ee785..785550b74f 100644 --- a/src/Mod/Points/App/PointsAlgos.cpp +++ b/src/Mod/Points/App/PointsAlgos.cpp @@ -228,7 +228,7 @@ private: template class ConverterT : public Converter { public: - virtual std::string toString(double f) const { + std::string toString(double f) const override { T c = static_cast(f); std::ostringstream oss; oss.precision(7); @@ -236,12 +236,12 @@ public: oss << c; return oss.str(); } - virtual double toDouble(Base::InputStream& str) const { + double toDouble(Base::InputStream& str) const override { T c; str >> c; return static_cast(c); } - virtual int getSizeOf() const { + int getSizeOf() const override { return sizeof(T); } }; @@ -256,35 +256,35 @@ public: _end = data.size(); _cur = 0; } - ~DataStreambuf() { + ~DataStreambuf() override { } protected: - virtual int_type uflow() { + int_type uflow() override { if (_cur == _end) return traits_type::eof(); return static_cast(_buffer[_cur++]) & 0x000000ff; } - virtual int_type underflow() { + int_type underflow() override { if (_cur == _end) return traits_type::eof(); return static_cast(_buffer[_cur]) & 0x000000ff; } - virtual int_type pbackfail(int_type ch) { + int_type pbackfail(int_type ch) override { if (_cur == _beg || (ch != traits_type::eof() && ch != _buffer[_cur-1])) return traits_type::eof(); return static_cast(_buffer[--_cur]) & 0x000000ff; } - virtual std::streamsize showmanyc() { + std::streamsize showmanyc() override { return _end - _cur; } - virtual pos_type seekoff(std::streambuf::off_type off, + pos_type seekoff(std::streambuf::off_type off, std::ios_base::seekdir way, std::ios_base::openmode = - std::ios::in | std::ios::out) { + std::ios::in | std::ios::out) override { int p_pos=-1; if (way == std::ios_base::beg) p_pos = _beg; @@ -303,9 +303,9 @@ protected: return ((p_pos+off) - _beg); } - virtual pos_type seekpos(std::streambuf::pos_type pos, + pos_type seekpos(std::streambuf::pos_type pos, std::ios_base::openmode which = - std::ios::in | std::ios::out) { + std::ios::in | std::ios::out) override { (void)which; return seekoff(pos, std::ios_base::beg); } @@ -1357,66 +1357,61 @@ void E57Reader::read(const std::string& filename) if ((n.type() == e57::E57_FLOAT) || (n.type() == e57::E57_SCALED_INTEGER)) { if (n.elementName() == "cartesianX") { ptr_xyz[0] = cnt_xyz++; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(xyz[0]) , buf_size , true , true - ) + ); } else if (n.elementName() == "cartesianY") { ptr_xyz[1] = cnt_xyz++; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(xyz[buf_size]) , buf_size , true , true - ) + ); } else if (n.elementName() == "cartesianZ") { ptr_xyz[2] = cnt_xyz++; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(xyz[2 * buf_size]) , buf_size , true , true - ) + ); } else if (n.elementName() == "intensity") { inty = true; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(intensity[0]) , buf_size , true , true - ) + ); } else { - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(nil[0]) , buf_size , true , true - ) + ); } @@ -1424,66 +1419,61 @@ void E57Reader::read(const std::string& filename) else if (n.type() == e57::E57_INTEGER) { if (n.elementName() == "colorRed") { ptr_rgb[0] = cnt_rgb++; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(rgb[0]) , buf_size , true , true - ) + ); } else if (n.elementName() == "colorGreen") { ptr_rgb[1] = cnt_rgb++; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(rgb[buf_size]) , buf_size , true , true - ) + ); } else if (n.elementName() == "colorBlue") { ptr_rgb[2] = cnt_rgb++; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(rgb[2 * buf_size]) , buf_size , true , true - ) + ); } else if (n.elementName() == "cartesianInvalidState") { inv_state = true; - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(state[0]) , buf_size , true , true - ) + ); } else { - sdb.push_back( - e57::SourceDestBuffer( + sdb.emplace_back( imfi , n.elementName() , &(nil[0]) , buf_size , true , true - ) + ); } } @@ -1619,9 +1609,9 @@ PlyWriter::~PlyWriter() void PlyWriter::write(const std::string& filename) { std::list properties; - properties.push_back("float x"); - properties.push_back("float y"); - properties.push_back("float z"); + properties.emplace_back("float x"); + properties.emplace_back("float y"); + properties.emplace_back("float z"); ConverterPtr convert_float(new ConverterT); ConverterPtr convert_uint(new ConverterT); @@ -1636,19 +1626,19 @@ void PlyWriter::write(const std::string& filename) bool hasNormals = (normals.size() == points.size()); if (hasNormals) { - properties.push_back("float nx"); - properties.push_back("float ny"); - properties.push_back("float nz"); + properties.emplace_back("float nx"); + properties.emplace_back("float ny"); + properties.emplace_back("float nz"); converters.push_back(convert_float); converters.push_back(convert_float); converters.push_back(convert_float); } if (hasColors) { - properties.push_back("uchar red"); - properties.push_back("uchar green"); - properties.push_back("uchar blue"); - properties.push_back("uchar alpha"); + properties.emplace_back("uchar red"); + properties.emplace_back("uchar green"); + properties.emplace_back("uchar blue"); + properties.emplace_back("uchar alpha"); converters.push_back(convert_uint); converters.push_back(convert_uint); converters.push_back(convert_uint); @@ -1656,7 +1646,7 @@ void PlyWriter::write(const std::string& filename) } if (hasIntensity) { - properties.push_back("float intensity"); + properties.emplace_back("float intensity"); converters.push_back(convert_float); } @@ -1778,14 +1768,14 @@ PcdWriter::~PcdWriter() void PcdWriter::write(const std::string& filename) { std::list fields; - fields.push_back("x"); - fields.push_back("y"); - fields.push_back("z"); + fields.emplace_back("x"); + fields.emplace_back("y"); + fields.emplace_back("z"); std::list types; - types.push_back("F"); - types.push_back("F"); - types.push_back("F"); + types.emplace_back("F"); + types.emplace_back("F"); + types.emplace_back("F"); ConverterPtr convert_float(new ConverterT); ConverterPtr convert_uint(new ConverterT); @@ -1800,26 +1790,26 @@ void PcdWriter::write(const std::string& filename) bool hasNormals = (normals.size() == points.size()); if (hasNormals) { - fields.push_back("normal_x"); - fields.push_back("normal_y"); - fields.push_back("normal_z"); - types.push_back("F"); - types.push_back("F"); - types.push_back("F"); + fields.emplace_back("normal_x"); + fields.emplace_back("normal_y"); + fields.emplace_back("normal_z"); + types.emplace_back("F"); + types.emplace_back("F"); + types.emplace_back("F"); converters.push_back(convert_float); converters.push_back(convert_float); converters.push_back(convert_float); } if (hasColors) { - fields.push_back("rgba"); - types.push_back("U"); + fields.emplace_back("rgba"); + types.emplace_back("U"); converters.push_back(convert_uint); } if (hasIntensity) { - fields.push_back("intensity"); - types.push_back("F"); + fields.emplace_back("intensity"); + types.emplace_back("F"); converters.push_back(convert_float); } diff --git a/src/Mod/Points/App/PointsAlgos.h b/src/Mod/Points/App/PointsAlgos.h index 4ade5608a3..6bee986ed5 100644 --- a/src/Mod/Points/App/PointsAlgos.h +++ b/src/Mod/Points/App/PointsAlgos.h @@ -76,16 +76,16 @@ class AscReader : public Reader { public: AscReader(); - ~AscReader(); - void read(const std::string& filename); + ~AscReader() override; + void read(const std::string& filename) override; }; class PlyReader : public Reader { public: PlyReader(); - ~PlyReader(); - void read(const std::string& filename); + ~PlyReader() override; + void read(const std::string& filename) override; private: std::size_t readHeader(std::istream&, std::string& format, std::size_t& offset, @@ -102,8 +102,8 @@ class PcdReader : public Reader { public: PcdReader(); - ~PcdReader(); - void read(const std::string& filename); + ~PcdReader() override; + void read(const std::string& filename) override; private: std::size_t readHeader(std::istream&, std::string& format, std::vector& fields, @@ -119,8 +119,8 @@ class E57Reader : public Reader { public: E57Reader(const bool& Color, const bool& State, const float& Distance); - ~E57Reader(); - void read(const std::string& filename); + ~E57Reader() override; + void read(const std::string& filename) override; protected: bool useColor, checkState; float minDistance; @@ -129,7 +129,7 @@ protected: class Writer { public: - Writer(const PointKernel&); + explicit Writer(const PointKernel&); virtual ~Writer(); virtual void write(const std::string& filename) = 0; @@ -152,25 +152,25 @@ protected: class AscWriter : public Writer { public: - AscWriter(const PointKernel&); - ~AscWriter(); - void write(const std::string& filename); + explicit AscWriter(const PointKernel&); + ~AscWriter() override; + void write(const std::string& filename) override; }; class PlyWriter : public Writer { public: - PlyWriter(const PointKernel&); - ~PlyWriter(); - void write(const std::string& filename); + explicit PlyWriter(const PointKernel&); + ~PlyWriter() override; + void write(const std::string& filename) override; }; class PcdWriter : public Writer { public: - PcdWriter(const PointKernel&); - ~PcdWriter(); - void write(const std::string& filename); + explicit PcdWriter(const PointKernel&); + ~PcdWriter() override; + void write(const std::string& filename) override; }; } // namespace Points diff --git a/src/Mod/Points/App/PointsFeature.h b/src/Mod/Points/App/PointsFeature.h index c171334ac4..667ffed87a 100644 --- a/src/Mod/Points/App/PointsFeature.h +++ b/src/Mod/Points/App/PointsFeature.h @@ -51,30 +51,30 @@ class PointsFeaturePy; */ class PointsExport Feature : public App::GeoFeature { - PROPERTY_HEADER(Points::Feature); + PROPERTY_HEADER_WITH_OVERRIDE(Points::Feature); public: /// Constructor Feature(); - virtual ~Feature(); + ~Feature() override; /** @name methods override Feature */ //@{ - void Restore(Base::XMLReader &reader); - void RestoreDocFile(Base::Reader &reader); - short mustExecute() const; + void Restore(Base::XMLReader &reader) override; + void RestoreDocFile(Base::Reader &reader) override; + short mustExecute() const override; /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "PointsGui::ViewProviderScattered"; } - virtual const App::PropertyComplexGeoData* getPropertyOfGeometry() const { + const App::PropertyComplexGeoData* getPropertyOfGeometry() const override { return &Points; } protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; //@} public: diff --git a/src/Mod/Points/App/PointsGrid.cpp b/src/Mod/Points/App/PointsGrid.cpp index 84086650fb..7a5c497c70 100644 --- a/src/Mod/Points/App/PointsGrid.cpp +++ b/src/Mod/Points/App/PointsGrid.cpp @@ -124,7 +124,7 @@ void PointsGrid::Rebuild (int iCtGridPerAxis) void PointsGrid::InitGrid () { - assert(_pclPoints != nullptr); + assert(_pclPoints); unsigned long i, j; @@ -475,7 +475,7 @@ void PointsGrid::SearchNearestFromPoint (const Base::Vector3d &rclPt, std::set &raclInd) const { const std::set &rclSet = _aulGrid[ulX][ulY][ulZ]; - if (rclSet.size() > 0) + if (!rclSet.empty()) { raclInd.insert(rclSet.begin(), rclSet.end()); return rclSet.size(); @@ -656,7 +656,7 @@ void PointsGrid::Validate (const PointKernel &rclPoints) void PointsGrid::Validate () { - if (_pclPoints == nullptr) + if (!_pclPoints) return; if (_pclPoints->size() != _ulCtElements) diff --git a/src/Mod/Points/App/PointsGrid.h b/src/Mod/Points/App/PointsGrid.h index 585de8e1b0..41ac53d609 100644 --- a/src/Mod/Points/App/PointsGrid.h +++ b/src/Mod/Points/App/PointsGrid.h @@ -52,7 +52,7 @@ public: /** @name Construction */ //@{ /// Construction - PointsGrid (const PointKernel &rclM); + explicit PointsGrid (const PointKernel &rclM); /// Construction PointsGrid (); /// Construction @@ -175,7 +175,7 @@ class PointsExport PointsGridIterator { public: /// Construction - PointsGridIterator (const PointsGrid &rclG); + explicit PointsGridIterator (const PointsGrid &rclG); /** Returns the bounding box of the current grid element. */ Base::BoundBox3d GetBoundBox () const { return _rclGrid.GetBoundBox(_ulX, _ulY, _ulZ); } diff --git a/src/Mod/Points/App/Properties.h b/src/Mod/Points/App/Properties.h index dc5c4a2ddf..f9e5da902a 100644 --- a/src/Mod/Points/App/Properties.h +++ b/src/Mod/Points/App/Properties.h @@ -44,27 +44,27 @@ namespace Points */ class PointsExport PropertyGreyValue : public App::PropertyFloat { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyGreyValue() { } - virtual ~PropertyGreyValue() + ~PropertyGreyValue() override { } }; class PointsExport PropertyGreyValueList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyGreyValueList(); - virtual ~PropertyGreyValueList(); + ~PropertyGreyValueList() override; - virtual void setSize(int newSize); - virtual int getSize() const; + void setSize(int newSize) override; + int getSize() const override; /** Sets the property */ @@ -84,18 +84,18 @@ public: return _lValueList; } - virtual PyObject *getPyObject(); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual App::Property *Copy() const; - virtual void Paste(const App::Property &from); - virtual unsigned int getMemSize () const; + App::Property *Copy() const override; + void Paste(const App::Property &from) override; + unsigned int getMemSize () const override; /** @name Modify */ //@{ @@ -108,14 +108,14 @@ private: class PointsExport PropertyNormalList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyNormalList(); - ~PropertyNormalList(); + ~PropertyNormalList() override; - virtual void setSize(int newSize); - virtual int getSize() const; + void setSize(int newSize) override; + int getSize() const override; void setValue(const Base::Vector3f&); void setValue(float x, float y, float z); @@ -134,19 +134,19 @@ public: return _lValueList; } - virtual PyObject *getPyObject(); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save (Base::Writer &writer) const; - virtual void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual void SaveDocFile (Base::Writer &writer) const; - virtual void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; - virtual App::Property *Copy() const; - virtual void Paste(const App::Property &from); + App::Property *Copy() const override; + void Paste(const App::Property &from) override; - virtual unsigned int getMemSize () const; + unsigned int getMemSize () const override; /** @name Modify */ //@{ @@ -169,7 +169,7 @@ struct PointsExport CurvatureInfo */ class PointsExport PropertyCurvatureList: public App::PropertyLists { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: enum { @@ -182,12 +182,12 @@ public: public: PropertyCurvatureList(); - ~PropertyCurvatureList(); + ~PropertyCurvatureList() override; - void setSize(int newSize) { + void setSize(int newSize) override { _lValueList.resize(newSize); } - int getSize() const { + int getSize() const override { return _lValueList.size(); } void setValue(const CurvatureInfo&); @@ -205,25 +205,25 @@ public: return _lValueList; } - virtual PyObject *getPyObject(); - virtual void setPyObject(PyObject *); + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; //@} /** @name Undo/Redo */ //@{ /// returns a new copy of the property (mainly for Undo/Redo and transactions) - App::Property *Copy() const; + App::Property *Copy() const override; /// paste the value from the property (mainly for Undo/Redo and transactions) - void Paste(const App::Property &from); - unsigned int getMemSize () const; + void Paste(const App::Property &from) override; + unsigned int getMemSize () const override; //@} /** @name Modify */ diff --git a/src/Mod/Points/App/PropertyPointKernel.h b/src/Mod/Points/App/PropertyPointKernel.h index 23b01a837b..415c3af34a 100644 --- a/src/Mod/Points/App/PropertyPointKernel.h +++ b/src/Mod/Points/App/PropertyPointKernel.h @@ -33,11 +33,11 @@ namespace Points */ class PointsExport PropertyPointKernel : public App::PropertyComplexGeoData { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyPointKernel(); - ~PropertyPointKernel(); + ~PropertyPointKernel() override; /** @name Getter/setter */ //@{ @@ -45,38 +45,38 @@ public: void setValue( const PointKernel& m); /// get the points (only const possible!) const PointKernel &getValue() const; - const Data::ComplexGeoData* getComplexData() const; - void setTransform(const Base::Matrix4D& rclTrf); - Base::Matrix4D getTransform() const; + const Data::ComplexGeoData* getComplexData() const override; + void setTransform(const Base::Matrix4D& rclTrf) override; + Base::Matrix4D getTransform() const override; //@} /** @name Getting basic geometric entities */ //@{ /** Returns the bounding box around the underlying mesh kernel */ - Base::BoundBox3d getBoundingBox() const; + Base::BoundBox3d getBoundingBox() const override; //@} /** @name Python interface */ //@{ - PyObject* getPyObject(); - void setPyObject(PyObject *value); + PyObject* getPyObject() override; + void setPyObject(PyObject *value) override; //@} /** @name Undo/Redo */ //@{ /// returns a new copy of the property (mainly for Undo/Redo and transactions) - App::Property *Copy() const; + App::Property *Copy() const override; /// paste the value from the property (mainly for Undo/Redo and transactions) - void Paste(const App::Property &from); - unsigned int getMemSize () const; + void Paste(const App::Property &from) override; + unsigned int getMemSize () const override; //@} /** @name Save/restore */ //@{ - void Save (Base::Writer &writer) const; - void Restore(Base::XMLReader &reader); - void SaveDocFile (Base::Writer &writer) const; - void RestoreDocFile(Base::Reader &reader); + void Save (Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; + void SaveDocFile (Base::Writer &writer) const override; + void RestoreDocFile(Base::Reader &reader) override; //@} /** @name Modification */ @@ -84,7 +84,7 @@ public: PointKernel* startEditing(); void finishEditing(); /// Transform the real 3d point kernel - void transformGeometry(const Base::Matrix4D &rclMat); + void transformGeometry(const Base::Matrix4D &rclMat) override; void removeIndices( const std::vector& ); //@} diff --git a/src/Mod/Points/App/Structured.h b/src/Mod/Points/App/Structured.h index 9acf72c20a..fb67f5bb93 100644 --- a/src/Mod/Points/App/Structured.h +++ b/src/Mod/Points/App/Structured.h @@ -36,12 +36,12 @@ namespace Points */ class PointsExport Structured : public Feature { - PROPERTY_HEADER(Points::Structured); + PROPERTY_HEADER_WITH_OVERRIDE(Points::Structured); public: /// Constructor Structured(); - virtual ~Structured(); + ~Structured() override; App::PropertyInteger Width; /**< The width of the structured cloud. */ App::PropertyInteger Height; /**< The height of the structured cloud. */ @@ -49,9 +49,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(); + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName() const { + const char* getViewProviderName() const override { return "PointsGui::ViewProviderStructured"; } //@} diff --git a/src/Mod/Points/Gui/AppPointsGui.cpp b/src/Mod/Points/Gui/AppPointsGui.cpp index d55bdaa2ac..ca8c32f89c 100644 --- a/src/Mod/Points/Gui/AppPointsGui.cpp +++ b/src/Mod/Points/Gui/AppPointsGui.cpp @@ -57,7 +57,7 @@ public: initialize("This module is the PointsGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Points/Gui/CMakeLists.txt b/src/Mod/Points/Gui/CMakeLists.txt index 82b89d4239..eef1165d7d 100644 --- a/src/Mod/Points/Gui/CMakeLists.txt +++ b/src/Mod/Points/Gui/CMakeLists.txt @@ -5,6 +5,7 @@ include_directories( ${EIGEN3_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) set(PointsGui_LIBS diff --git a/src/Mod/Points/Gui/DlgPointsReadImp.h b/src/Mod/Points/Gui/DlgPointsReadImp.h index 6d7b17f88c..d36e261104 100644 --- a/src/Mod/Points/Gui/DlgPointsReadImp.h +++ b/src/Mod/Points/Gui/DlgPointsReadImp.h @@ -38,8 +38,8 @@ class DlgPointsReadImp : public QDialog Q_OBJECT public: - DlgPointsReadImp(const char *FileName, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); - ~DlgPointsReadImp(); + explicit DlgPointsReadImp(const char *FileName, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags() ); + ~DlgPointsReadImp() override; private: std::unique_ptr ui; diff --git a/src/Mod/Points/Gui/ViewProvider.cpp b/src/Mod/Points/Gui/ViewProvider.cpp index 2f816e3f73..61422a3f5c 100644 --- a/src/Mod/Points/Gui/ViewProvider.cpp +++ b/src/Mod/Points/Gui/ViewProvider.cpp @@ -249,16 +249,16 @@ void ViewProviderPoints::setDisplayMode(const char* ModeName) std::vector ViewProviderPoints::getDisplayModes() const { std::vector StrList; - StrList.push_back("Points"); + StrList.emplace_back("Points"); // FIXME: This way all display modes are added even if the points feature // doesn't support it. // For the future a more flexible way is needed to add new display modes // at a later time #if 1 - StrList.push_back("Color"); - StrList.push_back("Shaded"); - StrList.push_back("Intensity"); + StrList.emplace_back("Color"); + StrList.emplace_back("Shaded"); + StrList.emplace_back("Intensity"); #else if (pcObject) { diff --git a/src/Mod/Points/Gui/ViewProvider.h b/src/Mod/Points/Gui/ViewProvider.h index c4bc4d05ec..c473d21b70 100644 --- a/src/Mod/Points/Gui/ViewProvider.h +++ b/src/Mod/Points/Gui/ViewProvider.h @@ -60,8 +60,8 @@ class ViewProviderPointsBuilder : public Gui::ViewProviderBuilder { public: ViewProviderPointsBuilder(){} - ~ViewProviderPointsBuilder(){} - virtual void buildNodes(const App::Property*, std::vector&) const; + ~ViewProviderPointsBuilder() override{} + void buildNodes(const App::Property*, std::vector&) const override; void createPoints(const App::Property*, SoCoordinate3*, SoPointSet*) const; void createPoints(const App::Property*, SoCoordinate3*, SoIndexedPointSet*) const; }; @@ -73,30 +73,30 @@ public: */ class PointsGuiExport ViewProviderPoints : public Gui::ViewProviderGeometryObject { - PROPERTY_HEADER(PointsGui::ViewProviderPoints); + PROPERTY_HEADER_WITH_OVERRIDE(PointsGui::ViewProviderPoints); public: ViewProviderPoints(); - virtual ~ViewProviderPoints(); + ~ViewProviderPoints() override; App::PropertyFloatConstraint PointSize; /// set the viewing mode - virtual void setDisplayMode(const char* ModeName); + void setDisplayMode(const char* ModeName) override; /// returns a list of all possible modes - virtual std::vector getDisplayModes() const; - virtual QIcon getIcon() const; + std::vector getDisplayModes() const override; + QIcon getIcon() const override; /// Sets the edit mnode - bool setEdit(int ModNum); + bool setEdit(int ModNum) override; /// Unsets the edit mode - void unsetEdit(int ModNum); + void unsetEdit(int ModNum) override; public: static void clipPointsCallback(void * ud, SoEventCallback * n); protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; void setVertexColorMode(App::PropertyColorList*); void setVertexGreyvalueMode(Points::PropertyGreyValueList*); void setVertexNormalMode(Points::PropertyNormalList*); @@ -120,22 +120,22 @@ private: */ class PointsGuiExport ViewProviderScattered : public ViewProviderPoints { - PROPERTY_HEADER(PointsGui::ViewProviderScattered); + PROPERTY_HEADER_WITH_OVERRIDE(PointsGui::ViewProviderScattered); public: ViewProviderScattered(); - virtual ~ViewProviderScattered(); + ~ViewProviderScattered() override; /** * Extracts the point data from the feature \a pcFeature and creates * an Inventor node \a SoNode with these data. */ - virtual void attach(App::DocumentObject *); + void attach(App::DocumentObject *) override; /// Update the point representation - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual void cut(const std::vector& picked, Gui::View3DInventorViewer &Viewer); + void cut(const std::vector& picked, Gui::View3DInventorViewer &Viewer) override; protected: SoPointSet * pcPoints; @@ -148,22 +148,22 @@ protected: */ class PointsGuiExport ViewProviderStructured : public ViewProviderPoints { - PROPERTY_HEADER(PointsGui::ViewProviderStructured); + PROPERTY_HEADER_WITH_OVERRIDE(PointsGui::ViewProviderStructured); public: ViewProviderStructured(); - virtual ~ViewProviderStructured(); + ~ViewProviderStructured() override; /** * Extracts the point data from the feature \a pcFeature and creates * an Inventor node \a SoNode with these data. */ - virtual void attach(App::DocumentObject *); + void attach(App::DocumentObject *) override; /// Update the point representation - virtual void updateData(const App::Property*); + void updateData(const App::Property*) override; protected: - virtual void cut(const std::vector& picked, Gui::View3DInventorViewer &Viewer); + void cut(const std::vector& picked, Gui::View3DInventorViewer &Viewer) override; protected: SoIndexedPointSet * pcPoints; diff --git a/src/Mod/Points/Gui/Workbench.h b/src/Mod/Points/Gui/Workbench.h index 0862a6d113..79628e5142 100644 --- a/src/Mod/Points/Gui/Workbench.h +++ b/src/Mod/Points/Gui/Workbench.h @@ -34,16 +34,16 @@ namespace PointsGui { */ class PointsGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; - Gui::MenuItem* setupMenuBar() const; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; + Gui::MenuItem* setupMenuBar() const override; }; } // namespace PointsGui diff --git a/src/Mod/Raytracing/App/AppRaytracingPy.cpp b/src/Mod/Raytracing/App/AppRaytracingPy.cpp index 379314a107..20fa6df33e 100644 --- a/src/Mod/Raytracing/App/AppRaytracingPy.cpp +++ b/src/Mod/Raytracing/App/AppRaytracingPy.cpp @@ -26,7 +26,9 @@ #include #include +#include #include +#include #include "PovTools.h" #include "LuxTools.h" // automatically generated..... @@ -67,20 +69,18 @@ public: initialize("This module is the Raytracing module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object writeProjectFile(const Py::Tuple& args) { - char *fromPython; - if (! PyArg_ParseTuple(args.ptr(), "(s)", &fromPython)) + const char *fromPython = "FreeCAD.pov"; + if (! PyArg_ParseTuple(args.ptr(), "|(s)", &fromPython)) throw Py::Exception(); - std::ofstream fout; - if (fromPython) - fout.open(fromPython); - else - fout.open("FreeCAD.pov"); + Base::ofstream fout; + Base::FileInfo fi(fromPython); + fout.open(fi); fout << FreeCAD ; fout.close(); diff --git a/src/Mod/Raytracing/App/CMakeLists.txt b/src/Mod/Raytracing/App/CMakeLists.txt index c1e2df18bd..97024d0fc8 100644 --- a/src/Mod/Raytracing/App/CMakeLists.txt +++ b/src/Mod/Raytracing/App/CMakeLists.txt @@ -11,6 +11,7 @@ include_directories( ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Raytracing/App/LuxFeature.h b/src/Mod/Raytracing/App/LuxFeature.h index c5b9908085..e69248844a 100644 --- a/src/Mod/Raytracing/App/LuxFeature.h +++ b/src/Mod/Raytracing/App/LuxFeature.h @@ -41,7 +41,7 @@ class Property; */ class RaytracingExport LuxFeature: public Raytracing::RaySegment { - PROPERTY_HEADER(Raytracing::LuxFeature); + PROPERTY_HEADER_WITH_OVERRIDE(Raytracing::LuxFeature); public: /// Constructor LuxFeature(void); @@ -52,12 +52,12 @@ public: /** @name methods override Feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute(void) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "Gui::ViewProviderDocumentObject"; } //@} diff --git a/src/Mod/Raytracing/App/LuxProject.cpp b/src/Mod/Raytracing/App/LuxProject.cpp index 36134d57ea..19dcce0cd7 100644 --- a/src/Mod/Raytracing/App/LuxProject.cpp +++ b/src/Mod/Raytracing/App/LuxProject.cpp @@ -69,7 +69,7 @@ void LuxProject::onDocumentRestored() App::DocumentObjectExecReturn *LuxProject::execute(void) { - if (std::string(PageResult.getValue()) == "") + if (std::string(PageResult.getValue()).empty()) PageResult.setValue(Template.getValue()); Base::FileInfo fi(Template.getValue()); diff --git a/src/Mod/Raytracing/App/LuxProject.h b/src/Mod/Raytracing/App/LuxProject.h index e67247a7ed..cf850972c2 100644 --- a/src/Mod/Raytracing/App/LuxProject.h +++ b/src/Mod/Raytracing/App/LuxProject.h @@ -41,7 +41,7 @@ class Property; //class RayFeature: public Part::PartFeature class RaytracingExport LuxProject: public App::DocumentObjectGroup { - PROPERTY_HEADER(Raytracing::LuxProject); + PROPERTY_HEADER_WITH_OVERRIDE(Raytracing::LuxProject); public: /// Constructor @@ -55,13 +55,13 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute(void) override; + short mustExecute() const override; + const char* getViewProviderName(void) const override { return "RaytracingGui::ViewProviderLux"; } /// get called after a document has been fully restored - virtual void onDocumentRestored(); + void onDocumentRestored() override; //@} diff --git a/src/Mod/Raytracing/App/PovTools.cpp b/src/Mod/Raytracing/App/PovTools.cpp index 97b1722456..4dbba9fe5d 100644 --- a/src/Mod/Raytracing/App/PovTools.cpp +++ b/src/Mod/Raytracing/App/PovTools.cpp @@ -317,7 +317,8 @@ void PovTools::writeShapeCSV(const char *FileName, BRepMesh_IncrementalMesh MESH(Shape,fMeshDeviation); // open the file and write - std::ofstream fout(FileName); + Base::FileInfo fi(FileName); + Base::ofstream fout(fi); // counting faces and start sequencer int l = 1; diff --git a/src/Mod/Raytracing/App/RayFeature.h b/src/Mod/Raytracing/App/RayFeature.h index 38890a3e56..8d1d757835 100644 --- a/src/Mod/Raytracing/App/RayFeature.h +++ b/src/Mod/Raytracing/App/RayFeature.h @@ -41,7 +41,7 @@ class Property; */ class RaytracingExport RayFeature: public Raytracing::RaySegment { - PROPERTY_HEADER(Raytracing::RayFeature); + PROPERTY_HEADER_WITH_OVERRIDE(Raytracing::RayFeature); public: /// Constructor RayFeature(void); @@ -52,12 +52,12 @@ public: /** @name methods override Feature */ //@{ - short mustExecute() const; + short mustExecute() const override; /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute(void) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "Gui::ViewProviderDocumentObject"; } //@} diff --git a/src/Mod/Raytracing/App/RayProject.cpp b/src/Mod/Raytracing/App/RayProject.cpp index 7d26586277..852888649b 100644 --- a/src/Mod/Raytracing/App/RayProject.cpp +++ b/src/Mod/Raytracing/App/RayProject.cpp @@ -69,7 +69,7 @@ void RayProject::onDocumentRestored() App::DocumentObjectExecReturn *RayProject::execute(void) { - if (std::string(PageResult.getValue()) == "") + if (std::string(PageResult.getValue()).empty()) PageResult.setValue(Template.getValue()); Base::FileInfo fi(Template.getValue()); diff --git a/src/Mod/Raytracing/App/RayProject.h b/src/Mod/Raytracing/App/RayProject.h index 401d9d74bf..f1f58432e0 100644 --- a/src/Mod/Raytracing/App/RayProject.h +++ b/src/Mod/Raytracing/App/RayProject.h @@ -40,7 +40,7 @@ class Property; */ class RaytracingExport RayProject: public App::DocumentObjectGroup { - PROPERTY_HEADER(Raytracing::RayProject); + PROPERTY_HEADER_WITH_OVERRIDE(Raytracing::RayProject); public: /// Constructor @@ -54,13 +54,13 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; - const char* getViewProviderName(void) const { + App::DocumentObjectExecReturn *execute(void) override; + short mustExecute() const override; + const char* getViewProviderName(void) const override { return "RaytracingGui::ViewProviderPovray"; } /// get called after a document has been fully restored - virtual void onDocumentRestored(); + void onDocumentRestored() override; //@} diff --git a/src/Mod/Raytracing/App/RaySegment.h b/src/Mod/Raytracing/App/RaySegment.h index 61ff34f17e..eac0df6c0f 100644 --- a/src/Mod/Raytracing/App/RaySegment.h +++ b/src/Mod/Raytracing/App/RaySegment.h @@ -41,12 +41,12 @@ namespace Raytracing */ class RaytracingExport RaySegment: public App::DocumentObject { - PROPERTY_HEADER(Raytracing::RaySegment); + PROPERTY_HEADER_WITH_OVERRIDE(Raytracing::RaySegment); public: /// Constructor RaySegment(void); - virtual ~RaySegment(); + ~RaySegment() override; App::PropertyString Result; @@ -54,10 +54,10 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute(void) override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "Gui::ViewProviderDocumentObject"; } //@} diff --git a/src/Mod/Raytracing/Gui/AppRaytracingGuiPy.cpp b/src/Mod/Raytracing/Gui/AppRaytracingGuiPy.cpp index d797d5d4e0..4d66397974 100644 --- a/src/Mod/Raytracing/Gui/AppRaytracingGuiPy.cpp +++ b/src/Mod/Raytracing/Gui/AppRaytracingGuiPy.cpp @@ -69,7 +69,7 @@ public: initialize("This module is the RaytracingGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object open(const Py::Tuple& args) diff --git a/src/Mod/Raytracing/Gui/CMakeLists.txt b/src/Mod/Raytracing/Gui/CMakeLists.txt index 0d84834dfa..31e8b524b4 100644 --- a/src/Mod/Raytracing/Gui/CMakeLists.txt +++ b/src/Mod/Raytracing/Gui/CMakeLists.txt @@ -14,6 +14,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Raytracing/Gui/Command.cpp b/src/Mod/Raytracing/Gui/Command.cpp index baaca3a5b6..e2a5e64a0f 100644 --- a/src/Mod/Raytracing/Gui/Command.cpp +++ b/src/Mod/Raytracing/Gui/Command.cpp @@ -355,8 +355,8 @@ void CmdRaytracingNewPovrayProject::activated(int iMsg) return; } - QAction* a = pcAction->actions()[iMsg]; - QFileInfo tfi(a->property("Template").toString()); + const QList actions = pcAction->actions(); + QFileInfo tfi(actions.at(iMsg)->property("Template").toString()); if (tfi.isReadable()) { try { openCommand("Create POV-Ray project"); @@ -410,7 +410,7 @@ Gui::Action * CmdRaytracingNewPovrayProject::createAction(void) _pcAction = pcAction; languageChange(); if (!pcAction->actions().isEmpty()) { - pcAction->setIcon(pcAction->actions()[0]->icon()); + pcAction->setIcon(qAsConst(pcAction)->actions()[0]->icon()); pcAction->setProperty("defaultAction", QVariant(0)); } @@ -614,7 +614,7 @@ void CmdRaytracingRender::activated(int) std::string renderer; if (renderType == Raytracing::RayProject::getClassTypeId()) { renderer = hGrp->GetASCII("PovrayExecutable", ""); - if (renderer == "") { + if (renderer.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("POV-Ray not found"), QObject::tr("Please set the path to the POV-Ray executable in the preferences.")); return; @@ -628,7 +628,7 @@ void CmdRaytracingRender::activated(int) } } else { renderer = hGrp->GetASCII("LuxrenderExecutable", ""); - if (renderer == "") { + if (renderer.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Luxrender not found"), QObject::tr("Please set the path to the luxrender or luxconsole executable in the preferences.")); return; @@ -801,8 +801,8 @@ void CmdRaytracingNewLuxProject::activated(int iMsg) return; } - QAction* a = pcAction->actions()[iMsg]; - QFileInfo tfi(a->property("Template").toString()); + const QList actions = pcAction->actions(); + QFileInfo tfi(actions.at(iMsg)->property("Template").toString()); if (tfi.isReadable()) { try { openCommand("Create LuxRender project"); @@ -852,7 +852,7 @@ Gui::Action * CmdRaytracingNewLuxProject::createAction(void) _pcAction = pcAction; languageChange(); if (!pcAction->actions().isEmpty()) { - pcAction->setIcon(pcAction->actions()[0]->icon()); + pcAction->setIcon(qAsConst(pcAction)->actions()[0]->icon()); pcAction->setProperty("defaultAction", QVariant(0)); } diff --git a/src/Mod/Raytracing/Gui/DlgSettingsRayImp.h b/src/Mod/Raytracing/Gui/DlgSettingsRayImp.h index fd0922fa20..3a6efce700 100644 --- a/src/Mod/Raytracing/Gui/DlgSettingsRayImp.h +++ b/src/Mod/Raytracing/Gui/DlgSettingsRayImp.h @@ -40,13 +40,13 @@ class DlgSettingsRayImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsRayImp( QWidget* parent = nullptr ); - ~DlgSettingsRayImp(); + explicit DlgSettingsRayImp( QWidget* parent = nullptr ); + ~DlgSettingsRayImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Raytracing/Gui/PovrayHighlighter.h b/src/Mod/Raytracing/Gui/PovrayHighlighter.h index 8bfcc9adaa..8e17704db7 100644 --- a/src/Mod/Raytracing/Gui/PovrayHighlighter.h +++ b/src/Mod/Raytracing/Gui/PovrayHighlighter.h @@ -36,7 +36,7 @@ class PovrayHighlighterP; class PovrayHighlighter : public Gui::SyntaxHighlighter { public: - PovrayHighlighter(QObject* parent); + explicit PovrayHighlighter(QObject* parent); virtual ~PovrayHighlighter(); protected: diff --git a/src/Mod/Raytracing/Gui/ViewProvider.h b/src/Mod/Raytracing/Gui/ViewProvider.h index 8550e67077..fdf84eaf30 100644 --- a/src/Mod/Raytracing/Gui/ViewProvider.h +++ b/src/Mod/Raytracing/Gui/ViewProvider.h @@ -32,36 +32,36 @@ namespace RaytracingGui { class ViewProviderLux : public Gui::ViewProviderDocumentObjectGroup { - PROPERTY_HEADER(RaytracingGui::ViewProviderLux); + PROPERTY_HEADER_WITH_OVERRIDE(RaytracingGui::ViewProviderLux); Q_DECLARE_TR_FUNCTIONS(RaytracingGui::ViewProviderLux) public: ViewProviderLux(); - virtual ~ViewProviderLux(); + ~ViewProviderLux() override; - bool doubleClicked(void); - void setupContextMenu(QMenu* menu, QObject* receiver, const char* member); + bool doubleClicked(void) override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; class ViewProviderPovray : public Gui::ViewProviderDocumentObjectGroup { - PROPERTY_HEADER(RaytracingGui::ViewProviderPovray); + PROPERTY_HEADER_WITH_OVERRIDE(RaytracingGui::ViewProviderPovray); Q_DECLARE_TR_FUNCTIONS(RaytracingGui::ViewProviderPovray) public: ViewProviderPovray(); - virtual ~ViewProviderPovray(); + ~ViewProviderPovray() override; - bool doubleClicked(void); - void setupContextMenu(QMenu* menu, QObject* receiver, const char* member); + bool doubleClicked(void) override; + void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; protected: - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; }; } // namespace RaytracingGui diff --git a/src/Mod/Raytracing/Gui/Workbench.h b/src/Mod/Raytracing/Gui/Workbench.h index a3b1b80873..3ba09ec6c4 100644 --- a/src/Mod/Raytracing/Gui/Workbench.h +++ b/src/Mod/Raytracing/Gui/Workbench.h @@ -33,15 +33,15 @@ namespace RaytracingGui { */ class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; }; } // namespace RaytracingGui diff --git a/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp b/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp index 8d57bca24d..b14636bba0 100644 --- a/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp +++ b/src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp @@ -79,9 +79,24 @@ public: Module() : Py::ExtensionModule("ReverseEngineering") { add_keyword_method("approxSurface",&Module::approxSurface, - "approxSurface(Points=,UDegree=3,VDegree=3,NbUPoles=6,NbVPoles=6,Smooth=True,\n" - "Weight=0.1,Grad=1.0,Bend=0.0,\n" - "Iterations=5,Correction=True,PatchFactor=1.0)" + "approxSurface(Points, UDegree=3, VDegree=3, NbUPoles=6, NbVPoles=6,\n" + "Smooth=True, Weight=0.1, Grad=1.0, Bend=0.0, Curv=0.0\n" + "Iterations=5, Correction=True, PatchFactor=1.0, UVDirs=((ux, uy, uz), (vx, vy, vz)))\n\n" + "Points: the input data (e.g. a point cloud or mesh)\n" + "UDegree: the degree in u parametric direction\n" + "VDegree: the degree in v parametric direction\n" + "NbUPoles: the number of control points in u parametric direction\n" + "NbVPoles: the number of control points in v parametric direction\n" + "Smooth: use energy terms to create a smooth surface\n" + "Weight: weight of the energy terms altogether\n" + "Grad: weight of the gradient term\n" + "Bend: weight of the bending energy term\n" + "Curv: weight of the deviation of curvature term\n" + "Iterations: number of iterations\n" + "Correction: perform a parameter correction of each iteration step\n" + "PatchFactor: create an extended surface\n" + "UVDirs: set the u,v parameter directions as tuple of two vectors\n" + " If not set then they will be determined by computing a best-fit plane\n" ); #if defined(HAVE_PCL_SURFACE) add_keyword_method("triangulate",&Module::triangulate, @@ -147,7 +162,7 @@ public: initialize("This module is the ReverseEngineering module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object approxSurface(const Py::Tuple& args, const Py::Dict& kwds) diff --git a/src/Mod/ReverseEngineering/App/ApproxSurface.cpp b/src/Mod/ReverseEngineering/App/ApproxSurface.cpp index c78de802ef..0df5c39618 100644 --- a/src/Mod/ReverseEngineering/App/ApproxSurface.cpp +++ b/src/Mod/ReverseEngineering/App/ApproxSurface.cpp @@ -720,7 +720,7 @@ Handle(Geom_BSplineSurface) ParameterCorrection::CreateSurface(const TColgp_Arra bool bParaCor, double fSizeFactor) { - if (_pvcPoints != nullptr) { + if (_pvcPoints) { delete _pvcPoints; _pvcPoints = nullptr; delete _pvcUVParam; @@ -1007,7 +1007,7 @@ namespace Reen { class ScalarProduct { public: - ScalarProduct(const math_Matrix& mat) : mat(mat) + explicit ScalarProduct(const math_Matrix& mat) : mat(mat) { } std::vector multiply(int col) const diff --git a/src/Mod/ReverseEngineering/App/ApproxSurface.h b/src/Mod/ReverseEngineering/App/ApproxSurface.h index eb7f764053..680b1dd210 100644 --- a/src/Mod/ReverseEngineering/App/ApproxSurface.h +++ b/src/Mod/ReverseEngineering/App/ApproxSurface.h @@ -55,14 +55,14 @@ public: * Constructor * @param iSize Length of Knots vector */ - SplineBasisfunction(int iSize); + explicit SplineBasisfunction(int iSize); /** * Constructor * @param vKnots Knot vector * @param iOrder Order (degree + 1) of the basic polynomial */ - SplineBasisfunction(TColStd_Array1OfReal& vKnots, int iOrder=1); + explicit SplineBasisfunction(TColStd_Array1OfReal& vKnots, int iOrder=1); /** * Constructor @@ -144,14 +144,14 @@ public: * Constructor * @param iSize Length of the knot vector */ - BSplineBasis(int iSize); + explicit BSplineBasis(int iSize); /** * Constructor * @param vKnots Knot vector * @param iOrder Order (degree + 1) of the basic polynomial */ - BSplineBasis(TColStd_Array1OfReal& vKnots, int iOrder=1); + explicit BSplineBasis(TColStd_Array1OfReal& vKnots, int iOrder=1); /** * Constructor @@ -190,7 +190,7 @@ public: * @param fParam Parameter value * @return ValueT */ - virtual ValueT LocalSupport(int iIndex, double fParam); + ValueT LocalSupport(int iIndex, double fParam) override; /** * Calculates the function value Nik(t) at the point fParam @@ -199,7 +199,7 @@ public: * @param fParam Parameter value * @return Function value Nik(t) */ - virtual double BasisFunction(int iIndex, double fParam); + double BasisFunction(int iIndex, double fParam) override; /** * Calculates the function values of the first iMaxDer derivatives at the point fParam @@ -211,13 +211,13 @@ public: * The list must be sufficiently long for iMaxDer+1 elements. * @return List of function values */ - virtual void DerivativesOfBasisFunction(int iIndex, int iMaxDer, double fParam, - TColStd_Array1OfReal& Derivat); + void DerivativesOfBasisFunction(int iIndex, int iMaxDer, double fParam, + TColStd_Array1OfReal& Derivat) override; /** * Calculates the kth derivative at the point fParam */ - virtual double DerivativeOfBasisFunction(int iIndex, int k, double fParam); + double DerivativeOfBasisFunction(int iIndex, int k, double fParam) override; /** * Calculates the integral of the product of two B-splines or their derivatives. @@ -229,7 +229,7 @@ public: /** * Destructor */ - virtual~ BSplineBasis(); + ~ BSplineBasis() override; protected: @@ -255,7 +255,7 @@ class ReenExport ParameterCorrection public: // Constructor - ParameterCorrection(unsigned usUOrder=4, //Order in u-direction (order = degree + 1) + explicit ParameterCorrection(unsigned usUOrder=4, //Order in u-direction (order = degree + 1) unsigned usVOrder=4, //Order in v-direction unsigned usUCtrlpoints=6, //Qty. of the control points in the u-direction unsigned usVCtrlpoints=6); //Qty. of the control points in the v-direction @@ -370,12 +370,12 @@ class ReenExport BSplineParameterCorrection : public ParameterCorrection { public: // Constructor - BSplineParameterCorrection(unsigned usUOrder=4, //Order in u-direction (order = degree + 1) + explicit BSplineParameterCorrection(unsigned usUOrder=4, //Order in u-direction (order = degree + 1) unsigned usVOrder=4, //Order in the v-direction unsigned usUCtrlpoints=6, //Qty. of the control points in u-direction unsigned usVCtrlpoints=6); //Qty. of the control points in v-direction - virtual ~BSplineParameterCorrection(){} + ~BSplineParameterCorrection() override{} protected: /** @@ -386,18 +386,18 @@ protected: /** * Carries out a parameter correction. */ - virtual void DoParameterCorrection(int iIter); + void DoParameterCorrection(int iIter) override; /** * Solve an overdetermined LGS with the help of the Householder-Tansformation */ - virtual bool SolveWithoutSmoothing(); + bool SolveWithoutSmoothing() override; /** * Solve a regular system of equations by LU decomposition. Depending on the weighting, * smoothing terms are included */ - virtual bool SolveWithSmoothing(double fWeight); + bool SolveWithSmoothing(double fWeight) override; public: /** @@ -443,7 +443,7 @@ public: /** * Use smoothing-terms */ - virtual void EnableSmoothing(bool bSmooth=true, double fSmoothInfl=1.0f); + void EnableSmoothing(bool bSmooth=true, double fSmoothInfl=1.0f) override; /** * Use smoothing-terms diff --git a/src/Mod/ReverseEngineering/App/CMakeLists.txt b/src/Mod/ReverseEngineering/App/CMakeLists.txt index 1ea1a8457a..13d5d2ab5a 100644 --- a/src/Mod/ReverseEngineering/App/CMakeLists.txt +++ b/src/Mod/ReverseEngineering/App/CMakeLists.txt @@ -29,6 +29,7 @@ include_directories( ${Boost_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} ${PCL_INCLUDE_DIRS} diff --git a/src/Mod/ReverseEngineering/App/Segmentation.h b/src/Mod/ReverseEngineering/App/Segmentation.h index e2df4a6d64..228b647b3f 100644 --- a/src/Mod/ReverseEngineering/App/Segmentation.h +++ b/src/Mod/ReverseEngineering/App/Segmentation.h @@ -49,7 +49,7 @@ private: class NormalEstimation { public: - NormalEstimation(const Points::PointKernel&); + explicit NormalEstimation(const Points::PointKernel&); /** \brief Set the number of k nearest neighbors to use for the feature estimation. * \param[in] k the number of k-nearest neighbors */ diff --git a/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp b/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp index 94cc7e1cca..c298cc3c88 100644 --- a/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp +++ b/src/Mod/ReverseEngineering/Gui/AppReverseEngineeringGui.cpp @@ -52,7 +52,7 @@ public: initialize("This module is the ReverseEngineeringGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/ReverseEngineering/Gui/CMakeLists.txt b/src/Mod/ReverseEngineering/Gui/CMakeLists.txt index a25f86a17a..183ec9aea1 100644 --- a/src/Mod/ReverseEngineering/Gui/CMakeLists.txt +++ b/src/Mod/ReverseEngineering/Gui/CMakeLists.txt @@ -13,6 +13,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/ReverseEngineering/Gui/Command.cpp b/src/Mod/ReverseEngineering/Gui/Command.cpp index e7c7fb9c94..b12cd51c2b 100644 --- a/src/Mod/ReverseEngineering/Gui/Command.cpp +++ b/src/Mod/ReverseEngineering/Gui/Command.cpp @@ -461,7 +461,7 @@ void CmdSegmentationFromComponents::activated(int) const Mesh::MeshObject& mesh = it->Mesh.getValue(); std::vector > comps = mesh.getComponents(); - for (auto jt : comps) { + for (const auto& jt : comps) { std::unique_ptr segment(mesh.meshFromSegment(jt)); Mesh::Feature* feaSegm = static_cast(group->addObject("Mesh::Feature", "Segment")); Mesh::MeshObject* feaMesh = feaSegm->Mesh.startEditing(); @@ -610,9 +610,7 @@ void CmdViewTriangulation::activated(int) "Width=%2.Width," "Height=%2.Height)" ) - .arg(document) - .arg(object) - ; + .arg(document, object); runCommand(Doc, command.toLatin1()); } diff --git a/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.h b/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.h index 6a06585a5a..02e6a22817 100644 --- a/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.h +++ b/src/Mod/ReverseEngineering/Gui/FitBSplineSurface.h @@ -35,15 +35,15 @@ class FitBSplineSurfaceWidget : public QWidget Q_OBJECT public: - FitBSplineSurfaceWidget(const App::DocumentObjectT&, QWidget* parent = nullptr); - ~FitBSplineSurfaceWidget(); + explicit FitBSplineSurfaceWidget(const App::DocumentObjectT&, QWidget* parent = nullptr); + ~FitBSplineSurfaceWidget() override; bool accept(); private: void restoreSettings(); void saveSettings(); - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private Q_SLOTS: void on_makePlacement_clicked(); @@ -58,14 +58,14 @@ class TaskFitBSplineSurface : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskFitBSplineSurface(const App::DocumentObjectT&); - ~TaskFitBSplineSurface(); + explicit TaskFitBSplineSurface(const App::DocumentObjectT&); + ~TaskFitBSplineSurface() override; public: - void open(); - bool accept(); + void open() override; + bool accept() override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/ReverseEngineering/Gui/Poisson.h b/src/Mod/ReverseEngineering/Gui/Poisson.h index eb8e3ed9e7..3277e73dd5 100644 --- a/src/Mod/ReverseEngineering/Gui/Poisson.h +++ b/src/Mod/ReverseEngineering/Gui/Poisson.h @@ -35,13 +35,13 @@ class PoissonWidget : public QWidget Q_OBJECT public: - PoissonWidget(const App::DocumentObjectT&, QWidget* parent = nullptr); - ~PoissonWidget(); + explicit PoissonWidget(const App::DocumentObjectT&, QWidget* parent = nullptr); + ~PoissonWidget() override; bool accept(); private: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: class Private; @@ -53,14 +53,14 @@ class TaskPoisson : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskPoisson(const App::DocumentObjectT&); - ~TaskPoisson(); + explicit TaskPoisson(const App::DocumentObjectT&); + ~TaskPoisson() override; public: - void open(); - bool accept(); + void open() override; + bool accept() override; - QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/ReverseEngineering/Gui/Segmentation.h b/src/Mod/ReverseEngineering/Gui/Segmentation.h index 8c684b6074..f46b7df756 100644 --- a/src/Mod/ReverseEngineering/Gui/Segmentation.h +++ b/src/Mod/ReverseEngineering/Gui/Segmentation.h @@ -41,12 +41,12 @@ class Segmentation : public QWidget Q_OBJECT public: - Segmentation(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~Segmentation(); + explicit Segmentation(Mesh::Feature* mesh, QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~Segmentation() override; void accept(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; @@ -59,13 +59,13 @@ private: class TaskSegmentation : public Gui::TaskView::TaskDialog { public: - TaskSegmentation(Mesh::Feature* mesh); - ~TaskSegmentation(); + explicit TaskSegmentation(Mesh::Feature* mesh); + ~TaskSegmentation() override; public: - bool accept(); + bool accept() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp b/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp index ff3ce8ecfe..82488df9cb 100644 --- a/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp +++ b/src/Mod/ReverseEngineering/Gui/SegmentationManual.cpp @@ -150,7 +150,7 @@ static void findGeometry(int minFaces, double tolerance, (surfFit, kernel, minFaces, tolerance)); finder.FindSegments(segm); - for (auto segmIt : segm) { + for (const auto& segmIt : segm) { const std::vector& data = segmIt->GetSegments(); for (const auto& dataIt : data) { vpm->addSelection(dataIt); diff --git a/src/Mod/ReverseEngineering/Gui/SegmentationManual.h b/src/Mod/ReverseEngineering/Gui/SegmentationManual.h index 86fcde49c9..0133ccbb6c 100644 --- a/src/Mod/ReverseEngineering/Gui/SegmentationManual.h +++ b/src/Mod/ReverseEngineering/Gui/SegmentationManual.h @@ -43,8 +43,8 @@ class SegmentationManual : public QWidget Q_OBJECT public: - SegmentationManual(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); - ~SegmentationManual(); + explicit SegmentationManual(QWidget* parent = nullptr, Qt::WindowFlags fl = Qt::WindowFlags()); + ~SegmentationManual() override; void reject(); void createSegment(); @@ -62,7 +62,7 @@ public Q_SLOTS: void on_sphereDetect_clicked(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: class Private; @@ -81,17 +81,17 @@ class TaskSegmentationManual : public Gui::TaskView::TaskDialog public: TaskSegmentationManual(); - ~TaskSegmentationManual(); + ~TaskSegmentationManual() override; public: - bool accept(); - void clicked(int); + bool accept() override; + void clicked(int) override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Close; } - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument(void) const override { return true; } - virtual void modifyStandardButtons(QDialogButtonBox*); + void modifyStandardButtons(QDialogButtonBox*) override; private: SegmentationManual* widget; diff --git a/src/Mod/ReverseEngineering/Gui/Workbench.h b/src/Mod/ReverseEngineering/Gui/Workbench.h index 28c01e8247..5c04fcca9d 100644 --- a/src/Mod/ReverseEngineering/Gui/Workbench.h +++ b/src/Mod/ReverseEngineering/Gui/Workbench.h @@ -33,16 +33,16 @@ namespace ReverseEngineeringGui { */ class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace ReverseEngineeringGui diff --git a/src/Mod/Robot/App/AppRobot.cpp b/src/Mod/Robot/App/AppRobot.cpp index 496494c069..021c48a892 100644 --- a/src/Mod/Robot/App/AppRobot.cpp +++ b/src/Mod/Robot/App/AppRobot.cpp @@ -55,7 +55,7 @@ public: initialize("This module is the Robot module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object simulateToFile(const Py::Tuple& args) diff --git a/src/Mod/Robot/App/CMakeLists.txt b/src/Mod/Robot/App/CMakeLists.txt index 82f90ee20f..56fe62b934 100644 --- a/src/Mod/Robot/App/CMakeLists.txt +++ b/src/Mod/Robot/App/CMakeLists.txt @@ -15,6 +15,7 @@ include_directories( ${EIGEN3_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) @@ -34,7 +35,7 @@ SET(Python_SRCS Robot6AxisPy.xml Robot6AxisPyImp.cpp TrajectoryPy.xml - TrajectoryPyImp.cpp + TrajectoryPyImp.cpp RobotObjectPy.xml RobotObjectPyImp.cpp WaypointPy.xml diff --git a/src/Mod/Robot/App/Edge2TracObject.cpp b/src/Mod/Robot/App/Edge2TracObject.cpp index 09341c1b25..dec177ec79 100644 --- a/src/Mod/Robot/App/Edge2TracObject.cpp +++ b/src/Mod/Robot/App/Edge2TracObject.cpp @@ -73,7 +73,7 @@ App::DocumentObjectExecReturn *Edge2TracObject::execute(void) const Part::TopoShape& TopShape = base->Shape.getShape(); const std::vector& SubVals = Source.getSubValuesStartsWith("Edge"); - if (SubVals.size() == 0) + if (SubVals.empty()) return new App::DocumentObjectExecReturn("No Edges specified"); // container for all the edges @@ -89,7 +89,7 @@ App::DocumentObjectExecReturn *Edge2TracObject::execute(void) Part::Edgecluster acluster(edges); Part::tEdgeClusterVector aclusteroutput = acluster.GetClusters(); - if(aclusteroutput.size() == 0) + if(aclusteroutput.empty()) return new App::DocumentObjectExecReturn("No Edges specified"); // set the number of cluster and edges diff --git a/src/Mod/Robot/App/PropertyTrajectory.cpp b/src/Mod/Robot/App/PropertyTrajectory.cpp index 458e1177d7..8bd149f72a 100644 --- a/src/Mod/Robot/App/PropertyTrajectory.cpp +++ b/src/Mod/Robot/App/PropertyTrajectory.cpp @@ -58,7 +58,7 @@ void PropertyTrajectory::setValue(const Trajectory& sh) } -const Trajectory &PropertyTrajectory::getValue(void)const +const Trajectory &PropertyTrajectory::getValue()const { return _Trajectory; } @@ -91,7 +91,7 @@ Base::BoundBox3d PropertyTrajectory::getBoundingBox() const } -PyObject *PropertyTrajectory::getPyObject(void) +PyObject *PropertyTrajectory::getPyObject() { return new TrajectoryPy(new Trajectory(_Trajectory)); } @@ -109,7 +109,7 @@ void PropertyTrajectory::setPyObject(PyObject *value) } } -App::Property *PropertyTrajectory::Copy(void) const +App::Property *PropertyTrajectory::Copy() const { PropertyTrajectory *prop = new PropertyTrajectory(); prop->_Trajectory = this->_Trajectory; @@ -124,7 +124,7 @@ void PropertyTrajectory::Paste(const App::Property &from) hasSetValue(); } -unsigned int PropertyTrajectory::getMemSize (void) const +unsigned int PropertyTrajectory::getMemSize () const { return _Trajectory.getMemSize(); } diff --git a/src/Mod/Robot/App/Robot6Axis.cpp b/src/Mod/Robot/App/Robot6Axis.cpp index f54a4ce4d2..5cb04af7c6 100644 --- a/src/Mod/Robot/App/Robot6Axis.cpp +++ b/src/Mod/Robot/App/Robot6Axis.cpp @@ -26,8 +26,10 @@ #ifndef _PreComp_ #endif +#include #include #include +#include #include "kdl_cp/chain.hpp" #include "kdl_cp/chainfksolver.hpp" @@ -136,7 +138,8 @@ void split(std::string const& string, const char delimiter, std::vector > &KinTable); diff --git a/src/Mod/Robot/App/Robot6AxisPyImp.cpp b/src/Mod/Robot/App/Robot6AxisPyImp.cpp index 0295b67264..a9609f1a9b 100644 --- a/src/Mod/Robot/App/Robot6AxisPyImp.cpp +++ b/src/Mod/Robot/App/Robot6AxisPyImp.cpp @@ -36,7 +36,7 @@ using namespace Robot; // returns a string which represents the object e.g. when printed in python -std::string Robot6AxisPy::representation(void) const +std::string Robot6AxisPy::representation() const { std::stringstream str; @@ -78,7 +78,7 @@ PyObject* Robot6AxisPy::check(PyObject * /*args*/) -Py::Float Robot6AxisPy::getAxis1(void) const +Py::Float Robot6AxisPy::getAxis1() const { return Py::Float(getRobot6AxisPtr()->getAxis(0)); } @@ -88,7 +88,7 @@ void Robot6AxisPy::setAxis1(Py::Float arg) getRobot6AxisPtr()->setAxis(0,(float)arg.operator double()); } -Py::Float Robot6AxisPy::getAxis2(void) const +Py::Float Robot6AxisPy::getAxis2() const { return Py::Float(getRobot6AxisPtr()->getAxis(1)); } @@ -98,7 +98,7 @@ void Robot6AxisPy::setAxis2(Py::Float arg) getRobot6AxisPtr()->setAxis(1,(float)arg.operator double()); } -Py::Float Robot6AxisPy::getAxis3(void) const +Py::Float Robot6AxisPy::getAxis3() const { return Py::Float(getRobot6AxisPtr()->getAxis(2)); } @@ -108,7 +108,7 @@ void Robot6AxisPy::setAxis3(Py::Float arg) getRobot6AxisPtr()->setAxis(2,(float)arg.operator double()); } -Py::Float Robot6AxisPy::getAxis4(void) const +Py::Float Robot6AxisPy::getAxis4() const { return Py::Float(getRobot6AxisPtr()->getAxis(3)); } @@ -118,7 +118,7 @@ void Robot6AxisPy::setAxis4(Py::Float arg) getRobot6AxisPtr()->setAxis(3,(float)arg.operator double()); } -Py::Float Robot6AxisPy::getAxis5(void) const +Py::Float Robot6AxisPy::getAxis5() const { return Py::Float(getRobot6AxisPtr()->getAxis(4)); } @@ -128,7 +128,7 @@ void Robot6AxisPy::setAxis5(Py::Float arg) getRobot6AxisPtr()->setAxis(4,(float)arg.operator double()); } -Py::Float Robot6AxisPy::getAxis6(void) const +Py::Float Robot6AxisPy::getAxis6() const { return Py::Float(getRobot6AxisPtr()->getAxis(5)); } @@ -138,7 +138,7 @@ void Robot6AxisPy::setAxis6(Py::Float arg) getRobot6AxisPtr()->setAxis(5,(float)arg.operator double()); } -Py::Object Robot6AxisPy::getTcp(void) const +Py::Object Robot6AxisPy::getTcp() const { return Py::asObject(new Base::PlacementPy(new Base::Placement(getRobot6AxisPtr()->getTcp()))); } @@ -164,7 +164,7 @@ void Robot6AxisPy::setTcp(Py::Object value) } -Py::Object Robot6AxisPy::getBase(void) const +Py::Object Robot6AxisPy::getBase() const { return Py::Object(); } diff --git a/src/Mod/Robot/App/RobotAlgos.cpp b/src/Mod/Robot/App/RobotAlgos.cpp index 21aea6cbb8..fe40610606 100644 --- a/src/Mod/Robot/App/RobotAlgos.cpp +++ b/src/Mod/Robot/App/RobotAlgos.cpp @@ -31,10 +31,10 @@ #include "kdl_cp/chainfksolver.hpp" #include "kdl_cp/chainfksolverpos_recursive.hpp" #include "kdl_cp/frames_io.hpp" -#include "kdl_cp/chainiksolver.hpp" -#include "kdl_cp/chainiksolvervel_pinv.hpp" -#include "kdl_cp/chainjnttojacsolver.hpp" -#include "kdl_cp/chainiksolverpos_nr.hpp" +#include "kdl_cp/chainiksolver.hpp" +#include "kdl_cp/chainiksolvervel_pinv.hpp" +#include "kdl_cp/chainjnttojacsolver.hpp" +#include "kdl_cp/chainiksolverpos_nr.hpp" #include #include @@ -64,7 +64,7 @@ using namespace KDL; -RobotAlgos::RobotAlgos(void) +RobotAlgos::RobotAlgos() { } @@ -73,7 +73,7 @@ RobotAlgos::~RobotAlgos() { } -void RobotAlgos::Test(void) +void RobotAlgos::Test() { //Definition of a kinematic chain & add segments to the chain KDL::Chain chain; @@ -133,4 +133,4 @@ void RobotAlgos::Test(void) } -} +} diff --git a/src/Mod/Robot/App/RobotObject.cpp b/src/Mod/Robot/App/RobotObject.cpp index cca5f32c3c..54c0a40f2d 100644 --- a/src/Mod/Robot/App/RobotObject.cpp +++ b/src/Mod/Robot/App/RobotObject.cpp @@ -67,7 +67,7 @@ RobotObject::~RobotObject() { } -short RobotObject::mustExecute(void) const +short RobotObject::mustExecute() const { return 0; } diff --git a/src/Mod/Robot/App/RobotObject.h b/src/Mod/Robot/App/RobotObject.h index 2bb2c572fe..c92eaa6c7b 100644 --- a/src/Mod/Robot/App/RobotObject.h +++ b/src/Mod/Robot/App/RobotObject.h @@ -36,27 +36,27 @@ namespace Robot class RobotExport RobotObject : public App::GeoFeature { - PROPERTY_HEADER(Robot::RobotObject); + PROPERTY_HEADER_WITH_OVERRIDE(Robot::RobotObject); public: /// Constructor - RobotObject(void); - virtual ~RobotObject(); + RobotObject(); + ~RobotObject() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "RobotGui::ViewProviderRobotObject"; } - virtual App::DocumentObjectExecReturn *execute(void) { + App::DocumentObjectExecReturn *execute() override { return App::DocumentObject::StdReturn; } - virtual short mustExecute(void) const; - virtual PyObject *getPyObject(void); + short mustExecute() const override; + PyObject *getPyObject() override; - virtual void Save (Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + void Save (Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; - Robot6Axis &getRobot(void){return robot;} + Robot6Axis &getRobot(){return robot;} App::PropertyFileIncluded RobotVrmlFile; App::PropertyFileIncluded RobotKinematicFile; @@ -75,7 +75,7 @@ public: protected: /// get called by the container when a property has changed - virtual void onChanged (const App::Property* prop); + void onChanged (const App::Property* prop) override; Robot6Axis robot; diff --git a/src/Mod/Robot/App/RobotObjectPyImp.cpp b/src/Mod/Robot/App/RobotObjectPyImp.cpp index ac95303829..86fda96b77 100644 --- a/src/Mod/Robot/App/RobotObjectPyImp.cpp +++ b/src/Mod/Robot/App/RobotObjectPyImp.cpp @@ -32,7 +32,7 @@ using namespace Robot; // returns a string which represents the object e.g. when printed in python -std::string RobotObjectPy::representation(void) const +std::string RobotObjectPy::representation() const { return std::string(""); } diff --git a/src/Mod/Robot/App/Simulation.cpp b/src/Mod/Robot/App/Simulation.cpp index 6445340982..c01e4043c7 100644 --- a/src/Mod/Robot/App/Simulation.cpp +++ b/src/Mod/Robot/App/Simulation.cpp @@ -97,7 +97,7 @@ void Simulation::setToTime(float t) } -void Simulation::reset(void) +void Simulation::reset() { Rob.setAxis(0,startAxis[0]); Rob.setAxis(1,startAxis[1]); diff --git a/src/Mod/Robot/App/Simulation.h b/src/Mod/Robot/App/Simulation.h index f33c84a637..5c1b99de9c 100644 --- a/src/Mod/Robot/App/Simulation.h +++ b/src/Mod/Robot/App/Simulation.h @@ -44,17 +44,17 @@ public: Simulation(const Trajectory &Trac,Robot6Axis &Rob); virtual ~Simulation(); - double getLength(void){return Trac.getLength();} - double getDuration(void){return Trac.getDuration();} + double getLength(){return Trac.getLength();} + double getDuration(){return Trac.getDuration();} - Base::Placement getPosition(void){return Trac.getPosition(Pos);} - double getVelocity(void){return Trac.getVelocity(Pos);} + Base::Placement getPosition(){return Trac.getPosition(Pos);} + double getVelocity(){return Trac.getVelocity(Pos);} void step(double tick); void setToWaypoint(unsigned int n); void setToTime(float t); // apply the start axis angles and set to time 0. Restores the exact start position - void reset(void); + void reset(); double Pos; double Axis[6]; diff --git a/src/Mod/Robot/App/Trajectory.cpp b/src/Mod/Robot/App/Trajectory.cpp index 11bc706c76..b827ad0a95 100644 --- a/src/Mod/Robot/App/Trajectory.cpp +++ b/src/Mod/Robot/App/Trajectory.cpp @@ -146,9 +146,9 @@ void Trajectory::deleteLast(unsigned int n) } -void Trajectory::generateTrajectory(void) +void Trajectory::generateTrajectory() { - if (vpcWaypoints.size() == 0) + if (vpcWaypoints.empty()) return; // delete the old and create a new one @@ -268,7 +268,7 @@ std::string Trajectory::getUniqueWaypointName(const char *Name) const const std::string &ObjName = (*it)->Name; if (ObjName.substr(0, CleanName.length()) == CleanName) { // same prefix std::string clSuffix(ObjName.substr(CleanName.length())); - if (clSuffix.size() > 0) { + if (!clSuffix.empty()) { std::string::size_type nPos = clSuffix.find_first_not_of("0123456789"); if (nPos==std::string::npos) nSuff = std::max(nSuff, std::atol(clSuffix.c_str())); @@ -293,7 +293,7 @@ void Trajectory::addWaypoint(const Waypoint &WPnt) -unsigned int Trajectory::getMemSize (void) const +unsigned int Trajectory::getMemSize () const { return 0; } diff --git a/src/Mod/Robot/App/TrajectoryDressUpObject.cpp b/src/Mod/Robot/App/TrajectoryDressUpObject.cpp index c01f1aa738..fb4d21c100 100644 --- a/src/Mod/Robot/App/TrajectoryDressUpObject.cpp +++ b/src/Mod/Robot/App/TrajectoryDressUpObject.cpp @@ -69,7 +69,7 @@ TrajectoryDressUpObject::~TrajectoryDressUpObject() { } -App::DocumentObjectExecReturn* TrajectoryDressUpObject::execute(void) +App::DocumentObjectExecReturn* TrajectoryDressUpObject::execute() { Robot::Trajectory result; diff --git a/src/Mod/Robot/App/TrajectoryPyImp.cpp b/src/Mod/Robot/App/TrajectoryPyImp.cpp index d80ff36927..9a2a621f91 100644 --- a/src/Mod/Robot/App/TrajectoryPyImp.cpp +++ b/src/Mod/Robot/App/TrajectoryPyImp.cpp @@ -35,7 +35,7 @@ using namespace Robot; // returns a string which represents the object e.g. when printed in python -std::string TrajectoryPy::representation(void) const +std::string TrajectoryPy::representation() const { std::stringstream str; str.precision(5); @@ -145,12 +145,12 @@ PyObject* TrajectoryPy::deleteLast(PyObject *args) -Py::Float TrajectoryPy::getDuration(void) const +Py::Float TrajectoryPy::getDuration() const { return Py::Float(getTrajectoryPtr()->getDuration()); } -Py::List TrajectoryPy::getWaypoints(void) const +Py::List TrajectoryPy::getWaypoints() const { Py::List list; for(unsigned int i = 0; i < getTrajectoryPtr()->getSize(); i++) @@ -159,7 +159,7 @@ Py::List TrajectoryPy::getWaypoints(void) const return list; } -Py::Float TrajectoryPy::getLength(void) const +Py::Float TrajectoryPy::getLength() const { return Py::Float(getTrajectoryPtr()->getLength()); } diff --git a/src/Mod/Robot/App/Waypoint.cpp b/src/Mod/Robot/App/Waypoint.cpp index 411ffde3e6..a098a181d8 100644 --- a/src/Mod/Robot/App/Waypoint.cpp +++ b/src/Mod/Robot/App/Waypoint.cpp @@ -90,7 +90,7 @@ Waypoint::~Waypoint() { } -unsigned int Waypoint::getMemSize (void) const +unsigned int Waypoint::getMemSize () const { return 0; } diff --git a/src/Mod/Robot/App/WaypointPyImp.cpp b/src/Mod/Robot/App/WaypointPyImp.cpp index 9e342b1d3f..6ef5810a0a 100644 --- a/src/Mod/Robot/App/WaypointPyImp.cpp +++ b/src/Mod/Robot/App/WaypointPyImp.cpp @@ -40,7 +40,7 @@ using namespace Robot; using namespace Base; // returns a string which represents the object e.g. when printed in python -std::string WaypointPy::representation(void) const +std::string WaypointPy::representation() const { double A,B,C; std::stringstream str; @@ -113,7 +113,7 @@ int WaypointPy::PyInit(PyObject* args, PyObject* kwd) else getWaypointPtr()->Type = Waypoint::UNDEF; - if (vel == nullptr) + if (!vel) switch (getWaypointPtr()->Type) { case Waypoint::PTP: getWaypointPtr()->Velocity = 100; @@ -132,7 +132,7 @@ int WaypointPy::PyInit(PyObject* args, PyObject* kwd) getWaypointPtr()->Cont = cont ? true : false; getWaypointPtr()->Tool = tool; getWaypointPtr()->Base = base; - if (acc == nullptr) + if (!acc) getWaypointPtr()->Acceleration = 100; else getWaypointPtr()->Acceleration = Base::UnitsApi::toDouble(acc, Base::Unit::Acceleration); @@ -141,7 +141,7 @@ int WaypointPy::PyInit(PyObject* args, PyObject* kwd) } -Py::Float WaypointPy::getVelocity(void) const +Py::Float WaypointPy::getVelocity() const { return Py::Float(getWaypointPtr()->Velocity); } @@ -152,7 +152,7 @@ void WaypointPy::setVelocity(Py::Float arg) } -Py::String WaypointPy::getName(void) const +Py::String WaypointPy::getName() const { return Py::String(getWaypointPtr()->Name.c_str()); } @@ -162,7 +162,7 @@ void WaypointPy::setName(Py::String arg) getWaypointPtr()->Name = arg.as_std_string("ascii"); } -Py::String WaypointPy::getType(void) const +Py::String WaypointPy::getType() const { if(getWaypointPtr()->Type == Waypoint::PTP) return Py::String("PTP"); @@ -194,7 +194,7 @@ void WaypointPy::setType(Py::String arg) } -Py::Object WaypointPy::getPos(void) const +Py::Object WaypointPy::getPos() const { return Py::Object(new PlacementPy(new Placement(getWaypointPtr()->EndPos)),true); } @@ -206,7 +206,7 @@ void WaypointPy::setPos(Py::Object arg) getWaypointPtr()->EndPos = *static_cast((*arg))->getPlacementPtr(); } -Py::Boolean WaypointPy::getCont(void) const +Py::Boolean WaypointPy::getCont() const { return Py::Boolean(getWaypointPtr()->Cont); } @@ -216,7 +216,7 @@ void WaypointPy::setCont(Py::Boolean arg) getWaypointPtr()->Cont = (bool)arg; } -Py::Long WaypointPy::getTool(void) const +Py::Long WaypointPy::getTool() const { return Py::Long((long)getWaypointPtr()->Tool); } @@ -230,7 +230,7 @@ void WaypointPy::setTool(Py::Long arg) throw Py::ValueError("negative tool not allowed!"); } -Py::Long WaypointPy::getBase(void) const +Py::Long WaypointPy::getBase() const { return Py::Long((long)getWaypointPtr()->Base); } diff --git a/src/Mod/Robot/App/kdl_cp/frameacc.hpp b/src/Mod/Robot/App/kdl_cp/frameacc.hpp index fd912c5a2e..afb3780d4d 100644 --- a/src/Mod/Robot/App/kdl_cp/frameacc.hpp +++ b/src/Mod/Robot/App/kdl_cp/frameacc.hpp @@ -25,6 +25,7 @@ * $Id: rrframes.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $ * $Name: $ ****************************************************************************/ +// clazy:excludeall=rule-of-two-soft #ifndef RRFRAMES_H #define RRFRAMES_H diff --git a/src/Mod/Robot/App/kdl_cp/frames.inl b/src/Mod/Robot/App/kdl_cp/frames.inl index d83e3aa69a..b3834e7ad7 100644 --- a/src/Mod/Robot/App/kdl_cp/frames.inl +++ b/src/Mod/Robot/App/kdl_cp/frames.inl @@ -24,6 +24,7 @@ * Suite 330, Boston, MA 02111-1307 USA * * * ***************************************************************************/ +// clazy:excludeall=rule-of-two-soft /** * \file frames.inl diff --git a/src/Mod/Robot/App/kdl_cp/framevel.hpp b/src/Mod/Robot/App/kdl_cp/framevel.hpp index 3cfa32a3cb..f9daf37980 100644 --- a/src/Mod/Robot/App/kdl_cp/framevel.hpp +++ b/src/Mod/Robot/App/kdl_cp/framevel.hpp @@ -19,6 +19,7 @@ * $Id: rframes.h,v 1.1.1.1 2002/08/26 14:14:21 rmoreas Exp $ * $Name: $ ****************************************************************************/ +// clazy:excludeall=rule-of-two-soft #ifndef KDL_FRAMEVEL_H #define KDL_FRAMEVEL_H diff --git a/src/Mod/Robot/App/kdl_cp/joint.hpp b/src/Mod/Robot/App/kdl_cp/joint.hpp index 798ce90775..820956b2e2 100644 --- a/src/Mod/Robot/App/kdl_cp/joint.hpp +++ b/src/Mod/Robot/App/kdl_cp/joint.hpp @@ -213,7 +213,7 @@ namespace KDL { class joint_type_exception: public std::exception{ - virtual const char* what() const throw(){ + const char* what() const throw() override{ return "Joint Type excption";} } joint_type_ex; diff --git a/src/Mod/Robot/App/kdl_cp/path_circle.cpp b/src/Mod/Robot/App/kdl_cp/path_circle.cpp index 5efd22bc80..e981df81ee 100644 --- a/src/Mod/Robot/App/kdl_cp/path_circle.cpp +++ b/src/Mod/Robot/App/kdl_cp/path_circle.cpp @@ -38,6 +38,7 @@ * $Id: path_circle.cpp,v 1.1.1.1.2.5 2003/07/24 13:26:15 psoetens Exp $ * $Name: $ ****************************************************************************/ +// clazy:excludeall=rule-of-two-soft #include "path_circle.hpp" diff --git a/src/Mod/Robot/App/kdl_cp/path_line.cpp b/src/Mod/Robot/App/kdl_cp/path_line.cpp index 789f5428db..1d14a91fc0 100644 --- a/src/Mod/Robot/App/kdl_cp/path_line.cpp +++ b/src/Mod/Robot/App/kdl_cp/path_line.cpp @@ -38,6 +38,7 @@ * $Id: path_line.cpp,v 1.1.1.1.2.3 2003/07/24 13:26:15 psoetens Exp $ * $Name: $ ****************************************************************************/ +// clazy:excludeall=rule-of-two-soft #include "path_line.hpp" diff --git a/src/Mod/Robot/App/kdl_cp/rotational_interpolation_sa.hpp b/src/Mod/Robot/App/kdl_cp/rotational_interpolation_sa.hpp index 1845e9a142..f01bdc1944 100644 --- a/src/Mod/Robot/App/kdl_cp/rotational_interpolation_sa.hpp +++ b/src/Mod/Robot/App/kdl_cp/rotational_interpolation_sa.hpp @@ -68,14 +68,14 @@ class RotationalInterpolation_SingleAxis: public RotationalInterpolation double angle; public: RotationalInterpolation_SingleAxis(); - virtual void SetStartEnd(Rotation start,Rotation end); - virtual double Angle(); - virtual Rotation Pos(double th) const; - virtual Vector Vel(double th,double thd) const; - virtual Vector Acc(double th,double thd,double thdd) const; - virtual void Write(std::ostream& os) const; - virtual RotationalInterpolation* Clone() const; - virtual ~RotationalInterpolation_SingleAxis(); + void SetStartEnd(Rotation start,Rotation end) override; + double Angle() override; + Rotation Pos(double th) const override; + Vector Vel(double th,double thd) const override; + Vector Acc(double th,double thd,double thdd) const override; + void Write(std::ostream& os) const override; + RotationalInterpolation* Clone() const override; + ~RotationalInterpolation_SingleAxis() override; }; } diff --git a/src/Mod/Robot/App/kdl_cp/utilities/utility_io.cxx b/src/Mod/Robot/App/kdl_cp/utilities/utility_io.cxx index a9bea12faf..f261c363fc 100644 --- a/src/Mod/Robot/App/kdl_cp/utilities/utility_io.cxx +++ b/src/Mod/Robot/App/kdl_cp/utilities/utility_io.cxx @@ -46,7 +46,7 @@ namespace KDL { count++; _check_istream(is); } while (ch!='\n'); - if (countp!=nullptr) *countp = count; + if (countp) *countp = count; return ch; } @@ -66,7 +66,7 @@ namespace KDL { break; } } while (true); - if (countp!=nullptr) *countp = count; + if (countp) *countp = count; ch = is.get(); return ch; } @@ -97,7 +97,7 @@ int _EatSpace( std::istream& is,int* countp=nullptr) { } } } while ((ch==' ')||(ch=='\n')||(ch=='\t')); - if (countp!=nullptr) *countp = count; + if (countp) *countp = count; return ch; } @@ -189,7 +189,7 @@ void EatWord(std::istream& is,const char* delim,char* storage,int maxsize) p = storage; size=0; int count = 0; - while ((count==0)&&(strchr(delim,ch)==nullptr)) { + while ((count==0)&&(strchr(delim,ch) == nullptr)) { *p = (char) toupper(ch); ++p; if (size==maxsize) { diff --git a/src/Mod/Robot/Gui/AppRobotGui.cpp b/src/Mod/Robot/Gui/AppRobotGui.cpp index 63ef038c0e..fcae584436 100644 --- a/src/Mod/Robot/Gui/AppRobotGui.cpp +++ b/src/Mod/Robot/Gui/AppRobotGui.cpp @@ -39,10 +39,10 @@ // use a different name to CreateCommand() -void CreateRobotCommands(void); -void CreateRobotCommandsExport(void); -void CreateRobotCommandsInsertRobots(void); -void CreateRobotCommandsTrajectory(void); +void CreateRobotCommands(); +void CreateRobotCommandsExport(); +void CreateRobotCommandsInsertRobots(); +void CreateRobotCommandsTrajectory(); void loadRobotResource() { @@ -60,7 +60,7 @@ public: initialize("This module is the RobotGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Robot/Gui/CMakeLists.txt b/src/Mod/Robot/Gui/CMakeLists.txt index 3140e66783..a76aa5b00b 100644 --- a/src/Mod/Robot/Gui/CMakeLists.txt +++ b/src/Mod/Robot/Gui/CMakeLists.txt @@ -16,6 +16,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${EIGEN3_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Robot/Gui/Command.cpp b/src/Mod/Robot/Gui/Command.cpp index 060e95f971..0065469030 100644 --- a/src/Mod/Robot/Gui/Command.cpp +++ b/src/Mod/Robot/Gui/Command.cpp @@ -89,7 +89,7 @@ void CmdRobotSetHomePos::activated(int) } -bool CmdRobotSetHomePos::isActive(void) +bool CmdRobotSetHomePos::isActive() { return hasActiveDocument(); } @@ -143,7 +143,7 @@ void CmdRobotRestoreHomePos::activated(int) } -bool CmdRobotRestoreHomePos::isActive(void) +bool CmdRobotRestoreHomePos::isActive() { return hasActiveDocument(); } @@ -183,7 +183,7 @@ void CmdRobotConstraintAxle::activated(int) } -bool CmdRobotConstraintAxle::isActive(void) +bool CmdRobotConstraintAxle::isActive() { return hasActiveDocument(); } @@ -260,7 +260,7 @@ void CmdRobotSimulate::activated(int) #endif } -bool CmdRobotSimulate::isActive(void) +bool CmdRobotSimulate::isActive() { return (hasActiveDocument() && !Gui::Control().activeDialog()); } @@ -271,7 +271,7 @@ bool CmdRobotSimulate::isActive(void) -void CreateRobotCommands(void) +void CreateRobotCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Robot/Gui/CommandExport.cpp b/src/Mod/Robot/Gui/CommandExport.cpp index 117c2ed637..4b791c2acd 100644 --- a/src/Mod/Robot/Gui/CommandExport.cpp +++ b/src/Mod/Robot/Gui/CommandExport.cpp @@ -95,7 +95,7 @@ void CmdRobotExportKukaCompact::activated(int) doCommand(Doc,"ExportCompactSub(App.activeDocument().%s,App.activeDocument().%s,'%s')",pcRobotObject->getNameInDocument(),pcTrajectoryObject->getNameInDocument(),(const char*)fn.toLatin1()); } -bool CmdRobotExportKukaCompact::isActive(void) +bool CmdRobotExportKukaCompact::isActive() { return hasActiveDocument(); } @@ -157,7 +157,7 @@ void CmdRobotExportKukaFull::activated(int) doCommand(Doc,"ExportFullSub(App.activeDocument().%s,App.activeDocument().%s,'%s')",pcRobotObject->getNameInDocument(),pcTrajectoryObject->getNameInDocument(),(const char*)fn.toLatin1()); } -bool CmdRobotExportKukaFull::isActive(void) +bool CmdRobotExportKukaFull::isActive() { return hasActiveDocument(); } @@ -166,7 +166,7 @@ bool CmdRobotExportKukaFull::isActive(void) -void CreateRobotCommandsExport(void) +void CreateRobotCommandsExport() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Robot/Gui/CommandInsertRobot.cpp b/src/Mod/Robot/Gui/CommandInsertRobot.cpp index 98d9b3745e..b6ff92c5de 100644 --- a/src/Mod/Robot/Gui/CommandInsertRobot.cpp +++ b/src/Mod/Robot/Gui/CommandInsertRobot.cpp @@ -76,7 +76,7 @@ void CmdRobotInsertKukaIR500::activated(int) } -bool CmdRobotInsertKukaIR500::isActive(void) +bool CmdRobotInsertKukaIR500::isActive() { return hasActiveDocument(); } @@ -117,7 +117,7 @@ void CmdRobotInsertKukaIR16::activated(int) } -bool CmdRobotInsertKukaIR16::isActive(void) +bool CmdRobotInsertKukaIR16::isActive() { return hasActiveDocument(); } @@ -158,7 +158,7 @@ void CmdRobotInsertKukaIR210::activated(int) } -bool CmdRobotInsertKukaIR210::isActive(void) +bool CmdRobotInsertKukaIR210::isActive() { return hasActiveDocument(); } @@ -198,7 +198,7 @@ void CmdRobotInsertKukaIR125::activated(int) } -bool CmdRobotInsertKukaIR125::isActive(void) +bool CmdRobotInsertKukaIR125::isActive() { return hasActiveDocument(); } @@ -250,13 +250,13 @@ void CmdRobotAddToolShape::activated(int) commitCommand(); } -bool CmdRobotAddToolShape::isActive(void) +bool CmdRobotAddToolShape::isActive() { //return false; // not yet implemetned thus not active return hasActiveDocument(); } -void CreateRobotCommandsInsertRobots(void) +void CreateRobotCommandsInsertRobots() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Robot/Gui/CommandTrajectory.cpp b/src/Mod/Robot/Gui/CommandTrajectory.cpp index 7114e48e95..804ce84724 100644 --- a/src/Mod/Robot/Gui/CommandTrajectory.cpp +++ b/src/Mod/Robot/Gui/CommandTrajectory.cpp @@ -79,7 +79,7 @@ void CmdRobotCreateTrajectory::activated(int) } -bool CmdRobotCreateTrajectory::isActive(void) +bool CmdRobotCreateTrajectory::isActive() { return hasActiveDocument(); } @@ -136,7 +136,7 @@ void CmdRobotInsertWaypoint::activated(int) } -bool CmdRobotInsertWaypoint::isActive(void) +bool CmdRobotInsertWaypoint::isActive() { return hasActiveDocument(); } @@ -178,16 +178,16 @@ void CmdRobotInsertWaypointPreselect::activated(int) Robot::TrajectoryObject *pcTrajectoryObject; - if(Sel[0].pObject->getTypeId() == Robot::TrajectoryObject::getClassTypeId()) + if (Sel[0].pObject->getTypeId() == Robot::TrajectoryObject::getClassTypeId()) pcTrajectoryObject = static_cast(Sel[0].pObject); - else { + else { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select one Trajectory object.")); return; } std::string TrakName = pcTrajectoryObject->getNameInDocument(); - if(PreSel.pDocName == nullptr){ + if (!PreSel.pDocName) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No preselection"), QObject::tr("You have to hover above a geometry (Preselection) with the mouse to use this command. See documentation for details.")); return; @@ -200,7 +200,7 @@ void CmdRobotInsertWaypointPreselect::activated(int) } -bool CmdRobotInsertWaypointPreselect::isActive(void) +bool CmdRobotInsertWaypointPreselect::isActive() { return hasActiveDocument(); } @@ -238,7 +238,7 @@ void CmdRobotSetDefaultOrientation::activated(int) } } -bool CmdRobotSetDefaultOrientation::isActive(void) +bool CmdRobotSetDefaultOrientation::isActive() { return true; } @@ -304,7 +304,7 @@ void CmdRobotSetDefaultValues::activated(int) } -bool CmdRobotSetDefaultValues::isActive(void) +bool CmdRobotSetDefaultValues::isActive() { return true; } @@ -368,7 +368,7 @@ void CmdRobotEdge2Trac::activated(int) } -bool CmdRobotEdge2Trac::isActive(void) +bool CmdRobotEdge2Trac::isActive() { return true; } @@ -415,7 +415,7 @@ void CmdRobotTrajectoryDressUp::activated(int) } } -bool CmdRobotTrajectoryDressUp::isActive(void) +bool CmdRobotTrajectoryDressUp::isActive() { return true; } @@ -455,7 +455,7 @@ void CmdRobotTrajectoryCompound::activated(int) } } -bool CmdRobotTrajectoryCompound::isActive(void) +bool CmdRobotTrajectoryCompound::isActive() { return true; } @@ -466,7 +466,7 @@ bool CmdRobotTrajectoryCompound::isActive(void) -void CreateRobotCommandsTrajectory(void) +void CreateRobotCommandsTrajectory() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Robot/Gui/TaskDlgEdge2Trac.h b/src/Mod/Robot/Gui/TaskDlgEdge2Trac.h index e676e83041..f7f0658ae0 100644 --- a/src/Mod/Robot/Gui/TaskDlgEdge2Trac.h +++ b/src/Mod/Robot/Gui/TaskDlgEdge2Trac.h @@ -44,23 +44,23 @@ class RobotGuiExport TaskDlgEdge2Trac : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgEdge2Trac(Robot::Edge2TracObject *); - ~TaskDlgEdge2Trac(); + explicit TaskDlgEdge2Trac(Robot::Edge2TracObject *); + ~TaskDlgEdge2Trac() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or rject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel; } protected: diff --git a/src/Mod/Robot/Gui/TaskDlgSimulate.h b/src/Mod/Robot/Gui/TaskDlgSimulate.h index dd2b18fe25..e46a06506b 100644 --- a/src/Mod/Robot/Gui/TaskDlgSimulate.h +++ b/src/Mod/Robot/Gui/TaskDlgSimulate.h @@ -43,22 +43,22 @@ class RobotGuiExport TaskDlgSimulate : public Gui::TaskView::TaskDialog public: TaskDlgSimulate(Robot::RobotObject *pcRobotObject,Robot::TrajectoryObject *pcTrajectoryObject); - ~TaskDlgSimulate(); + ~TaskDlgSimulate() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or rject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Close|QDialogButtonBox::Help; } protected: diff --git a/src/Mod/Robot/Gui/TaskDlgTrajectoryDressUp.h b/src/Mod/Robot/Gui/TaskDlgTrajectoryDressUp.h index 5b3f55d508..3add544ec1 100644 --- a/src/Mod/Robot/Gui/TaskDlgTrajectoryDressUp.h +++ b/src/Mod/Robot/Gui/TaskDlgTrajectoryDressUp.h @@ -44,23 +44,23 @@ class RobotGuiExport TaskDlgTrajectoryDressUp : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgTrajectoryDressUp(Robot::TrajectoryDressUpObject *); - ~TaskDlgTrajectoryDressUp(); + explicit TaskDlgTrajectoryDressUp(Robot::TrajectoryDressUpObject *); + ~TaskDlgTrajectoryDressUp() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or rject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user press the help button - virtual void helpRequested(); + void helpRequested() override; /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok|QDialogButtonBox::Apply|QDialogButtonBox::Cancel; } protected: diff --git a/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp b/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp index bfd8baabf9..1ffe3fa893 100644 --- a/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp +++ b/src/Mod/Robot/Gui/TaskEdge2TracParameter.cpp @@ -65,7 +65,7 @@ TaskEdge2TracParameter::TaskEdge2TracParameter(Robot::Edge2TracObject *pcObject, setHideShowObject(); } -void TaskEdge2TracParameter::setHideShowObject(void) +void TaskEdge2TracParameter::setHideShowObject() { HideShowObj = pcObject->Source.getValue(); @@ -77,7 +77,7 @@ void TaskEdge2TracParameter::setHideShowObject(void) } } -void TaskEdge2TracParameter::hideShow(void) +void TaskEdge2TracParameter::hideShow() { setHideShowObject(); diff --git a/src/Mod/Robot/Gui/TaskEdge2TracParameter.h b/src/Mod/Robot/Gui/TaskEdge2TracParameter.h index c93391c545..675fb353a3 100644 --- a/src/Mod/Robot/Gui/TaskEdge2TracParameter.h +++ b/src/Mod/Robot/Gui/TaskEdge2TracParameter.h @@ -50,13 +50,13 @@ class TaskEdge2TracParameter : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskEdge2TracParameter(Robot::Edge2TracObject *pcObject,QWidget *parent = nullptr); - ~TaskEdge2TracParameter(); + explicit TaskEdge2TracParameter(Robot::Edge2TracObject *pcObject,QWidget *parent = nullptr); + ~TaskEdge2TracParameter() override; void setEdgeAndClusterNbr(int NbrEdges,int NbrClusters); private Q_SLOTS: - void hideShow(void); + void hideShow(); void sizingValueChanged(double Value); void orientationToggled(bool Value); @@ -64,7 +64,7 @@ protected: Robot::Edge2TracObject *pcObject; App::DocumentObject *HideShowObj; - void setHideShowObject(void); + void setHideShowObject(); private: private: diff --git a/src/Mod/Robot/Gui/TaskRobot6Axis.cpp b/src/Mod/Robot/Gui/TaskRobot6Axis.cpp index 005ffcabdd..7b839058b8 100644 --- a/src/Mod/Robot/Gui/TaskRobot6Axis.cpp +++ b/src/Mod/Robot/Gui/TaskRobot6Axis.cpp @@ -115,7 +115,7 @@ void TaskRobot6Axis::setRobot(Robot::RobotObject *pcRobotObject) viewTool(pcRobot->Tool.getValue()); } -void TaskRobot6Axis::createPlacementDlg(void) +void TaskRobot6Axis::createPlacementDlg() { Gui::Dialog::Placement plc; plc.setPlacement(pcRobot->Tool.getValue()); diff --git a/src/Mod/Robot/Gui/TaskRobot6Axis.h b/src/Mod/Robot/Gui/TaskRobot6Axis.h index 80147ec32d..348fdbe208 100644 --- a/src/Mod/Robot/Gui/TaskRobot6Axis.h +++ b/src/Mod/Robot/Gui/TaskRobot6Axis.h @@ -51,8 +51,8 @@ class TaskRobot6Axis : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskRobot6Axis(Robot::RobotObject *pcRobotObject,QWidget *parent = nullptr); - ~TaskRobot6Axis(); + explicit TaskRobot6Axis(Robot::RobotObject *pcRobotObject,QWidget *parent = nullptr); + ~TaskRobot6Axis() override; void setRobot(Robot::RobotObject *pcRobotObject); @@ -64,7 +64,7 @@ private Q_SLOTS: void changeSliderA4(int value); void changeSliderA5(int value); void changeSliderA6(int value); - void createPlacementDlg(void); + void createPlacementDlg(); protected: Robot::RobotObject *pcRobot; diff --git a/src/Mod/Robot/Gui/TaskRobotControl.h b/src/Mod/Robot/Gui/TaskRobotControl.h index 51f0f7e5e7..16b6f39d67 100644 --- a/src/Mod/Robot/Gui/TaskRobotControl.h +++ b/src/Mod/Robot/Gui/TaskRobotControl.h @@ -50,8 +50,8 @@ class TaskRobotControl : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskRobotControl(Robot::RobotObject *pcRobotObject,QWidget *parent = nullptr); - ~TaskRobotControl(); + explicit TaskRobotControl(Robot::RobotObject *pcRobotObject,QWidget *parent = nullptr); + ~TaskRobotControl() override; void setRobot(Robot::RobotObject *pcRobotObject); diff --git a/src/Mod/Robot/Gui/TaskRobotMessages.h b/src/Mod/Robot/Gui/TaskRobotMessages.h index 763878a106..19bf9f6429 100644 --- a/src/Mod/Robot/Gui/TaskRobotMessages.h +++ b/src/Mod/Robot/Gui/TaskRobotMessages.h @@ -50,8 +50,8 @@ class TaskRobotMessages : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskRobotMessages(Robot::RobotObject *pcRobotObject,QWidget *parent = nullptr); - ~TaskRobotMessages(); + explicit TaskRobotMessages(Robot::RobotObject *pcRobotObject,QWidget *parent = nullptr); + ~TaskRobotMessages() override; private Q_SLOTS: diff --git a/src/Mod/Robot/Gui/TaskTrajectory.cpp b/src/Mod/Robot/Gui/TaskTrajectory.cpp index a85420bbac..9edcc38613 100644 --- a/src/Mod/Robot/Gui/TaskTrajectory.cpp +++ b/src/Mod/Robot/Gui/TaskTrajectory.cpp @@ -129,7 +129,7 @@ void TaskTrajectory::viewTool(const Base::Placement& pos) ui->label_Pos->setText(result); } -void TaskTrajectory::setTo(void) +void TaskTrajectory::setTo() { sim.Tool = pcRobot->Tool.getValue(); @@ -139,11 +139,11 @@ void TaskTrajectory::setTo(void) sim.setToTime(timePos); } ViewProv->setAxisTo(sim.Axis[0],sim.Axis[1],sim.Axis[2],sim.Axis[3],sim.Axis[4],sim.Axis[5],sim.Rob.getTcp()); - axisChanged(sim.Axis[0],sim.Axis[1],sim.Axis[2],sim.Axis[3],sim.Axis[4],sim.Axis[5],sim.Rob.getTcp()); + Q_EMIT axisChanged(sim.Axis[0],sim.Axis[1],sim.Axis[2],sim.Axis[3],sim.Axis[4],sim.Axis[5],sim.Rob.getTcp()); viewTool(sim.Rob.getTcp()); } -void TaskTrajectory::start(void) +void TaskTrajectory::start() { timePos = 0.0f; ui->timeSpinBox->setValue(timePos); @@ -151,23 +151,23 @@ void TaskTrajectory::start(void) setTo(); } -void TaskTrajectory::stop(void) +void TaskTrajectory::stop() { timer->stop(); Run = false; } -void TaskTrajectory::run(void) +void TaskTrajectory::run() { timer->start(); Run = true; } -void TaskTrajectory::back(void) +void TaskTrajectory::back() { } -void TaskTrajectory::forward(void) +void TaskTrajectory::forward() { } -void TaskTrajectory::end(void) +void TaskTrajectory::end() { timePos = duration; ui->timeSpinBox->setValue(timePos); @@ -175,7 +175,7 @@ void TaskTrajectory::end(void) setTo(); } -void TaskTrajectory::timerDone(void) +void TaskTrajectory::timerDone() { if(timePos < duration){ timePos += .1f; diff --git a/src/Mod/Robot/Gui/TaskTrajectory.h b/src/Mod/Robot/Gui/TaskTrajectory.h index b1f6ffe5e2..fad5c932fc 100644 --- a/src/Mod/Robot/Gui/TaskTrajectory.h +++ b/src/Mod/Robot/Gui/TaskTrajectory.h @@ -59,20 +59,20 @@ class TaskTrajectory : public Gui::TaskView::TaskBox public: TaskTrajectory(Robot::RobotObject *pcRobotObject,Robot::TrajectoryObject *pcTrajectoryObject,QWidget *parent = nullptr); - ~TaskTrajectory(); + ~TaskTrajectory() override; /// Observer message from the Selection void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, Gui::SelectionSingleton::MessageType Reason); private Q_SLOTS: - void start(void); - void stop(void); - void run(void); - void back(void); - void forward(void); - void end(void); + void start(); + void stop(); + void run(); + void back(); + void forward(); + void end(); - void timerDone(void); + void timerDone(); void valueChanged ( int value ); void valueChanged ( double d ); @@ -80,7 +80,7 @@ Q_SIGNALS: void axisChanged(float A1,float A2,float A3,float A4,float A5,float A6,const Base::Placement &Tcp); protected: - void setTo(void); + void setTo(); void viewTool(const Base::Placement& pos); QTimer *timer; diff --git a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp index e515562a12..2042746665 100644 --- a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp +++ b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.cpp @@ -80,7 +80,7 @@ TaskTrajectoryDressUpParameter::~TaskTrajectoryDressUpParameter() delete ui; } -void TaskTrajectoryDressUpParameter::writeValues(void) +void TaskTrajectoryDressUpParameter::writeValues() { pcObject->Speed.setValue ( ui->doubleSpinBoxSpeed->value()*1000.0); pcObject->Acceleration.setValue ( ui->doubleSpinBoxAccel->value()*1000.0); @@ -91,7 +91,7 @@ void TaskTrajectoryDressUpParameter::writeValues(void) pcObject->PosAdd.setValue(PosAdd); } -void TaskTrajectoryDressUpParameter::createPlacementDlg(void) +void TaskTrajectoryDressUpParameter::createPlacementDlg() { Gui::Dialog::Placement plc; plc.setPlacement(PosAdd); @@ -103,7 +103,7 @@ void TaskTrajectoryDressUpParameter::createPlacementDlg(void) } -void TaskTrajectoryDressUpParameter::viewPlacement(void) +void TaskTrajectoryDressUpParameter::viewPlacement() { double A,B,C; Base::Vector3d pos = PosAdd.getPosition(); diff --git a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h index 600a049a63..ab986d7177 100644 --- a/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h +++ b/src/Mod/Robot/Gui/TaskTrajectoryDressUpParameter.h @@ -44,21 +44,21 @@ class TaskTrajectoryDressUpParameter : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskTrajectoryDressUpParameter(Robot::TrajectoryDressUpObject *obj,QWidget *parent = nullptr); - ~TaskTrajectoryDressUpParameter(); + explicit TaskTrajectoryDressUpParameter(Robot::TrajectoryDressUpObject *obj,QWidget *parent = nullptr); + ~TaskTrajectoryDressUpParameter() override; /// this methode write the values from the Gui to the object, usually in accept() - void writeValues(void); + void writeValues(); private Q_SLOTS: /// edit the placement - void createPlacementDlg(void); + void createPlacementDlg(); protected: Base::Placement PosAdd; - void viewPlacement(void); + void viewPlacement(); private: QWidget* proxy; diff --git a/src/Mod/Robot/Gui/TaskWatcher.h b/src/Mod/Robot/Gui/TaskWatcher.h index ada9668270..be6e9bf97d 100644 --- a/src/Mod/Robot/Gui/TaskWatcher.h +++ b/src/Mod/Robot/Gui/TaskWatcher.h @@ -43,10 +43,10 @@ class RobotGuiExport TaskWatcherRobot : public Gui::TaskView::TaskWatcher public: TaskWatcherRobot(); - ~TaskWatcherRobot(); + ~TaskWatcherRobot() override; /// is called when the document or the selection changes. - virtual bool shouldShow(void); + bool shouldShow() override; protected: TaskRobot6Axis *rob; diff --git a/src/Mod/Robot/Gui/TrajectorySimulate.cpp b/src/Mod/Robot/Gui/TrajectorySimulate.cpp index 4d0724fa76..20661926dc 100644 --- a/src/Mod/Robot/Gui/TrajectorySimulate.cpp +++ b/src/Mod/Robot/Gui/TrajectorySimulate.cpp @@ -109,13 +109,13 @@ TrajectorySimulate::~TrajectorySimulate() { } -void TrajectorySimulate::setTo(void) +void TrajectorySimulate::setTo() { sim.setToTime(timePos); ViewProv->setAxisTo(sim.Axis[0],sim.Axis[1],sim.Axis[2],sim.Axis[3],sim.Axis[4],sim.Axis[5],sim.Rob.getTcp()); } -void TrajectorySimulate::start(void) +void TrajectorySimulate::start() { timePos = 0.0f; ui->timeSpinBox->setValue(timePos); @@ -123,23 +123,23 @@ void TrajectorySimulate::start(void) setTo(); } -void TrajectorySimulate::stop(void) +void TrajectorySimulate::stop() { timer->stop(); Run = false; } -void TrajectorySimulate::run(void) +void TrajectorySimulate::run() { timer->start(); Run = true; } -void TrajectorySimulate::back(void) +void TrajectorySimulate::back() { } -void TrajectorySimulate::forward(void) +void TrajectorySimulate::forward() { } -void TrajectorySimulate::end(void) +void TrajectorySimulate::end() { timePos = duration; ui->timeSpinBox->setValue(timePos); @@ -147,7 +147,7 @@ void TrajectorySimulate::end(void) setTo(); } -void TrajectorySimulate::timerDone(void) +void TrajectorySimulate::timerDone() { if(timePos < duration){ timePos += .1f; diff --git a/src/Mod/Robot/Gui/TrajectorySimulate.h b/src/Mod/Robot/Gui/TrajectorySimulate.h index 86fe1c2531..19b1d813ce 100644 --- a/src/Mod/Robot/Gui/TrajectorySimulate.h +++ b/src/Mod/Robot/Gui/TrajectorySimulate.h @@ -47,22 +47,22 @@ class TrajectorySimulate : public QDialog public: TrajectorySimulate(Robot::RobotObject *pcRobotObject,Robot::TrajectoryObject *pcTrajectoryObject,QWidget *parent = nullptr); - ~TrajectorySimulate(); + ~TrajectorySimulate() override; private Q_SLOTS: - void start(void); - void stop(void); - void run(void); - void back(void); - void forward(void); - void end(void); + void start(); + void stop(); + void run(); + void back(); + void forward(); + void end(); - void timerDone(void); + void timerDone(); void valueChanged ( int value ); void valueChanged ( double d ); protected: - void setTo(void); + void setTo(); QTimer *timer; diff --git a/src/Mod/Robot/Gui/ViewProviderEdge2TracObject.cpp b/src/Mod/Robot/Gui/ViewProviderEdge2TracObject.cpp index a772c57bc7..a07ff7b290 100644 --- a/src/Mod/Robot/Gui/ViewProviderEdge2TracObject.cpp +++ b/src/Mod/Robot/Gui/ViewProviderEdge2TracObject.cpp @@ -35,7 +35,7 @@ using namespace RobotGui; PROPERTY_SOURCE(RobotGui::ViewProviderEdge2TracObject, RobotGui::ViewProviderTrajectory) -bool ViewProviderEdge2TracObject::doubleClicked(void) +bool ViewProviderEdge2TracObject::doubleClicked() { Gui::TaskView::TaskDialog* dlg = new TaskDlgEdge2Trac(static_cast(getObject())); Gui::Control().showDialog(dlg); diff --git a/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp b/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp index 58d6842f93..45ae12a071 100644 --- a/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp +++ b/src/Mod/Robot/Gui/ViewProviderRobotObject.cpp @@ -92,7 +92,7 @@ ViewProviderRobotObject::~ViewProviderRobotObject() void ViewProviderRobotObject::setDragger() { - assert(pcDragger==nullptr); + assert(!pcDragger); pcDragger = new SoJackDragger(); pcDragger->addMotionCallback(sDraggerMotionCallback,this); pcTcpRoot->addChild(pcDragger); @@ -146,12 +146,12 @@ void ViewProviderRobotObject::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode( ModeName ); } -std::vector ViewProviderRobotObject::getDisplayModes(void) const +std::vector ViewProviderRobotObject::getDisplayModes() const { std::vector StrList; - StrList.push_back("VRML"); - StrList.push_back("Simple"); - StrList.push_back("Off"); + StrList.emplace_back("VRML"); + StrList.emplace_back("Simple"); + StrList.emplace_back("Off"); return StrList; } diff --git a/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp b/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp index bf1d90f4ac..ade7eb6171 100644 --- a/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp +++ b/src/Mod/Robot/Gui/ViewProviderTrajectory.cpp @@ -96,7 +96,7 @@ ViewProviderTrajectory::~ViewProviderTrajectory() void ViewProviderTrajectory::attach(App::DocumentObject *pcObj) { - ViewProviderDocumentObject::attach(pcObj); + ViewProviderGeometryObject::attach(pcObj); // Draw trajectory lines SoSeparator* linesep = new SoSeparator; @@ -130,10 +130,10 @@ void ViewProviderTrajectory::setDisplayMode(const char* ModeName) ViewProviderGeometryObject::setDisplayMode( ModeName ); } -std::vector ViewProviderTrajectory::getDisplayModes(void) const +std::vector ViewProviderTrajectory::getDisplayModes() const { std::vector StrList; - StrList.push_back("Waypoints"); + StrList.emplace_back("Waypoints"); return StrList; } diff --git a/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp b/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp index 94a17da9ba..0b426e093e 100644 --- a/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp +++ b/src/Mod/Robot/Gui/ViewProviderTrajectoryCompound.cpp @@ -60,7 +60,7 @@ void ViewProviderTrajectoryCompound::unsetEdit(int) } -std::vector ViewProviderTrajectoryCompound::claimChildren(void)const +std::vector ViewProviderTrajectoryCompound::claimChildren()const { return std::vector(static_cast(getObject())->Source.getValues()); } diff --git a/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp b/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp index 1fdee009a5..6397e31635 100644 --- a/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp +++ b/src/Mod/Robot/Gui/ViewProviderTrajectoryDressUp.cpp @@ -58,7 +58,7 @@ void ViewProviderTrajectoryDressUp::unsetEdit(int) } -std::vector ViewProviderTrajectoryDressUp::claimChildren(void)const +std::vector ViewProviderTrajectoryDressUp::claimChildren()const { std::vector temp; temp.push_back(static_cast(getObject())->Source.getValue()); diff --git a/src/Mod/Sketcher/App/Analyse.h b/src/Mod/Sketcher/App/Analyse.h index 875fbb8e96..97f7c498a6 100644 --- a/src/Mod/Sketcher/App/Analyse.h +++ b/src/Mod/Sketcher/App/Analyse.h @@ -44,7 +44,7 @@ struct Constraint_Equal typedef ConstraintIds argument_type; typedef bool result_type; struct Sketcher::ConstraintIds c; - Constraint_Equal(const ConstraintIds& c) : c(c) + explicit Constraint_Equal(const ConstraintIds& c) : c(c) { } bool operator()(const ConstraintIds& x) const diff --git a/src/Mod/Sketcher/App/AppSketcherPy.cpp b/src/Mod/Sketcher/App/AppSketcherPy.cpp index bc80dbfa25..9a7389c055 100644 --- a/src/Mod/Sketcher/App/AppSketcherPy.cpp +++ b/src/Mod/Sketcher/App/AppSketcherPy.cpp @@ -58,7 +58,7 @@ public: initialize("This module is the Sketcher module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object open(const Py::Tuple& args) diff --git a/src/Mod/Sketcher/App/CMakeLists.txt b/src/Mod/Sketcher/App/CMakeLists.txt index bff82ed3ee..d6a600bd4b 100644 --- a/src/Mod/Sketcher/App/CMakeLists.txt +++ b/src/Mod/Sketcher/App/CMakeLists.txt @@ -24,6 +24,7 @@ include_directories( ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Sketcher/App/Constraint.cpp b/src/Mod/Sketcher/App/Constraint.cpp index ba88abce23..33094f54a7 100644 --- a/src/Mod/Sketcher/App/Constraint.cpp +++ b/src/Mod/Sketcher/App/Constraint.cpp @@ -47,7 +47,6 @@ Constraint::Constraint() : Value(0.0), Type(None), AlignmentType(Undef), - Name(""), First(GeoEnum::GeoUndef), FirstPos(PointPos::none), Second(GeoEnum::GeoUndef), @@ -74,12 +73,12 @@ Constraint::Constraint() tag = gen(); } -Constraint *Constraint::clone(void) const +Constraint *Constraint::clone() const { return new Constraint(*this); } -Constraint *Constraint::copy(void) const +Constraint *Constraint::copy() const { Constraint *temp = new Constraint(); temp->Value = this->Value; @@ -102,7 +101,7 @@ Constraint *Constraint::copy(void) const return temp; } -PyObject *Constraint::getPyObject(void) +PyObject *Constraint::getPyObject() { return new ConstraintPy(new Constraint(*this)); } @@ -140,7 +139,7 @@ Quantity Constraint::getPresentationValue() const return quantity; } -unsigned int Constraint::getMemSize (void) const +unsigned int Constraint::getMemSize () const { return 0; } diff --git a/src/Mod/Sketcher/App/Constraint.h b/src/Mod/Sketcher/App/Constraint.h index 46b462b0de..d7b8c90c78 100644 --- a/src/Mod/Sketcher/App/Constraint.h +++ b/src/Mod/Sketcher/App/Constraint.h @@ -95,17 +95,17 @@ public: Constraint(Constraint&&) = delete; Constraint& operator=(Constraint&&) = delete; - virtual ~Constraint() = default; + ~Constraint() override = default; - Constraint *clone(void) const; // does copy the tag, it will be treated as a rename by the expression engine. - Constraint *copy(void) const; // does not copy the tag, but generates a new one + Constraint *clone() const; // does copy the tag, it will be treated as a rename by the expression engine. + Constraint *copy() const; // does not copy the tag, but generates a new one // from base class - virtual unsigned int getMemSize(void) const override; - virtual void Save(Base::Writer &/*writer*/) const override; - virtual void Restore(Base::XMLReader &/*reader*/) override; + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; Base::Quantity getPresentationValue() const; inline void setValue(double newValue) { diff --git a/src/Mod/Sketcher/App/ConstraintPyImp.cpp b/src/Mod/Sketcher/App/ConstraintPyImp.cpp index fe7942c590..6c83337376 100644 --- a/src/Mod/Sketcher/App/ConstraintPyImp.cpp +++ b/src/Mod/Sketcher/App/ConstraintPyImp.cpp @@ -105,13 +105,13 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) this->getConstraintPtr()->Type = Equal; valid = true; } - else if (strstr(ConstraintType,"InternalAlignment") != nullptr) { + else if (strstr(ConstraintType,"InternalAlignment")) { this->getConstraintPtr()->Type = InternalAlignment; valid = true; - if(strstr(ConstraintType,"EllipseMajorDiameter") != nullptr) + if(strstr(ConstraintType,"EllipseMajorDiameter")) this->getConstraintPtr()->AlignmentType=EllipseMajorDiameter; - else if(strstr(ConstraintType,"EllipseMinorDiameter") != nullptr) + else if(strstr(ConstraintType,"EllipseMinorDiameter")) this->getConstraintPtr()->AlignmentType=EllipseMinorDiameter; else { this->getConstraintPtr()->AlignmentType=Undef; @@ -198,14 +198,14 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) this->getConstraintPtr()->Type = PointOnObject; valid = true; } - else if (strstr(ConstraintType,"InternalAlignment") != nullptr) { + else if (strstr(ConstraintType,"InternalAlignment")) { this->getConstraintPtr()->Type = InternalAlignment; valid = true; - if(strstr(ConstraintType,"EllipseFocus1") != nullptr) + if(strstr(ConstraintType,"EllipseFocus1")) this->getConstraintPtr()->AlignmentType=EllipseFocus1; - else if(strstr(ConstraintType,"EllipseFocus2") != nullptr) + else if(strstr(ConstraintType,"EllipseFocus2")) this->getConstraintPtr()->AlignmentType=EllipseFocus2; else { this->getConstraintPtr()->AlignmentType=Undef; @@ -313,12 +313,12 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) this->getConstraintPtr()->ThirdPos = (Sketcher::PointPos) intArg4; return 0; } - else if (strstr(ConstraintType,"InternalAlignment") != nullptr) { // InteralAlignment with InternalElementIndex argument + else if (strstr(ConstraintType,"InternalAlignment")) { // InteralAlignment with InternalElementIndex argument this->getConstraintPtr()->Type = InternalAlignment; valid = true; - if(strstr(ConstraintType,"BSplineControlPoint") != nullptr) { + if(strstr(ConstraintType,"BSplineControlPoint")) { this->getConstraintPtr()->AlignmentType=BSplineControlPoint; } else { @@ -470,7 +470,7 @@ int ConstraintPy::PyInit(PyObject* args, PyObject* /*kwd*/) } // returns a string which represents the object e.g. when printed in python -std::string ConstraintPy::representation(void) const +std::string ConstraintPy::representation() const { std::stringstream result; result << "getConstraintPtr()->Type) { case None : return Py::String("None");break; @@ -551,7 +551,7 @@ Py::String ConstraintPy::getType(void) const } } -Py::Long ConstraintPy::getFirst(void) const +Py::Long ConstraintPy::getFirst() const { return Py::Long(this->getConstraintPtr()->First); } @@ -561,7 +561,7 @@ void ConstraintPy::setFirst(Py::Long arg) this->getConstraintPtr()->First = arg; } -Py::Long ConstraintPy::getFirstPos(void) const +Py::Long ConstraintPy::getFirstPos() const { return Py::Long(static_cast(this->getConstraintPtr()->FirstPos)); } @@ -581,7 +581,7 @@ void ConstraintPy::setFirstPos(Py::Long arg) } } -Py::Long ConstraintPy::getSecond(void) const +Py::Long ConstraintPy::getSecond() const { return Py::Long(this->getConstraintPtr()->Second); } @@ -591,7 +591,7 @@ void ConstraintPy::setSecond(Py::Long arg) this->getConstraintPtr()->Second = arg; } -Py::Long ConstraintPy::getSecondPos(void) const +Py::Long ConstraintPy::getSecondPos() const { return Py::Long(static_cast(this->getConstraintPtr()->SecondPos)); } @@ -611,7 +611,7 @@ void ConstraintPy::setSecondPos(Py::Long arg) } } -Py::Long ConstraintPy::getThird(void) const +Py::Long ConstraintPy::getThird() const { return Py::Long(this->getConstraintPtr()->Third); } @@ -621,7 +621,7 @@ void ConstraintPy::setThird(Py::Long arg) this->getConstraintPtr()->Third = arg; } -Py::Long ConstraintPy::getThirdPos(void) const +Py::Long ConstraintPy::getThirdPos() const { return Py::Long(static_cast(this->getConstraintPtr()->ThirdPos)); } @@ -641,7 +641,7 @@ void ConstraintPy::setThirdPos(Py::Long arg) } } -Py::String ConstraintPy::getName(void) const +Py::String ConstraintPy::getName() const { return Py::String(this->getConstraintPtr()->Name); } @@ -651,22 +651,22 @@ void ConstraintPy::setName(Py::String arg) this->getConstraintPtr()->Name = arg; } -Py::Float ConstraintPy::getValue(void) const +Py::Float ConstraintPy::getValue() const { return Py::Float(this->getConstraintPtr()->getValue()); } -Py::Boolean ConstraintPy::getDriving(void) const +Py::Boolean ConstraintPy::getDriving() const { return Py::Boolean(this->getConstraintPtr()->isDriving); } -Py::Boolean ConstraintPy::getInVirtualSpace(void) const +Py::Boolean ConstraintPy::getInVirtualSpace() const { return Py::Boolean(this->getConstraintPtr()->isInVirtualSpace); } -Py::Boolean ConstraintPy::getIsActive(void) const +Py::Boolean ConstraintPy::getIsActive() const { return Py::Boolean(this->getConstraintPtr()->isActive); } diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp b/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp index 93e40f7603..a0921a5473 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryExtension.cpp @@ -61,7 +61,7 @@ void ExternalGeometryExtension::saveAttributes(Base::Writer &writer) const << "\" Flags=\"" << Flags.to_string(); } -std::unique_ptr ExternalGeometryExtension::copy(void) const +std::unique_ptr ExternalGeometryExtension::copy() const { auto cpy = std::make_unique(); @@ -74,7 +74,7 @@ std::unique_ptr ExternalGeometryExtension::copy(void) c #endif } -PyObject * ExternalGeometryExtension::getPyObject(void) +PyObject * ExternalGeometryExtension::getPyObject() { return new ExternalGeometryExtensionPy(new ExternalGeometryExtension(*this)); } diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtension.h b/src/Mod/Sketcher/App/ExternalGeometryExtension.h index 1c0422996f..6185d77ece 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtension.h +++ b/src/Mod/Sketcher/App/ExternalGeometryExtension.h @@ -66,29 +66,29 @@ public: public: ExternalGeometryExtension() = default; - virtual ~ExternalGeometryExtension() override = default; + ~ExternalGeometryExtension() override = default; - virtual std::unique_ptr copy(void) const override; + std::unique_ptr copy() const override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; // START_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) - virtual bool testFlag(int flag) const override { return Flags.test((size_t)(flag)); } - virtual void setFlag(int flag, bool v=true) override { Flags.set((size_t)(flag),v); } + bool testFlag(int flag) const override { return Flags.test((size_t)(flag)); } + void setFlag(int flag, bool v=true) override { Flags.set((size_t)(flag),v); } // END_CREDIT_BLOCK: Credit under LGPL for this block to Zheng, Lei (realthunder) - virtual bool isClear() const override {return Flags.none();} - virtual size_t flagSize() const override {return Flags.size();} + bool isClear() const override {return Flags.none();} + size_t flagSize() const override {return Flags.size();} - virtual const std::string& getRef() const override {return Ref;} - virtual void setRef(const std::string & ref) override {Ref = ref;} + const std::string& getRef() const override {return Ref;} + void setRef(const std::string & ref) override {Ref = ref;} static bool getFlagsFromName(std::string str, ExternalGeometryExtension::Flag &flag); protected: - virtual void copyAttributes(Part::GeometryExtension * cpy) const override; - virtual void restoreAttributes(Base::XMLReader &reader) override; - virtual void saveAttributes(Base::Writer &writer) const override; + void copyAttributes(Part::GeometryExtension * cpy) const override; + void restoreAttributes(Base::XMLReader &reader) override; + void saveAttributes(Base::Writer &writer) const override; private: ExternalGeometryExtension(const ExternalGeometryExtension&) = default; diff --git a/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp index 4f6ba756b0..f4d9c9eedd 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryExtensionPyImp.cpp @@ -35,7 +35,7 @@ using namespace Sketcher; // returns a string which represents the object e.g. when printed in python -std::string ExternalGeometryExtensionPy::representation(void) const +std::string ExternalGeometryExtensionPy::representation() const { std::stringstream str; @@ -45,7 +45,7 @@ std::string ExternalGeometryExtensionPy::representation(void) const str << "getName().size()>0) + if(!getExternalGeometryExtensionPtr()->getName().empty()) str << "\'" << getExternalGeometryExtensionPtr()->getName() << "\', "; str << "\"" << ref; @@ -140,7 +140,7 @@ PyObject* ExternalGeometryExtensionPy::setFlag(PyObject *args) Py_Return; } -Py::String ExternalGeometryExtensionPy::getRef(void) const +Py::String ExternalGeometryExtensionPy::getRef() const { return Py::String(this->getExternalGeometryExtensionPtr()->getRef()); } diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp index a60d60e464..7e11451732 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacade.cpp @@ -46,7 +46,7 @@ ExternalGeometryFacade::ExternalGeometryFacade(): Geo(nullptr), SketchGeoExtensi ExternalGeometryFacade::ExternalGeometryFacade(const Part::Geometry * geometry) : Geo(geometry) { - if(geometry != nullptr) + if(geometry) initExtensions(); else THROWM(Base::ValueError, "ExternalGeometryFacade initialized with Geometry null pointer"); @@ -54,7 +54,7 @@ ExternalGeometryFacade::ExternalGeometryFacade(const Part::Geometry * geometry) std::unique_ptr ExternalGeometryFacade::getFacade(Part::Geometry * geometry) { - if(geometry != nullptr) + if(geometry) return std::unique_ptr(new ExternalGeometryFacade(geometry)); else return std::unique_ptr(nullptr); @@ -62,7 +62,7 @@ std::unique_ptr ExternalGeometryFacade::getFacade(Part:: std::unique_ptr ExternalGeometryFacade::getFacade(const Part::Geometry * geometry) { - if(geometry != nullptr) + if(geometry) return std::unique_ptr(new ExternalGeometryFacade(geometry)); else return std::unique_ptr(nullptr); @@ -72,7 +72,7 @@ void ExternalGeometryFacade::setGeometry(Part::Geometry *geometry) { Geo = geometry; - if(geometry != nullptr) + if(geometry) initExtensions(); else THROWM(Base::ValueError, "ExternalGeometryFacade initialized with Geometry null pointer"); @@ -140,7 +140,7 @@ void ExternalGeometryFacade::copyId(const Part::Geometry * src, Part::Geometry * gfdst->setId(gfsrc->getId()); } -PyObject * ExternalGeometryFacade::getPyObject(void) +PyObject * ExternalGeometryFacade::getPyObject() { return new ExternalGeometryFacadePy(new ExternalGeometryFacade(this->Geo)); } diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacade.h b/src/Mod/Sketcher/App/ExternalGeometryFacade.h index 8db4252fa3..2b0e218741 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacade.h +++ b/src/Mod/Sketcher/App/ExternalGeometryFacade.h @@ -54,7 +54,7 @@ class SketcherExport ExternalGeometryFacade : public Base::BaseClass, private IS TYPESYSTEM_HEADER_WITH_OVERRIDE(); private: - ExternalGeometryFacade(const Part::Geometry * geometry); + explicit ExternalGeometryFacade(const Part::Geometry * geometry); ExternalGeometryFacade(); // As TYPESYSTEM requirement friend class ExternalGeometryFacadePy; @@ -71,33 +71,33 @@ public: void setGeometry(Part::Geometry *geometry); /** External GeometryExtension Interface **/ - virtual bool testFlag(int flag) const override { return getExternalGeoExt()->testFlag(flag); } - virtual void setFlag(int flag, bool v=true) override { getExternalGeoExt()->setFlag(flag, v); } + bool testFlag(int flag) const override { return getExternalGeoExt()->testFlag(flag); } + void setFlag(int flag, bool v=true) override { getExternalGeoExt()->setFlag(flag, v); } - virtual bool isClear() const override {return getExternalGeoExt()->isClear();} - virtual size_t flagSize() const override {return getExternalGeoExt()->flagSize();} + bool isClear() const override {return getExternalGeoExt()->isClear();} + size_t flagSize() const override {return getExternalGeoExt()->flagSize();} - virtual const std::string& getRef() const override {return getExternalGeoExt()->getRef();} - virtual void setRef(const std::string & ref) override {getExternalGeoExt()->setRef(ref);} + const std::string& getRef() const override {return getExternalGeoExt()->getRef();} + void setRef(const std::string & ref) override {getExternalGeoExt()->setRef(ref);} /** GeometryExtension Interface **/ - inline virtual long getId() const override {return getGeoExt()->getId();} - virtual void setId(long id) override {getGeoExt()->setId(id);} + inline long getId() const override {return getGeoExt()->getId();} + void setId(long id) override {getGeoExt()->setId(id);} - virtual InternalType::InternalType getInternalType() const override {return getGeoExt()->getInternalType();} - virtual void setInternalType(InternalType::InternalType type) override {getGeoExt()->setInternalType(type);} + InternalType::InternalType getInternalType() const override {return getGeoExt()->getInternalType();} + void setInternalType(InternalType::InternalType type) override {getGeoExt()->setInternalType(type);} - virtual bool testGeometryMode(int flag) const override { return getGeoExt()->testGeometryMode(flag); } - virtual void setGeometryMode(int flag, bool v=true) override { getGeoExt()->setGeometryMode(flag, v); } + bool testGeometryMode(int flag) const override { return getGeoExt()->testGeometryMode(flag); } + void setGeometryMode(int flag, bool v=true) override { getGeoExt()->setGeometryMode(flag, v); } - virtual int getGeometryLayerId() const override { return getGeoExt()->getGeometryLayerId();} - virtual void setGeometryLayerId(int geolayer) override { getGeoExt()->setGeometryLayerId(geolayer);} + int getGeometryLayerId() const override { return getGeoExt()->getGeometryLayerId();} + void setGeometryLayerId(int geolayer) override { getGeoExt()->setGeometryLayerId(geolayer);} // Convenience accessor bool getBlocked() const { return this->testGeometryMode(GeometryMode::Blocked);} void setBlocked(bool status = true) {this->setGeometryMode(GeometryMode::Blocked, status);} - inline bool getConstruction(void) const {return this->testGeometryMode(GeometryMode::Construction);}; + inline bool getConstruction() const {return this->testGeometryMode(GeometryMode::Construction);}; inline void setConstruction(bool construction) {this->setGeometryMode(GeometryMode::Construction, construction);}; // Geometry Extension Information @@ -120,13 +120,13 @@ public: > GeometryT * getGeometry() const {return dynamic_cast(Geo);} - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; /** Geometry Interface **/ TopoDS_Shape toShape() const {return getGeo()->toShape();}; const Handle(Geom_Geometry)& handle() const {return getGeo()->handle();}; - Part::Geometry *copy(void) const {return getGeo()->copy();}; - Part::Geometry *clone(void) const {return getGeo()->clone();}; + Part::Geometry *copy() const {return getGeo()->copy();}; + Part::Geometry *clone() const {return getGeo()->clone();}; boost::uuids::uuid getTag() const {return getGeo()->getTag();}; std::vector> getExtensions() const {return getGeo()->getExtensions();}; @@ -146,17 +146,17 @@ public: void translate(const Base::Vector3d & vec) {return getGeo()->translate(vec);}; private: - void initExtensions(void); - void initExtensions(void) const; + void initExtensions(); + void initExtensions() const; - const Part::Geometry * getGeo(void) const {return Geo;} - Part::Geometry * getGeo(void) {return const_cast(Geo);} + const Part::Geometry * getGeo() const {return Geo;} + Part::Geometry * getGeo() {return const_cast(Geo);} - std::shared_ptr getGeoExt(void) const {return SketchGeoExtension;} - std::shared_ptr getGeoExt (void) {return std::const_pointer_cast(SketchGeoExtension);} + std::shared_ptr getGeoExt() const {return SketchGeoExtension;} + std::shared_ptr getGeoExt () {return std::const_pointer_cast(SketchGeoExtension);} - std::shared_ptr getExternalGeoExt(void) const {return ExternalGeoExtension;} - std::shared_ptr getExternalGeoExt (void) {return std::const_pointer_cast(ExternalGeoExtension);} + std::shared_ptr getExternalGeoExt() const {return ExternalGeoExtension;} + std::shared_ptr getExternalGeoExt () {return std::const_pointer_cast(ExternalGeoExtension);} private: const Part::Geometry * Geo; diff --git a/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp b/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp index 8fbe92bc97..f757e45ef4 100644 --- a/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp +++ b/src/Mod/Sketcher/App/ExternalGeometryFacadePyImp.cpp @@ -49,7 +49,7 @@ using namespace Sketcher; // returns a string which represents the object e.g. when printed in python -std::string ExternalGeometryFacadePy::representation(void) const +std::string ExternalGeometryFacadePy::representation() const { std::stringstream str; str << "getBlocked()); } @@ -496,7 +496,7 @@ PyObject* ExternalGeometryFacadePy::getExtensions(PyObject *args) } -Py::Boolean ExternalGeometryFacadePy::getConstruction(void) const +Py::Boolean ExternalGeometryFacadePy::getConstruction() const { return Py::Boolean(getExternalGeometryFacadePtr()->getConstruction()); } @@ -507,7 +507,7 @@ void ExternalGeometryFacadePy::setConstruction(Py::Boolean arg) getExternalGeometryFacadePtr()->setConstruction(arg); } -Py::Long ExternalGeometryFacadePy::getGeometryLayerId(void) const +Py::Long ExternalGeometryFacadePy::getGeometryLayerId() const { return Py::Long(this->getExternalGeometryFacadePtr()->getGeometryLayerId()); } @@ -517,13 +517,13 @@ void ExternalGeometryFacadePy::setGeometryLayerId(Py::Long Id) this->getExternalGeometryFacadePtr()->setGeometryLayerId(long(Id)); } -Py::String ExternalGeometryFacadePy::getTag(void) const +Py::String ExternalGeometryFacadePy::getTag() const { std::string tmp = boost::uuids::to_string(getExternalGeometryFacadePtr()->getTag()); return Py::String(tmp); } -Py::Object ExternalGeometryFacadePy::getGeometry(void) const +Py::Object ExternalGeometryFacadePy::getGeometry() const { // We return a clone std::unique_ptr geo(getExternalGeometryFacadePtr()->getGeometry()->clone()); diff --git a/src/Mod/Sketcher/App/GeoList.cpp b/src/Mod/Sketcher/App/GeoList.cpp index e6d21e455e..f3a97d18c5 100644 --- a/src/Mod/Sketcher/App/GeoList.cpp +++ b/src/Mod/Sketcher/App/GeoList.cpp @@ -224,7 +224,7 @@ Base::Vector3d GeoListModel::getPoint(const Part::Geometry * geo, Sketcher::P } template -void GeoListModel::rebuildVertexIndex(void) const +void GeoListModel::rebuildVertexIndex() const { VertexId2GeoElementId.clear(); GeoElementId2VertexId.clear(); diff --git a/src/Mod/Sketcher/App/GeometryFacade.cpp b/src/Mod/Sketcher/App/GeometryFacade.cpp index e86baed471..f8d174423a 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.cpp +++ b/src/Mod/Sketcher/App/GeometryFacade.cpp @@ -46,20 +46,20 @@ GeometryFacade::GeometryFacade(): Geo(nullptr), OwnerGeo(false), SketchGeoExtens GeometryFacade::GeometryFacade(const Part::Geometry * geometry, bool owner) : Geo(geometry), OwnerGeo(owner) { - assert(geometry != nullptr); // This should never be nullptr, as this constructor is protected + assert(geometry); // This should never be nullptr, as this constructor is protected initExtension(); } GeometryFacade::~GeometryFacade() { - if (OwnerGeo && Geo != nullptr) + if (OwnerGeo && Geo) delete Geo; } std::unique_ptr GeometryFacade::getFacade(Part::Geometry * geometry, bool owner) { - if(geometry != nullptr) + if(geometry) return std::unique_ptr(new GeometryFacade(geometry, owner)); else return std::unique_ptr(nullptr); @@ -68,7 +68,7 @@ std::unique_ptr GeometryFacade::getFacade(Part::Geometry * geome std::unique_ptr GeometryFacade::getFacade(const Part::Geometry * geometry) { - if(geometry != nullptr) + if(geometry) return std::unique_ptr(new GeometryFacade(geometry)); else return std::unique_ptr(nullptr); @@ -79,7 +79,7 @@ void GeometryFacade::setGeometry(Part::Geometry *geometry) { Geo = geometry; - if(geometry != nullptr) + if(geometry) initExtension(); else THROWM(Base::ValueError, "GeometryFacade initialized with Geometry null pointer"); @@ -113,7 +113,7 @@ void GeometryFacade::initExtension() const void GeometryFacade::throwOnNullPtr(const Part::Geometry * geo) { - if(geo == nullptr) + if(!geo) THROWM(Base::ValueError, "Geometry is nullptr!"); } @@ -168,7 +168,7 @@ bool GeometryFacade::getBlocked(const Part::Geometry * geometry) return gf->getBlocked(); } -PyObject * GeometryFacade::getPyObject(void) +PyObject * GeometryFacade::getPyObject() { return new GeometryFacadePy(new GeometryFacade(this->Geo)); } diff --git a/src/Mod/Sketcher/App/GeometryFacade.h b/src/Mod/Sketcher/App/GeometryFacade.h index 4ca789bdbb..e01c951bd0 100644 --- a/src/Mod/Sketcher/App/GeometryFacade.h +++ b/src/Mod/Sketcher/App/GeometryFacade.h @@ -108,7 +108,7 @@ class SketcherExport GeometryFacade : public Base::BaseClass, private ISketchGeo TYPESYSTEM_HEADER_WITH_OVERRIDE(); protected: - GeometryFacade(const Part::Geometry * geometry, bool owner = false); + explicit GeometryFacade(const Part::Geometry * geometry, bool owner = false); GeometryFacade(); // As TYPESYSTEM requirement friend class GeometryFacadePy; @@ -133,7 +133,7 @@ public: GeometryFacade(GeometryFacade&&) = default; GeometryFacade& operator=(GeometryFacade&&) = default; - ~GeometryFacade(); + ~GeometryFacade() override; void setGeometry(Part::Geometry *geometry); void setOwner(bool owner) { @@ -146,23 +146,23 @@ public: } // Geometry Extension Interface - inline virtual long getId() const override {return getGeoExt()->getId();} - virtual void setId(long id) override {getGeoExt()->setId(id);} + inline long getId() const override {return getGeoExt()->getId();} + void setId(long id) override {getGeoExt()->setId(id);} - virtual InternalType::InternalType getInternalType() const override {return getGeoExt()->getInternalType();} - virtual void setInternalType(InternalType::InternalType type) override {getGeoExt()->setInternalType(type);} + InternalType::InternalType getInternalType() const override {return getGeoExt()->getInternalType();} + void setInternalType(InternalType::InternalType type) override {getGeoExt()->setInternalType(type);} - virtual bool testGeometryMode(int flag) const override { return getGeoExt()->testGeometryMode(flag); } - virtual void setGeometryMode(int flag, bool v=true) override { getGeoExt()->setGeometryMode(flag, v); } + bool testGeometryMode(int flag) const override { return getGeoExt()->testGeometryMode(flag); } + void setGeometryMode(int flag, bool v=true) override { getGeoExt()->setGeometryMode(flag, v); } - virtual int getGeometryLayerId() const override { return getGeoExt()->getGeometryLayerId();} - virtual void setGeometryLayerId(int geolayer) override { getGeoExt()->setGeometryLayerId(geolayer);} + int getGeometryLayerId() const override { return getGeoExt()->getGeometryLayerId();} + void setGeometryLayerId(int geolayer) override { getGeoExt()->setGeometryLayerId(geolayer);} // Convenience accessor bool getBlocked() const { return this->testGeometryMode(GeometryMode::Blocked);} void setBlocked(bool status = true) {this->setGeometryMode(GeometryMode::Blocked, status);} - inline bool getConstruction(void) const {return this->testGeometryMode(GeometryMode::Construction);} + inline bool getConstruction() const {return this->testGeometryMode(GeometryMode::Construction);} inline void setConstruction(bool construction) {this->setGeometryMode(GeometryMode::Construction, construction);} bool isInternalAligned() const { return this->getInternalType() != InternalType::None; } @@ -186,13 +186,13 @@ public: > const GeometryT * getGeometry() const {return dynamic_cast(Geo);} - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; // Geometry Interface TopoDS_Shape toShape() const {return getGeo()->toShape();} const Handle(Geom_Geometry)& handle() const {return getGeo()->handle();} - Part::Geometry *copy(void) const {return getGeo()->copy();} - Part::Geometry *clone(void) const {return getGeo()->clone();} + Part::Geometry *copy() const {return getGeo()->copy();} + Part::Geometry *clone() const {return getGeo()->clone();} boost::uuids::uuid getTag() const {return getGeo()->getTag();} std::vector> getExtensions() const {return getGeo()->getExtensions();} @@ -215,14 +215,14 @@ public: bool isGeoType(const Base::Type &type) const { return getGeo()->getTypeId() == type;} private: - void initExtension(void); - void initExtension(void) const; + void initExtension(); + void initExtension() const; - const Part::Geometry * getGeo(void) const {return Geo;} - Part::Geometry * getGeo(void) {return const_cast(Geo);} + const Part::Geometry * getGeo() const {return Geo;} + Part::Geometry * getGeo() {return const_cast(Geo);} - std::shared_ptr getGeoExt(void) const {return SketchGeoExtension;} - std::shared_ptr getGeoExt (void) {return std::const_pointer_cast(SketchGeoExtension);} + std::shared_ptr getGeoExt() const {return SketchGeoExtension;} + std::shared_ptr getGeoExt () {return std::const_pointer_cast(SketchGeoExtension);} static void throwOnNullPtr(const Part::Geometry * geo); @@ -266,18 +266,18 @@ class SketcherExport GeometryTypedFacade : public GeometryFacade static_assert( std::is_base_of::type>::value && !std::is_same::type>::value, "Only for classes derived from Geometry!"); private: - GeometryTypedFacade(const Part::Geometry * geometry, bool owner = false):GeometryFacade(geometry, owner) {} + explicit GeometryTypedFacade(const Part::Geometry * geometry, bool owner = false):GeometryFacade(geometry, owner) {} GeometryTypedFacade():GeometryFacade() {} public: // Factory methods static std::unique_ptr> getTypedFacade(GeometryT * geometry, bool owner = false) { - if(geometry != nullptr) + if(geometry) return std::unique_ptr>(new GeometryTypedFacade(geometry, owner)); else return std::unique_ptr>(nullptr); } static std::unique_ptr> getTypedFacade(const GeometryT * geometry) { - if(geometry != nullptr) + if(geometry) return std::unique_ptr>(new GeometryTypedFacade(geometry)); else return std::unique_ptr>(nullptr); diff --git a/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp b/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp index 7e06147854..0521e9395d 100644 --- a/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp +++ b/src/Mod/Sketcher/App/GeometryFacadePyImp.cpp @@ -49,7 +49,7 @@ using namespace Sketcher; // returns a string which represents the object e.g. when printed in python -std::string GeometryFacadePy::representation(void) const +std::string GeometryFacadePy::representation() const { std::stringstream str; str << "getBlocked()); } @@ -473,7 +473,7 @@ PyObject* GeometryFacadePy::getExtensions(PyObject *args) } -Py::Boolean GeometryFacadePy::getConstruction(void) const +Py::Boolean GeometryFacadePy::getConstruction() const { return Py::Boolean(getGeometryFacadePtr()->getConstruction()); } @@ -483,7 +483,7 @@ void GeometryFacadePy::setConstruction(Py::Boolean arg) getGeometryFacadePtr()->setConstruction(arg); } -Py::Long GeometryFacadePy::getGeometryLayerId(void) const +Py::Long GeometryFacadePy::getGeometryLayerId() const { return Py::Long(this->getGeometryFacadePtr()->getGeometryLayerId()); } @@ -493,13 +493,13 @@ void GeometryFacadePy::setGeometryLayerId(Py::Long Id) this->getGeometryFacadePtr()->setGeometryLayerId(long(Id)); } -Py::String GeometryFacadePy::getTag(void) const +Py::String GeometryFacadePy::getTag() const { std::string tmp = boost::uuids::to_string(getGeometryFacadePtr()->getTag()); return Py::String(tmp); } -Py::Object GeometryFacadePy::getGeometry(void) const +Py::Object GeometryFacadePy::getGeometry() const { // We return a clone std::unique_ptr geo(getGeometryFacadePtr()->getGeometry()->clone()); diff --git a/src/Mod/Sketcher/App/PropertyConstraintList.cpp b/src/Mod/Sketcher/App/PropertyConstraintList.cpp index 19a9d80863..0a40474f1a 100644 --- a/src/Mod/Sketcher/App/PropertyConstraintList.cpp +++ b/src/Mod/Sketcher/App/PropertyConstraintList.cpp @@ -85,7 +85,7 @@ App::ObjectIdentifier PropertyConstraintList::makeSimplePath(const Constraint * App::ObjectIdentifier PropertyConstraintList::makePath(int idx, const Constraint * c) { - return c->Name.size() == 0 ? makeArrayPath(idx) : makeSimplePath(c); + return c->Name.empty() ? makeArrayPath(idx) : makeSimplePath(c); } void PropertyConstraintList::setSize(int newSize) @@ -99,7 +99,7 @@ void PropertyConstraintList::setSize(int newSize) } /* Signal removed elements */ - if (removed.size() > 0) + if (!removed.empty()) signalConstraintsRemoved(removed); /* Actually delete them */ @@ -110,7 +110,7 @@ void PropertyConstraintList::setSize(int newSize) _lValueList.resize(newSize); } -int PropertyConstraintList::getSize(void) const +int PropertyConstraintList::getSize() const { return static_cast(_lValueList.size()); } @@ -126,7 +126,7 @@ void PropertyConstraintList::set1Value(const int idx, const Constraint* lValue) std::map renamed; renamed[makePath(idx, _lValueList[idx])] = makePath(idx, lValue); - if (renamed.size() > 0) + if (!renamed.empty()) signalConstraintsRenamed(renamed); } @@ -148,13 +148,13 @@ void PropertyConstraintList::setValue(const Constraint* lValue) int start = 0; /* Determine if it is a rename or not * */ - if (_lValueList.size() > 0 && lValue->tag == _lValueList[0]->tag) { + if (!_lValueList.empty() && lValue->tag == _lValueList[0]->tag) { renamed[makePath(0, _lValueList[0])] = makePath(0, lValue); start = 1; } /* Signal rename changes */ - if (renamed.size() > 0) + if (!renamed.empty()) signalConstraintsRenamed(renamed); /* Collect info about removals */ @@ -164,7 +164,7 @@ void PropertyConstraintList::setValue(const Constraint* lValue) } /* Signal removes */ - if (removed.size() > 0) + if (!removed.empty()) signalConstraintsRemoved(removed); // Cleanup @@ -228,11 +228,11 @@ void PropertyConstraintList::applyValues(std::vector&& lValue) valueMap = std::move(newValueMap); /* Signal removes first, in case renamed values below have the same names as some of the removed ones. */ - if (removed.size() > 0 && !restoreFromTransaction) + if (!removed.empty() && !restoreFromTransaction) signalConstraintsRemoved(removed); /* Signal renames */ - if (renamed.size() > 0 && !restoreFromTransaction) + if (!renamed.empty() && !restoreFromTransaction) signalConstraintsRenamed(renamed); _lValueList = std::move(lValue); @@ -242,7 +242,7 @@ void PropertyConstraintList::applyValues(std::vector&& lValue) delete v; } -PyObject *PropertyConstraintList::getPyObject(void) +PyObject *PropertyConstraintList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) @@ -345,7 +345,7 @@ void PropertyConstraintList::Restore(Base::XMLReader &reader) setValues(std::move(values)); } -Property *PropertyConstraintList::Copy(void) const +Property *PropertyConstraintList::Copy() const { PropertyConstraintList *p = new PropertyConstraintList(); p->applyValidGeometryKeys(validGeometryKeys); @@ -360,7 +360,7 @@ void PropertyConstraintList::Paste(const Property &from) setValues(FromList._lValueList); } -unsigned int PropertyConstraintList::getMemSize(void) const +unsigned int PropertyConstraintList::getMemSize() const { int size = sizeof(PropertyConstraintList); for (int i = 0; i < getSize(); i++) @@ -477,7 +477,7 @@ string PropertyConstraintList::getConstraintName(int i) bool PropertyConstraintList::validConstraintName(const std::string & name) { - return name.size() > 0; + return !name.empty(); } ObjectIdentifier PropertyConstraintList::createPath(int ConstrNbr) const @@ -582,7 +582,7 @@ ObjectIdentifier PropertyConstraintList::canonicalPath(const ObjectIdentifier &p if (c1.isArray()) { size_t idx = c1.getIndex(); - if (idx < _lValueList.size() && _lValueList[idx]->Name.size() > 0) + if (idx < _lValueList.size() && !_lValueList[idx]->Name.empty()) return ObjectIdentifier(*this) << ObjectIdentifier::SimpleComponent(_lValueList[idx]->Name); return p; } @@ -595,7 +595,7 @@ ObjectIdentifier PropertyConstraintList::canonicalPath(const ObjectIdentifier &p void PropertyConstraintList::getPaths(std::vector &paths) const { for (std::vector::const_iterator it = _lValueList.begin(); it != _lValueList.end(); ++it) { - if ((*it)->Name.size() > 0) + if (!(*it)->Name.empty()) paths.push_back(ObjectIdentifier(*this) << ObjectIdentifier::SimpleComponent((*it)->Name)); } } diff --git a/src/Mod/Sketcher/App/PropertyConstraintList.h b/src/Mod/Sketcher/App/PropertyConstraintList.h index f2daec8cf6..d95caf80c8 100644 --- a/src/Mod/Sketcher/App/PropertyConstraintList.h +++ b/src/Mod/Sketcher/App/PropertyConstraintList.h @@ -58,12 +58,12 @@ public: * A destructor. * A more elaborate description of the destructor. */ - virtual ~PropertyConstraintList(); + ~PropertyConstraintList() override; - virtual void setSize(int newSize) override; - virtual int getSize(void) const override; + void setSize(int newSize) override; + int getSize() const override; - const char* getEditorName(void) const override { + const char* getEditorName() const override { return "SketcherGui::PropertyConstraintListItem"; } @@ -102,23 +102,23 @@ public: return (invalidGeometry || invalidIndices) ? nullptr : _lValueList[idx]; } - const std::vector &getValues(void) const { + const std::vector &getValues() const { return (invalidGeometry || invalidIndices) ? _emptyValueList : _lValueList; } - const std::vector &getValuesForce(void) const {//to suppress check for invalid geometry, to be used for sketch repairing. + const std::vector &getValuesForce() const {//to suppress check for invalid geometry, to be used for sketch repairing. return _lValueList; } - virtual PyObject *getPyObject(void) override; - virtual void setPyObject(PyObject *) override; + PyObject *getPyObject() override; + void setPyObject(PyObject *) override; - virtual void Save(Base::Writer &writer) const override; - virtual void Restore(Base::XMLReader &reader) override; + void Save(Base::Writer &writer) const override; + void Restore(Base::XMLReader &reader) override; - virtual Property *Copy(void) const override; - virtual void Paste(const App::Property &from) override; + Property *Copy() const override; + void Paste(const App::Property &from) override; - virtual unsigned int getMemSize(void) const override; + unsigned int getMemSize() const override; void acceptGeometry(const std::vector &GeoList); bool checkGeometry(const std::vector &GeoList); @@ -131,12 +131,12 @@ public: const Constraint *getConstraint(const App::ObjectIdentifier &path) const; - virtual void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; - virtual const boost::any getPathValue(const App::ObjectIdentifier & path) const override; - virtual App::ObjectIdentifier canonicalPath(const App::ObjectIdentifier & p) const override; - virtual void getPaths(std::vector & paths) const override; + void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; + const boost::any getPathValue(const App::ObjectIdentifier & path) const override; + App::ObjectIdentifier canonicalPath(const App::ObjectIdentifier & p) const override; + void getPaths(std::vector & paths) const override; - virtual bool getPyPathValue(const App::ObjectIdentifier &path, Py::Object &res) const override; + bool getPyPathValue(const App::ObjectIdentifier &path, Py::Object &res) const override; typedef std::pair ConstraintInfo ; diff --git a/src/Mod/Sketcher/App/PythonConverter.cpp b/src/Mod/Sketcher/App/PythonConverter.cpp index 0437bd12c4..4d75f1b085 100644 --- a/src/Mod/Sketcher/App/PythonConverter.cpp +++ b/src/Mod/Sketcher/App/PythonConverter.cpp @@ -126,7 +126,7 @@ std::string PythonConverter::convert(const std::string & doc, const std::vector< constraintlist % cg); } - if(constraints.size() > 0) { + if(!constraints.empty()) { constraintlist = boost::str(boost::format("%s\n%s.addConstraint(constraintList)\ndel constraintList\n") % constraintlist % doc); } diff --git a/src/Mod/Sketcher/App/Sketch.cpp b/src/Mod/Sketcher/App/Sketch.cpp index 0ff1ff38a0..7404ddd63d 100644 --- a/src/Mod/Sketcher/App/Sketch.cpp +++ b/src/Mod/Sketcher/App/Sketch.cpp @@ -88,7 +88,7 @@ Sketch::~Sketch() clear(); } -void Sketch::clear(void) +void Sketch::clear() { // clear all internal data sets Points.clear(); @@ -320,7 +320,7 @@ int Sketch::setUpSketch(const std::vector &GeoList, void Sketch::fixParametersAndDiagnose(std::vector ¶ms_to_block) { - if(params_to_block.size() > 0) { // only there are parameters to fix + if(!params_to_block.empty()) { // only there are parameters to fix for( auto p : params_to_block ) { auto findparam = std::find(Parameters.begin(),Parameters.end(), p); @@ -411,12 +411,12 @@ bool Sketch::analyseBlockedConstraintDependentParameters(std::vector &block bool unsatisfied_groups = false; for(size_t i = 0; i < prop_groups.size(); i++) { // 4.1. unsatisfiable group - if(prop_groups[i].blockable_params_in_group.size() == 0) { + if(prop_groups[i].blockable_params_in_group.empty()) { // this group does not contain any blockable parameter, so it is by definition satisfied (or impossible to satisfy by block constraints) continue; } // 4.2. satisfiable and not satisfied - if(prop_groups[i].blocking_param_in_group == nullptr) { + if(!prop_groups[i].blocking_param_in_group) { unsatisfied_groups = true; } } @@ -425,12 +425,12 @@ bool Sketch::analyseBlockedConstraintDependentParameters(std::vector &block } -void Sketch::clearTemporaryConstraints(void) +void Sketch::clearTemporaryConstraints() { GCSsys.clearByTag(GCS::DefaultTemporaryConstraint); } -void Sketch::calculateDependentParametersElements(void) +void Sketch::calculateDependentParametersElements() { // initialize solve extensions to a know state solverExtensions.resize(Geoms.size()); @@ -1477,7 +1477,7 @@ void Sketch::updateExtension(int geoId, std::unique_ptr } -Py::Tuple Sketch::getPyGeometry(void) const +Py::Tuple Sketch::getPyGeometry() const { Py::Tuple tuple(Geoms.size()); int i=0; @@ -2677,7 +2677,7 @@ int Sketch::addAngleConstraint(int geoId1, PointPos pos1, int geoId2, PointPos p l2p2 = &Points[Geoms[geoId2].startPointId]; } - if (l1p1 == nullptr || l2p1 == nullptr) + if (!l1p1 || !l2p1) return -1; int tag = ++ConstraintsCounter; @@ -3577,7 +3577,7 @@ bool Sketch::updateNonDrivingConstraints() // solving ========================================================== -int Sketch::solve(void) +int Sketch::solve() { Base::TimeInfo start_time; std::string solvername; @@ -4226,7 +4226,7 @@ Base::Vector3d Sketch::getPoint(int geoId, PointPos pos) const return Base::Vector3d(); } -TopoShape Sketch::toShape(void) const +TopoShape Sketch::toShape() const { TopoShape result; std::vector::const_iterator it=Geoms.begin(); @@ -4269,7 +4269,7 @@ TopoShape Sketch::toShape(void) const // Hint: Use ShapeAnalysis_FreeBounds::ConnectEdgesToWires() as an alternative // // sort them together to wires - while (edge_list.size() > 0) { + while (!edge_list.empty()) { BRepBuilderAPI_MakeWire mkWire; // add and erase first edge mkWire.Add(edge_list.front()); @@ -4333,7 +4333,7 @@ TopoShape Sketch::toShape(void) const // Persistence implementer ------------------------------------------------- -unsigned int Sketch::getMemSize(void) const +unsigned int Sketch::getMemSize() const { return 0; } diff --git a/src/Mod/Sketcher/App/Sketch.h b/src/Mod/Sketcher/App/Sketch.h index b6f33e7663..5819ae18d4 100644 --- a/src/Mod/Sketcher/App/Sketch.h +++ b/src/Mod/Sketcher/App/Sketch.h @@ -41,25 +41,25 @@ namespace Sketcher class SketcherExport Sketch :public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Sketch(); - ~Sketch(); + ~Sketch() override; // from base class - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; /// solve the actual set up sketch - int solve(void); + int solve(); /// resets the solver int resetSolver(); /// get standard (aka fine) solver precision double getSolverPrecision(){ return GCSsys.getFinePrecision(); } /// delete all geometry and constraints, leave an empty sketch - void clear(void); + void clear(); /** set the sketch up with geoms and constraints * * returns the degree of freedom of a sketch and calculates a list of @@ -76,7 +76,7 @@ public: int setUpSketch(const std::vector &GeoList, const std::vector &ConstraintList, int extGeoCount=0); /// return the actual geometry of the sketch a TopoShape - Part::TopoShape toShape(void) const; + Part::TopoShape toShape() const; /// add unspecified geometry int addGeometry(const Part::Geometry *geo, bool fixed=false); /// add unspecified geometry @@ -96,7 +96,7 @@ public: void updateExtension(int geoId, std::unique_ptr && ext); /// get the geometry as python objects - Py::Tuple getPyGeometry(void) const; + Py::Tuple getPyGeometry() const; /// retrieves the index of a point int getPointId(int geoId, PointPos pos) const; @@ -104,17 +104,17 @@ public: Base::Vector3d getPoint(int geoId, PointPos pos) const; // Inline methods - inline bool hasConflicts(void) const { return !Conflicting.empty(); } - inline const std::vector &getConflicting(void) const { return Conflicting; } - inline bool hasRedundancies(void) const { return !Redundant.empty(); } - inline const std::vector &getRedundant(void) const { return Redundant; } - inline bool hasPartialRedundancies(void) const { return !PartiallyRedundant.empty(); } - inline const std::vector &getPartiallyRedundant(void) const { return PartiallyRedundant; } + inline bool hasConflicts() const { return !Conflicting.empty(); } + inline const std::vector &getConflicting() const { return Conflicting; } + inline bool hasRedundancies() const { return !Redundant.empty(); } + inline const std::vector &getRedundant() const { return Redundant; } + inline bool hasPartialRedundancies() const { return !PartiallyRedundant.empty(); } + inline const std::vector &getPartiallyRedundant() const { return PartiallyRedundant; } inline float getSolveTime() const { return SolveTime; } - inline bool hasMalformedConstraints(void) const { return !MalformedConstraints.empty(); } - inline const std::vector &getMalformedConstraints(void) const { return MalformedConstraints; } + inline bool hasMalformedConstraints() const { return !MalformedConstraints.empty(); } + inline const std::vector &getMalformedConstraints() const { return MalformedConstraints; } public: std::set < std::pair< int, Sketcher::PointPos>> getDependencyGroup(int geoId, PointPos pos) const; @@ -394,7 +394,7 @@ public: double calculateConstraintError(int icstr) { return GCSsys.calculateConstraintErrorByTag(icstr);} /// Returns the size of the Geometry - int getGeometrySize(void) const {return Geoms.size();} + int getGeometrySize() const {return Geoms.size();} enum GeoType { None = 0, @@ -486,7 +486,7 @@ public: GCS::Algorithm defaultSolverRedundant; inline void setDogLegGaussStep(GCS::DogLegGaussStep mode){GCSsys.dogLegGaussStep=mode;} inline void setDebugMode(GCS::DebugMode mode) {debugMode=mode;GCSsys.debugMode=mode;} - inline GCS::DebugMode getDebugMode(void) {return debugMode;} + inline GCS::DebugMode getDebugMode() {return debugMode;} inline void setMaxIter(int maxiter){GCSsys.maxIter=maxiter;} inline void setMaxIterRedundant(int maxiter){GCSsys.maxIterRedundant=maxiter;} inline void setSketchSizeMultiplier(bool mult){GCSsys.sketchSizeMultiplier=mult;} @@ -514,12 +514,12 @@ protected: private: - bool updateGeometry(void); - bool updateNonDrivingConstraints(void); + bool updateGeometry(); + bool updateNonDrivingConstraints(); - void calculateDependentParametersElements(void); + void calculateDependentParametersElements(); - void clearTemporaryConstraints(void); + void clearTemporaryConstraints(); int internalSolve(std::string & solvername, int level = 0); diff --git a/src/Mod/Sketcher/App/SketchAnalysis.cpp b/src/Mod/Sketcher/App/SketchAnalysis.cpp index 91d8082bac..ccb2bddb35 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.cpp +++ b/src/Mod/Sketcher/App/SketchAnalysis.cpp @@ -71,7 +71,7 @@ struct SketchAnalysis::VertexIds { struct SketchAnalysis::Vertex_Less { - Vertex_Less(double tolerance) : tolerance(tolerance){} + explicit Vertex_Less(double tolerance) : tolerance(tolerance){} bool operator()(const VertexIds& x, const VertexIds& y) const { @@ -98,7 +98,7 @@ struct SketchAnalysis::VertexID_Less struct SketchAnalysis::Vertex_EqualTo { - Vertex_EqualTo(double tolerance) : tolerance(tolerance){} + explicit Vertex_EqualTo(double tolerance) : tolerance(tolerance){} bool operator()(const VertexIds& x, const VertexIds& y) const { @@ -122,7 +122,7 @@ struct SketchAnalysis::EdgeIds { struct SketchAnalysis::Edge_Less { - Edge_Less(double tolerance) : tolerance(tolerance){} + explicit Edge_Less(double tolerance) : tolerance(tolerance){} bool operator()(const EdgeIds& x, const EdgeIds& y) const { @@ -136,7 +136,7 @@ private: struct SketchAnalysis::Edge_EqualTo { - Edge_EqualTo(double tolerance) : tolerance(tolerance){} + explicit Edge_EqualTo(double tolerance) : tolerance(tolerance){} bool operator()(const EdgeIds& x, const EdgeIds& y) const { @@ -295,7 +295,7 @@ int SketchAnalysis::detectMissingPointOnPointConstraints(double precision, bool std::set *tempGrp = nullptr; for (auto it = coincVertexGrps.begin(); it < coincVertexGrps.end(); ++it) { if ( (it->find(v1) != it->end()) || (it->find(v2) != it->end()) ) { - if (tempGrp == nullptr) { + if (!tempGrp) { tempGrp = &*it; } else { @@ -881,7 +881,7 @@ int SketchAnalysis::autoconstraint(double precision, double angleprecision, bool } -std::vector SketchAnalysis::getOpenVertices(void) const +std::vector SketchAnalysis::getOpenVertices() const { std::vector points; TopoDS_Shape shape = sketch->Shape.getValue(); diff --git a/src/Mod/Sketcher/App/SketchAnalysis.h b/src/Mod/Sketcher/App/SketchAnalysis.h index ee7936623f..bb6bf97abf 100644 --- a/src/Mod/Sketcher/App/SketchAnalysis.h +++ b/src/Mod/Sketcher/App/SketchAnalysis.h @@ -63,7 +63,7 @@ public: /// They may also apply a variaty of types of Constraints. /// /// A third type of routines do not relate to autoconstraining at all, and include validation methods for sketches. - SketchAnalysis(Sketcher::SketchObject * Obj); + explicit SketchAnalysis(Sketcher::SketchObject * Obj); ~SketchAnalysis(); // Simple routines (see constructor) @@ -74,7 +74,7 @@ public: /// Point on Point constraint simple routine Analyse step (see constructor) void analyseMissingPointOnPointCoincident(double angleprecision = M_PI/8); /// Point on Point constraint simple routine Get step (see constructor) - std::vector &getMissingPointOnPointConstraints(void) {return vertexConstraints;} + std::vector &getMissingPointOnPointConstraints() {return vertexConstraints;} /// Vertical/Horizontal constraints simple routine Set step (see constructor) void setMissingPointOnPointConstraints(std::vector& cl) {vertexConstraints = cl;} /// Point on Point constraint simple routine Make step (see constructor) @@ -84,7 +84,7 @@ public: /// Vertical/Horizontal constraints simple routine Detect step (see constructor) int detectMissingVerticalHorizontalConstraints(double angleprecision = M_PI/8); /// Vertical/Horizontal constraints simple routine Get step (see constructor) - std::vector &getMissingVerticalHorizontalConstraints(void) {return verthorizConstraints;} + std::vector &getMissingVerticalHorizontalConstraints() {return verthorizConstraints;} /// Vertical/Horizontal constraints simple routine Set step (see constructor) void setMissingVerticalHorizontalConstraints(std::vector& cl) {verthorizConstraints = cl;} /// Vertical/Horizontal constraints simple routine Make step (see constructor) @@ -93,9 +93,9 @@ public: /// Equality constraints simple routine Detect step (see constructor) int detectMissingEqualityConstraints(double precision); /// Equality constraints simple routine Get step for line segments (see constructor) - std::vector &getMissingLineEqualityConstraints(void) {return lineequalityConstraints;} + std::vector &getMissingLineEqualityConstraints() {return lineequalityConstraints;} /// Equality constraints simple routine Get step for radii (see constructor) - std::vector &getMissingRadiusConstraints(void) {return radiusequalityConstraints;} + std::vector &getMissingRadiusConstraints() {return radiusequalityConstraints;} /// Equality constraints simple routine Set step for line segments (see constructor) void setMissingLineEqualityConstraints(std::vector& cl) {lineequalityConstraints = cl;} /// Equality constraints simple routine Set step for radii (see constructor) @@ -124,7 +124,7 @@ public: void solvesketch(int &status, int &dofs, bool updategeo); // third type of routines - std::vector getOpenVertices(void) const; + std::vector getOpenVertices() const; protected: Sketcher::SketchObject* sketch; diff --git a/src/Mod/Sketcher/App/SketchGeometryExtension.cpp b/src/Mod/Sketcher/App/SketchGeometryExtension.cpp index 9ed69b1757..eb8d422c78 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/SketchGeometryExtension.cpp @@ -91,7 +91,7 @@ void SketchGeometryExtension::saveAttributes(Base::Writer &writer) const << "\" geometryLayer=\"" << GeometryLayer; } -std::unique_ptr SketchGeometryExtension::copy(void) const +std::unique_ptr SketchGeometryExtension::copy() const { auto cpy = std::make_unique(); @@ -104,7 +104,7 @@ std::unique_ptr SketchGeometryExtension::copy(void) con #endif } -PyObject * SketchGeometryExtension::getPyObject(void) +PyObject * SketchGeometryExtension::getPyObject() { return new SketchGeometryExtensionPy(new SketchGeometryExtension(*this)); } diff --git a/src/Mod/Sketcher/App/SketchGeometryExtension.h b/src/Mod/Sketcher/App/SketchGeometryExtension.h index 9276c1d849..b0e9555d31 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtension.h +++ b/src/Mod/Sketcher/App/SketchGeometryExtension.h @@ -83,24 +83,24 @@ class SketcherExport SketchGeometryExtension : public Part::GeometryPersistenceE public: SketchGeometryExtension(); - SketchGeometryExtension(long cid); - virtual ~SketchGeometryExtension() override = default; + explicit SketchGeometryExtension(long cid); + ~SketchGeometryExtension() override = default; - virtual std::unique_ptr copy(void) const override; + std::unique_ptr copy() const override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual long getId() const override {return Id;} - virtual void setId(long id) override {Id = id;} + long getId() const override {return Id;} + void setId(long id) override {Id = id;} - virtual InternalType::InternalType getInternalType() const override {return InternalGeometryType;} - virtual void setInternalType(InternalType::InternalType type) override {InternalGeometryType = type;} + InternalType::InternalType getInternalType() const override {return InternalGeometryType;} + void setInternalType(InternalType::InternalType type) override {InternalGeometryType = type;} - virtual bool testGeometryMode(int flag) const override { return GeometryModeFlags.test((size_t)(flag)); }; - virtual void setGeometryMode(int flag, bool v=true) override { GeometryModeFlags.set((size_t)(flag), v); }; + bool testGeometryMode(int flag) const override { return GeometryModeFlags.test((size_t)(flag)); }; + void setGeometryMode(int flag, bool v=true) override { GeometryModeFlags.set((size_t)(flag), v); }; - virtual int getGeometryLayerId() const override { return GeometryLayer;} - virtual void setGeometryLayerId(int geolayer) override { GeometryLayer = geolayer;} + int getGeometryLayerId() const override { return GeometryLayer;} + void setGeometryLayerId(int geolayer) override { GeometryLayer = geolayer;} constexpr static std::array internaltype2str {{ "None", "EllipseMajorDiameter", "EllipseMinorDiameter","EllipseFocus1", "EllipseFocus2", "HyperbolaMajor", "HyperbolaMinor", "HyperbolaFocus", "ParabolaFocus", "BSplineControlPoint", "BSplineKnotPoint" }}; @@ -111,9 +111,9 @@ public: static bool getGeometryModeFromName(std::string str, GeometryMode::GeometryMode &type); protected: - virtual void copyAttributes(Part::GeometryExtension * cpy) const override; - virtual void restoreAttributes(Base::XMLReader &reader) override; - virtual void saveAttributes(Base::Writer &writer) const override; + void copyAttributes(Part::GeometryExtension * cpy) const override; + void restoreAttributes(Base::XMLReader &reader) override; + void saveAttributes(Base::Writer &writer) const override; private: SketchGeometryExtension(const SketchGeometryExtension&) = default; diff --git a/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp b/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp index 3ae885087a..357ae797a2 100644 --- a/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchGeometryExtensionPyImp.cpp @@ -35,12 +35,12 @@ using namespace Sketcher; // returns a string which represents the object e.g. when printed in python -std::string SketchGeometryExtensionPy::representation(void) const +std::string SketchGeometryExtensionPy::representation() const { std::stringstream str; str << "getName().size()>0) + if(!getSketchGeometryExtensionPtr()->getName().empty()) str << "\'" << getSketchGeometryExtensionPtr()->getName() << "\', "; str << "\""; @@ -79,7 +79,7 @@ int SketchGeometryExtensionPy::PyInit(PyObject* args, PyObject* /*kwd*/) return -1; } -Py::Long SketchGeometryExtensionPy::getId(void) const +Py::Long SketchGeometryExtensionPy::getId() const { return Py::Long(this->getSketchGeometryExtensionPtr()->getId()); } @@ -89,7 +89,7 @@ void SketchGeometryExtensionPy::setId(Py::Long Id) this->getSketchGeometryExtensionPtr()->setId(long(Id)); } -Py::String SketchGeometryExtensionPy::getInternalType(void) const +Py::String SketchGeometryExtensionPy::getInternalType() const { int internaltypeindex = (int)this->getSketchGeometryExtensionPtr()->getInternalType(); @@ -114,7 +114,7 @@ void SketchGeometryExtensionPy::setInternalType(Py::String arg) throw Py::ValueError("Argument is not a valid internal geometry type."); } -Py::Boolean SketchGeometryExtensionPy::getBlocked(void) const +Py::Boolean SketchGeometryExtensionPy::getBlocked() const { return Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(GeometryMode::Blocked)); } @@ -124,7 +124,7 @@ void SketchGeometryExtensionPy::setBlocked(Py::Boolean arg) getSketchGeometryExtensionPtr()->setGeometryMode(GeometryMode::Blocked, arg); } -Py::Boolean SketchGeometryExtensionPy::getConstruction(void) const +Py::Boolean SketchGeometryExtensionPy::getConstruction() const { return Py::Boolean(getSketchGeometryExtensionPtr()->testGeometryMode(GeometryMode::Construction)); } @@ -173,7 +173,7 @@ PyObject* SketchGeometryExtensionPy::setGeometryMode(PyObject *args) Py_Return; } -Py::Long SketchGeometryExtensionPy::getGeometryLayerId(void) const +Py::Long SketchGeometryExtensionPy::getGeometryLayerId() const { return Py::Long(this->getSketchGeometryExtensionPtr()->getGeometryLayerId()); } diff --git a/src/Mod/Sketcher/App/SketchObject.cpp b/src/Mod/Sketcher/App/SketchObject.cpp index fdd946fc2a..6283553543 100644 --- a/src/Mod/Sketcher/App/SketchObject.cpp +++ b/src/Mod/Sketcher/App/SketchObject.cpp @@ -169,7 +169,7 @@ short SketchObject::mustExecute() const return Part2DObject::mustExecute(); } -App::DocumentObjectExecReturn *SketchObject::execute(void) +App::DocumentObjectExecReturn *SketchObject::execute() { try { App::DocumentObjectExecReturn* rtn = Part2DObject::execute();//to positionBySupport @@ -227,7 +227,7 @@ App::DocumentObjectExecReturn *SketchObject::execute(void) return App::DocumentObject::StdReturn; } -int SketchObject::hasConflicts(void) const +int SketchObject::hasConflicts() const { if (lastDoF < 0) // over-constrained sketch return -2; @@ -560,7 +560,7 @@ int SketchObject::setDatumsDriving(bool isdriving) return 0; } -int SketchObject::moveDatumsToEnd(void) +int SketchObject::moveDatumsToEnd() { Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. @@ -828,7 +828,7 @@ Base::Vector3d SketchObject::getPoint(int GeoId, PointPos PosId) const return Base::Vector3d(); } -int SketchObject::getAxisCount(void) const +int SketchObject::getAxisCount() const { const std::vector< Part::Geometry * > &vals = getInternalGeometry(); @@ -3343,7 +3343,7 @@ bool SketchObject::isExternalAllowed(App::Document *pDoc, App::DocumentObject *p App::Part* part_this = App::Part::getPartOfObject(this); App::Part* part_obj = App::Part::getPartOfObject(pObj); if (part_this == part_obj){ //either in the same part, or in the root of document - if (body_this == nullptr) { + if (!body_this) { return true; } else if (body_this == body_obj) { return true; @@ -3402,7 +3402,7 @@ bool SketchObject::isCarbonCopyAllowed(App::Document *pDoc, App::DocumentObject App::Part* part_this = App::Part::getPartOfObject(this); App::Part* part_obj = App::Part::getPartOfObject(pObj); if (part_this == part_obj){ //either in the same part, or in the root of document - if (body_this != nullptr) { + if (body_this) { if (body_this != body_obj) { if (!this->allowOtherBody) { if (rsn) @@ -4111,7 +4111,7 @@ int SketchObject::addCopy(const std::vector &geoIdList, const Base::Vector3 std::vector newgeoIdList(geoIdList); - if(newgeoIdList.size() == 0) {// default option to operate on all the geometry + if(newgeoIdList.empty()) {// default option to operate on all the geometry for(int i = 0; i < int(geovals.size()); i++) newgeoIdList.push_back(i); } @@ -5361,7 +5361,7 @@ int SketchObject::deleteUnusedInternalGeometry(int GeoId, bool delgeoid) std::sort(delgeometries.begin(), delgeometries.end()); // indices over an erased element get automatically updated!! - if (delgeometries.size()>0) { + if (!delgeometries.empty()) { for (std::vector::reverse_iterator it=delgeometries.rbegin(); it!=delgeometries.rend(); ++it) { delGeometry(*it,false); } @@ -5453,7 +5453,7 @@ int SketchObject::deleteUnusedInternalGeometry(int GeoId, bool delgeoid) std::sort(delgeometries.begin(), delgeometries.end()); // indices over an erased element get automatically updated!! - if (delgeometries.size()>0) { + if (!delgeometries.empty()) { for (std::vector::reverse_iterator it=delgeometries.rbegin(); it!=delgeometries.rend(); ++it) { delGeometry(*it,false); } @@ -6536,7 +6536,7 @@ Part::Geometry* projectLine(const BRepAdaptor_Curve& curve, const Handle(Geom_Pl } } -bool SketchObject::evaluateSupport(void) +bool SketchObject::evaluateSupport() { // returns false if the shape is broken, null or non-planar App::DocumentObject *link = Support.getValue(); @@ -6545,7 +6545,7 @@ bool SketchObject::evaluateSupport(void) return true; } -void SketchObject::validateExternalLinks(void) +void SketchObject::validateExternalLinks() { Base::StateLocker lock(managedoperation, true); // no need to check input data validity as this is an sketchobject managed operation. @@ -6609,7 +6609,7 @@ void SketchObject::validateExternalLinks(void) } } -void SketchObject::rebuildExternalGeometry(void) +void SketchObject::rebuildExternalGeometry() { // get the actual lists of the externals std::vector Objects = ExternalGeometry.getValues(); @@ -7182,14 +7182,14 @@ void SketchObject::rebuildExternalGeometry(void) rebuildVertexIndex(); } -std::vector SketchObject::getCompleteGeometry(void) const +std::vector SketchObject::getCompleteGeometry() const { std::vector vals = getInternalGeometry(); vals.insert(vals.end(), ExternalGeo.rbegin(), ExternalGeo.rend()); // in reverse order return vals; } -GeoListFacade SketchObject::getGeoListFacade(void) const +GeoListFacade SketchObject::getGeoListFacade() const { std::vector facade; facade.reserve( Geometry.getSize() + ExternalGeo.size() ); @@ -7203,7 +7203,7 @@ GeoListFacade SketchObject::getGeoListFacade(void) const return GeoListFacade::getGeoListModel(std::move(facade), Geometry.getSize()); } -void SketchObject::rebuildVertexIndex(void) +void SketchObject::rebuildVertexIndex() { VertexId2GeoId.resize(0); VertexId2PosId.resize(0); @@ -7494,7 +7494,7 @@ void SketchObject::appendConstraintsMsg(const std::vector &vector, std::stringstream ss; if (msg.length() > 0) ss << msg; - if (vector.size() > 0) { + if (!vector.empty()) { if (vector.size() == 1) ss << singularmsg << std::endl; else @@ -7671,7 +7671,7 @@ std::string SketchObject::validateExpression(const App::ObjectIdentifier &path, { const App::Property * prop = path.getProperty(); - assert(expr != nullptr); + assert(expr); if (!prop) return "Property not found"; @@ -7685,10 +7685,10 @@ std::string SketchObject::validateExpression(const App::ObjectIdentifier &path, auto deps = expr->getDeps(); auto it = deps.find(this); - if(it!=deps.end()) { + if (it!=deps.end()) { auto it2 = it->second.find("Constraints"); - if(it2 != it->second.end()) { - for(auto &oid : it2->second) { + if (it2 != it->second.end()) { + for (auto &oid : it2->second) { const Constraint * constraint = Constraints.getConstraint(oid); if (!constraint->isDriving) @@ -7710,7 +7710,7 @@ double SketchObject::calculateAngleViaPoint(int GeoId1, int GeoId2, double px, d const Part::Geometry *p1=this->getGeometry(GeoId1); const Part::Geometry *p2=this->getGeometry(GeoId2); - if(p1!=nullptr && p2!=nullptr) { + if (p1 && p2) { int i1 = sk.addGeometry(this->getGeometry(GeoId1)); int i2 = sk.addGeometry(this->getGeometry(GeoId2)); @@ -7794,7 +7794,7 @@ double SketchObject::calculateConstraintError(int ConstrId) return result; } -PyObject *SketchObject::getPyObject(void) +PyObject *SketchObject::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -7803,7 +7803,7 @@ PyObject *SketchObject::getPyObject(void) return Py::new_reference_to(PythonObject); } -unsigned int SketchObject::getMemSize(void) const +unsigned int SketchObject::getMemSize() const { return 0; } @@ -8039,7 +8039,7 @@ void SketchObject::restoreFinished() } } -void SketchObject::migrateSketch(void) +void SketchObject::migrateSketch() { bool noextensions = false; @@ -8366,22 +8366,22 @@ int SketchObject::detectMissingEqualityConstraints(double precision) return analyser->detectMissingEqualityConstraints(precision); } -std::vector & SketchObject::getMissingPointOnPointConstraints(void) +std::vector & SketchObject::getMissingPointOnPointConstraints() { return analyser->getMissingPointOnPointConstraints(); } -std::vector & SketchObject::getMissingVerticalHorizontalConstraints(void) +std::vector & SketchObject::getMissingVerticalHorizontalConstraints() { return analyser->getMissingVerticalHorizontalConstraints(); } -std::vector & SketchObject::getMissingLineEqualityConstraints(void) +std::vector & SketchObject::getMissingLineEqualityConstraints() { return analyser->getMissingLineEqualityConstraints(); } -std::vector & SketchObject::getMissingRadiusConstraints(void) +std::vector & SketchObject::getMissingRadiusConstraints() { return analyser->getMissingRadiusConstraints(); } @@ -8432,7 +8432,7 @@ int SketchObject::autoRemoveRedundants(bool updategeo) { auto redundants = getLastRedundant(); - if(redundants.size() == 0) + if(redundants.empty()) return 0; for(size_t i=0;i SketchObject::getOpenVertices(void) const +std::vector SketchObject::getOpenVertices() const { std::vector points; @@ -8529,10 +8529,10 @@ int SketchObject::getGeometryId(int GeoId, long &id) const namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Sketcher::SketchObjectPython, Sketcher::SketchObject) -template<> const char* Sketcher::SketchObjectPython::getViewProviderName(void) const { +template<> const char* Sketcher::SketchObjectPython::getViewProviderName() const { return "SketcherGui::ViewProviderPython"; } -template<> PyObject* Sketcher::SketchObjectPython::getPyObject(void) { +template<> PyObject* Sketcher::SketchObjectPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new FeaturePythonPyT(this),true); diff --git a/src/Mod/Sketcher/App/SketchObject.h b/src/Mod/Sketcher/App/SketchObject.h index e7ab10c28d..ae802807ee 100644 --- a/src/Mod/Sketcher/App/SketchObject.h +++ b/src/Mod/Sketcher/App/SketchObject.h @@ -57,7 +57,7 @@ class SketcherExport SketchObject : public Part::Part2DObject public: SketchObject(); - ~SketchObject(); + ~SketchObject() override; /// Property /** @@ -76,10 +76,10 @@ public: //@{ short mustExecute() const override; /// recalculate the Feature (if no recompute is needed see also solve() and solverNeedsUpdate boolean) - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "SketcherGui::ViewProviderSketch"; } //@} @@ -185,18 +185,18 @@ public: std::unique_ptr getGeometryFacade(int GeoId) const; /// returns a list of all internal geometries - const std::vector &getInternalGeometry(void) const { return Geometry.getValues(); } + const std::vector &getInternalGeometry() const { return Geometry.getValues(); } /// returns a list of projected external geometries - const std::vector &getExternalGeometry(void) const { return ExternalGeo; } + const std::vector &getExternalGeometry() const { return ExternalGeo; } /// rebuilds external geometry (projection onto the sketch plane) - void rebuildExternalGeometry(void); + void rebuildExternalGeometry(); /// returns the number of external Geometry entities - int getExternalGeometryCount(void) const { return ExternalGeo.size(); } + int getExternalGeometryCount() const { return ExternalGeo.size(); } /// retrieves a vector containing both normal and external Geometry (including the sketch axes) - std::vector getCompleteGeometry(void) const; + std::vector getCompleteGeometry() const; - GeoListFacade getGeoListFacade(void) const; + GeoListFacade getGeoListFacade() const; /// converts a GeoId index into an index of the CompleteGeometry vector int getCompleteGeometryIndex(int GeoId) const; @@ -204,7 +204,7 @@ public: int getGeoIdFromCompleteGeometryIndex(int completeGeometryIndex) const; /// returns non zero if the sketch contains conflicting constraints - int hasConflicts(void) const; + int hasConflicts() const; /** * sets the geometry of sketchObject as the solvedsketch geometry * returns the DoF of such a geometry. @@ -241,7 +241,7 @@ public: /// Make all dimensionals Driving/non-Driving int setDatumsDriving(bool isdriving); /// Move Dimensional constraints at the end of the properties array - int moveDatumsToEnd(void); + int moveDatumsToEnd(); /// set the driving status of this constraint and solve int setVirtualSpace(int ConstrId, bool isinvirtualspace); @@ -354,9 +354,9 @@ public: /// retrieves for a Vertex number the corresponding GeoId and PosId void getGeoVertexIndex(int VertexId, int &GeoId, PointPos &PosId) const; - int getHighestVertexIndex(void) const { return VertexId2GeoId.size() - 1; } // Most recently created - int getHighestCurveIndex(void) const { return Geometry.getSize() - 1; } - void rebuildVertexIndex(void); + int getHighestVertexIndex() const { return VertexId2GeoId.size() - 1; } // Most recently created + int getHighestCurveIndex() const { return Geometry.getSize() - 1; } + void rebuildVertexIndex(); /// retrieves for a GeoId and PosId the Vertex number int getVertexIndexGeoPos(int GeoId, PointPos PosId) const; @@ -397,17 +397,17 @@ public: int port_reversedExternalArcs(bool justAnalyze); // from base class - virtual PyObject *getPyObject(void) override; - virtual unsigned int getMemSize(void) const override; - virtual void Save(Base::Writer &/*writer*/) const override; - virtual void Restore(Base::XMLReader &/*reader*/) override; + PyObject *getPyObject() override; + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; /// returns the number of construction lines (to be used as axes) - virtual int getAxisCount(void) const override; + int getAxisCount() const override; /// retrieves an axis iterating through the construction lines of the sketch (indices start at 0) - virtual Base::Axis getAxis(int axId) const override; + Base::Axis getAxis(int axId) const override; /// verify and accept the assigned geometry - virtual void acceptGeometry() override; + void acceptGeometry() override; /// Check if constraint has invalid indexes bool evaluateConstraint(const Constraint *constraint) const; /// Check for constraints with invalid indexes @@ -415,9 +415,9 @@ public: /// Remove constraints with invalid indexes void validateConstraints(); /// Checks if support is valid - bool evaluateSupport(void); + bool evaluateSupport(); /// validate External Links (remove invalid external links) - void validateExternalLinks(void); + void validateExternalLinks(); /// gets DoF of last solver execution inline int getLastDoF() const {return lastDoF;} @@ -434,17 +434,17 @@ public: /// gets solver SolveTime of last solver execution inline float getLastSolveTime() const {return lastSolveTime;} /// gets the conflicting constraints of the last solver execution - inline const std::vector &getLastConflicting(void) const { return lastConflicting; } + inline const std::vector &getLastConflicting() const { return lastConflicting; } /// gets the redundant constraints of last solver execution - inline const std::vector &getLastRedundant(void) const { return lastRedundant; } + inline const std::vector &getLastRedundant() const { return lastRedundant; } /// gets the redundant constraints of last solver execution - inline const std::vector &getLastPartiallyRedundant(void) const { return lastPartiallyRedundant; } + inline const std::vector &getLastPartiallyRedundant() const { return lastPartiallyRedundant; } /// gets the redundant constraints of last solver execution - inline const std::vector &getLastMalformedConstraints(void) const { return lastMalformedConstraints; } + inline const std::vector &getLastMalformedConstraints() const { return lastMalformedConstraints; } public: /* Solver exposed interface */ /// gets the solved sketch as a reference - inline const Sketch &getSolvedSketch(void) const {return solvedSketch;} + inline const Sketch &getSolvedSketch() const {return solvedSketch;} /// enables/disables solver initial solution recalculation when moving point mode (useful for dragging) inline void setRecalculateInitialSolutionWhileMovingPoint(bool recalculateInitialSolutionWhileMovingPoint) {solvedSketch.setRecalculateInitialSolutionWhileMovingPoint(recalculateInitialSolutionWhileMovingPoint);} @@ -517,10 +517,10 @@ public: int detectMissingVerticalHorizontalConstraints(double angleprecision = M_PI/8); int detectMissingEqualityConstraints(double precision); - std::vector &getMissingPointOnPointConstraints(void); - std::vector &getMissingVerticalHorizontalConstraints(void); - std::vector &getMissingLineEqualityConstraints(void); - std::vector &getMissingRadiusConstraints(void); + std::vector &getMissingPointOnPointConstraints(); + std::vector &getMissingVerticalHorizontalConstraints(); + std::vector &getMissingLineEqualityConstraints(); + std::vector &getMissingRadiusConstraints(); void setMissingRadiusConstraints(std::vector &cl); void setMissingLineEqualityConstraints(std::vector& cl); @@ -538,7 +538,7 @@ public: int renameConstraint(int GeoId, std::string name); // Validation routines - std::vector getOpenVertices(void) const; + std::vector getOpenVertices() const; public: // geometry extension functionalities for single element sketch object user convenience int setGeometryId(int GeoId, long id); @@ -546,11 +546,11 @@ public: // geometry extension functionalities for single element sketch object u protected: /// get called by the container when a property has changed - virtual void onChanged(const App::Property* /*prop*/) override; - virtual void onDocumentRestored() override; - virtual void restoreFinished() override; + void onChanged(const App::Property* /*prop*/) override; + void onDocumentRestored() override; + void restoreFinished() override; - virtual void setExpression(const App::ObjectIdentifier &path, std::shared_ptr expr) override; + void setExpression(const App::ObjectIdentifier &path, std::shared_ptr expr) override; std::string validateExpression(const App::ObjectIdentifier &path, std::shared_ptr expr); @@ -581,10 +581,10 @@ protected: // check whether constraint may be changed driving status int testDrivingChange(int ConstrId, bool isdriving); - virtual void onUndoRedoFinished() override; + void onUndoRedoFinished() override; // migration functions - void migrateSketch(void); + void migrateSketch(); static void appendConstraintsMsg(const std::vector &vector, const std::string & singularmsg, diff --git a/src/Mod/Sketcher/App/SketchObjectPyImp.cpp b/src/Mod/Sketcher/App/SketchObjectPyImp.cpp index 1c7fbc97e1..aa841dde63 100644 --- a/src/Mod/Sketcher/App/SketchObjectPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchObjectPyImp.cpp @@ -51,7 +51,7 @@ using namespace Sketcher; // returns a string which represents the object e.g. when printed in python -std::string SketchObjectPy::representation(void) const +std::string SketchObjectPy::representation() const { return ""; } @@ -1682,7 +1682,7 @@ PyObject* SketchObjectPy::autoRemoveRedundants(PyObject *args) Py_Return; } -Py::List SketchObjectPy::getMissingPointOnPointConstraints(void) const +Py::List SketchObjectPy::getMissingPointOnPointConstraints() const { std::vector constraints = this->getSketchObjectPtr()->getMissingPointOnPointConstraints(); @@ -1708,7 +1708,7 @@ void SketchObjectPy::setMissingPointOnPointConstraints(Py::List arg) return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); }; - for (auto ti : arg) { + for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = (long)Py::Long(t.getItem(0)); @@ -1723,7 +1723,7 @@ void SketchObjectPy::setMissingPointOnPointConstraints(Py::List arg) this->getSketchObjectPtr()->setMissingPointOnPointConstraints(constraints); } -Py::List SketchObjectPy::getMissingVerticalHorizontalConstraints(void) const +Py::List SketchObjectPy::getMissingVerticalHorizontalConstraints() const { std::vector constraints = this->getSketchObjectPtr()->getMissingVerticalHorizontalConstraints(); @@ -1749,7 +1749,7 @@ void SketchObjectPy::setMissingVerticalHorizontalConstraints(Py::List arg) return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); }; - for (auto ti : arg) { + for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = (long)Py::Long(t.getItem(0)); @@ -1764,7 +1764,7 @@ void SketchObjectPy::setMissingVerticalHorizontalConstraints(Py::List arg) this->getSketchObjectPtr()->setMissingVerticalHorizontalConstraints(constraints); } -Py::List SketchObjectPy::getMissingLineEqualityConstraints(void) const +Py::List SketchObjectPy::getMissingLineEqualityConstraints() const { std::vector constraints = this->getSketchObjectPtr()->getMissingLineEqualityConstraints(); @@ -1789,7 +1789,7 @@ void SketchObjectPy::setMissingLineEqualityConstraints(Py::List arg) return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); }; - for (auto ti : arg) { + for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = (long)Py::Long(t.getItem(0)); @@ -1804,7 +1804,7 @@ void SketchObjectPy::setMissingLineEqualityConstraints(Py::List arg) this->getSketchObjectPtr()->setMissingLineEqualityConstraints(constraints); } -Py::List SketchObjectPy::getMissingRadiusConstraints(void) const +Py::List SketchObjectPy::getMissingRadiusConstraints() const { std::vector constraints = this->getSketchObjectPtr()->getMissingRadiusConstraints(); @@ -1829,7 +1829,7 @@ void SketchObjectPy::setMissingRadiusConstraints(Py::List arg) return (checkitem(t,i,0)?Sketcher::PointPos::none:(checkitem(t,i,1)?Sketcher::PointPos::start:(checkitem(t,i,2)?Sketcher::PointPos::end:Sketcher::PointPos::mid))); }; - for (auto ti : arg) { + for (const auto& ti : arg) { Py::Tuple t(ti); ConstraintIds c; c.First = (long)Py::Long(t.getItem(0)); @@ -1863,7 +1863,7 @@ PyObject* SketchObjectPy::getGeometryWithDependentParameters(PyObject *args) return Py::new_reference_to(list); } -Py::List SketchObjectPy::getOpenVertices(void) const +Py::List SketchObjectPy::getOpenVertices() const { std::vector points = this->getSketchObjectPtr()->getOpenVertices(); @@ -1878,23 +1878,23 @@ Py::List SketchObjectPy::getOpenVertices(void) const return list; } -Py::Long SketchObjectPy::getConstraintCount(void) const +Py::Long SketchObjectPy::getConstraintCount() const { return Py::Long(this->getSketchObjectPtr()->Constraints.getSize()); } -Py::Long SketchObjectPy::getGeometryCount(void) const +Py::Long SketchObjectPy::getGeometryCount() const { return Py::Long(this->getSketchObjectPtr()->Geometry.getSize()); } -Py::Long SketchObjectPy::getAxisCount(void) const +Py::Long SketchObjectPy::getAxisCount() const { return Py::Long(this->getSketchObjectPtr()->getAxisCount()); } -Py::List SketchObjectPy::getGeometryFacadeList(void) const +Py::List SketchObjectPy::getGeometryFacadeList() const { Py::List list; diff --git a/src/Mod/Sketcher/App/SketchObjectSF.cpp b/src/Mod/Sketcher/App/SketchObjectSF.cpp index 62cda0f236..5356c1334b 100644 --- a/src/Mod/Sketcher/App/SketchObjectSF.cpp +++ b/src/Mod/Sketcher/App/SketchObjectSF.cpp @@ -50,7 +50,7 @@ short SketchObjectSF::mustExecute() const return 0; } -App::DocumentObjectExecReturn *SketchObjectSF::execute(void) +App::DocumentObjectExecReturn *SketchObjectSF::execute() { 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/SketchObjectSF.h b/src/Mod/Sketcher/App/SketchObjectSF.h index f2eb6b4b92..a25fbc1ff5 100644 --- a/src/Mod/Sketcher/App/SketchObjectSF.h +++ b/src/Mod/Sketcher/App/SketchObjectSF.h @@ -37,7 +37,7 @@ namespace Sketcher class SketchObjectSF :public Part::Part2DObject { - PROPERTY_HEADER(Sketcher::SketchObjectSF); + PROPERTY_HEADER_WITH_OVERRIDE(Sketcher::SketchObjectSF); public: SketchObjectSF(); @@ -48,8 +48,8 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// Uses the standard ViewProvider //const char* getViewProviderName(void) const { // return "SketcherGui::ViewProviderSketchSF"; diff --git a/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp b/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp index 0e29918fe9..18a0d89b6c 100644 --- a/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchObjectSFPyImp.cpp @@ -31,7 +31,7 @@ using namespace Sketcher; // returns a string which represents the object e.g. when printed in python -std::string SketchObjectSFPy::representation(void) const +std::string SketchObjectSFPy::representation() const { return ""; } diff --git a/src/Mod/Sketcher/App/SketchPyImp.cpp b/src/Mod/Sketcher/App/SketchPyImp.cpp index 52f5455490..a00ea2669b 100644 --- a/src/Mod/Sketcher/App/SketchPyImp.cpp +++ b/src/Mod/Sketcher/App/SketchPyImp.cpp @@ -41,7 +41,7 @@ using namespace Sketcher; using namespace Part; // returns a string which represents the object e.g. when printed in python -std::string SketchPy::representation(void) const +std::string SketchPy::representation() const { return std::string(""); } @@ -165,13 +165,13 @@ PyObject* SketchPy::movePoint(PyObject *args) // +++ attributes implementer ++++++++++++++++++++++++++++++++++++++++++++++++ -Py::Long SketchPy::getConstraint(void) const +Py::Long SketchPy::getConstraint() const { //return Py::Int(); throw Py::AttributeError("Not yet implemented"); } -Py::Tuple SketchPy::getConflicts(void) const +Py::Tuple SketchPy::getConflicts() const { std::vector c = getSketchPtr()->getConflicting(); Py::Tuple t(c.size()); @@ -182,7 +182,7 @@ Py::Tuple SketchPy::getConflicts(void) const return t; } -Py::Tuple SketchPy::getRedundancies(void) const +Py::Tuple SketchPy::getRedundancies() const { std::vector c = getSketchPtr()->getRedundant(); Py::Tuple t(c.size()); @@ -193,12 +193,12 @@ Py::Tuple SketchPy::getRedundancies(void) const return t; } -Py::Tuple SketchPy::getGeometries(void) const +Py::Tuple SketchPy::getGeometries() const { return getSketchPtr()->getPyGeometry(); } -Py::Object SketchPy::getShape(void) const +Py::Object SketchPy::getShape() const { return Py::asObject(new TopoShapePy(new TopoShape(getSketchPtr()->toShape()))); } diff --git a/src/Mod/Sketcher/App/SolverGeometryExtension.cpp b/src/Mod/Sketcher/App/SolverGeometryExtension.cpp index 83c90b737b..8d79c6ccea 100644 --- a/src/Mod/Sketcher/App/SolverGeometryExtension.cpp +++ b/src/Mod/Sketcher/App/SolverGeometryExtension.cpp @@ -51,7 +51,7 @@ void SolverGeometryExtension::copyAttributes(Part::GeometryExtension * cpy) cons static_cast(cpy)->Mid = this->Mid; } -std::unique_ptr SolverGeometryExtension::copy(void) const +std::unique_ptr SolverGeometryExtension::copy() const { auto cpy = std::make_unique(); @@ -64,7 +64,7 @@ std::unique_ptr SolverGeometryExtension::copy(void) con #endif } -PyObject * SolverGeometryExtension::getPyObject(void) +PyObject * SolverGeometryExtension::getPyObject() { THROWM(Base::NotImplementedError, "SolverGeometryExtension does not have a Python counterpart"); } diff --git a/src/Mod/Sketcher/App/SolverGeometryExtension.h b/src/Mod/Sketcher/App/SolverGeometryExtension.h index d893616294..ddd6728a94 100644 --- a/src/Mod/Sketcher/App/SolverGeometryExtension.h +++ b/src/Mod/Sketcher/App/SolverGeometryExtension.h @@ -51,7 +51,7 @@ public: class PointParameterStatus { public: - PointParameterStatus(ParameterStatus status) {setStatus(status);} + explicit PointParameterStatus(ParameterStatus status) {setStatus(status);} PointParameterStatus(ParameterStatus statusx, ParameterStatus statusy) {setStatus(statusx, statusy);} PointParameterStatus(const PointParameterStatus &) = default; @@ -234,13 +234,13 @@ public: SolverGeometryExtension(); - virtual ~SolverGeometryExtension() override = default; + ~SolverGeometryExtension() override = default; - virtual std::unique_ptr copy(void) const override; + std::unique_ptr copy() const override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - virtual void notifyAttachment(Part::Geometry * geo) override; + void notifyAttachment(Part::Geometry * geo) override; SolverStatus getGeometry() const {return ( Edge.getStatus() == Independent && Start.getStatus() == Independent && @@ -290,7 +290,7 @@ public: } protected: - virtual void copyAttributes(Part::GeometryExtension * cpy) const override; + void copyAttributes(Part::GeometryExtension * cpy) const override; private: SolverGeometryExtension(const SolverGeometryExtension&) = default; diff --git a/src/Mod/Sketcher/App/planegcs/Constraints.h b/src/Mod/Sketcher/App/planegcs/Constraints.h index 3e07d03d00..414a902f55 100644 --- a/src/Mod/Sketcher/App/planegcs/Constraints.h +++ b/src/Mod/Sketcher/App/planegcs/Constraints.h @@ -137,10 +137,10 @@ namespace GCS inline double* param2() { return pvec[1]; } public: ConstraintEqual(double *p1, double *p2, double p1p2ratio=1.0); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // Difference @@ -152,10 +152,10 @@ namespace GCS inline double* difference() { return pvec[2]; } public: ConstraintDifference(double *p1, double *p2, double *d); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // P2PDistance @@ -172,11 +172,11 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintP2PDistance(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); - virtual double maxStep(MAP_pD_D &dir, double lim=1.); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; + double maxStep(MAP_pD_D &dir, double lim=1.) override; }; // P2PAngle @@ -194,11 +194,11 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintP2PAngle(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); - virtual double maxStep(MAP_pD_D &dir, double lim=1.); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; + double maxStep(MAP_pD_D &dir, double lim=1.) override; }; // P2LDistance @@ -217,11 +217,11 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintP2LDistance(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); - virtual double maxStep(MAP_pD_D &dir, double lim=1.); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; + double maxStep(MAP_pD_D &dir, double lim=1.) override; double abs(double darea); }; @@ -241,10 +241,10 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintPointOnLine(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // PointOnPerpBisector @@ -264,11 +264,11 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintPointOnPerpBisector(){}; #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; - virtual double error(); - virtual double grad(double *); + double error() override; + double grad(double *) override; }; // Parallel @@ -288,10 +288,10 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintParallel(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // Perpendicular @@ -312,10 +312,10 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintPerpendicular(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // L2LAngle @@ -338,11 +338,11 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintL2LAngle(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); - virtual double maxStep(MAP_pD_D &dir, double lim=1.); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; + double maxStep(MAP_pD_D &dir, double lim=1.) override; }; // MidpointOnLine @@ -363,10 +363,10 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintMidpointOnLine(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // TangentCircumf @@ -387,10 +387,10 @@ namespace GCS inline ConstraintTangentCircumf(bool internal_){internal=internal_;} #endif inline bool getInternal() {return internal;}; - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // PointOnEllipse class ConstraintPointOnEllipse : public Constraint @@ -409,10 +409,10 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintPointOnEllipse(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintEllipseTangentLine : public Constraint @@ -424,20 +424,20 @@ namespace GCS void errorgrad(double* err, double* grad, double *param); //error and gradient combined. Values are returned through pointers. public: ConstraintEllipseTangentLine(Line &l, Ellipse &e); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintInternalAlignmentPoint2Ellipse : public Constraint { public: ConstraintInternalAlignmentPoint2Ellipse(Ellipse &e, Point &p1, InternalAlignmentType alignmentType); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; private: void errorgrad(double* err, double* grad, double *param); //error and gradient combined. Values are returned through pointers. void ReconstructGeomPointers(); //writes pointers in pvec to the parameters of crv1, crv2 and poa @@ -450,10 +450,10 @@ namespace GCS { public: ConstraintInternalAlignmentPoint2Hyperbola(Hyperbola &e, Point &p1, InternalAlignmentType alignmentType); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; private: void errorgrad(double* err, double* grad, double *param); //error and gradient combined. Values are returned through pointers. void ReconstructGeomPointers(); //writes pointers in pvec to the parameters of crv1, crv2 and poa @@ -471,10 +471,10 @@ namespace GCS void errorgrad(double* err, double* grad, double *param); //error and gradient combined. Values are returned through pointers. public: ConstraintEqualMajorAxesConic(MajorRadiusConic * a1, MajorRadiusConic * a2); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintEqualFocalDistance : public Constraint @@ -486,10 +486,10 @@ namespace GCS void errorgrad(double* err, double* grad, double *param); //error and gradient combined. Values are returned through pointers. public: ConstraintEqualFocalDistance(ArcOfParabola * a1, ArcOfParabola * a2); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintCurveValue : public Constraint @@ -510,12 +510,12 @@ namespace GCS * @param u : pointer to u parameter corresponding to the point */ ConstraintCurveValue(Point &p, double* pcoord, Curve& crv, double* u); - ~ConstraintCurveValue(); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); - virtual double maxStep(MAP_pD_D &dir, double lim=1.); + ~ConstraintCurveValue() override; + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; + double maxStep(MAP_pD_D &dir, double lim=1.) override; }; // PointOnHyperbola @@ -535,10 +535,10 @@ namespace GCS #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintPointOnHyperbola(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; // PointOnParabola @@ -552,14 +552,14 @@ namespace GCS public: ConstraintPointOnParabola(Point &p, Parabola &e); ConstraintPointOnParabola(Point &p, ArcOfParabola &a); - ~ConstraintPointOnParabola(); + ~ConstraintPointOnParabola() override; #ifdef _GCS_EXTRACT_SOLVER_SUBSYSTEM_ inline ConstraintPointOnParabola(){} #endif - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintAngleViaPoint : public Constraint @@ -580,11 +580,11 @@ namespace GCS void ReconstructGeomPointers(); //writes pointers in pvec to the parameters of crv1, crv2 and poa public: ConstraintAngleViaPoint(Curve &acrv1, Curve &acrv2, Point p, double* angle); - ~ConstraintAngleViaPoint(); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ~ConstraintAngleViaPoint() override; + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintSnell : public Constraint //snell's law angles constrainer. Point needs to lie on all three curves to be constraied. @@ -610,11 +610,11 @@ namespace GCS public: //n1dn2 = n1 divided by n2. from n1 to n2. flipn1 = true instructs to flip ray1's tangent ConstraintSnell(Curve &ray1, Curve &ray2, Curve &boundary, Point p, double* n1, double* n2, bool flipn1, bool flipn2); - ~ConstraintSnell(); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ~ConstraintSnell() override; + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; class ConstraintEqualLineLength : public Constraint @@ -626,10 +626,10 @@ namespace GCS void errorgrad(double* err, double* grad, double *param); //error and gradient combined. Values are returned through pointers. public: ConstraintEqualLineLength(Line &l1, Line &l2); - virtual ConstraintType getTypeId(); - virtual void rescale(double coef=1.); - virtual double error(); - virtual double grad(double *); + ConstraintType getTypeId() override; + void rescale(double coef=1.) override; + double error() override; + double grad(double *) override; }; diff --git a/src/Mod/Sketcher/App/planegcs/GCS.cpp b/src/Mod/Sketcher/App/planegcs/GCS.cpp index 3b6bf45ec7..9ff9d4f6a8 100644 --- a/src/Mod/Sketcher/App/planegcs/GCS.cpp +++ b/src/Mod/Sketcher/App/planegcs/GCS.cpp @@ -357,7 +357,7 @@ void SolverReportingManager::LogGroupOfConstraints(const std::string & str, std: tempstream << str << ":" << '\n'; - for(auto group : constraintgroups) { + for(const auto& group : constraintgroups) { tempstream << "["; for(auto c :group) @@ -1429,7 +1429,7 @@ void System::initSolution(Algorithm alg) return; } std::vector clistR; - if (redundant.size()) { + if (!redundant.empty()) { for (std::vector::const_iterator constr=clist.begin(); constr != clist.end(); ++constr) { if (redundant.count(*constr) == 0) clistR.push_back(*constr); @@ -1523,9 +1523,9 @@ void System::initSolution(Algorithm alg) subSystems.push_back(nullptr); subSystemsAux.push_back(nullptr); - if (clist0.size() > 0) + if (!clist0.empty()) subSystems[cid] = new SubSystem(clist0, plists[cid], reductionmaps[cid]); - if (clist1.size() > 0) + if (!clist1.empty()) subSystemsAux[cid] = new SubSystem(clist1, plists[cid], reductionmaps[cid]); } diff --git a/src/Mod/Sketcher/App/planegcs/Geo.h b/src/Mod/Sketcher/App/planegcs/Geo.h index a3a8915285..8324aa76be 100644 --- a/src/Mod/Sketcher/App/planegcs/Geo.h +++ b/src/Mod/Sketcher/App/planegcs/Geo.h @@ -123,50 +123,50 @@ namespace GCS { public: Line(){} - virtual ~Line(){} + ~Line() override{} Point p1; Point p2; DeriVector2 CalculateNormal(const Point &p, const double* derivparam = nullptr) const override; DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual Line* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + Line* Copy() override; }; class Circle: public Curve { public: Circle(){rad = nullptr;} - virtual ~Circle(){} + ~Circle() override{} Point center; double *rad; DeriVector2 CalculateNormal(const Point &p, const double* derivparam = nullptr) const override; DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual Circle* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + Circle* Copy() override; }; class Arc: public Circle { public: Arc(){startAngle=nullptr;endAngle=nullptr;rad=nullptr;} - virtual ~Arc(){} + ~Arc() override{} double *startAngle; double *endAngle; //double *rad; //inherited Point start; Point end; //Point center; //inherited - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual Arc* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + Arc* Copy() override; }; class MajorRadiusConic: public Curve { public: - virtual ~MajorRadiusConic(){} + ~MajorRadiusConic() override{} virtual double getRadMaj(const DeriVector2 ¢er, const DeriVector2 &f1, double b, double db, double &ret_dRadMaj) const = 0; virtual double getRadMaj(double* derivparam, double &ret_dRadMaj) const = 0; virtual double getRadMaj() const = 0; @@ -177,25 +177,25 @@ namespace GCS { public: Ellipse(){ radmin = nullptr;} - virtual ~Ellipse(){} + ~Ellipse() override{} Point center; Point focus1; double *radmin; - virtual double getRadMaj(const DeriVector2 ¢er, const DeriVector2 &f1, double b, double db, double &ret_dRadMaj) const override; - virtual double getRadMaj(double* derivparam, double &ret_dRadMaj) const override; - virtual double getRadMaj() const override; + double getRadMaj(const DeriVector2 ¢er, const DeriVector2 &f1, double b, double db, double &ret_dRadMaj) const override; + double getRadMaj(double* derivparam, double &ret_dRadMaj) const override; + double getRadMaj() const override; DeriVector2 CalculateNormal(const Point &p, const double* derivparam = nullptr) const override; DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual Ellipse* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + Ellipse* Copy() override; }; class ArcOfEllipse: public Ellipse { public: ArcOfEllipse(){startAngle=nullptr;endAngle=nullptr;radmin = nullptr;} - virtual ~ArcOfEllipse(){} + ~ArcOfEllipse() override{} double *startAngle; double *endAngle; //double *radmin; //inherited @@ -204,80 +204,80 @@ namespace GCS //Point center; //inherited //double *focus1.x; //inherited //double *focus1.y; //inherited - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual ArcOfEllipse* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + ArcOfEllipse* Copy() override; }; class Hyperbola: public MajorRadiusConic { public: Hyperbola(){ radmin = nullptr;} - virtual ~Hyperbola(){} + ~Hyperbola() override{} Point center; Point focus1; double *radmin; - virtual double getRadMaj(const DeriVector2 ¢er, const DeriVector2 &f1, double b, double db, double &ret_dRadMaj) const override; - virtual double getRadMaj(double* derivparam, double &ret_dRadMaj) const override; - virtual double getRadMaj() const override; + double getRadMaj(const DeriVector2 ¢er, const DeriVector2 &f1, double b, double db, double &ret_dRadMaj) const override; + double getRadMaj(double* derivparam, double &ret_dRadMaj) const override; + double getRadMaj() const override; DeriVector2 CalculateNormal(const Point &p, const double* derivparam = nullptr) const override; - virtual DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual Hyperbola* Copy() override; + DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + Hyperbola* Copy() override; }; class ArcOfHyperbola: public Hyperbola { public: ArcOfHyperbola(){startAngle=nullptr;endAngle=nullptr;radmin = nullptr;} - virtual ~ArcOfHyperbola(){} + ~ArcOfHyperbola() override{} // parameters double *startAngle; double *endAngle; Point start; Point end; // interface helpers - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual ArcOfHyperbola* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + ArcOfHyperbola* Copy() override; }; class Parabola: public Curve { public: Parabola(){ } - virtual ~Parabola(){} + ~Parabola() override{} Point vertex; Point focus1; DeriVector2 CalculateNormal(const Point &p, const double* derivparam = nullptr) const override; - virtual DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual Parabola* Copy() override; + DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + Parabola* Copy() override; }; class ArcOfParabola: public Parabola { public: ArcOfParabola(){startAngle=nullptr;endAngle=nullptr;} - virtual ~ArcOfParabola(){} + ~ArcOfParabola() override{} // parameters double *startAngle; double *endAngle; Point start; Point end; // interface helpers - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual ArcOfParabola* Copy() override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + ArcOfParabola* Copy() override; }; class BSpline: public Curve { public: BSpline(){periodic=false;degree=2;} - virtual ~BSpline(){} + ~BSpline() override{} // parameters VEC_P poles; VEC_pD weights; @@ -294,10 +294,10 @@ namespace GCS VEC_I knotpointGeoids; // geoids of knotpoints as to index Geom array // interface helpers DeriVector2 CalculateNormal(const Point &p, const double* derivparam = nullptr) const override; - virtual DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; - virtual int PushOwnParams(VEC_pD &pvec) override; - virtual void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; - virtual BSpline* Copy() override; + DeriVector2 Value(double u, double du, const double* derivparam = nullptr) const override; + int PushOwnParams(VEC_pD &pvec) override; + void ReconstructOnNewPvec (VEC_pD &pvec, int &cnt) override; + BSpline* Copy() override; }; } //namespace GCS diff --git a/src/Mod/Sketcher/App/planegcs/SubSystem.cpp b/src/Mod/Sketcher/App/planegcs/SubSystem.cpp index 39c84a7874..270f2168f9 100644 --- a/src/Mod/Sketcher/App/planegcs/SubSystem.cpp +++ b/src/Mod/Sketcher/App/planegcs/SubSystem.cpp @@ -68,7 +68,7 @@ void SubSystem::initialize(VEC_pD ¶ms, MAP_pD_pD &reductionmap) plist.clear(); MAP_pD_I rindex; - if (reductionmap.size() > 0) { + if (!reductionmap.empty()) { int i=0; MAP_pD_I pindex; for (VEC_pD::const_iterator itt=tmpplist.begin(); diff --git a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp index d7d6104f1f..e5afafc317 100644 --- a/src/Mod/Sketcher/Gui/AppSketcherGui.cpp +++ b/src/Mod/Sketcher/Gui/AppSketcherGui.cpp @@ -43,13 +43,13 @@ // create the commands -void CreateSketcherCommands(void); -void CreateSketcherCommandsCreateGeo(void); -void CreateSketcherCommandsConstraints(void); -void CreateSketcherCommandsConstraintAccel(void); -void CreateSketcherCommandsAlterGeo(void); -void CreateSketcherCommandsBSpline(void); -void CreateSketcherCommandsVirtualSpace(void); +void CreateSketcherCommands(); +void CreateSketcherCommandsCreateGeo(); +void CreateSketcherCommandsConstraints(); +void CreateSketcherCommandsConstraintAccel(); +void CreateSketcherCommandsAlterGeo(); +void CreateSketcherCommandsBSpline(); +void CreateSketcherCommandsVirtualSpace(); void loadSketcherResource() { @@ -68,7 +68,7 @@ public: initialize("This module is the SketcherGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Sketcher/Gui/CMakeLists.txt b/src/Mod/Sketcher/Gui/CMakeLists.txt index 820218dfd9..056ae1492f 100644 --- a/src/Mod/Sketcher/Gui/CMakeLists.txt +++ b/src/Mod/Sketcher/Gui/CMakeLists.txt @@ -14,6 +14,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ${EIGEN3_INCLUDE_DIR} ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Sketcher/Gui/Command.cpp b/src/Mod/Sketcher/Gui/Command.cpp index 69ff5b6128..e4fe78854d 100644 --- a/src/Mod/Sketcher/Gui/Command.cpp +++ b/src/Mod/Sketcher/Gui/Command.cpp @@ -71,12 +71,12 @@ namespace SketcherGui { } //Pass untranslated strings, enclosed in QT_TR_NOOP() - ExceptionWrongInput(const char* ErrMsg){ + explicit ExceptionWrongInput(const char* ErrMsg){ this->ErrMsg = QObject::tr( ErrMsg ); this->setMessage(ErrMsg); } - virtual ~ExceptionWrongInput() throw() {} + ~ExceptionWrongInput() throw() override {} QString ErrMsg; }; @@ -87,11 +87,11 @@ namespace SketcherGui { std::vector* allmodes = nullptr){ //convert pointers into valid references, to avoid checking for null pointers everywhere Attacher::SuggestResult::eSuggestResult buf; - if (pMsgId == nullptr) + if (!pMsgId) pMsgId = &buf; Attacher::SuggestResult::eSuggestResult &msg = *pMsgId; QString buf2; - if (message == nullptr) + if (!message) message = &buf2; QString &msg_str = *message; @@ -250,7 +250,7 @@ void CmdSketcherNewSketch::activated(int iMsg) } -bool CmdSketcherNewSketch::isActive(void) +bool CmdSketcherNewSketch::isActive() { if (getActiveGuiDocument()) return true; @@ -283,7 +283,7 @@ void CmdSketcherEditSketch::activated(int iMsg) } } -bool CmdSketcherEditSketch::isActive(void) +bool CmdSketcherEditSketch::isActive() { return Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) == 1; } @@ -320,7 +320,7 @@ void CmdSketcherLeaveSketch::activated(int iMsg) doCommand(Doc,"App.ActiveDocument.recompute()"); } -bool CmdSketcherLeaveSketch::isActive(void) +bool CmdSketcherLeaveSketch::isActive() { Gui::Document *doc = getActiveGuiDocument(); if (doc) { @@ -362,7 +362,7 @@ void CmdSketcherStopOperation::activated(int iMsg) } } -bool CmdSketcherStopOperation::isActive(void) +bool CmdSketcherStopOperation::isActive() { Gui::Document *doc = getActiveGuiDocument(); if (doc) { @@ -495,7 +495,7 @@ void CmdSketcherReorientSketch::activated(int iMsg) doCommand(Gui,"Gui.ActiveDocument.setEdit('%s')", sketch->getNameInDocument()); } -bool CmdSketcherReorientSketch::isActive(void) +bool CmdSketcherReorientSketch::isActive() { return Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) == 1; } @@ -664,7 +664,7 @@ void CmdSketcherMapSketch::activated(int iMsg) } } -bool CmdSketcherMapSketch::isActive(void) +bool CmdSketcherMapSketch::isActive() { App::Document* doc = App::GetApplication().getActiveDocument(); Base::Type sketch_type = Base::Type::fromName("Sketcher::SketchObject"); @@ -703,7 +703,7 @@ void CmdSketcherViewSketch::activated(int iMsg) } } -bool CmdSketcherViewSketch::isActive(void) +bool CmdSketcherViewSketch::isActive() { Gui::Document *doc = getActiveGuiDocument(); if (doc) { @@ -746,7 +746,7 @@ void CmdSketcherValidateSketch::activated(int iMsg) Gui::Control().showDialog(new TaskSketcherValidation(Obj)); } -bool CmdSketcherValidateSketch::isActive(void) +bool CmdSketcherValidateSketch::isActive() { if (Gui::Control().activeDialog()) return false; @@ -774,7 +774,7 @@ void CmdSketcherMirrorSketch::activated(int iMsg) { Q_UNUSED(iMsg); std::vector selection = getSelection().getSelectionEx(nullptr, Sketcher::SketchObject::getClassTypeId()); - if (selection.size() < 1) { + if (selection.empty()) { QMessageBox::warning(Gui::getMainWindow(), qApp->translate("CmdSketcherMirrorSketch", "Wrong selection"), qApp->translate("CmdSketcherMirrorSketch", "Select one or more sketches.")); @@ -855,7 +855,7 @@ void CmdSketcherMirrorSketch::activated(int iMsg) doCommand(Gui,"App.activeDocument().recompute()"); } -bool CmdSketcherMirrorSketch::isActive(void) +bool CmdSketcherMirrorSketch::isActive() { return Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 0; } @@ -936,7 +936,7 @@ void CmdSketcherMergeSketches::activated(int iMsg) doCommand(Doc, "App.activeDocument().recompute()"); } -bool CmdSketcherMergeSketches::isActive(void) +bool CmdSketcherMergeSketches::isActive() { return Gui::Selection().countObjectsOfType(Sketcher::SketchObject::getClassTypeId()) > 1; } @@ -967,7 +967,7 @@ void CmdSketcherViewSection::activated(int iMsg) doCommand(Doc,"ActiveSketch.ViewObject.TempoVis.sketchClipPlane(ActiveSketch)"); } -bool CmdSketcherViewSection::isActive(void) +bool CmdSketcherViewSection::isActive() { Gui::Document *doc = getActiveGuiDocument(); if (doc) { @@ -979,7 +979,7 @@ bool CmdSketcherViewSection::isActive(void) return false; } -void CreateSketcherCommands(void) +void CreateSketcherCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp b/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp index 44681cf8e7..8d1bd371ac 100644 --- a/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp +++ b/src/Mod/Sketcher/Gui/CommandAlterGeometry.cpp @@ -83,13 +83,34 @@ CmdSketcherToggleConstruction::CmdSketcherToggleConstruction() // list of toggle construction commands Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateLine"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateRectangle"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateRectangle_Center"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateOblong"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CompCreateRectangles"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreatePolyline"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateSlot"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateArc"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_Create3PointArc"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CompCreateArc"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateEllipseByCenter"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateEllipseBy3Points"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateArcOfEllipse"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateArcOfHyperbola"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateArcOfParabola"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CompCreateConic"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateCircle"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_Create3PointCircle"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CompCreateCircle"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateTriangle"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateSquare"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreatePentagon"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateHexagon"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateHeptagon"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateOctagon"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateRegularPolygon"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CompCreateRegularPolygon"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreateBSpline"); + rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CreatePeriodicBSpline"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CompCreateBSpline"); rcCmdMgr.addCommandMode("ToggleConstruction", "Sketcher_CarbonCopy"); } @@ -171,14 +192,14 @@ void CmdSketcherToggleConstruction::activated(int iMsg) } } -bool CmdSketcherToggleConstruction::isActive(void) +bool CmdSketcherToggleConstruction::isActive() { return isAlterGeoActive( getActiveGuiDocument() ); } } -void CreateSketcherCommandsAlterGeo(void) +void CreateSketcherCommandsAlterGeo() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/CommandConstraints.cpp b/src/Mod/Sketcher/Gui/CommandConstraints.cpp index 5a00829c75..3abd55408c 100644 --- a/src/Mod/Sketcher/Gui/CommandConstraints.cpp +++ b/src/Mod/Sketcher/Gui/CommandConstraints.cpp @@ -503,7 +503,7 @@ struct SketchSelection{ Circle, Arc }; - int setUp(void); + int setUp(); struct SketchSelectionItem { GeoType type; int GeoId; @@ -513,7 +513,7 @@ struct SketchSelection{ QString ErrorMsg; }; -int SketchSelection::setUp(void) +int SketchSelection::setUp() { std::vector selection = Gui::Selection().getSelectionEx(); @@ -600,12 +600,12 @@ namespace SketcherGui { { App::DocumentObject* object; public: - GenericConstraintSelection(App::DocumentObject* obj) + explicit GenericConstraintSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()) , object(obj), allowedSelTypes(0) {} - bool allow(App::Document *, App::DocumentObject *pObj, const char *sSubName) + bool allow(App::Document *, App::DocumentObject *pObj, const char *sSubName) override { if (pObj != this->object) return false; @@ -641,12 +641,12 @@ class CmdSketcherConstraint : public Gui::Command { friend class DrawSketchHandlerGenConstraint; public: - CmdSketcherConstraint(const char* name) + explicit CmdSketcherConstraint(const char* name) : Command(name) {} - virtual ~CmdSketcherConstraint(){} + ~CmdSketcherConstraint() override{} - virtual const char* className() const + const char* className() const override { return "CmdSketcherConstraint"; } protected: @@ -667,29 +667,29 @@ protected: std::vector > allowedSelSequences; virtual void applyConstraint(std::vector &, int) {} - virtual void activated(int /*iMsg*/); - virtual bool isActive(void) + void activated(int /*iMsg*/) override; + bool isActive() override { return isCommandActive(getActiveGuiDocument()); } }; class DrawSketchHandlerGenConstraint: public DrawSketchHandler { public: - DrawSketchHandlerGenConstraint(CmdSketcherConstraint *_cmd) + explicit DrawSketchHandlerGenConstraint(CmdSketcherConstraint *_cmd) : cmd(_cmd), seqIndex(0) {} - virtual ~DrawSketchHandlerGenConstraint() + ~DrawSketchHandlerGenConstraint() override { Gui::Selection().rmvSelectionGate(); } - virtual void mouseMove(Base::Vector2d /*onSketchPos*/) override {} + void mouseMove(Base::Vector2d /*onSketchPos*/) override {} - virtual bool pressButton(Base::Vector2d /*onSketchPos*/) override + bool pressButton(Base::Vector2d /*onSketchPos*/) override { return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { SelIdPair selIdPair; selIdPair.GeoId = GeoEnum::GeoUndef; @@ -780,7 +780,7 @@ public: } private: - virtual void activated() override + void activated() override { selFilterGate = new GenericConstraintSelection(sketchgui->getObject()); @@ -862,12 +862,12 @@ class CmdSketcherConstrainHorizontal : public CmdSketcherConstraint { public: CmdSketcherConstrainHorizontal(); - virtual ~CmdSketcherConstrainHorizontal(){} - virtual const char* className() const + ~CmdSketcherConstrainHorizontal() override{} + const char* className() const override { return "CmdSketcherConstrainHorizontal"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; @@ -1100,12 +1100,12 @@ class CmdSketcherConstrainVertical : public CmdSketcherConstraint { public: CmdSketcherConstrainVertical(); - virtual ~CmdSketcherConstrainVertical(){} - virtual const char* className() const + ~CmdSketcherConstrainVertical() override{} + const char* className() const override { return "CmdSketcherConstrainVertical"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; @@ -1334,13 +1334,13 @@ class CmdSketcherConstrainLock : public CmdSketcherConstraint { public: CmdSketcherConstrainLock(); - virtual ~CmdSketcherConstrainLock(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainLock() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainLock"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainLock::CmdSketcherConstrainLock() @@ -1561,12 +1561,12 @@ class CmdSketcherConstrainBlock : public CmdSketcherConstraint { public: CmdSketcherConstrainBlock(); - virtual ~CmdSketcherConstrainBlock(){} - virtual const char* className() const + ~CmdSketcherConstrainBlock() override{} + const char* className() const override { return "CmdSketcherConstrainBlock"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainBlock::CmdSketcherConstrainBlock() @@ -1779,20 +1779,20 @@ public: GeoId1 = GeoId2 = GeoEnum::GeoUndef; PosId1 = PosId2 = Sketcher::PointPos::none; } - virtual ~DrawSketchHandlerCoincident() + ~DrawSketchHandlerCoincident() override { Gui::Selection().rmvSelectionGate(); } - virtual void mouseMove(Base::Vector2d onSketchPos) override {Q_UNUSED(onSketchPos);} + void mouseMove(Base::Vector2d onSketchPos) override {Q_UNUSED(onSketchPos);} - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { int VtId = getPreselectPoint(); int CrsId = getPreselectCross(); @@ -1853,7 +1853,7 @@ public: return true; } private: - virtual void activated() override + void activated() override { Gui::Selection().rmvSelectionGate(); GenericConstraintSelection* selFilterGate = new GenericConstraintSelection(sketchgui->getObject()); @@ -1873,12 +1873,12 @@ class CmdSketcherConstrainCoincident : public CmdSketcherConstraint { public: CmdSketcherConstrainCoincident(); - virtual ~CmdSketcherConstrainCoincident(){} - virtual const char* className() const + ~CmdSketcherConstrainCoincident() override{} + const char* className() const override { return "CmdSketcherConstrainCoincident"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; // returns true if a substitution took place bool substituteConstraintCombinations(SketchObject * Obj, int GeoId1, PointPos PosId1, @@ -2082,13 +2082,13 @@ class CmdSketcherConstrainDistance : public CmdSketcherConstraint { public: CmdSketcherConstrainDistance(); - virtual ~CmdSketcherConstrainDistance(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainDistance() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainDistance"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainDistance::CmdSketcherConstrainDistance() @@ -2138,7 +2138,7 @@ void CmdSketcherConstrainDistance::activated(int iMsg) const std::vector &SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - if (SubNames.size() < 1 || SubNames.size() > 2) { + if (SubNames.empty() || SubNames.size() > 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select exactly one line or one point and one line or two points from the sketch.")); return; @@ -2429,12 +2429,12 @@ class CmdSketcherConstrainPointOnObject : public CmdSketcherConstraint { public: CmdSketcherConstrainPointOnObject(); - virtual ~CmdSketcherConstrainPointOnObject(){} - virtual const char* className() const + ~CmdSketcherConstrainPointOnObject() override{} + const char* className() const override { return "CmdSketcherConstrainPointOnObject"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; // returns true if a substitution took place bool substituteConstraintCombinations(SketchObject * Obj, int GeoId1, PointPos PosId1, int GeoId2); @@ -2529,8 +2529,8 @@ void CmdSketcherConstrainPointOnObject::activated(int iMsg) points.push_back(id); } - if ((points.size() == 1 && curves.size() >= 1) || - (points.size() >= 1 && curves.size() == 1)) { + if ((points.size() == 1 && !curves.empty()) || + (!points.empty() && curves.size() == 1)) { openCommand(QT_TRANSLATE_NOOP("Command", "Add point on object constraint")); int cnt = 0; @@ -2679,13 +2679,13 @@ class CmdSketcherConstrainDistanceX : public CmdSketcherConstraint { public: CmdSketcherConstrainDistanceX(); - virtual ~CmdSketcherConstrainDistanceX(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainDistanceX() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainDistanceX"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainDistanceX::CmdSketcherConstrainDistanceX() @@ -2735,7 +2735,7 @@ void CmdSketcherConstrainDistanceX::activated(int iMsg) const std::vector &SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - if (SubNames.size() < 1 || SubNames.size() > 2) { + if (SubNames.empty() || SubNames.size() > 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select exactly one line or up to two points from the sketch.")); return; @@ -2933,13 +2933,13 @@ class CmdSketcherConstrainDistanceY : public CmdSketcherConstraint { public: CmdSketcherConstrainDistanceY(); - virtual ~CmdSketcherConstrainDistanceY(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainDistanceY() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainDistanceY"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainDistanceY::CmdSketcherConstrainDistanceY() @@ -2987,7 +2987,7 @@ void CmdSketcherConstrainDistanceY::activated(int iMsg) const std::vector &SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - if (SubNames.size() < 1 || SubNames.size() > 2) { + if (SubNames.empty() || SubNames.size() > 2) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select exactly one line or up to two points from the sketch.")); return; @@ -3180,12 +3180,12 @@ class CmdSketcherConstrainParallel : public CmdSketcherConstraint { public: CmdSketcherConstrainParallel(); - virtual ~CmdSketcherConstrainParallel(){} - virtual const char* className() const + ~CmdSketcherConstrainParallel() override{} + const char* className() const override { return "CmdSketcherConstrainParallel"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainParallel::CmdSketcherConstrainParallel() @@ -3330,12 +3330,12 @@ class CmdSketcherConstrainPerpendicular : public CmdSketcherConstraint { public: CmdSketcherConstrainPerpendicular(); - virtual ~CmdSketcherConstrainPerpendicular(){} - virtual const char* className() const + ~CmdSketcherConstrainPerpendicular() override{} + const char* className() const override { return "CmdSketcherConstrainPerpendicular"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainPerpendicular::CmdSketcherConstrainPerpendicular() @@ -3972,12 +3972,12 @@ class CmdSketcherConstrainTangent : public CmdSketcherConstraint { public: CmdSketcherConstrainTangent(); - virtual ~CmdSketcherConstrainTangent(){} - virtual const char* className() const + ~CmdSketcherConstrainTangent() override{} + const char* className() const override { return "CmdSketcherConstrainTangent"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; // returns true if a substitution took place bool substituteConstraintCombinations(SketchObject * Obj, int GeoId1, int GeoId2); }; @@ -4415,7 +4415,6 @@ void CmdSketcherConstrainTangent::applyConstraint(std::vector &selSeq { SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); - QString strError; int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; @@ -4693,13 +4692,13 @@ class CmdSketcherConstrainRadius : public CmdSketcherConstraint { public: CmdSketcherConstrainRadius(); - virtual ~CmdSketcherConstrainRadius(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainRadius() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainRadius"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainRadius::CmdSketcherConstrainRadius() @@ -4780,10 +4779,10 @@ void CmdSketcherConstrainRadius::activated(int iMsg) double radius = arc->getRadius(); if(issegmentfixed) { - externalGeoIdRadiusMap.push_back(std::make_pair(GeoId, radius)); + externalGeoIdRadiusMap.emplace_back(GeoId, radius); } else { - geoIdRadiusMap.push_back(std::make_pair(GeoId, radius)); + geoIdRadiusMap.emplace_back(GeoId, radius); } nonpoles = true; @@ -4793,10 +4792,10 @@ void CmdSketcherConstrainRadius::activated(int iMsg) double radius = circle->getRadius(); if(issegmentfixed) { - externalGeoIdRadiusMap.push_back(std::make_pair(GeoId, radius)); + externalGeoIdRadiusMap.emplace_back(GeoId, radius); } else { - geoIdRadiusMap.push_back(std::make_pair(GeoId, radius)); + geoIdRadiusMap.emplace_back(GeoId, radius); } if(isBsplinePole(geom)) @@ -4993,13 +4992,13 @@ class CmdSketcherConstrainDiameter : public CmdSketcherConstraint { public: CmdSketcherConstrainDiameter(); - virtual ~CmdSketcherConstrainDiameter(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainDiameter() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainDiameter"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainDiameter::CmdSketcherConstrainDiameter() @@ -5077,10 +5076,10 @@ void CmdSketcherConstrainDiameter::activated(int iMsg) double radius = arc->getRadius(); if(issegmentfixed) { - externalGeoIdDiameterMap.push_back(std::make_pair(GeoId, 2*radius)); + externalGeoIdDiameterMap.emplace_back(GeoId, 2*radius); } else { - geoIdDiameterMap.push_back(std::make_pair(GeoId, 2*radius)); + geoIdDiameterMap.emplace_back(GeoId, 2*radius); } } else if (geom && geom->getTypeId() == Part::GeomCircle::getClassTypeId()) { @@ -5094,10 +5093,10 @@ void CmdSketcherConstrainDiameter::activated(int iMsg) } if(issegmentfixed) { - externalGeoIdDiameterMap.push_back(std::make_pair(GeoId, 2*radius)); + externalGeoIdDiameterMap.emplace_back(GeoId, 2*radius); } else { - geoIdDiameterMap.push_back(std::make_pair(GeoId, 2*radius)); + geoIdDiameterMap.emplace_back(GeoId, 2*radius); } } } @@ -5267,13 +5266,13 @@ class CmdSketcherConstrainRadiam : public CmdSketcherConstraint { public: CmdSketcherConstrainRadiam(); - virtual ~CmdSketcherConstrainRadiam(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainRadiam() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainRadiam"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainRadiam::CmdSketcherConstrainRadiam() @@ -5282,7 +5281,7 @@ CmdSketcherConstrainRadiam::CmdSketcherConstrainRadiam() sAppModule = "Sketcher"; sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Constrain auto radius/diameter"); - sToolTipText = QT_TR_NOOP("Fix automatically diameter on circle and radius on arc/pole"); + sToolTipText = QT_TR_NOOP("Fix the diameter if a circle is chosen, or the radius if an arc/spline pole is chosen"); sWhatsThis = "Sketcher_ConstrainRadiam"; sStatusTip = sToolTipText; sPixmap = "Constraint_Radiam"; @@ -5367,10 +5366,10 @@ void CmdSketcherConstrainRadiam::activated(int iMsg) continue; if(issegmentfixed) { - externalGeoIdRadiamMap.push_back(std::make_pair(GeoId, radius)); + externalGeoIdRadiamMap.emplace_back(GeoId, radius); } else { - geoIdRadiamMap.push_back(std::make_pair(GeoId, radius)); + geoIdRadiamMap.emplace_back(GeoId, radius); } } @@ -5585,7 +5584,7 @@ CmdSketcherCompConstrainRadDia::CmdSketcherCompConstrainRadDia() sGroup = "Sketcher"; sMenuText = QT_TR_NOOP("Constrain arc or circle"); sToolTipText = QT_TR_NOOP("Constrain an arc or a circle"); - sWhatsThis = "Sketcher_CompCreateCircle"; + sWhatsThis = "Sketcher_CompConstrainRadDia"; sStatusTip = sToolTipText; sAccel = "R"; eType = ForEdit; @@ -5619,7 +5618,7 @@ void CmdSketcherCompConstrainRadDia::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompConstrainRadDia::createAction(void) +Gui::Action * CmdSketcherCompConstrainRadDia::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -5702,7 +5701,7 @@ void CmdSketcherCompConstrainRadDia::languageChange() arc3->setStatusTip(QApplication::translate("Sketcher_ConstrainRadiam", "Fix the radius/diameter of a circle or an arc")); } -bool CmdSketcherCompConstrainRadDia::isActive(void) +bool CmdSketcherCompConstrainRadDia::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -5713,13 +5712,13 @@ class CmdSketcherConstrainAngle : public CmdSketcherConstraint { public: CmdSketcherConstrainAngle(); - virtual ~CmdSketcherConstrainAngle(){} - virtual void updateAction(int mode); - virtual const char* className() const + ~CmdSketcherConstrainAngle() override{} + void updateAction(int mode) override; + const char* className() const override { return "CmdSketcherConstrainAngle"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainAngle::CmdSketcherConstrainAngle() @@ -5778,7 +5777,7 @@ void CmdSketcherConstrainAngle::activated(int iMsg) const std::vector &SubNames = selection[0].getSubNames(); Sketcher::SketchObject* Obj = static_cast(selection[0].getObject()); - if (SubNames.size() < 1 || SubNames.size() > 3) { + if (SubNames.empty() || SubNames.size() > 3) { //goto ExitWithMessage; QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("Select one or two lines from the sketch. Or select two edges and a point.")); @@ -6241,12 +6240,12 @@ class CmdSketcherConstrainEqual : public CmdSketcherConstraint { public: CmdSketcherConstrainEqual(); - virtual ~CmdSketcherConstrainEqual(){} - virtual const char* className() const + ~CmdSketcherConstrainEqual() override{} + const char* className() const override { return "CmdSketcherConstrainEqual"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainEqual::CmdSketcherConstrainEqual() @@ -6403,7 +6402,6 @@ void CmdSketcherConstrainEqual::applyConstraint(std::vector &selSeq, { SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); - QString strError; int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef; @@ -6458,12 +6456,12 @@ class CmdSketcherConstrainSymmetric : public CmdSketcherConstraint { public: CmdSketcherConstrainSymmetric(); - virtual ~CmdSketcherConstrainSymmetric(){} - virtual const char* className() const + ~CmdSketcherConstrainSymmetric() override{} + const char* className() const override { return "CmdSketcherConstrainSymmetric"; } protected: - virtual void activated(int iMsg); - virtual void applyConstraint(std::vector &selSeq, int seqIndex); + void activated(int iMsg) override; + void applyConstraint(std::vector &selSeq, int seqIndex) override; }; CmdSketcherConstrainSymmetric::CmdSketcherConstrainSymmetric() @@ -6651,7 +6649,6 @@ void CmdSketcherConstrainSymmetric::applyConstraint(std::vector &selS { SketcherGui::ViewProviderSketch* sketchgui = static_cast(getActiveGuiDocument()->getInEdit()); Sketcher::SketchObject* Obj = sketchgui->getSketchObject(); - QString strError; int GeoId1 = GeoEnum::GeoUndef, GeoId2 = GeoEnum::GeoUndef, GeoId3 = GeoEnum::GeoUndef; Sketcher::PointPos PosId1 = Sketcher::PointPos::none, PosId2 = Sketcher::PointPos::none, PosId3 = Sketcher::PointPos::none; @@ -6923,7 +6920,7 @@ void CmdSketcherConstrainSnellsLaw::activated(int iMsg) } } -bool CmdSketcherConstrainSnellsLaw::isActive(void) +bool CmdSketcherConstrainSnellsLaw::isActive() { return isCreateConstraintActive( getActiveGuiDocument() ); } @@ -7096,12 +7093,12 @@ void CmdSketcherConstrainInternalAlignment::activated(int iMsg) } // if some element is missing and we are adding an element of that type - if((!(focus1 && focus2) && pointids.size() >= 1) || - (!(major && minor) && lineids.size() >= 1) ){ + if((!(focus1 && focus2) && !pointids.empty()) || + (!(major && minor) && !lineids.empty()) ){ openCommand(QT_TRANSLATE_NOOP("Command", "Add internal alignment constraint")); - if(pointids.size()>=1) + if(!pointids.empty()) { if(!focus1) { Gui::cmdAppObjectArgs(selection[0].getObject(), @@ -7129,7 +7126,7 @@ void CmdSketcherConstrainInternalAlignment::activated(int iMsg) extra_elements=true; } - if(lineids.size()>=1) + if(!lineids.empty()) { if(!major) { Gui::cmdAppObjectArgs(selection[0].getObject(), @@ -7213,7 +7210,7 @@ void CmdSketcherConstrainInternalAlignment::activated(int iMsg) return; } - if(ellipseids.size()>0){ + if(!ellipseids.empty()){ QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("You cannot internally constrain an ellipse " "on an arc of ellipse. " @@ -7274,12 +7271,12 @@ void CmdSketcherConstrainInternalAlignment::activated(int iMsg) } // if some element is missing and we are adding an element of that type - if((!(focus1 && focus2) && pointids.size() >= 1) || - (!(major && minor) && lineids.size() >= 1) ){ + if((!(focus1 && focus2) && !pointids.empty()) || + (!(major && minor) && !lineids.empty()) ){ openCommand(QT_TRANSLATE_NOOP("Command", "Add internal alignment constraint")); - if(pointids.size()>=1) + if(!pointids.empty()) { if(!focus1) { Gui::cmdAppObjectArgs(selection[0].getObject(), @@ -7307,7 +7304,7 @@ void CmdSketcherConstrainInternalAlignment::activated(int iMsg) extra_elements=true; } - if(lineids.size()>=1) + if(!lineids.empty()) { if(!major) { Gui::cmdAppObjectArgs(selection[0].getObject(), @@ -7385,7 +7382,7 @@ void CmdSketcherConstrainInternalAlignment::activated(int iMsg) } } -bool CmdSketcherConstrainInternalAlignment::isActive(void) +bool CmdSketcherConstrainInternalAlignment::isActive() { return isCreateConstraintActive(getActiveGuiDocument()); } @@ -7514,7 +7511,7 @@ void CmdSketcherToggleDrivingConstraint::activated(int iMsg) } } -bool CmdSketcherToggleDrivingConstraint::isActive(void) +bool CmdSketcherToggleDrivingConstraint::isActive() { return isCommandActive( getActiveGuiDocument() ); } @@ -7598,13 +7595,13 @@ void CmdSketcherToggleActiveConstraint::activated(int iMsg) } } -bool CmdSketcherToggleActiveConstraint::isActive(void) +bool CmdSketcherToggleActiveConstraint::isActive() { return isCreateConstraintActive( getActiveGuiDocument() ); } -void CreateSketcherCommandsConstraints(void) +void CreateSketcherCommandsConstraints() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp b/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp index 4dbf7b323e..71978a4d28 100644 --- a/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp +++ b/src/Mod/Sketcher/Gui/CommandCreateGeo.cpp @@ -91,6 +91,23 @@ using namespace std; using namespace SketcherGui; +#define CONSTRUCTION_UPDATE_ACTION(CLASS, ICON) \ + /* This macro creates an updateAction() function that will toggle between normal & construction icon */ \ + void CLASS::updateAction(int mode) \ + { \ + auto act = getAction(); \ + if (act) { \ + switch (mode) { \ + case Normal: \ + act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON)); \ + break; \ + case Construction: \ + act->setIcon(Gui::BitmapFactory().iconFromTheme(ICON "_Constr")); \ + break; \ + } \ + } \ + } + namespace SketcherGui { GeometryCreationMode geometryCreationMode=Normal; } @@ -113,27 +130,15 @@ CmdSketcherCreateLine::CmdSketcherCreateLine() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateLine,"Sketcher_CreateLine") + void CmdSketcherCreateLine::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerLine() ); } -void CmdSketcherCreateLine::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateLine_Constr")); - break; - } -} - -bool CmdSketcherCreateLine::isActive(void) +bool CmdSketcherCreateLine::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -157,27 +162,15 @@ CmdSketcherCreateRectangle::CmdSketcherCreateRectangle() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangle,"Sketcher_CreateRectangle") + void CmdSketcherCreateRectangle::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBox(DrawSketchHandlerBox::Diagonal) ); } -void CmdSketcherCreateRectangle::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Constr")); - break; - } -} - -bool CmdSketcherCreateRectangle::isActive(void) +bool CmdSketcherCreateRectangle::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -198,27 +191,15 @@ CmdSketcherCreateRectangleCenter::CmdSketcherCreateRectangleCenter() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRectangleCenter,"Sketcher_CreateRectangle_Center") + void CmdSketcherCreateRectangleCenter::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBox(DrawSketchHandlerBox::CenterAndCorner) ); } -void CmdSketcherCreateRectangleCenter::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateRectangle_Center_Constr")); - break; - } -} - -bool CmdSketcherCreateRectangleCenter::isActive(void) +bool CmdSketcherCreateRectangleCenter::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -242,27 +223,15 @@ CmdSketcherCreateOblong::CmdSketcherCreateOblong() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOblong,"Sketcher_CreateOblong") + void CmdSketcherCreateOblong::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerOblong()); } -void CmdSketcherCreateOblong::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateOblong_Constr")); - break; - } -} - -bool CmdSketcherCreateOblong::isActive(void) +bool CmdSketcherCreateOblong::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -303,7 +272,7 @@ void CmdSketcherCompCreateRectangles::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action* CmdSketcherCompCreateRectangles::createAction(void) +Gui::Action* CmdSketcherCompCreateRectangles::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -373,7 +342,7 @@ void CmdSketcherCompCreateRectangles::languageChange() rectangle3->setStatusTip(rectangle3->toolTip()); } -bool CmdSketcherCompCreateRectangles::isActive(void) +bool CmdSketcherCompCreateRectangles::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -396,27 +365,15 @@ CmdSketcherCreatePolyline::CmdSketcherCreatePolyline() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePolyline,"Sketcher_CreatePolyline") + void CmdSketcherCreatePolyline::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerLineSet() ); } -void CmdSketcherCreatePolyline::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePolyline")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreatePolyline_Constr")); - break; - } -} - -bool CmdSketcherCreatePolyline::isActive(void) +bool CmdSketcherCreatePolyline::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -424,7 +381,7 @@ bool CmdSketcherCreatePolyline::isActive(void) // ====================================================================================== -DEF_STD_CMD_A(CmdSketcherCreateArc) +DEF_STD_CMD_AU(CmdSketcherCreateArc) CmdSketcherCreateArc::CmdSketcherCreateArc() : Command("Sketcher_CreateArc") @@ -440,13 +397,15 @@ CmdSketcherCreateArc::CmdSketcherCreateArc() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArc,"Sketcher_CreateArc") + void CmdSketcherCreateArc::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArc() ); } -bool CmdSketcherCreateArc::isActive(void) +bool CmdSketcherCreateArc::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -454,7 +413,7 @@ bool CmdSketcherCreateArc::isActive(void) // ====================================================================================== -DEF_STD_CMD_A(CmdSketcherCreate3PointArc) +DEF_STD_CMD_AU(CmdSketcherCreate3PointArc) CmdSketcherCreate3PointArc::CmdSketcherCreate3PointArc() : Command("Sketcher_Create3PointArc") @@ -470,13 +429,15 @@ CmdSketcherCreate3PointArc::CmdSketcherCreate3PointArc() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointArc,"Sketcher_Create3PointArc") + void CmdSketcherCreate3PointArc::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandler3PointArc() ); } -bool CmdSketcherCreate3PointArc::isActive(void) +bool CmdSketcherCreate3PointArc::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -514,7 +475,7 @@ void CmdSketcherCompCreateArc::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateArc::createAction(void) +Gui::Action * CmdSketcherCompCreateArc::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -576,7 +537,7 @@ void CmdSketcherCompCreateArc::languageChange() arc2->setStatusTip(QApplication::translate("Sketcher_Create3PointArc","Create an arc by its end points and a point along the arc")); } -bool CmdSketcherCompCreateArc::isActive(void) +bool CmdSketcherCompCreateArc::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -585,7 +546,7 @@ bool CmdSketcherCompCreateArc::isActive(void) // ====================================================================================== -DEF_STD_CMD_A(CmdSketcherCreateCircle) +DEF_STD_CMD_AU(CmdSketcherCreateCircle) CmdSketcherCreateCircle::CmdSketcherCreateCircle() : Command("Sketcher_CreateCircle") @@ -601,20 +562,22 @@ CmdSketcherCreateCircle::CmdSketcherCreateCircle() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateCircle,"Sketcher_CreateCircle") + void CmdSketcherCreateCircle::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerCircle() ); } -bool CmdSketcherCreateCircle::isActive(void) +bool CmdSketcherCreateCircle::isActive() { return isCommandActive(getActiveGuiDocument()); } // ====================================================================================== /// @brief Macro that declares a new sketcher command class 'CmdSketcherCreateEllipseByCenter' -DEF_STD_CMD_A(CmdSketcherCreateEllipseByCenter) +DEF_STD_CMD_AU(CmdSketcherCreateEllipseByCenter) /** * @brief ctor @@ -628,24 +591,26 @@ CmdSketcherCreateEllipseByCenter::CmdSketcherCreateEllipseByCenter() sToolTipText = QT_TR_NOOP("Create an ellipse by center in the sketch"); sWhatsThis = "Sketcher_CreateEllipseByCenter"; sStatusTip = sToolTipText; - sPixmap = "Sketcher_Conics_Ellipse_Center"; + sPixmap = "Sketcher_CreateEllipseByCenter"; sAccel = "G, E, E"; eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseByCenter, "Sketcher_CreateEllipseByCenter") + void CmdSketcherCreateEllipseByCenter::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerEllipse(0) ); } -bool CmdSketcherCreateEllipseByCenter::isActive(void) +bool CmdSketcherCreateEllipseByCenter::isActive() { return isCommandActive(getActiveGuiDocument()); } /// @brief Macro that declares a new sketcher command class 'CmdSketcherCreateEllipseBy3Points' -DEF_STD_CMD_A(CmdSketcherCreateEllipseBy3Points) +DEF_STD_CMD_AU(CmdSketcherCreateEllipseBy3Points) /** * @brief ctor @@ -664,18 +629,20 @@ CmdSketcherCreateEllipseBy3Points::CmdSketcherCreateEllipseBy3Points() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateEllipseBy3Points,"Sketcher_CreateEllipse_3points") + void CmdSketcherCreateEllipseBy3Points::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerEllipse(1) ); } -bool CmdSketcherCreateEllipseBy3Points::isActive(void) +bool CmdSketcherCreateEllipseBy3Points::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateArcOfEllipse) +DEF_STD_CMD_AU(CmdSketcherCreateArcOfEllipse) CmdSketcherCreateArcOfEllipse::CmdSketcherCreateArcOfEllipse() : Command("Sketcher_CreateArcOfEllipse") @@ -691,18 +658,20 @@ CmdSketcherCreateArcOfEllipse::CmdSketcherCreateArcOfEllipse() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfEllipse,"Sketcher_CreateElliptical_Arc") + void CmdSketcherCreateArcOfEllipse::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArcOfEllipse() ); } -bool CmdSketcherCreateArcOfEllipse::isActive(void) +bool CmdSketcherCreateArcOfEllipse::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateArcOfHyperbola) +DEF_STD_CMD_AU(CmdSketcherCreateArcOfHyperbola) CmdSketcherCreateArcOfHyperbola::CmdSketcherCreateArcOfHyperbola() : Command("Sketcher_CreateArcOfHyperbola") @@ -718,17 +687,19 @@ CmdSketcherCreateArcOfHyperbola::CmdSketcherCreateArcOfHyperbola() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfHyperbola,"Sketcher_CreateHyperbolic_Arc") + void CmdSketcherCreateArcOfHyperbola::activated(int /*iMsg*/) { ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArcOfHyperbola() ); } -bool CmdSketcherCreateArcOfHyperbola::isActive(void) +bool CmdSketcherCreateArcOfHyperbola::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateArcOfParabola) +DEF_STD_CMD_AU(CmdSketcherCreateArcOfParabola) CmdSketcherCreateArcOfParabola::CmdSketcherCreateArcOfParabola() : Command("Sketcher_CreateArcOfParabola") @@ -744,12 +715,14 @@ CmdSketcherCreateArcOfParabola::CmdSketcherCreateArcOfParabola() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateArcOfParabola,"Sketcher_CreateParabolic_Arc") + void CmdSketcherCreateArcOfParabola::activated(int /*iMsg*/) { ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerArcOfParabola() ); } -bool CmdSketcherCreateArcOfParabola::isActive(void) +bool CmdSketcherCreateArcOfParabola::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -804,15 +777,14 @@ void CmdSketcherCompCreateConic::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateConic::createAction(void) +Gui::Action * CmdSketcherCompCreateConic::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); applyCommandData(this->className(), pcAction); QAction* ellipseByCenter = pcAction->addAction(QString()); - ellipseByCenter->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse")); - /// @todo replace with correct icon + ellipseByCenter->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); QAction* ellipseBy3Points = pcAction->addAction(QString()); ellipseBy3Points->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); @@ -846,7 +818,7 @@ void CmdSketcherCompCreateConic::updateAction(int mode) int index = pcAction->property("defaultAction").toInt(); switch (mode) { case Normal: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse")); + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter")); a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points")); a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc")); a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc")); @@ -854,7 +826,7 @@ void CmdSketcherCompCreateConic::updateAction(int mode) getAction()->setIcon(a[index]->icon()); break; case Construction: - a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_Constr")); + a[0]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipseByCenter_Constr")); a[1]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateEllipse_3points_Constr")); a[2]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateElliptical_Arc_Constr")); a[3]->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateHyperbolic_Arc_Constr")); @@ -895,14 +867,14 @@ void CmdSketcherCompCreateConic::languageChange() arcofparabola->setStatusTip(QApplication::translate("Sketcher_CreateArcOfParabola","Create an arc of parabola by its focus, vertex, and endpoints")); } -bool CmdSketcherCompCreateConic::isActive(void) +bool CmdSketcherCompCreateConic::isActive() { return isCommandActive(getActiveGuiDocument()); } // ====================================================================================== -DEF_STD_CMD_A(CmdSketcherCreateBSpline) +DEF_STD_CMD_AU(CmdSketcherCreateBSpline) CmdSketcherCreateBSpline::CmdSketcherCreateBSpline() : Command("Sketcher_CreateBSpline") @@ -918,33 +890,21 @@ CmdSketcherCreateBSpline::CmdSketcherCreateBSpline() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateBSpline,"Sketcher_CreateBSpline") + void CmdSketcherCreateBSpline::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBSpline(0) ); } -/*void CmdSketcherCreateBSpline::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateBSpline_Constr")); - break; - } -}*/ - -bool CmdSketcherCreateBSpline::isActive(void) +bool CmdSketcherCreateBSpline::isActive() { return isCommandActive(getActiveGuiDocument()); } /// @brief Macro that declares a new sketcher command class 'CmdSketcherCreateBSpline' -DEF_STD_CMD_A(CmdSketcherCreatePeriodicBSpline) +DEF_STD_CMD_AU(CmdSketcherCreatePeriodicBSpline) /** * @brief ctor @@ -963,13 +923,15 @@ CmdSketcherCreatePeriodicBSpline::CmdSketcherCreatePeriodicBSpline() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePeriodicBSpline,"Sketcher_Create_Periodic_BSpline") + void CmdSketcherCreatePeriodicBSpline::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerBSpline(1) ); } -bool CmdSketcherCreatePeriodicBSpline::isActive(void) +bool CmdSketcherCreatePeriodicBSpline::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1016,7 +978,7 @@ void CmdSketcherCompCreateBSpline::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateBSpline::createAction(void) +Gui::Action * CmdSketcherCompCreateBSpline::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1080,7 +1042,7 @@ void CmdSketcherCompCreateBSpline::languageChange() periodicbspline->setStatusTip(QApplication::translate("Sketcher_Create_Periodic_BSpline","Create a periodic B-spline by control points")); } -bool CmdSketcherCompCreateBSpline::isActive(void) +bool CmdSketcherCompCreateBSpline::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1088,7 +1050,7 @@ bool CmdSketcherCompCreateBSpline::isActive(void) // ====================================================================================== -DEF_STD_CMD_A(CmdSketcherCreate3PointCircle) +DEF_STD_CMD_AU(CmdSketcherCreate3PointCircle) CmdSketcherCreate3PointCircle::CmdSketcherCreate3PointCircle() : Command("Sketcher_Create3PointCircle") @@ -1104,13 +1066,15 @@ CmdSketcherCreate3PointCircle::CmdSketcherCreate3PointCircle() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreate3PointCircle,"Sketcher_Create3PointCircle") + void CmdSketcherCreate3PointCircle::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandler3PointCircle() ); } -bool CmdSketcherCreate3PointCircle::isActive(void) +bool CmdSketcherCreate3PointCircle::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1148,7 +1112,7 @@ void CmdSketcherCompCreateCircle::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateCircle::createAction(void) +Gui::Action * CmdSketcherCompCreateCircle::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1210,7 +1174,7 @@ void CmdSketcherCompCreateCircle::languageChange() arc2->setStatusTip(QApplication::translate("Sketcher_Create3PointCircle", "Create a circle by 3 rim points")); } -bool CmdSketcherCompCreateCircle::isActive(void) +bool CmdSketcherCompCreateCircle::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1241,7 +1205,7 @@ void CmdSketcherCreatePoint::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerPoint()); } -bool CmdSketcherCreatePoint::isActive(void) +bool CmdSketcherCreatePoint::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1270,7 +1234,7 @@ void CmdSketcherCreateFillet::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerFillet(DrawSketchHandlerFillet::SimpleFillet)); } -bool CmdSketcherCreateFillet::isActive(void) +bool CmdSketcherCreateFillet::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1299,7 +1263,7 @@ void CmdSketcherCreatePointFillet::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerFillet(DrawSketchHandlerFillet::ConstraintPreservingFillet)); } -bool CmdSketcherCreatePointFillet::isActive(void) +bool CmdSketcherCreatePointFillet::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1345,7 +1309,7 @@ void CmdSketcherCompCreateFillets::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateFillets::createAction(void) +Gui::Action * CmdSketcherCompCreateFillets::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1400,7 +1364,7 @@ void CmdSketcherCompCreateFillets::languageChange() pointFillet->setStatusTip(QApplication::translate("Sketcher_CreatePointFillet","Fillet that preserves constraints and intersection point")); } -bool CmdSketcherCompCreateFillets::isActive(void) +bool CmdSketcherCompCreateFillets::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1429,7 +1393,7 @@ void CmdSketcherTrimming::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerTrimming()); } -bool CmdSketcherTrimming::isActive(void) +bool CmdSketcherTrimming::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1460,7 +1424,7 @@ void CmdSketcherExtend::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerExtend()); } -bool CmdSketcherExtend::isActive(void) +bool CmdSketcherExtend::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1491,7 +1455,7 @@ void CmdSketcherSplit::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerSplitting()); } -bool CmdSketcherSplit::isActive(void) +bool CmdSketcherSplit::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1518,7 +1482,7 @@ void CmdSketcherExternal::activated(int iMsg) ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerExternal()); } -bool CmdSketcherExternal::isActive(void) +bool CmdSketcherExternal::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1541,31 +1505,19 @@ CmdSketcherCarbonCopy::CmdSketcherCarbonCopy() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCarbonCopy,"Sketcher_CarbonCopy") + void CmdSketcherCarbonCopy::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerCarbonCopy()); } -bool CmdSketcherCarbonCopy::isActive(void) +bool CmdSketcherCarbonCopy::isActive() { return isCommandActive(getActiveGuiDocument()); } -void CmdSketcherCarbonCopy::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CarbonCopy")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CarbonCopy_Constr")); - break; - } -} - /** * Create Slot @@ -1587,34 +1539,22 @@ CmdSketcherCreateSlot::CmdSketcherCreateSlot() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateSlot,"Sketcher_CreateSlot") + void CmdSketcherCreateSlot::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(), new DrawSketchHandlerSlot()); } -void CmdSketcherCreateSlot::updateAction(int mode) -{ - switch (mode) { - case Normal: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSlot")); - break; - case Construction: - if (getAction()) - getAction()->setIcon(Gui::BitmapFactory().iconFromTheme("Sketcher_CreateSlot_Constr")); - break; - } -} - -bool CmdSketcherCreateSlot::isActive(void) +bool CmdSketcherCreateSlot::isActive() { return isCommandActive(getActiveGuiDocument()); } /* Create Regular Polygon ==============================================*/ -DEF_STD_CMD_A(CmdSketcherCreateTriangle) +DEF_STD_CMD_AU(CmdSketcherCreateTriangle) CmdSketcherCreateTriangle::CmdSketcherCreateTriangle() : Command("Sketcher_CreateTriangle") @@ -1630,18 +1570,20 @@ CmdSketcherCreateTriangle::CmdSketcherCreateTriangle() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateTriangle,"Sketcher_CreateTriangle") + void CmdSketcherCreateTriangle::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(3) ); } -bool CmdSketcherCreateTriangle::isActive(void) +bool CmdSketcherCreateTriangle::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateSquare) +DEF_STD_CMD_AU(CmdSketcherCreateSquare) CmdSketcherCreateSquare::CmdSketcherCreateSquare() : Command("Sketcher_CreateSquare") @@ -1657,18 +1599,20 @@ CmdSketcherCreateSquare::CmdSketcherCreateSquare() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateSquare,"Sketcher_CreateSquare") + void CmdSketcherCreateSquare::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(4) ); } -bool CmdSketcherCreateSquare::isActive(void) +bool CmdSketcherCreateSquare::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreatePentagon) +DEF_STD_CMD_AU(CmdSketcherCreatePentagon) CmdSketcherCreatePentagon::CmdSketcherCreatePentagon() : Command("Sketcher_CreatePentagon") @@ -1684,19 +1628,21 @@ CmdSketcherCreatePentagon::CmdSketcherCreatePentagon() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreatePentagon,"Sketcher_CreatePentagon") + void CmdSketcherCreatePentagon::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(5) ); } -bool CmdSketcherCreatePentagon::isActive(void) +bool CmdSketcherCreatePentagon::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateHexagon) +DEF_STD_CMD_AU(CmdSketcherCreateHexagon) CmdSketcherCreateHexagon::CmdSketcherCreateHexagon() : Command("Sketcher_CreateHexagon") @@ -1712,18 +1658,20 @@ CmdSketcherCreateHexagon::CmdSketcherCreateHexagon() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateHexagon,"Sketcher_CreateHexagon") + void CmdSketcherCreateHexagon::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(6) ); } -bool CmdSketcherCreateHexagon::isActive(void) +bool CmdSketcherCreateHexagon::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateHeptagon) +DEF_STD_CMD_AU(CmdSketcherCreateHeptagon) CmdSketcherCreateHeptagon::CmdSketcherCreateHeptagon() : Command("Sketcher_CreateHeptagon") @@ -1739,18 +1687,20 @@ CmdSketcherCreateHeptagon::CmdSketcherCreateHeptagon() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateHeptagon,"Sketcher_CreateHeptagon") + void CmdSketcherCreateHeptagon::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(7) ); } -bool CmdSketcherCreateHeptagon::isActive(void) +bool CmdSketcherCreateHeptagon::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateOctagon) +DEF_STD_CMD_AU(CmdSketcherCreateOctagon) CmdSketcherCreateOctagon::CmdSketcherCreateOctagon() : Command("Sketcher_CreateOctagon") @@ -1766,18 +1716,20 @@ CmdSketcherCreateOctagon::CmdSketcherCreateOctagon() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateOctagon,"Sketcher_CreateOctagon") + void CmdSketcherCreateOctagon::activated(int iMsg) { Q_UNUSED(iMsg); ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(8) ); } -bool CmdSketcherCreateOctagon::isActive(void) +bool CmdSketcherCreateOctagon::isActive() { return isCommandActive(getActiveGuiDocument()); } -DEF_STD_CMD_A(CmdSketcherCreateRegularPolygon) +DEF_STD_CMD_AU(CmdSketcherCreateRegularPolygon) CmdSketcherCreateRegularPolygon::CmdSketcherCreateRegularPolygon() : Command("Sketcher_CreateRegularPolygon") @@ -1793,6 +1745,8 @@ CmdSketcherCreateRegularPolygon::CmdSketcherCreateRegularPolygon() eType = ForEdit; } +CONSTRUCTION_UPDATE_ACTION(CmdSketcherCreateRegularPolygon,"Sketcher_CreateRegularPolygon") + void CmdSketcherCreateRegularPolygon::activated(int iMsg) { Q_UNUSED(iMsg); @@ -1803,7 +1757,7 @@ void CmdSketcherCreateRegularPolygon::activated(int iMsg) ActivateHandler(getActiveGuiDocument(),new DrawSketchHandlerRegularPolygon(srpd.sides)); } -bool CmdSketcherCreateRegularPolygon::isActive(void) +bool CmdSketcherCreateRegularPolygon::isActive() { return isCommandActive(getActiveGuiDocument()); } @@ -1859,7 +1813,7 @@ void CmdSketcherCompCreateRegularPolygon::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompCreateRegularPolygon::createAction(void) +Gui::Action * CmdSketcherCompCreateRegularPolygon::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1961,12 +1915,12 @@ void CmdSketcherCompCreateRegularPolygon::languageChange() regular->setStatusTip(QApplication::translate("Sketcher_CreateOctagon","Create a regular polygon by its center and by one corner")); } -bool CmdSketcherCompCreateRegularPolygon::isActive(void) +bool CmdSketcherCompCreateRegularPolygon::isActive() { return isCommandActive(getActiveGuiDocument()); } -void CreateSketcherCommandsCreateGeo(void) +void CreateSketcherCommandsCreateGeo() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp index 7374d4075c..104b680d33 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherBSpline.cpp @@ -158,7 +158,7 @@ void CmdSketcherBSplineDegree::activated(int iMsg) ShowRestoreInformationLayer("BSplineDegreeVisible"); } -bool CmdSketcherBSplineDegree::isActive(void) +bool CmdSketcherBSplineDegree::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -187,7 +187,7 @@ void CmdSketcherBSplinePolygon::activated(int iMsg) ShowRestoreInformationLayer("BSplineControlPolygonVisible"); } -bool CmdSketcherBSplinePolygon::isActive(void) +bool CmdSketcherBSplinePolygon::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -216,7 +216,7 @@ void CmdSketcherBSplineComb::activated(int iMsg) ShowRestoreInformationLayer("BSplineCombVisible"); } -bool CmdSketcherBSplineComb::isActive(void) +bool CmdSketcherBSplineComb::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -245,7 +245,7 @@ void CmdSketcherBSplineKnotMultiplicity::activated(int iMsg) ShowRestoreInformationLayer("BSplineKnotMultiplicityVisible"); } -bool CmdSketcherBSplineKnotMultiplicity::isActive(void) +bool CmdSketcherBSplineKnotMultiplicity::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -274,7 +274,7 @@ void CmdSketcherBSplinePoleWeight::activated(int iMsg) ShowRestoreInformationLayer("BSplinePoleWeightVisible"); } -bool CmdSketcherBSplinePoleWeight::isActive(void) +bool CmdSketcherBSplinePoleWeight::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -325,7 +325,7 @@ void CmdSketcherCompBSplineShowHideGeometryInformation::activated(int iMsg) pcAction->setToolTip(a[iMsg]->toolTip()); } -Gui::Action * CmdSketcherCompBSplineShowHideGeometryInformation::createAction(void) +Gui::Action * CmdSketcherCompBSplineShowHideGeometryInformation::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -403,7 +403,7 @@ void CmdSketcherCompBSplineShowHideGeometryInformation::updateAction(int /*mode* { } -bool CmdSketcherCompBSplineShowHideGeometryInformation::isActive(void) +bool CmdSketcherCompBSplineShowHideGeometryInformation::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -477,7 +477,7 @@ void CmdSketcherConvertToNURBS::activated(int iMsg) tryAutoRecomputeIfNotSolve(Obj); } -bool CmdSketcherConvertToNURBS::isActive(void) +bool CmdSketcherConvertToNURBS::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), true); } @@ -549,7 +549,7 @@ void CmdSketcherIncreaseDegree::activated(int iMsg) getSelection().clearSelection(); } -bool CmdSketcherIncreaseDegree::isActive(void) +bool CmdSketcherIncreaseDegree::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), true); } @@ -627,7 +627,7 @@ void CmdSketcherDecreaseDegree::activated(int iMsg) getSelection().clearSelection(); } -bool CmdSketcherDecreaseDegree::isActive(void) +bool CmdSketcherDecreaseDegree::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), true); } @@ -766,7 +766,7 @@ void CmdSketcherIncreaseKnotMultiplicity::activated(int iMsg) getSelection().clearSelection(); } -bool CmdSketcherIncreaseKnotMultiplicity::isActive(void) +bool CmdSketcherIncreaseKnotMultiplicity::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), true); } @@ -889,7 +889,7 @@ void CmdSketcherDecreaseKnotMultiplicity::activated(int iMsg) getSelection().clearSelection(); } -bool CmdSketcherDecreaseKnotMultiplicity::isActive(void) +bool CmdSketcherDecreaseKnotMultiplicity::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), true); } @@ -934,7 +934,7 @@ void CmdSketcherCompModifyKnotMultiplicity::activated(int iMsg) pcAction->setIcon(a[iMsg]->icon()); } -Gui::Action * CmdSketcherCompModifyKnotMultiplicity::createAction(void) +Gui::Action * CmdSketcherCompModifyKnotMultiplicity::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -984,7 +984,7 @@ void CmdSketcherCompModifyKnotMultiplicity::updateAction(int /*mode*/) { } -bool CmdSketcherCompModifyKnotMultiplicity::isActive(void) +bool CmdSketcherCompModifyKnotMultiplicity::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), false); } @@ -1124,7 +1124,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_InsertKnot"); } @@ -1167,7 +1167,7 @@ void CmdSketcherInsertKnot::activated(int iMsg) // get the needed lists and objects const std::vector &SubNames = selection[0].getSubNames(); - if (SubNames.size() == 0) { + if (SubNames.empty()) { // Check that only one object is selected, // as we need only one object to get the new GeoId after multiplicity change QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Selection is empty"), @@ -1192,12 +1192,12 @@ void CmdSketcherInsertKnot::activated(int iMsg) getSelection().clearSelection(); } -bool CmdSketcherInsertKnot::isActive(void) +bool CmdSketcherInsertKnot::isActive() { return isSketcherBSplineActive(getActiveGuiDocument(), true); } -void CreateSketcherCommandsBSpline(void) +void CreateSketcherCommandsBSpline() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp b/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp index ccf7d7b403..be5131ec2c 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherTools.cpp @@ -133,7 +133,7 @@ void CmdSketcherSelectConstraints::activated(int iMsg) } -bool CmdSketcherSelectConstraints::isActive(void) +bool CmdSketcherSelectConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -179,7 +179,7 @@ void CmdSketcherSelectOrigin::activated(int iMsg) Gui::Selection().addSelection(doc_name.c_str(), obj_name.c_str(), ss.str().c_str()); } -bool CmdSketcherSelectOrigin::isActive(void) +bool CmdSketcherSelectOrigin::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -223,7 +223,7 @@ void CmdSketcherSelectVerticalAxis::activated(int iMsg) Gui::Selection().addSelection(doc_name.c_str(), obj_name.c_str(), ss.str().c_str()); } -bool CmdSketcherSelectVerticalAxis::isActive(void) +bool CmdSketcherSelectVerticalAxis::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -267,7 +267,7 @@ void CmdSketcherSelectHorizontalAxis::activated(int iMsg) Gui::Selection().addSelection(doc_name.c_str(), obj_name.c_str(), ss.str().c_str()); } -bool CmdSketcherSelectHorizontalAxis::isActive(void) +bool CmdSketcherSelectHorizontalAxis::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -324,7 +324,7 @@ void CmdSketcherSelectRedundantConstraints::activated(int iMsg) Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), constraintSubNames); } -bool CmdSketcherSelectRedundantConstraints::isActive(void) +bool CmdSketcherSelectRedundantConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -380,7 +380,7 @@ void CmdSketcherSelectMalformedConstraints::activated(int iMsg) Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), constraintSubNames); } -bool CmdSketcherSelectMalformedConstraints::isActive(void) +bool CmdSketcherSelectMalformedConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -436,7 +436,7 @@ void CmdSketcherSelectPartiallyRedundantConstraints::activated(int iMsg) Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), constraintSubNames); } -bool CmdSketcherSelectPartiallyRedundantConstraints::isActive(void) +bool CmdSketcherSelectPartiallyRedundantConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -491,7 +491,7 @@ void CmdSketcherSelectConflictingConstraints::activated(int iMsg) Gui::Selection().addSelections(doc_name.c_str(), obj_name.c_str(), constraintSubNames); } -bool CmdSketcherSelectConflictingConstraints::isActive(void) +bool CmdSketcherSelectConflictingConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -612,7 +612,7 @@ void CmdSketcherSelectElementsAssociatedWithConstraints::activated(int iMsg) } -bool CmdSketcherSelectElementsAssociatedWithConstraints::isActive(void) +bool CmdSketcherSelectElementsAssociatedWithConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -703,7 +703,7 @@ void CmdSketcherSelectElementsWithDoFs::activated(int iMsg) } -bool CmdSketcherSelectElementsWithDoFs::isActive(void) +bool CmdSketcherSelectElementsWithDoFs::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -816,7 +816,7 @@ void CmdSketcherRestoreInternalAlignmentGeometry::activated(int iMsg) } } -bool CmdSketcherRestoreInternalAlignmentGeometry::isActive(void) +bool CmdSketcherRestoreInternalAlignmentGeometry::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -1018,7 +1018,7 @@ void CmdSketcherSymmetry::activated(int iMsg) tryAutoRecomputeIfNotSolve(Obj); } -bool CmdSketcherSymmetry::isActive(void) +bool CmdSketcherSymmetry::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -1032,7 +1032,7 @@ public: Clone, Move }; - SketcherCopy(const char* name); + explicit SketcherCopy(const char* name); void activate(SketcherCopy::Op op); virtual void activate() = 0; }; @@ -1094,7 +1094,7 @@ public: { } - virtual ~DrawSketchHandlerCopy(){} + ~DrawSketchHandlerCopy() override{} /// mode table enum SelectMode { STATUS_SEEK_First, /**< enum value ----. */ @@ -1106,7 +1106,7 @@ public: Snap5Degree }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { @@ -1139,7 +1139,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d) override + bool pressButton(Base::Vector2d) override { if (Mode == STATUS_SEEK_First) { drawEdit(EditCurve); @@ -1148,7 +1148,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode == STATUS_End) @@ -1181,13 +1181,13 @@ public: if (Op != SketcherCopy::Move) { // add auto constraints for the destination copy - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, currentgeoid+nElements, OriginPos); sugConstr1.clear(); } } else { - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, OriginGeoId, OriginPos); sugConstr1.clear(); } @@ -1203,7 +1203,7 @@ public: return true; } private: - virtual void activated() override + void activated() override { setCursor(QPixmap(cursor_createcopy), 7, 7); Origin = static_cast(sketchgui->getObject())->getPoint(OriginGeoId, OriginPos); @@ -1351,13 +1351,13 @@ class CmdSketcherCopy : public SketcherCopy { public: CmdSketcherCopy(); - virtual ~CmdSketcherCopy(){} - virtual const char* className() const + ~CmdSketcherCopy() override{} + const char* className() const override { return "CmdSketcherCopy"; } - virtual void activate(); + void activate() override; protected: - virtual void activated(int iMsg); - virtual bool isActive(void); + void activated(int iMsg) override; + bool isActive() override; }; CmdSketcherCopy::CmdSketcherCopy() @@ -1386,7 +1386,7 @@ void CmdSketcherCopy::activate() SketcherCopy::activate(SketcherCopy::Copy); } -bool CmdSketcherCopy::isActive(void) +bool CmdSketcherCopy::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -1397,13 +1397,13 @@ class CmdSketcherClone : public SketcherCopy { public: CmdSketcherClone(); - virtual ~CmdSketcherClone(){} - virtual const char* className() const + ~CmdSketcherClone() override{} + const char* className() const override { return "CmdSketcherClone"; } - virtual void activate(); + void activate() override; protected: - virtual void activated(int iMsg); - virtual bool isActive(void); + void activated(int iMsg) override; + bool isActive() override; }; CmdSketcherClone::CmdSketcherClone() @@ -1431,7 +1431,7 @@ void CmdSketcherClone::activate() SketcherCopy::activate(SketcherCopy::Clone); } -bool CmdSketcherClone::isActive(void) +bool CmdSketcherClone::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -1440,13 +1440,13 @@ class CmdSketcherMove : public SketcherCopy { public: CmdSketcherMove(); - virtual ~CmdSketcherMove(){} - virtual const char* className() const + ~CmdSketcherMove() override{} + const char* className() const override { return "CmdSketcherMove"; } - virtual void activate(); + void activate() override; protected: - virtual void activated(int iMsg); - virtual bool isActive(void); + void activated(int iMsg) override; + bool isActive() override; }; CmdSketcherMove::CmdSketcherMove() @@ -1474,7 +1474,7 @@ void CmdSketcherMove::activate() SketcherCopy::activate(SketcherCopy::Move); } -bool CmdSketcherMove::isActive(void) +bool CmdSketcherMove::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -1526,7 +1526,7 @@ void CmdSketcherCompCopy::activated(int iMsg) } } -Gui::Action * CmdSketcherCompCopy::createAction(void) +Gui::Action * CmdSketcherCompCopy::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1574,7 +1574,7 @@ void CmdSketcherCompCopy::languageChange() move->setStatusTip(QApplication::translate("Sketcher_Move","Moves the geometry taking as reference the last selected point")); } -bool CmdSketcherCompCopy::isActive(void) +bool CmdSketcherCompCopy::isActive() { return isCommandActive( getActiveGuiDocument(), true ); } @@ -1643,7 +1643,7 @@ public: { } - virtual ~DrawSketchHandlerRectangularArray(){} + ~DrawSketchHandlerRectangularArray() override{} /// mode table enum SelectMode { STATUS_SEEK_First, /**< enum value ----. */ @@ -1655,7 +1655,7 @@ public: Snap5Degree }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { @@ -1690,7 +1690,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d) override + bool pressButton(Base::Vector2d) override { if (Mode == STATUS_SEEK_First) { drawEdit(EditCurve); @@ -1699,7 +1699,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode == STATUS_End) { @@ -1725,7 +1725,7 @@ public: } // add auto constraints for the destination copy - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, OriginGeoId+nElements, OriginPos); sugConstr1.clear(); } @@ -1740,7 +1740,7 @@ public: return true; } private: - virtual void activated() override + void activated() override { setCursor(QPixmap(cursor_createrectangulararray), 7, 7); Origin = static_cast(sketchgui->getObject())->getPoint(OriginGeoId, OriginPos); @@ -1896,7 +1896,7 @@ void CmdSketcherRectangularArray::activated(int iMsg) } } -bool CmdSketcherRectangularArray::isActive(void) +bool CmdSketcherRectangularArray::isActive() { return isCommandActive(getActiveGuiDocument(), true); } @@ -1959,7 +1959,7 @@ void CmdSketcherDeleteAllGeometry::activated(int iMsg) } } -bool CmdSketcherDeleteAllGeometry::isActive(void) +bool CmdSketcherDeleteAllGeometry::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -2022,7 +2022,7 @@ void CmdSketcherDeleteAllConstraints::activated(int iMsg) } -bool CmdSketcherDeleteAllConstraints::isActive(void) +bool CmdSketcherDeleteAllConstraints::isActive() { return isCommandActive(getActiveGuiDocument(), false); } @@ -2140,12 +2140,12 @@ void CmdSketcherRemoveAxesAlignment::activated(int iMsg) } -bool CmdSketcherRemoveAxesAlignment::isActive(void) +bool CmdSketcherRemoveAxesAlignment::isActive() { return isCommandActive(getActiveGuiDocument(), true); } -void CreateSketcherCommandsConstraintAccel(void) +void CreateSketcherCommandsConstraintAccel() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp b/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp index 5311c42768..fc28768b62 100644 --- a/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp +++ b/src/Mod/Sketcher/Gui/CommandSketcherVirtualSpace.cpp @@ -182,12 +182,12 @@ void CmdSketcherSwitchVirtualSpace::activated(int iMsg) } } -bool CmdSketcherSwitchVirtualSpace::isActive(void) +bool CmdSketcherSwitchVirtualSpace::isActive() { return isSketcherVirtualSpaceActive(getActiveGuiDocument(), false); } -void CreateSketcherCommandsVirtualSpace(void) +void CreateSketcherCommandsVirtualSpace() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Sketcher/Gui/ConstraintFilters.h b/src/Mod/Sketcher/Gui/ConstraintFilters.h index c5158ce917..dc4c571eb3 100644 --- a/src/Mod/Sketcher/Gui/ConstraintFilters.h +++ b/src/Mod/Sketcher/Gui/ConstraintFilters.h @@ -108,7 +108,7 @@ namespace ConstraintFilter { return (... | (1 << static_cast>(args))); } - /// Array of FilterValue bit sets of size the the number of FilterValues indicating for each FilterValue, which other + /// Array of FilterValue bit sets of size of the number of FilterValues indicating for each FilterValue, which other /// FilterValues are comprised therein. It defines the dependencies between filters. constexpr std::array< FilterValueBitset, FilterValueLength> filterAggregates { buildBitset(FilterValue::All, FilterValue::Geometric, FilterValue::Datums, FilterValue::Named, FilterValue::NonDriving, FilterValue::Horizontal, diff --git a/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.cpp b/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.cpp index db57c3a17e..8cc4fc0147 100644 --- a/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.cpp +++ b/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.cpp @@ -37,7 +37,7 @@ using namespace SketcherGui; -ConstraintMultiFilterDialog::ConstraintMultiFilterDialog(void) +ConstraintMultiFilterDialog::ConstraintMultiFilterDialog() : QDialog(Gui::getMainWindow()), ui(new Ui_ConstraintMultiFilterDialog) { ui->setupUi(this); diff --git a/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.h b/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.h index a3ccdebe15..5b97159634 100644 --- a/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.h +++ b/src/Mod/Sketcher/Gui/ConstraintMultiFilterDialog.h @@ -37,8 +37,8 @@ class ConstraintMultiFilterDialog : public QDialog Q_OBJECT public: - ConstraintMultiFilterDialog(void); - ~ConstraintMultiFilterDialog(); + ConstraintMultiFilterDialog(); + ~ConstraintMultiFilterDialog() override; void setMultiFilter(const FilterValueBitset & bitset); FilterValueBitset getMultiFilter(); diff --git a/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.cpp b/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.cpp index b107047610..cb6e479e84 100644 --- a/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.cpp +++ b/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.cpp @@ -38,7 +38,7 @@ using namespace SketcherGui; -ConstraintSettingsDialog::ConstraintSettingsDialog(void) +ConstraintSettingsDialog::ConstraintSettingsDialog() : QDialog(Gui::getMainWindow()), ui(new Ui_ConstraintSettingsDialog) { ui->setupUi(this); diff --git a/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.h b/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.h index e190692ddd..103f22504c 100644 --- a/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.h +++ b/src/Mod/Sketcher/Gui/ConstraintSettingsDialog.h @@ -37,8 +37,8 @@ class ConstraintSettingsDialog : public QDialog Q_OBJECT public: - ConstraintSettingsDialog(void); - ~ConstraintSettingsDialog(); + ConstraintSettingsDialog(); + ~ConstraintSettingsDialog() override; Q_SIGNALS: void emit_filterInternalAlignment_stateChanged(int); @@ -46,8 +46,8 @@ Q_SIGNALS: void emit_visualisationTrackingFilter_stateChanged(int); public Q_SLOTS: - void accept(); - void reject(); + void accept() override; + void reject() override; void on_filterInternalAlignment_stateChanged(int state); void on_extendedInformation_stateChanged(int state); void on_visualisationTrackingFilter_stateChanged(int state); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp index 9723b199a1..73279f8d23 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.cpp @@ -796,7 +796,7 @@ void DrawSketchHandler::createAutoConstraints(const std::vector if (!sketchgui->Autoconstraints.getValue()) return; // If Autoconstraints property is not set quit - if (autoConstrs.size() > 0) { + if (!autoConstrs.empty()) { if(createowncommand) { // Open the Command diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandler.h b/src/Mod/Sketcher/Gui/DrawSketchHandler.h index fbd82d908d..455f162d3c 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandler.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandler.h @@ -61,7 +61,7 @@ private: void updateCurvedEdgeCountSegmentsParameter(); /** Observer for parameter group. */ - virtual void OnChange(Base::Subject &rCaller, const char * sReason) override; + void OnChange(Base::Subject &rCaller, const char * sReason) override; private: int curvedEdgeCountSegments; @@ -123,14 +123,14 @@ public: virtual bool onSelectionChanged(const Gui::SelectionChanges&) { return false; } virtual void registerPressedKey(bool /*pressed*/, int /*key*/){} - virtual void quit(void); + virtual void quit(); friend class ViewProviderSketch; // get the actual highest vertex index, the next use will be +1 - int getHighestVertexIndex(void); + int getHighestVertexIndex(); // get the actual highest edge index, the next use will be +1 - int getHighestCurveIndex(void); + int getHighestCurveIndex(); int seekAutoConstraint(std::vector &suggestedConstraints, const Base::Vector2d &Pos, const Base::Vector2d &Dir, @@ -142,7 +142,7 @@ public: void setPositionText(const Base::Vector2d &Pos, const SbString &text); void setPositionText(const Base::Vector2d &Pos); - void resetPositionText(void); + void resetPositionText(); void renderSuggestConstraintsCursor(std::vector &suggestedConstraints); private: // NVI @@ -172,10 +172,10 @@ protected: void updateCursor(); /// restitutes the cursor that was in use at the moment of starting the DrawSketchHandler (i.e. oldCursor) - void unsetCursor(void); + void unsetCursor(); /// restitutes the DSH cached cursor (e.g. without any tail due to autoconstraints, ...) - void applyCursor(void); + void applyCursor(); /// returns the color to be used for the crosshair (configurable as a parameter) unsigned long getCrosshairColor(); @@ -196,9 +196,9 @@ protected: void drawPositionAtCursor(const Base::Vector2d & position); void drawDirectionAtCursor(const Base::Vector2d & position, const Base::Vector2d & origin); - int getPreselectPoint(void) const; - int getPreselectCurve(void) const; - int getPreselectCross(void) const; + int getPreselectPoint() const; + int getPreselectCurve() const; + int getPreselectCross() const; Sketcher::SketchObject * getSketchObject(); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h index a8224fc7e9..64653e4222 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArc.h @@ -56,7 +56,7 @@ public: STATUS_End }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -120,7 +120,7 @@ public: } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ CenterPoint = onSketchPos; @@ -159,7 +159,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode==STATUS_End) { @@ -182,19 +182,19 @@ public: } // Auto Constraint center point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::mid); sugConstr1.clear(); } // Auto Constraint first picked point - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex(), (arcAngle > 0) ? Sketcher::PointPos::start : Sketcher::PointPos::end ); sugConstr2.clear(); } // Auto Constraint second picked point - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, getHighestCurveIndex(), (arcAngle > 0) ? Sketcher::PointPos::end : Sketcher::PointPos::start); sugConstr3.clear(); } @@ -224,7 +224,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Arc"); } @@ -256,7 +256,7 @@ public: STATUS_End }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -371,7 +371,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ // 32 point curve + center + endpoint @@ -399,7 +399,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); // Need to look at. rx might need fixing. @@ -423,19 +423,19 @@ public: } // Auto Constraint first picked point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex(), arcPos1); sugConstr1.clear(); } // Auto Constraint second picked point - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex(), arcPos2); sugConstr2.clear(); } // Auto Constraint third picked point - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, getHighestCurveIndex(), Sketcher::PointPos::none); sugConstr3.clear(); } @@ -464,7 +464,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_3PointArc"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h index 905b171f27..18330f3c67 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfEllipse.h @@ -51,7 +51,7 @@ public: STATUS_Close }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -161,7 +161,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ EditCurve[0] = onSketchPos; @@ -187,7 +187,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode==STATUS_Close) { @@ -275,25 +275,25 @@ public: Gui::Command::commitCommand(); // add auto constraints for the center point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, currentgeoid, Sketcher::PointPos::mid); sugConstr1.clear(); } // add suggested constraints for arc - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, currentgeoid, Sketcher::PointPos::none); sugConstr2.clear(); } // add suggested constraints for start of arc - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::start:Sketcher::PointPos::end); sugConstr3.clear(); } // add suggested constraints for start of arc - if (sugConstr4.size() > 0) { + if (!sugConstr4.empty()) { createAutoConstraints(sugConstr4, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::end:Sketcher::PointPos::start); sugConstr4.clear(); } @@ -322,7 +322,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_ArcOfEllipse"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h index 3bb3c9dd62..9d313fcd39 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfHyperbola.h @@ -51,7 +51,7 @@ public: STATUS_Close }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -162,7 +162,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ EditCurve[0] = onSketchPos; @@ -190,7 +190,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d /*onSketchPos*/) override + bool releaseButton(Base::Vector2d /*onSketchPos*/) override { if (Mode==STATUS_Close) { unsetCursor(); @@ -288,25 +288,25 @@ public: Gui::Command::commitCommand(); // add auto constraints for the center point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, currentgeoid, Sketcher::PointPos::mid); sugConstr1.clear(); } // add suggested constraints for arc - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, currentgeoid, Sketcher::PointPos::none); sugConstr2.clear(); } // add suggested constraints for start of arc - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::start:Sketcher::PointPos::end); sugConstr3.clear(); } // add suggested constraints for start of arc - if (sugConstr4.size() > 0) { + if (!sugConstr4.empty()) { createAutoConstraints(sugConstr4, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::end:Sketcher::PointPos::start); sugConstr4.clear(); } @@ -336,7 +336,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_ArcOfHyperbola"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h index 43ca50c27f..c400af0097 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerArcOfParabola.h @@ -54,7 +54,7 @@ public: STATUS_Close }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -161,7 +161,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ EditCurve[0] = onSketchPos; @@ -188,7 +188,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d /*onSketchPos*/) override + bool releaseButton(Base::Vector2d /*onSketchPos*/) override { if (Mode==STATUS_Close) { unsetCursor(); @@ -246,25 +246,25 @@ public: Gui::Command::commitCommand(); // add auto constraints for the focus point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, currentgeoid+1, Sketcher::PointPos::start); sugConstr1.clear(); } // add suggested constraints for vertex point - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, currentgeoid, Sketcher::PointPos::mid); sugConstr2.clear(); } // add suggested constraints for start of arc - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::start:Sketcher::PointPos::end); sugConstr3.clear(); } // add suggested constraints for start of arc - if (sugConstr4.size() > 0) { + if (!sugConstr4.empty()) { createAutoConstraints(sugConstr4, currentgeoid, isOriginalArcCCW?Sketcher::PointPos::end:Sketcher::PointPos::start); sugConstr4.clear(); } @@ -293,7 +293,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_ArcOfParabola"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h index 704c91a3fe..30655db9e8 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerBSpline.h @@ -35,7 +35,7 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo class DrawSketchHandlerBSpline: public DrawSketchHandler { public: - DrawSketchHandlerBSpline(int constructionMethod) + explicit DrawSketchHandlerBSpline(int constructionMethod) : Mode(STATUS_SEEK_FIRST_CONTROLPOINT) , MousePressMode(MOUSE_NOT_PRESSED) , ConstrMethod(constructionMethod) @@ -63,7 +63,7 @@ public: MOUSE_NOT_PRESSED }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { prevCursorPosition = onSketchPos; @@ -88,7 +88,7 @@ public: } } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { prevCursorPosition = onSketchPos; @@ -126,7 +126,7 @@ public: //static_cast(sketchgui->getObject())->solve(); // add auto constraints on pole - if (sugConstr.back().size() > 0) { + if (!sugConstr.back().empty()) { createAutoConstraints(sugConstr.back(), poleGeoIds.back(), Sketcher::PointPos::mid, false); } @@ -185,7 +185,7 @@ public: //static_cast(sketchgui->getObject())->solve(); // add auto constraints on pole - if (sugConstr.back().size() > 0) { + if (!sugConstr.back().empty()) { createAutoConstraints(sugConstr.back(), poleGeoIds.back(), Sketcher::PointPos::mid, false); } @@ -199,7 +199,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { prevCursorPosition = onSketchPos; MousePressMode = MOUSE_NOT_PRESSED; @@ -207,7 +207,7 @@ public: return finishCommand(onSketchPos); } - virtual void registerPressedKey(bool pressed, int key) override + void registerPressedKey(bool pressed, int key) override { if (SoKeyboardEvent::D == key && pressed) { SplineDegree = QInputDialog::getInt( @@ -281,7 +281,7 @@ public: return; } - virtual void quit(void) override + void quit() override { // We must see if we need to create a B-spline before cancelling everything // and now just like any other Handler, @@ -335,7 +335,7 @@ private: IsClosed = false; } - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_BSpline"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h index ef5ea909d9..7e1c44a1b3 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCarbonCopy.h @@ -36,7 +36,7 @@ class CarbonCopySelection : public Gui::SelectionFilterGate { App::DocumentObject* object; public: - CarbonCopySelection(App::DocumentObject* obj) + explicit CarbonCopySelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()), object(obj) {} @@ -97,20 +97,20 @@ public: Gui::Selection().rmvSelectionGate(); } - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Gui::Selection().getPreselection().pObjectName) applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); /* this is ok not to call to purgeHandler @@ -120,11 +120,11 @@ public: return true; } - virtual bool onSelectionChanged(const Gui::SelectionChanges& msg) override + bool onSelectionChanged(const Gui::SelectionChanges& msg) override { if (msg.Type == Gui::SelectionChanges::AddSelection) { App::DocumentObject* obj = sketchgui->getObject()->getDocument()->getObject(msg.pObjectName); - if (obj == nullptr) + if (!obj) throw Base::ValueError("Sketcher: Carbon Copy: Invalid object in selection"); if (obj->getTypeId() == Sketcher::SketchObject::getClassTypeId()) { @@ -155,7 +155,7 @@ public: } private: - virtual void activated() override + void activated() override { setAxisPickStyle(false); Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); @@ -170,11 +170,11 @@ private: Gui::Selection().addSelectionGate(new CarbonCopySelection(sketchgui->getObject())); } - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_CarbonCopy"); } - virtual void deactivated() override + void deactivated() override { Q_UNUSED(sketchgui); setAxisPickStyle(true); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h index 3f5a875e22..0024dcd7b6 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerCircle.h @@ -44,7 +44,7 @@ public: STATUS_Close }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -82,7 +82,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ EditCurve[0] = onSketchPos; @@ -94,7 +94,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode==STATUS_Close) { @@ -119,13 +119,13 @@ public: } // add auto constraints for the center point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::mid); sugConstr1.clear(); } // add suggested constraints for circumference - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex(), Sketcher::PointPos::none); sugConstr2.clear(); } @@ -154,7 +154,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Circle"); } @@ -180,7 +180,7 @@ public: STATUS_End }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -239,7 +239,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { // N point curve + center + endpoint @@ -264,7 +264,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); // Need to look at. rx might need fixing. @@ -288,19 +288,19 @@ public: } // Auto Constraint first picked point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::none); sugConstr1.clear(); } // Auto Constraint second picked point - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex(), Sketcher::PointPos::none); sugConstr2.clear(); } // Auto Constraint third picked point - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, getHighestCurveIndex(), Sketcher::PointPos::none); sugConstr3.clear(); } @@ -329,7 +329,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_3PointCircle"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h index 342048cc7f..5b322213fe 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerEllipse.h @@ -75,7 +75,7 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo class DrawSketchHandlerEllipse : public DrawSketchHandler { public: - DrawSketchHandlerEllipse(int constructionMethod) + explicit DrawSketchHandlerEllipse(int constructionMethod) : mode(STATUS_Close) , method(CENTER_PERIAPSIS_B) , constrMethod(constructionMethod) @@ -104,7 +104,7 @@ public: * @brief Updates the ellipse when the cursor moves * @param onSketchPos the position of the cursor on the sketch */ - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (method == PERIAPSIS_APOAPSIS_B) { if (mode == STATUS_SEEK_PERIAPSIS) { @@ -196,7 +196,7 @@ public: * @param onSketchPos the position of the cursor on the sketch * @return */ - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (method == PERIAPSIS_APOAPSIS_B) { if (mode == STATUS_SEEK_PERIAPSIS) { @@ -231,7 +231,7 @@ public: * @param onSketchPos the position of the cursor on the sketch * @return */ - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (mode == STATUS_Close) { @@ -257,7 +257,7 @@ private: * @brief Slot called when the create ellipse command is activated * @param sketchgui A pointer to the active sketch */ - virtual void activated() override + void activated() override { if (constrMethod == 0) { method = CENTER_PERIAPSIS_B; @@ -267,7 +267,7 @@ private: mode = STATUS_SEEK_PERIAPSIS; } } - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Ellipse"); } @@ -739,30 +739,30 @@ private: if (method == CENTER_PERIAPSIS_B) { // add auto constraints for the center point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, currentgeoid, Sketcher::PointPos::mid); sugConstr1.clear(); } - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, currentgeoid, Sketcher::PointPos::none); sugConstr2.clear(); } - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, currentgeoid, Sketcher::PointPos::none); sugConstr3.clear(); } } if (method == PERIAPSIS_APOAPSIS_B) { - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, currentgeoid, Sketcher::PointPos::none); sugConstr1.clear(); } - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, currentgeoid, Sketcher::PointPos::none); sugConstr2.clear(); } - if (sugConstr3.size() > 0) { + if (!sugConstr3.empty()) { createAutoConstraints(sugConstr3, currentgeoid, Sketcher::PointPos::none); sugConstr3.clear(); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h index 5c4e704a97..cd4a736d9e 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExtend.h @@ -36,7 +36,7 @@ class ExtendSelection : public Gui::SelectionFilterGate { App::DocumentObject* object; public: - ExtendSelection(App::DocumentObject* obj) + explicit ExtendSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()) , object(obj) , disabled(false) @@ -90,7 +90,7 @@ public: STATUS_SEEK_Second, }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode == STATUS_SEEK_Second) { @@ -203,13 +203,13 @@ public: } } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode == STATUS_SEEK_First) { @@ -253,7 +253,7 @@ public: Gui::Command::updateActive(); // constrain chosen point - if (SugConstr.size() > 0) { + if (!SugConstr.empty()) { createAutoConstraints(SugConstr, BaseGeoId, (ExtendFromStart) ? Sketcher::PointPos::start : Sketcher::PointPos::end); SugConstr.clear(); } @@ -288,7 +288,7 @@ public: } private: - virtual void activated() override + void activated() override { Gui::Selection().clearSelection(); Gui::Selection().rmvSelectionGate(); @@ -296,7 +296,7 @@ private: Gui::Selection().addSelectionGate(filterGate); } - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Extension"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h index ea0738e8af..cf438a188a 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerExternal.h @@ -36,7 +36,7 @@ class ExternalSelection : public Gui::SelectionFilterGate { App::DocumentObject* object; public: - ExternalSelection(App::DocumentObject* obj) + explicit ExternalSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()), object(obj) {} @@ -99,20 +99,20 @@ public: Gui::Selection().rmvSelectionGate(); } - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Gui::Selection().getPreselection().pObjectName) applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); /* this is ok not to call to purgeHandler @@ -122,11 +122,11 @@ public: return true; } - virtual bool onSelectionChanged(const Gui::SelectionChanges& msg) override + bool onSelectionChanged(const Gui::SelectionChanges& msg) override { if (msg.Type == Gui::SelectionChanges::AddSelection) { App::DocumentObject* obj = sketchgui->getObject()->getDocument()->getObject(msg.pObjectName); - if (obj == nullptr) + if (!obj) throw Base::ValueError("Sketcher: External geometry: Invalid object in selection"); std::string subName(msg.pSubName); if (obj->getTypeId().isDerivedFrom(App::Plane::getClassTypeId()) || @@ -165,7 +165,7 @@ public: } private: - virtual void activated() override + void activated() override { setAxisPickStyle(false); Gui::MDIView *mdi = Gui::Application::Instance->activeDocument()->getActiveView(); @@ -180,11 +180,11 @@ private: Gui::Selection().addSelectionGate(new ExternalSelection(sketchgui->getObject())); } - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_External"); } - virtual void deactivated() override + void deactivated() override { Q_UNUSED(sketchgui); setAxisPickStyle(true); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h index 228171596a..6920eb8858 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerFillet.h @@ -35,7 +35,7 @@ class FilletSelection : public Gui::SelectionFilterGate { App::DocumentObject* object; public: - FilletSelection(App::DocumentObject* obj) + explicit FilletSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()), object(obj) {} @@ -80,7 +80,7 @@ public: ConstraintPreservingFillet }; - DrawSketchHandlerFillet(FilletType filletType) : filletType(filletType), Mode(STATUS_SEEK_First), firstCurve(0) {} + explicit DrawSketchHandlerFillet(FilletType filletType) : filletType(filletType), Mode(STATUS_SEEK_First), firstCurve(0) {} virtual ~DrawSketchHandlerFillet() { Gui::Selection().rmvSelectionGate(); @@ -91,18 +91,18 @@ public: STATUS_SEEK_Second }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { bool construction=false; int VtId = getPreselectPoint(); @@ -270,7 +270,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { Gui::Selection().rmvSelectionGate(); Gui::Selection().addSelectionGate(new FilletSelection(sketchgui->getObject())); diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h index 14fcbe56f1..169bc79e3b 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerLine.h @@ -43,7 +43,7 @@ public: STATUS_End }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { setPositionText(onSketchPos); @@ -69,7 +69,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ EditCurve[0] = onSketchPos; @@ -84,7 +84,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode==STATUS_End){ @@ -147,7 +147,7 @@ public: private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Line"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h index e4afd76a0a..4604e75697 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerLineSet.h @@ -80,7 +80,7 @@ public: SNAP_MODE_45Degree }; - virtual void registerPressedKey(bool pressed, int key) override + void registerPressedKey(bool pressed, int key) override { if (Mode != STATUS_SEEK_Second) return; // SegmentMode can be changed only in STATUS_SEEK_Second mode @@ -159,7 +159,7 @@ public: } } - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { suppressTransition = false; if (Mode==STATUS_SEEK_First) { @@ -285,7 +285,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { @@ -381,7 +381,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { if (Mode == STATUS_Do || Mode == STATUS_Close) { bool addedGeometry = true; @@ -478,7 +478,7 @@ public: } } - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { // exclude any coincidence constraints std::vector sugConstr; for (unsigned int i=0; i < sugConstr2.size(); i++) { @@ -528,7 +528,7 @@ public: Gui::Command::commitCommand(); // Add auto constraints - if (sugConstr1.size() > 0) { // this is relevant only to the very first point + if (!sugConstr1.empty()) { // this is relevant only to the very first point createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr1.clear(); } @@ -545,7 +545,7 @@ public: virtualsugConstr1 = sugConstr2; // these are the initial constraints for the next iteration. - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex(), (SegmentMode == SEGMENT_MODE_Arc && startAngle > endAngle) ? Sketcher::PointPos::start : Sketcher::PointPos::end); @@ -583,7 +583,7 @@ public: return true; } - virtual void quit(void) override { + void quit() override { // We must see if we need to create a B-spline before cancelling everything // and now just like any other Handler, @@ -621,7 +621,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Lineset"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h index 58b35ac46b..b8fbcf6b33 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerPoint.h @@ -37,7 +37,7 @@ public: DrawSketchHandlerPoint() : selectionDone(false) {} virtual ~DrawSketchHandlerPoint() {} - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { setPositionText(onSketchPos); if (seekAutoConstraint(sugConstr, onSketchPos, Base::Vector2d(0.f,0.f))) { @@ -47,14 +47,14 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { EditPoint = onSketchPos; selectionDone = true; return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (selectionDone){ @@ -74,7 +74,7 @@ public: } // add auto constraints for the line segment start - if (sugConstr.size() > 0) { + if (!sugConstr.empty()) { createAutoConstraints(sugConstr, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr.clear(); } @@ -99,7 +99,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Point"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h index f43af0ae62..8e66dd0558 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerPolygon.h @@ -36,7 +36,7 @@ extern GeometryCreationMode geometryCreationMode; // defined in CommandCreateGeo class DrawSketchHandlerRegularPolygon: public DrawSketchHandler { public: - DrawSketchHandlerRegularPolygon( size_t nof_corners ): + explicit DrawSketchHandlerRegularPolygon( size_t nof_corners ): Corners( nof_corners ), AngleOfSeparation( 2.0*M_PI/static_cast(Corners) ), cos_v( cos( AngleOfSeparation ) ), @@ -53,7 +53,7 @@ public: STATUS_End }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { @@ -94,7 +94,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ StartPos = onSketchPos; @@ -106,7 +106,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode==STATUS_End){ @@ -126,13 +126,13 @@ public: Gui::Command::commitCommand(); // add auto constraints at the center of the polygon - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::mid); sugConstr1.clear(); } // add auto constraints to the last side of the polygon - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex() - 1, Sketcher::PointPos::end); sugConstr2.clear(); } @@ -169,7 +169,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Regular_Polygon"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h index 6793433e78..980729db7d 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerRectangle.h @@ -40,7 +40,7 @@ public: CenterAndCorner }; - DrawSketchHandlerBox(ConstructionMethod constrMethod = Diagonal): Mode(STATUS_SEEK_First), + explicit DrawSketchHandlerBox(ConstructionMethod constrMethod = Diagonal): Mode(STATUS_SEEK_First), EditCurve(5), constructionMethod(constrMethod){} virtual ~DrawSketchHandlerBox(){} @@ -54,7 +54,7 @@ public: public: - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First) { @@ -101,7 +101,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode==STATUS_SEEK_First){ if(constructionMethod == Diagonal) { @@ -135,7 +135,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode==STATUS_End){ @@ -232,13 +232,13 @@ public: if(constructionMethod == Diagonal) { // add auto constraints at the start of the first side - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex() - 3 , Sketcher::PointPos::start); sugConstr1.clear(); } // add auto constraints at the end of the second side - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex() - 2, Sketcher::PointPos::end); sugConstr2.clear(); } @@ -246,13 +246,13 @@ public: } else if (constructionMethod == CenterAndCorner) { // add auto constraints at the start of the first side - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr1.clear(); } // add auto constraints at the end of the second side - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex() - 3, Sketcher::PointPos::end); sugConstr2.clear(); } @@ -285,7 +285,7 @@ public: private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Create_Box"); } @@ -314,7 +314,7 @@ public: STATUS_End }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { @@ -341,7 +341,7 @@ public: // we draw the lines with 36 segments, 8 for each arc and 4 lines // draw the arcs for (int i = 0; i < 8; i++) { - // calculate the x,y positions forming the the arc + // calculate the x,y positions forming the arc double angle = i * M_PI / 16.0; double x_i = -radius * sin(angle); double y_i = -radius * cos(angle); @@ -388,7 +388,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { StartPos = onSketchPos; @@ -401,7 +401,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode == STATUS_End) { @@ -525,13 +525,13 @@ public: Gui::Command::commitCommand(); // add auto constraints at the StartPos auxiliary point - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex() - 1, Sketcher::PointPos::start); sugConstr1.clear(); } // add auto constraints at the EndPos auxiliary point - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex(), Sketcher::PointPos::start); sugConstr2.clear(); } @@ -567,7 +567,7 @@ public: } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Oblong"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h index 6965aa2b41..b763db6248 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSlot.h @@ -62,7 +62,7 @@ public: SNAP_DIR_Vert }; - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { @@ -132,7 +132,7 @@ public: applyCursor(); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { if (Mode == STATUS_SEEK_First) { StartPos = onSketchPos; @@ -144,7 +144,7 @@ public: return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); if (Mode == STATUS_End) { @@ -241,13 +241,13 @@ public: Gui::Command::commitCommand(); // add auto constraints at the center of the first arc - if (sugConstr1.size() > 0) { + if (!sugConstr1.empty()) { createAutoConstraints(sugConstr1, getHighestCurveIndex() - 3, Sketcher::PointPos::mid); sugConstr1.clear(); } // add auto constraints at the center of the second arc - if (sugConstr2.size() > 0) { + if (!sugConstr2.empty()) { createAutoConstraints(sugConstr2, getHighestCurveIndex() - 2, Sketcher::PointPos::mid); sugConstr2.clear(); } @@ -283,7 +283,7 @@ public: return true; } private: - virtual QString getCrosshairCursorSVGName() const override + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Slot"); } diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h index b3108a6357..9a0630ea78 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerSplitting.h @@ -37,7 +37,7 @@ class SplittingSelection : public Gui::SelectionFilterGate { App::DocumentObject* object; public: - SplittingSelection(App::DocumentObject* obj) + explicit SplittingSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()), object(obj) {} @@ -72,18 +72,18 @@ public: Gui::Selection().rmvSelectionGate(); } - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { int GeoId = getPreselectCurve(); if (GeoId >= 0) { @@ -112,14 +112,14 @@ public: } private: - virtual void activated() override + void activated() override { Gui::Selection().clearSelection(); Gui::Selection().rmvSelectionGate(); Gui::Selection().addSelectionGate(new SplittingSelection(sketchgui->getObject())); } - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Splitting"); } }; diff --git a/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h b/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h index 9e27b166cf..bee6475dfb 100644 --- a/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h +++ b/src/Mod/Sketcher/Gui/DrawSketchHandlerTrimming.h @@ -36,7 +36,7 @@ class TrimmingSelection : public Gui::SelectionFilterGate { App::DocumentObject* object; public: - TrimmingSelection(App::DocumentObject* obj) + explicit TrimmingSelection(App::DocumentObject* obj) : Gui::SelectionFilterGate(nullPointer()), object(obj) {} @@ -74,7 +74,7 @@ public: Gui::Selection().rmvSelectionGate(); } - virtual void mouseMove(Base::Vector2d onSketchPos) override + void mouseMove(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); @@ -113,13 +113,13 @@ public: } } - virtual bool pressButton(Base::Vector2d onSketchPos) override + bool pressButton(Base::Vector2d onSketchPos) override { Q_UNUSED(onSketchPos); return true; } - virtual bool releaseButton(Base::Vector2d onSketchPos) override + bool releaseButton(Base::Vector2d onSketchPos) override { int GeoId = getPreselectCurve(); if (GeoId > -1) { @@ -151,14 +151,14 @@ public: } private: - virtual void activated() override + void activated() override { Gui::Selection().clearSelection(); Gui::Selection().rmvSelectionGate(); Gui::Selection().addSelectionGate(new TrimmingSelection(sketchgui->getObject())); } - virtual QString getCrosshairCursorSVGName() const override { + QString getCrosshairCursorSVGName() const override { return QString::fromLatin1("Sketcher_Pointer_Trimming"); } diff --git a/src/Mod/Sketcher/Gui/EditDatumDialog.cpp b/src/Mod/Sketcher/Gui/EditDatumDialog.cpp index 4314709036..e46539589d 100644 --- a/src/Mod/Sketcher/Gui/EditDatumDialog.cpp +++ b/src/Mod/Sketcher/Gui/EditDatumDialog.cpp @@ -85,7 +85,7 @@ void EditDatumDialog::exec(bool atCursor) Base::Quantity init_val; QDialog dlg(Gui::getMainWindow()); - if (ui_ins_datum == nullptr) { + if (!ui_ins_datum) { ui_ins_datum.reset(new Ui_InsertDatum); ui_ins_datum->setupUi(&dlg); } @@ -244,7 +244,7 @@ void EditDatumDialog::drivingToggled(bool state) void EditDatumDialog::datumChanged() { - if (ui_ins_datum->labelEdit->text() != ui_ins_datum->labelEdit->getHistory()[0]) { + if (ui_ins_datum->labelEdit->text() != qAsConst(ui_ins_datum->labelEdit)->getHistory()[0]) { ui_ins_datum->cbDriving->setChecked(false); } } diff --git a/src/Mod/Sketcher/Gui/EditDatumDialog.h b/src/Mod/Sketcher/Gui/EditDatumDialog.h index 5e009a0d61..0f28dbcde2 100644 --- a/src/Mod/Sketcher/Gui/EditDatumDialog.h +++ b/src/Mod/Sketcher/Gui/EditDatumDialog.h @@ -40,7 +40,7 @@ class EditDatumDialog : public QObject { public: EditDatumDialog(ViewProviderSketch* vp, int ConstrNbr); EditDatumDialog(Sketcher::SketchObject* pcSketch, int ConstrNbr); - ~EditDatumDialog(); + ~EditDatumDialog() override; void exec(bool atCursor=true); diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp index 88988058ce..ce44190052 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.cpp @@ -497,7 +497,7 @@ void EditModeCoinManager::setPositionText(const Base::Vector2d &Pos) setPositionText(Pos,text); } -void EditModeCoinManager::resetPositionText(void) +void EditModeCoinManager::resetPositionText() { editModeScenegraphNodes.textX->string = ""; } diff --git a/src/Mod/Sketcher/Gui/EditModeCoinManager.h b/src/Mod/Sketcher/Gui/EditModeCoinManager.h index fb30f63631..77e2a76bb4 100644 --- a/src/Mod/Sketcher/Gui/EditModeCoinManager.h +++ b/src/Mod/Sketcher/Gui/EditModeCoinManager.h @@ -117,8 +117,8 @@ class SketcherGuiExport EditModeCoinManager }; public: - ParameterObserver(EditModeCoinManager & client); - ~ParameterObserver(); + explicit ParameterObserver(EditModeCoinManager & client); + ~ParameterObserver() override; void subscribeToParameters(); @@ -194,7 +194,7 @@ public: void drawEdit(const std::list> &list); void setPositionText(const Base::Vector2d &Pos, const SbString &txt); void setPositionText(const Base::Vector2d &Pos); - void resetPositionText(void); + void resetPositionText(); void setAxisPickStyle(bool on); //@} diff --git a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp index 58d1e77209..fdea96b2bd 100644 --- a/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp +++ b/src/Mod/Sketcher/Gui/EditModeConstraintCoinManager.cpp @@ -1394,7 +1394,7 @@ void EditModeConstraintCoinManager::updateConstraintColor(const std::vectoricons/geometry/Sketcher_CreateBSpline_Constr.svg icons/geometry/Sketcher_CreateCircle.svg icons/geometry/Sketcher_CreateCircle_Constr.svg - icons/geometry/Sketcher_CreateEllipse.svg icons/geometry/Sketcher_CreateEllipse_3points.svg icons/geometry/Sketcher_CreateEllipse_3points_Constr.svg - icons/geometry/Sketcher_CreateEllipse_Constr.svg + icons/geometry/Sketcher_CreateEllipseByCenter.svg + icons/geometry/Sketcher_CreateEllipseByCenter_Constr.svg icons/geometry/Sketcher_CreateElliptical_Arc.svg icons/geometry/Sketcher_CreateElliptical_Arc_Constr.svg icons/geometry/Sketcher_CreateFillet.svg diff --git a/src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipse.svg b/src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipseByCenter.svg similarity index 100% rename from src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipse.svg rename to src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipseByCenter.svg diff --git a/src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipse_Constr.svg b/src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipseByCenter_Constr.svg similarity index 100% rename from src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipse_Constr.svg rename to src/Mod/Sketcher/Gui/Resources/icons/geometry/Sketcher_CreateEllipseByCenter_Constr.svg diff --git a/src/Mod/Sketcher/Gui/ShortcutListener.h b/src/Mod/Sketcher/Gui/ShortcutListener.h index 193bf17475..80d0ae7f65 100644 --- a/src/Mod/Sketcher/Gui/ShortcutListener.h +++ b/src/Mod/Sketcher/Gui/ShortcutListener.h @@ -44,11 +44,11 @@ class ShortcutListener: public QObject //Q_OBJECT public: - ShortcutListener(ViewProviderSketch * vp); - ~ShortcutListener(); + explicit ShortcutListener(ViewProviderSketch * vp); + ~ShortcutListener() override; protected: - bool eventFilter(QObject *obj, QEvent *event); + bool eventFilter(QObject *obj, QEvent *event) override; ViewProviderSketch * pViewProvider; }; diff --git a/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp b/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp index 9ce815def9..2609e7981d 100644 --- a/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchMirrorDialog.cpp @@ -38,7 +38,7 @@ using namespace SketcherGui; -SketchMirrorDialog::SketchMirrorDialog(void) +SketchMirrorDialog::SketchMirrorDialog() : QDialog(Gui::getMainWindow()) , RefGeoid(-1) , RefPosid(Sketcher::PointPos::none) diff --git a/src/Mod/Sketcher/Gui/SketchMirrorDialog.h b/src/Mod/Sketcher/Gui/SketchMirrorDialog.h index debea06eec..1c117bd653 100644 --- a/src/Mod/Sketcher/Gui/SketchMirrorDialog.h +++ b/src/Mod/Sketcher/Gui/SketchMirrorDialog.h @@ -34,13 +34,13 @@ class SketchMirrorDialog : public QDialog Q_OBJECT public: - SketchMirrorDialog(void); - ~SketchMirrorDialog(); + SketchMirrorDialog(); + ~SketchMirrorDialog() override; int RefGeoid; Sketcher::PointPos RefPosid; - void accept(); + void accept() override; private: std::unique_ptr ui; diff --git a/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp b/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp index f34091bfe7..9f66cae031 100644 --- a/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchOrientationDialog.cpp @@ -37,7 +37,7 @@ using namespace SketcherGui; -SketchOrientationDialog::SketchOrientationDialog(void) +SketchOrientationDialog::SketchOrientationDialog() : QDialog(Gui::getMainWindow()), ui(new Ui_SketchOrientationDialog) { DirType = 0; diff --git a/src/Mod/Sketcher/Gui/SketchOrientationDialog.h b/src/Mod/Sketcher/Gui/SketchOrientationDialog.h index b80289c56d..914dde0a19 100644 --- a/src/Mod/Sketcher/Gui/SketchOrientationDialog.h +++ b/src/Mod/Sketcher/Gui/SketchOrientationDialog.h @@ -35,13 +35,13 @@ class SketcherGuiExport SketchOrientationDialog : public QDialog Q_OBJECT public: - SketchOrientationDialog(void); - ~SketchOrientationDialog(); + SketchOrientationDialog(); + ~SketchOrientationDialog() override; Base::Placement Pos; int DirType; - void accept(); + void accept() override; protected Q_SLOTS: void onPreview(); diff --git a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp index fdd23e42df..f13418f3b7 100644 --- a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.cpp @@ -37,7 +37,7 @@ using namespace SketcherGui; -SketchRectangularArrayDialog::SketchRectangularArrayDialog(void) +SketchRectangularArrayDialog::SketchRectangularArrayDialog() : QDialog(Gui::getMainWindow()), ui(new Ui_SketchRectangularArrayDialog) { ui->setupUi(this); @@ -68,7 +68,7 @@ void SketchRectangularArrayDialog::accept() QDialog::accept(); } -void SketchRectangularArrayDialog::updateValues(void) +void SketchRectangularArrayDialog::updateValues() { Rows = ui->RowsQuantitySpinBox->value(); Cols = ui->ColsQuantitySpinBox->value(); diff --git a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h index 602fb9fdc6..550dc5a72f 100644 --- a/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h +++ b/src/Mod/Sketcher/Gui/SketchRectangularArrayDialog.h @@ -34,10 +34,10 @@ class SketchRectangularArrayDialog : public QDialog Q_OBJECT public: - SketchRectangularArrayDialog(void); - ~SketchRectangularArrayDialog(); + SketchRectangularArrayDialog(); + ~SketchRectangularArrayDialog() override; - void accept(); + void accept() override; int Rows; int Cols; @@ -46,7 +46,7 @@ public: bool Clone; protected: - void updateValues(void); + void updateValues(); private: std::unique_ptr ui; }; diff --git a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp index 91bbe2bd5a..ccf0ec3011 100644 --- a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp +++ b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.cpp @@ -37,7 +37,7 @@ using namespace SketcherGui; -SketcherRegularPolygonDialog::SketcherRegularPolygonDialog(void) +SketcherRegularPolygonDialog::SketcherRegularPolygonDialog() : QDialog(Gui::getMainWindow()), ui(new Ui_SketcherRegularPolygonDialog) { ui->setupUi(this); @@ -60,7 +60,7 @@ void SketcherRegularPolygonDialog::accept() QDialog::accept(); } -void SketcherRegularPolygonDialog::updateValues(void) +void SketcherRegularPolygonDialog::updateValues() { sides = ui->sidesQuantitySpinBox->value(); } diff --git a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h index 1a21de3945..973d4f5d5b 100644 --- a/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h +++ b/src/Mod/Sketcher/Gui/SketcherRegularPolygonDialog.h @@ -34,15 +34,15 @@ class SketcherRegularPolygonDialog : public QDialog Q_OBJECT public: - SketcherRegularPolygonDialog(void); - ~SketcherRegularPolygonDialog(); + SketcherRegularPolygonDialog(); + ~SketcherRegularPolygonDialog() override; - void accept(); + void accept() override; int sides; protected: - void updateValues(void); + void updateValues(); private: std::unique_ptr ui; }; diff --git a/src/Mod/Sketcher/Gui/SketcherSettings.h b/src/Mod/Sketcher/Gui/SketcherSettings.h index d833fcce7d..13e4b3f2b6 100644 --- a/src/Mod/Sketcher/Gui/SketcherSettings.h +++ b/src/Mod/Sketcher/Gui/SketcherSettings.h @@ -41,14 +41,14 @@ class SketcherSettings : public Gui::Dialog::PreferencePage Q_OBJECT public: - SketcherSettings(QWidget* parent = nullptr); - ~SketcherSettings(); + explicit SketcherSettings(QWidget* parent = nullptr); + ~SketcherSettings() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; @@ -64,14 +64,14 @@ class SketcherSettingsDisplay : public Gui::Dialog::PreferencePage Q_OBJECT public: - SketcherSettingsDisplay(QWidget* parent = nullptr); - ~SketcherSettingsDisplay(); + explicit SketcherSettingsDisplay(QWidget* parent = nullptr); + ~SketcherSettingsDisplay() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private Q_SLOTS: void onBtnTVApplyClicked(bool); @@ -89,14 +89,14 @@ class SketcherSettingsColors : public Gui::Dialog::PreferencePage Q_OBJECT public: - SketcherSettingsColors(QWidget* parent = nullptr); - ~SketcherSettingsColors(); + explicit SketcherSettingsColors(QWidget* parent = nullptr); + ~SketcherSettingsColors() override; - void saveSettings(); - void loadSettings(); + void saveSettings() override; + void loadSettings() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Sketcher/Gui/SoDatumLabel.cpp b/src/Mod/Sketcher/Gui/SoDatumLabel.cpp index 8f0be3b09c..69b25dd7d8 100644 --- a/src/Mod/Sketcher/Gui/SoDatumLabel.cpp +++ b/src/Mod/Sketcher/Gui/SoDatumLabel.cpp @@ -458,7 +458,7 @@ void SoDatumLabel::GLRender(SoGLRenderAction * action) } const unsigned char * dataptr = this->image.getValue(imgsize, nc); - if (dataptr == nullptr) // no image + if (!dataptr) // no image return; srcw = imgsize[0]; diff --git a/src/Mod/Sketcher/Gui/SoDatumLabel.h b/src/Mod/Sketcher/Gui/SoDatumLabel.h index 8a33870eae..d283780e70 100644 --- a/src/Mod/Sketcher/Gui/SoDatumLabel.h +++ b/src/Mod/Sketcher/Gui/SoDatumLabel.h @@ -76,11 +76,11 @@ public: bool useAntialiasing; protected: - virtual ~SoDatumLabel() {}; - virtual void GLRender(SoGLRenderAction *action); - virtual void computeBBox(SoAction *, SbBox3f &box, SbVec3f ¢er); - virtual void generatePrimitives(SoAction * action); - virtual void notify(SoNotList * l); + ~SoDatumLabel() override {}; + void GLRender(SoGLRenderAction *action) override; + void computeBBox(SoAction *, SbBox3f &box, SbVec3f ¢er) override; + void generatePrimitives(SoAction * action) override; + void notify(SoNotList * l) override; private: void drawImage(); diff --git a/src/Mod/Sketcher/Gui/SoZoomTranslation.h b/src/Mod/Sketcher/Gui/SoZoomTranslation.h index 582bf162f3..94b81a7e00 100644 --- a/src/Mod/Sketcher/Gui/SoZoomTranslation.h +++ b/src/Mod/Sketcher/Gui/SoZoomTranslation.h @@ -41,14 +41,14 @@ public: SoSFVec3f abPos; protected: - virtual ~SoZoomTranslation() {}; - virtual void doAction(SoAction * action); - virtual void getPrimitiveCount(SoGetPrimitiveCountAction * action); - virtual void getMatrix(SoGetMatrixAction * action); - virtual void GLRender(SoGLRenderAction *action); - virtual void getBoundingBox(SoGetBoundingBoxAction * action); - virtual void callback(SoCallbackAction * action); - virtual void pick(SoPickAction * action); + ~SoZoomTranslation() override {}; + void doAction(SoAction * action) override; + void getPrimitiveCount(SoGetPrimitiveCountAction * action) override; + void getMatrix(SoGetMatrixAction * action) override; + void GLRender(SoGLRenderAction *action) override; + void getBoundingBox(SoGetBoundingBoxAction * action) override; + void callback(SoCallbackAction * action) override; + void pick(SoPickAction * action) override; float getScaleFactor(SoAction * action) const; }; diff --git a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h index 924ce5737a..73a057f1d7 100644 --- a/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h +++ b/src/Mod/Sketcher/Gui/TaskDlgEditSketch.h @@ -45,25 +45,25 @@ class SketcherGuiExport TaskDlgEditSketch : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgEditSketch(ViewProviderSketch *sketchView); - ~TaskDlgEditSketch(); + explicit TaskDlgEditSketch(ViewProviderSketch *sketchView); + ~TaskDlgEditSketch() override; ViewProviderSketch* getSketchView() const { return sketchView; } public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); - virtual bool isAllowedAlterDocument(void) const + bool reject() override; + bool isAllowedAlterDocument() const override { return false; } /// returns for Close and Help button - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Close; } protected: diff --git a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp index cf67d86d23..82e5ef65d4 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.cpp @@ -96,10 +96,10 @@ public: updateVirtualSpaceStatus(); } - ~ConstraintItem() + ~ConstraintItem() override { } - void setData(int role, const QVariant & value) + void setData(int role, const QVariant & value) override { if (role == Qt::EditRole) this->value = value; @@ -107,7 +107,7 @@ public: QListWidgetItem::setData(role, value); } - QVariant data (int role) const + QVariant data (int role) const override { if (ConstraintNbr < 0 || ConstraintNbr >= sketch->Constraints.getSize()) return QVariant(); @@ -148,7 +148,7 @@ public: case Sketcher::Weight: case Sketcher::Diameter: case Sketcher::Angle: - name = QString::fromLatin1("%1 (%2)").arg(name).arg(constraint->getPresentationValue().getUserString()); + name = QString::fromLatin1("%1 (%2)").arg(name, constraint->getPresentationValue().getUserString()); break; case Sketcher::SnellsLaw: { double v = constraint->getPresentationValue().getValue(); @@ -382,7 +382,7 @@ public: class ExpressionDelegate : public QStyledItemDelegate { public: - ExpressionDelegate(QListWidget * _view) : QStyledItemDelegate(_view), view(_view) { } + explicit ExpressionDelegate(QListWidget * _view) : QStyledItemDelegate(_view), view(_view) { } protected: QPixmap getIcon(const char* name, const QSize& size) const { @@ -400,7 +400,7 @@ protected: return icon; } - void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { + void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const override { QStyleOptionViewItem options = option; initStyleOption(&options, index); @@ -464,7 +464,7 @@ void ConstraintView::contextMenuEvent (QContextMenuEvent* event) for (auto&& it : items) { auto ci = static_cast(it); std::string constraint_name = Sketcher::PropertyConstraintList::getConstraintName(ci->ConstraintNbr); - constraintSubNames.push_back(constraint_name.c_str()); + constraintSubNames.emplace_back(constraint_name.c_str()); } if(!constraintSubNames.empty()) @@ -537,7 +537,7 @@ void ConstraintView::updateDrivingStatus() ConstraintItem *it = dynamic_cast(item); if (it) { - onUpdateDrivingStatus(item, !it->isDriving()); + Q_EMIT onUpdateDrivingStatus(item, !it->isDriving()); } } @@ -547,7 +547,7 @@ void ConstraintView::updateActiveStatus() ConstraintItem *it = dynamic_cast(item); if (it) { - onUpdateActiveStatus(item, !it->isActive()); + Q_EMIT onUpdateActiveStatus(item, !it->isActive()); } } @@ -563,7 +563,7 @@ void ConstraintView::hideConstraints() void ConstraintView::modifyCurrentItem() { - /*emit*/itemActivated(currentItem()); + Q_EMIT itemActivated(currentItem()); } void ConstraintView::renameCurrentItem() @@ -708,7 +708,7 @@ TaskSketcherConstraints::TaskSketcherConstraints(ViewProviderSketch *sketchView) ); QObject::connect( - ui->visibilityButton->actions()[0], SIGNAL(changed()), + qAsConst(ui->visibilityButton)->actions()[0], SIGNAL(changed()), this , SLOT (on_visibilityButton_trackingaction_changed()) ); @@ -1079,8 +1079,8 @@ void TaskSketcherConstraints::on_visualisationTrackingFilter_stateChanged(int st { QSignalBlocker block(this); - if(ui->visibilityButton->actions()[0]->isChecked() != (state == Qt::Checked)) - ui->visibilityButton->actions()[0]->setChecked(state); + if (qAsConst(ui->visibilityButton)->actions()[0]->isChecked() != (state == Qt::Checked)) + qAsConst(ui->visibilityButton)->actions()[0]->setChecked(state); } if(state == Qt::Checked) @@ -1093,7 +1093,7 @@ void TaskSketcherConstraints::on_visibilityButton_trackingaction_changed() ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher"); bool visibilityTracksFilter = hGrp->GetBool("VisualisationTrackingFilter",false); - bool bstate = ui->visibilityButton->actions()[0]->isChecked(); + bool bstate = qAsConst(ui->visibilityButton)->actions()[0]->isChecked(); if(visibilityTracksFilter != bstate) { hGrp->SetBool("VisualisationTrackingFilter", bstate); @@ -1120,7 +1120,7 @@ void TaskSketcherConstraints::on_listWidgetConstraints_emitCenterSelectedItems() sketchView->centerSelection(); } -void TaskSketcherConstraints::on_listWidgetConstraints_itemSelectionChanged(void) +void TaskSketcherConstraints::on_listWidgetConstraints_itemSelectionChanged() { std::string doc_name = sketchView->getSketchObject()->getDocument()->getName(); std::string obj_name = sketchView->getSketchObject()->getNameInDocument(); @@ -1419,7 +1419,7 @@ bool TaskSketcherConstraints::isConstraintFiltered(QListWidgetItem * item) return !visible; } -void TaskSketcherConstraints::slotConstraintsChanged(void) +void TaskSketcherConstraints::slotConstraintsChanged() { assert(sketchView); // Build up ListView with the constraints @@ -1430,7 +1430,7 @@ void TaskSketcherConstraints::slotConstraintsChanged(void) for (int i = 0; i < ui->listWidgetConstraints->count(); ++i) { ConstraintItem * it = dynamic_cast(ui->listWidgetConstraints->item(i)); - assert(it != nullptr); + assert(it); it->ConstraintNbr = i; it->value = QVariant(); diff --git a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h index 319e044ba3..5748ea31aa 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherConstraints.h @@ -48,10 +48,10 @@ class ConstraintView : public QListWidget public: explicit ConstraintView(QWidget *parent = nullptr); - ~ConstraintView(); + ~ConstraintView() override; protected: - void contextMenuEvent (QContextMenuEvent* event); + void contextMenuEvent (QContextMenuEvent* event) override; Q_SIGNALS: void onUpdateDrivingStatus(QListWidgetItem *item, bool status); @@ -83,14 +83,14 @@ class TaskSketcherConstraints : public Gui::TaskView::TaskBox, public Gui::Selec }; public: - TaskSketcherConstraints(ViewProviderSketch *sketchView); - ~TaskSketcherConstraints(); + explicit TaskSketcherConstraints(ViewProviderSketch *sketchView); + ~TaskSketcherConstraints() override; /// Observer message from the Selection - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; private: - void slotConstraintsChanged(void); + void slotConstraintsChanged(); bool isConstraintFiltered(QListWidgetItem * item); void change3DViewVisibilityToTrackFilter(); void changeFilteredVisibility(bool show, ActionTarget target = ActionTarget::All); @@ -106,12 +106,12 @@ private: public Q_SLOTS: void on_comboBoxFilter_currentIndexChanged(int); - void on_listWidgetConstraints_itemSelectionChanged(void); + void on_listWidgetConstraints_itemSelectionChanged(); void on_listWidgetConstraints_itemActivated(QListWidgetItem *item); void on_listWidgetConstraints_itemChanged(QListWidgetItem * item); void on_listWidgetConstraints_updateDrivingStatus(QListWidgetItem *item, bool status); void on_listWidgetConstraints_updateActiveStatus(QListWidgetItem *item, bool status); - void on_listWidgetConstraints_emitCenterSelectedItems(void); + void on_listWidgetConstraints_emitCenterSelectedItems(); void on_filterInternalAlignment_stateChanged(int state); void on_extendedInformation_stateChanged(int state); void on_visualisationTrackingFilter_stateChanged(int state); @@ -125,7 +125,7 @@ public Q_SLOTS: void on_settingsDialogButton_clicked(bool); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; ViewProviderSketch *sketchView; typedef boost::signals2::connection Connection; Connection connectionConstraintsChanged; diff --git a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h index f72e3819a3..a77bfef635 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherCreateCommands.h @@ -45,16 +45,16 @@ class TaskSketcherCreateCommands : public TaskBox, public Gui::SelectionSingleto Q_OBJECT public: - TaskSketcherCreateCommands(QWidget *parent = nullptr); - ~TaskSketcherCreateCommands(); + explicit TaskSketcherCreateCommands(QWidget *parent = nullptr); + ~TaskSketcherCreateCommands() override; /// Observer message from the Selection void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason); + Gui::SelectionSingleton::MessageType Reason) override; private Q_SLOTS: protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: diff --git a/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp b/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp index 049a050ee7..c2881bd9f7 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherElements.cpp @@ -115,7 +115,7 @@ public: { } - ~ElementItem() + ~ElementItem() override { } @@ -240,7 +240,7 @@ void ElementView::keyPressEvent(QKeyEvent * event) { case Qt::Key_Z: // signal - onFilterShortcutPressed(); + Q_EMIT onFilterShortcutPressed(); break; default: QListWidget::keyPressEvent( event ); @@ -276,7 +276,7 @@ TaskSketcherElements::TaskSketcherElements(ViewProviderSketch *sketchView) QString zKey = QString::fromLatin1("Z"); ui->Explanation->setText(tr("

"%1": multiple selection

" "

"%2": switch to next valid type

") - .arg(cmdKey).arg(zKey)); + .arg(cmdKey, zKey)); ui->listWidgetElements->setSelectionMode(QAbstractItemView::ExtendedSelection); ui->listWidgetElements->setEditTriggers(QListWidget::NoEditTriggers); ui->listWidgetElements->setMouseTracking(true); @@ -470,7 +470,7 @@ void TaskSketcherElements::on_listWidgetElements_itemSelectionChanged(void) bool multipleconsecutiveselection=false; // shift type of selection in listWidget if (!inhibitSelectionUpdate) { - if(itf!=nullptr) { + if (itf) { switch(element){ case 0: itf->isLineSelected=!itf->isLineSelected; @@ -1128,7 +1128,7 @@ TaskSketcherElements::MultIcon::MultIcon(const char* name) { int hue, sat, val, alp; Normal = Gui::BitmapFactory().iconFromTheme(name); - QImage imgConstr(Normal.pixmap(Normal.availableSizes()[0]).toImage()); + QImage imgConstr(Normal.pixmap(qAsConst(Normal).availableSizes()[0]).toImage()); QImage imgExt(imgConstr); for(int ix=0 ; ixrenderingOrder && event->type() == QEvent::ChildRemoved) { - emitRenderOrderChanged(); + Q_EMIT emitRenderOrderChanged(); } return false; } diff --git a/src/Mod/Sketcher/Gui/TaskSketcherGeneral.h b/src/Mod/Sketcher/Gui/TaskSketcherGeneral.h index f6c94019cb..509a323140 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherGeneral.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherGeneral.h @@ -46,10 +46,10 @@ class SketcherGeneralWidget : public QWidget Q_OBJECT public: - SketcherGeneralWidget(QWidget *parent=nullptr); - ~SketcherGeneralWidget(); + explicit SketcherGeneralWidget(QWidget *parent=nullptr); + ~SketcherGeneralWidget() override; - bool eventFilter(QObject *object, QEvent *event); + bool eventFilter(QObject *object, QEvent *event) override; void saveSettings(); void saveOrderingOrder(); @@ -72,7 +72,7 @@ Q_SIGNALS: void emitRenderOrderChanged(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; @@ -84,11 +84,11 @@ class TaskSketcherGeneral : public Gui::TaskView::TaskBox, Q_OBJECT public: - TaskSketcherGeneral(ViewProviderSketch *sketchView); - ~TaskSketcherGeneral(); + explicit TaskSketcherGeneral(ViewProviderSketch *sketchView); + ~TaskSketcherGeneral() override; /// Observer message from the Selection void OnChange(Gui::SelectionSingleton::SubjectType &rCaller, - Gui::SelectionSingleton::MessageType Reason); + Gui::SelectionSingleton::MessageType Reason) override; public Q_SLOTS: void onToggleGridView(bool on); diff --git a/src/Mod/Sketcher/Gui/TaskSketcherMessages.h b/src/Mod/Sketcher/Gui/TaskSketcherMessages.h index 300059c905..b211daf83d 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherMessages.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherMessages.h @@ -44,8 +44,8 @@ class TaskSketcherMessages : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskSketcherMessages(ViewProviderSketch *sketchView); - ~TaskSketcherMessages(); + explicit TaskSketcherMessages(ViewProviderSketch *sketchView); + ~TaskSketcherMessages() override; void slotSetUp(const QString &state, const QString &msg, const QString& link, const QString& linkText); diff --git a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp index affe5cc06e..3e46555bca 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.cpp @@ -92,7 +92,7 @@ TaskSketcherSolverAdvanced::~TaskSketcherSolverAdvanced() { } -void TaskSketcherSolverAdvanced::updateDefaultMethodParameters(void) +void TaskSketcherSolverAdvanced::updateDefaultMethodParameters() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); @@ -161,7 +161,7 @@ void TaskSketcherSolverAdvanced::updateDefaultMethodParameters(void) } } -void TaskSketcherSolverAdvanced::updateRedundantMethodParameters(void) +void TaskSketcherSolverAdvanced::updateRedundantMethodParameters() { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Sketcher/SolverAdvanced"); @@ -560,7 +560,7 @@ void TaskSketcherSolverAdvanced::on_pushButtonDefaults_clicked(bool checked/* = updateSketchObject(); } -void TaskSketcherSolverAdvanced::updateSketchObject(void) +void TaskSketcherSolverAdvanced::updateSketchObject() { const_cast(sketchView->getSketchObject()->getSolvedSketch()).setDebugMode((GCS::DebugMode) ui->comboBoxDebugMode->currentIndex()); const_cast(sketchView->getSketchObject()->getSolvedSketch()).setSketchSizeMultiplierRedundant(ui->checkBoxRedundantSketchSizeMultiplier->isChecked()); diff --git a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h index 2e2dcfde1b..652df7f770 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherSolverAdvanced.h @@ -42,8 +42,8 @@ class TaskSketcherSolverAdvanced : public Gui::TaskView::TaskBox Q_OBJECT public: - TaskSketcherSolverAdvanced(ViewProviderSketch *sketchView); - ~TaskSketcherSolverAdvanced(); + explicit TaskSketcherSolverAdvanced(ViewProviderSketch *sketchView); + ~TaskSketcherSolverAdvanced() override; private Q_SLOTS: void on_comboBoxDefaultSolver_currentIndexChanged(int index); @@ -68,9 +68,9 @@ private Q_SLOTS: void on_pushButtonSolve_clicked(bool checked = false); protected: - void updateDefaultMethodParameters(void); - void updateRedundantMethodParameters(void); - void updateSketchObject(void); + void updateDefaultMethodParameters(); + void updateRedundantMethodParameters(); + void updateSketchObject(); protected: ViewProviderSketch *sketchView; diff --git a/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp b/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp index c0cda9f54c..293efc1a1c 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp +++ b/src/Mod/Sketcher/Gui/TaskSketcherValidation.cpp @@ -230,7 +230,7 @@ void SketcherValidation::on_findReversed_clicked() } } hidePoints(); - if(points.size()>0){ + if(!points.empty()){ int nc = sketch->port_reversedExternalArcs(/*justAnalyze=*/true); showPoints(points); if(nc>0){ diff --git a/src/Mod/Sketcher/Gui/TaskSketcherValidation.h b/src/Mod/Sketcher/Gui/TaskSketcherValidation.h index 3a51f5c7a6..2b7cc58b27 100644 --- a/src/Mod/Sketcher/Gui/TaskSketcherValidation.h +++ b/src/Mod/Sketcher/Gui/TaskSketcherValidation.h @@ -42,11 +42,11 @@ class SketcherValidation : public QWidget Q_OBJECT public: - SketcherValidation(Sketcher::SketchObject* Obj, QWidget* parent = nullptr); - ~SketcherValidation(); + explicit SketcherValidation(Sketcher::SketchObject* Obj, QWidget* parent = nullptr); + ~SketcherValidation() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private Q_SLOTS: void on_findButton_clicked(); @@ -78,9 +78,9 @@ class TaskSketcherValidation : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskSketcherValidation(Sketcher::SketchObject* Obj); - ~TaskSketcherValidation(); - virtual QDialogButtonBox::StandardButtons getStandardButtons(void) const + explicit TaskSketcherValidation(Sketcher::SketchObject* Obj); + ~TaskSketcherValidation() override; + QDialogButtonBox::StandardButtons getStandardButtons(void) const override { return QDialogButtonBox::Close; } }; diff --git a/src/Mod/Sketcher/Gui/ViewProviderPython.cpp b/src/Mod/Sketcher/Gui/ViewProviderPython.cpp index 3870d332b6..3724731172 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderPython.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderPython.cpp @@ -56,7 +56,7 @@ void ViewProviderCustom::onChanged(const App::Property* prop) } } } - PartGui::ViewProviderPart::onChanged(prop); + ViewProviderSketch::onChanged(prop); } void ViewProviderCustom::updateData(const App::Property* prop) diff --git a/src/Mod/Sketcher/Gui/ViewProviderPython.h b/src/Mod/Sketcher/Gui/ViewProviderPython.h index d1325153cd..32ace07776 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderPython.h +++ b/src/Mod/Sketcher/Gui/ViewProviderPython.h @@ -31,17 +31,17 @@ namespace SketcherGui { class SketcherGuiExport ViewProviderCustom : public ViewProviderSketch { - PROPERTY_HEADER(SketcherGui::ViewProviderCustom); + PROPERTY_HEADER_WITH_OVERRIDE(SketcherGui::ViewProviderCustom); public: /// constructor ViewProviderCustom(); /// destructor - virtual ~ViewProviderCustom(); - virtual void updateData(const App::Property*); + ~ViewProviderCustom() override; + void updateData(const App::Property*) override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; std::map propView; }; diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp index a462354e76..a1ae8b5fa4 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.cpp @@ -352,7 +352,7 @@ void ViewProviderSketch::forceUpdateData() void ViewProviderSketch::activateHandler(DrawSketchHandler *newHandler) { assert(editCoinManager); - assert(sketchHandler == nullptr); + assert(!sketchHandler); sketchHandler = std::unique_ptr(newHandler); Mode = STATUS_SKETCH_UseHandler; @@ -376,7 +376,7 @@ void ViewProviderSketch::deactivateHandler() } /// removes the active handler -void ViewProviderSketch::purgeHandler(void) +void ViewProviderSketch::purgeHandler() { deactivateHandler(); Gui::Selection().clearSelection(); @@ -1043,7 +1043,7 @@ bool ViewProviderSketch::mouseWheelEvent(int delta, const SbVec2s &cursorPos, co return true; } -void ViewProviderSketch::editDoubleClicked(void) +void ViewProviderSketch::editDoubleClicked() { if (preselection.isPreselectPointValid()) { Base::Console().Log("double click point:%d\n",preselection.PreselectPoint); @@ -1551,7 +1551,7 @@ void ViewProviderSketch::moveConstraint(int constNum, const Base::Vector2d &toPo draw(true,false); } -bool ViewProviderSketch::isSelectable(void) const +bool ViewProviderSketch::isSelectable() const { if (isEditing()) return false; @@ -1564,7 +1564,7 @@ void ViewProviderSketch::onSelectionChanged(const Gui::SelectionChanges& msg) // are we in edit? if (isInEditMode()) { // ignore external object - if(msg.Object.getObjectName().size() && msg.Object.getDocument()!=getObject()->getDocument()) + if(!msg.Object.getObjectName().empty() && msg.Object.getDocument()!=getObject()->getDocument()) return; bool handled=false; @@ -2429,14 +2429,14 @@ void ViewProviderSketch::doBoxSelection(const SbVec2s &startPos, const SbVec2s & } } -void ViewProviderSketch::updateColor(void) +void ViewProviderSketch::updateColor() { assert(isInEditMode()); editCoinManager->updateColor(); } -bool ViewProviderSketch::doubleClicked(void) +bool ViewProviderSketch::doubleClicked() { Gui::Application::Instance->activeDocument()->setEdit(this); return true; @@ -2883,7 +2883,7 @@ QString ViewProviderSketch::appendConstraintMsg(const QString & singularmsg, { QString msg; QTextStream ss(&msg); - if (vector.size() > 0) { + if (!vector.empty()) { if (vector.size() == 1) ss << singularmsg; else @@ -3022,7 +3022,7 @@ void ViewProviderSketch::unsetEdit(int ModNum) "ActiveSketch.ViewObject.TempoVis = None\n" "del(tv)\n" "del(ActiveSketch)\n" - ).arg(QString::fromLatin1(getDocument()->getDocument()->getName())).arg( + ).arg(QString::fromLatin1(getDocument()->getDocument()->getName()), QString::fromLatin1(getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); @@ -3046,7 +3046,7 @@ void ViewProviderSketch::setEditViewer(Gui::View3DInventorViewer* viewer, int Mo " ActiveSketch.ViewObject.TempoVis.saveCamera()\n" " if ActiveSketch.ViewObject.ForceOrtho:\n" " ActiveSketch.ViewObject.Document.ActiveView.setCameraType('Orthographic')\n" - ).arg(QString::fromLatin1(getDocument()->getDocument()->getName())).arg( + ).arg(QString::fromLatin1(getDocument()->getDocument()->getName()), QString::fromLatin1(getSketchObject()->getNameInDocument())); QByteArray cmdstr_bytearray = cmdstr.toLatin1(); Gui::Command::runCommand(Gui::Command::Gui, cmdstr_bytearray); @@ -3122,21 +3122,21 @@ void ViewProviderSketch::unsetEditViewer(Gui::View3DInventorViewer* viewer) static_cast(root)->selectionRole.setValue(true); } -int ViewProviderSketch::getPreselectPoint(void) const +int ViewProviderSketch::getPreselectPoint() const { if (isInEditMode()) return preselection.PreselectPoint; return -1; } -int ViewProviderSketch::getPreselectCurve(void) const +int ViewProviderSketch::getPreselectCurve() const { if (isInEditMode()) return preselection.PreselectCurve; return -1; } -int ViewProviderSketch::getPreselectCross(void) const +int ViewProviderSketch::getPreselectCross() const { // TODO: This function spreads over several files. It should be refactored into something less "numeric" at a second stage. if (isInEditMode()) @@ -3144,12 +3144,12 @@ int ViewProviderSketch::getPreselectCross(void) const return -1; } -Sketcher::SketchObject *ViewProviderSketch::getSketchObject(void) const +Sketcher::SketchObject *ViewProviderSketch::getSketchObject() const { return dynamic_cast(pcObject); } -const Sketcher::Sketch &ViewProviderSketch::getSolvedSketch(void) const +const Sketcher::Sketch &ViewProviderSketch::getSolvedSketch() const { return const_cast(getSketchObject())->getSolvedSketch(); } @@ -3168,7 +3168,7 @@ void ViewProviderSketch::deleteSelected() // get the needed lists and objects const std::vector &SubNames = selection[0].getSubNames(); - if(SubNames.size()>0) { + if(!SubNames.empty()) { App::Document* doc = getSketchObject()->getDocument(); doc->openTransaction("Delete sketch geometry"); @@ -3379,7 +3379,7 @@ void ViewProviderSketch::setPositionText(const Base::Vector2d &Pos) editCoinManager->setPositionText(Pos); } -void ViewProviderSketch::resetPositionText(void) +void ViewProviderSketch::resetPositionText() { editCoinManager->resetPositionText(); } @@ -3401,7 +3401,7 @@ void ViewProviderSketch::setPreselectRootPoint() } -void ViewProviderSketch::resetPreselectPoint(void) +void ViewProviderSketch::resetPreselectPoint() { preselection.PreselectPoint = Preselection::InvalidPoint; preselection.PreselectCurve = Preselection::InvalidCurve; @@ -3419,7 +3419,7 @@ void ViewProviderSketch::removeSelectPoint(int SelectPoint) selection.SelPointSet.erase(SelectPoint); } -void ViewProviderSketch::clearSelectPoints(void) +void ViewProviderSketch::clearSelectPoints() { selection.SelPointSet.clear(); } diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketch.h b/src/Mod/Sketcher/Gui/ViewProviderSketch.h index a3f9a8d19f..e8a19f6b18 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketch.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketch.h @@ -154,7 +154,7 @@ private: class ParameterObserver : public ParameterGrp::ObserverType { public: - ParameterObserver(ViewProviderSketch & client); + explicit ParameterObserver(ViewProviderSketch & client); ~ParameterObserver(); void initParameters(); @@ -392,7 +392,7 @@ public: /// constructor ViewProviderSketch(); /// destructor - virtual ~ViewProviderSketch(); + ~ViewProviderSketch() override; /** @name Properties */ //@{ @@ -415,7 +415,7 @@ public: /// sets an DrawSketchHandler in control void activateHandler(DrawSketchHandler *newHandler); /// removes the active handler - void purgeHandler(void); + void purgeHandler(); //@} @@ -443,7 +443,7 @@ public: /// is called by GuiCommands to set the drawing mode void setSketchMode(SketchMode mode) {Mode = mode;} /// get the sketch mode - SketchMode getSketchMode(void) const {return Mode;} + SketchMode getSketchMode() const {return Mode;} //@} /** @name Drawing functions */ @@ -454,22 +454,22 @@ public: void draw(bool temp=false, bool rebuildinformationoverlay=true); /// helper change the color of the sketch according to selection and solver status - void updateColor(void); + void updateColor(); //@} /** @name Selection functions */ //@{ /// Is the view provider selectable - bool isSelectable(void) const override; + bool isSelectable() const override; /// Observer message from the Selection - virtual void onSelectionChanged(const Gui::SelectionChanges& msg) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; //@} /** @name Access to Sketch and Solver objects */ //@{ /// get the pointer to the sketch document object - Sketcher::SketchObject *getSketchObject(void) const; + Sketcher::SketchObject *getSketchObject() const; /** returns a const reference to the last solved sketch object. It guarantees that * the solver object does not lose synchronisation with the SketchObject properties. @@ -481,7 +481,7 @@ public: * -> inline int moveTemporaryPoint(int geoId, PointPos pos, Base::Vector3d toPoint, bool relative=false) * -> inline void updateSolverExtension(int geoId, std::unique_ptr && ext) */ - const Sketcher::Sketch &getSolvedSketch(void) const; + const Sketcher::Sketch &getSolvedSketch() const; //@} /** @name miscelanea utilities */ @@ -495,38 +495,38 @@ public: /** @name constraint Virtual Space visibility management */ //@{ /// updates the visibility of the virtual space of constraints - void updateVirtualSpace(void); + void updateVirtualSpace(); /// determines whether the constraints in the normal space or the ones in the virtual are to be shown void setIsShownVirtualSpace(bool isshownvirtualspace); /// returns whether the virtual space is being shown - bool getIsShownVirtualSpace(void) const; + bool getIsShownVirtualSpace() const; //@} /** @name base class implementer */ //@{ - virtual void attach(App::DocumentObject *) override; - virtual void updateData(const App::Property *) override; + void attach(App::DocumentObject *) override; + void updateData(const App::Property *) override; - virtual void setupContextMenu(QMenu *menu, QObject *receiver, const char *member) override; + void setupContextMenu(QMenu *menu, QObject *receiver, const char *member) override; /// is called when the Provider is in edit and a deletion request occurs - virtual bool onDelete(const std::vector &) override; + bool onDelete(const std::vector &) override; /// Is called by the tree if the user double clicks on the object. It returns the string /// for the transaction that will be shown in the undo/redo dialog. /// If null is returned then no transaction will be opened. - virtual const char* getTransactionText() const override { return nullptr; } + const char* getTransactionText() const override { return nullptr; } /// is called by the tree if the user double clicks on the object - virtual bool doubleClicked(void) override; + bool doubleClicked() override; /// is called when the Provider is in edit and the mouse is moved - virtual bool mouseMove(const SbVec2s &pos, Gui::View3DInventorViewer *viewer) override; + bool mouseMove(const SbVec2s &pos, Gui::View3DInventorViewer *viewer) override; /// is called when the Provider is in edit and a key event ocours. Only ESC ends edit. - virtual bool keyPressed(bool pressed, int key) override; + bool keyPressed(bool pressed, int key) override; /// is called when the Provider is in edit and the mouse is clicked - virtual bool mouseButtonPressed(int Button, bool pressed, const SbVec2s& cursorPos, const Gui::View3DInventorViewer* viewer) override; - virtual bool mouseWheelEvent(int delta, const SbVec2s &cursorPos, const Gui::View3DInventorViewer* viewer) override; + bool mouseButtonPressed(int Button, bool pressed, const SbVec2s& cursorPos, const Gui::View3DInventorViewer* viewer) override; + bool mouseWheelEvent(int delta, const SbVec2s &cursorPos, const Gui::View3DInventorViewer* viewer) override; //@} /// Control the overlays appearing on the Tree and reflecting different sketcher states - virtual QIcon mergeColorfulOverlayIcons (const QIcon & orig) const override; + QIcon mergeColorfulOverlayIcons (const QIcon & orig) const override; /** @name Signals for controlling information in Task dialogs */ //@{ @@ -547,10 +547,10 @@ public: protected: /** @name enter/exit edit mode */ //@{ - virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; - virtual void setEditViewer(Gui::View3DInventorViewer*, int ModNum) override; - virtual void unsetEditViewer(Gui::View3DInventorViewer*) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; + void setEditViewer(Gui::View3DInventorViewer*, int ModNum) override; + void unsetEditViewer(Gui::View3DInventorViewer*) override; //@} /** @name miscelanea editing functions */ @@ -558,13 +558,13 @@ protected: /// purges the DrawHandler if existing and tidies up void deactivateHandler(); /// get called if a subelement is double clicked while editing - void editDoubleClicked(void); + void editDoubleClicked(); //@} /** @name Solver Information */ //@{ /// update solver information based on last solving at SketchObject - void UpdateSolverInformation(void); + void UpdateSolverInformation(); /// Auxiliary function to generate messages about conflicting, redundant and malformed constraints static QString appendConstraintMsg( const QString & singularmsg, @@ -582,7 +582,7 @@ protected: /** @name base class implementer */ //@{ /// get called by the container whenever a property has been changed - virtual void onChanged(const App::Property *prop) override; + void onChanged(const App::Property *prop) override; //@} private: @@ -606,12 +606,12 @@ private: //@{ /// helper to detect preselection bool detectAndShowPreselection (SoPickedPoint * Point, const SbVec2s &cursorPos); - int getPreselectPoint(void) const; - int getPreselectCurve(void) const; - int getPreselectCross(void) const; + int getPreselectPoint() const; + int getPreselectCurve() const; + int getPreselectCross() const; void setPreselectPoint(int PreselectPoint); void setPreselectRootPoint(); - void resetPreselectPoint(void); + void resetPreselectPoint(); bool setPreselect(const std::string &subNameSuffix, float x = 0, float y = 0, float z = 0); //@} @@ -624,7 +624,7 @@ private: void addSelectPoint(int SelectPoint); void removeSelectPoint(int SelectPoint); - void clearSelectPoints(void); + void clearSelectPoints(); bool isSelected(const std::string & ss) const; void rmvSelection(const std::string &subNameSuffix); @@ -703,7 +703,7 @@ private: void setConstraintSelectability(bool enabled = true); void setPositionText(const Base::Vector2d &Pos, const SbString &txt); void setPositionText(const Base::Vector2d &Pos); - void resetPositionText(void); + void resetPositionText(); /// draw the edit curve void drawEdit(const std::vector &EditCurve); diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp index 42c491532e..66a45b099a 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.cpp @@ -45,7 +45,7 @@ void ViewProviderSketchGeometryExtension::copyAttributes(Part::GeometryExtension static_cast(cpy)->RepresentationFactor = this->RepresentationFactor; } -std::unique_ptr ViewProviderSketchGeometryExtension::copy(void) const +std::unique_ptr ViewProviderSketchGeometryExtension::copy() const { auto cpy = std::make_unique(); @@ -58,7 +58,7 @@ std::unique_ptr ViewProviderSketchGeometryExtension::co #endif } -PyObject * ViewProviderSketchGeometryExtension::getPyObject(void) +PyObject * ViewProviderSketchGeometryExtension::getPyObject() { THROWM(Base::NotImplementedError, "ViewProviderSketchGeometryExtension does not have a Python counterpart"); } diff --git a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h index 3be807c066..f1d9a6b2ae 100644 --- a/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h +++ b/src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.h @@ -34,11 +34,11 @@ class SketcherGuiExport ViewProviderSketchGeometryExtension : public Part::Geome public: ViewProviderSketchGeometryExtension(); - virtual ~ViewProviderSketchGeometryExtension() override = default; + ~ViewProviderSketchGeometryExtension() override = default; - virtual std::unique_ptr copy(void) const override; + std::unique_ptr copy() const override; - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; // Data Members @@ -52,7 +52,7 @@ public: virtual void setRepresentationFactor(double representationFactor) {RepresentationFactor = representationFactor;} protected: - virtual void copyAttributes(Part::GeometryExtension * cpy) const override; + void copyAttributes(Part::GeometryExtension * cpy) const override; private: ViewProviderSketchGeometryExtension(const ViewProviderSketchGeometryExtension&) = default; diff --git a/src/Mod/Sketcher/Gui/Workbench.h b/src/Mod/Sketcher/Gui/Workbench.h index 61a57f0ed1..a8f9fd00be 100644 --- a/src/Mod/Sketcher/Gui/Workbench.h +++ b/src/Mod/Sketcher/Gui/Workbench.h @@ -36,16 +36,16 @@ namespace SketcherGui { */ class SketcherGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; SketcherGuiExport void addSketcherWorkbenchSketchActions(Gui::MenuItem& sketch); diff --git a/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp b/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp index 9ed7ff379c..cb25a3e4db 100644 --- a/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp +++ b/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp @@ -30,7 +30,7 @@ public: initialize("This module is the Spreadsheet module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Spreadsheet/App/CMakeLists.txt b/src/Mod/Spreadsheet/App/CMakeLists.txt index 4c4cbc3205..40b116ba8f 100644 --- a/src/Mod/Spreadsheet/App/CMakeLists.txt +++ b/src/Mod/Spreadsheet/App/CMakeLists.txt @@ -8,6 +8,7 @@ include_directories( ${PYTHON_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) set(Spreadsheet_LIBS diff --git a/src/Mod/Spreadsheet/App/Cell.cpp b/src/Mod/Spreadsheet/App/Cell.cpp index 4cfdd0d085..cccb19b8ca 100644 --- a/src/Mod/Spreadsheet/App/Cell.cpp +++ b/src/Mod/Spreadsheet/App/Cell.cpp @@ -186,7 +186,7 @@ void Cell::setExpression(App::ExpressionPtr &&expr) /* Remove dependencies */ owner->removeDependencies(address); - if(expr && expr->comment.size()) { + if(expr && !expr->comment.empty()) { if(!boost::starts_with(expr->comment,"sheet()->getFullName() << '.' << address.toString()); @@ -370,7 +370,7 @@ void Cell::setContent(const char * value) } } - if (!newExpr && *value != '\0') { + if (!newExpr && value && *value != '\0') { newExpr = std::make_unique(owner->sheet(), value); } @@ -423,7 +423,7 @@ void Cell::setStyle(const std::set & _style) PropertySheet::AtomicPropertyChange signaller(*owner); style = _style; - setUsed(STYLE_SET, style.size() > 0); + setUsed(STYLE_SET, !style.empty()); setDirty(); signaller.tryInvoke(); @@ -509,7 +509,7 @@ bool Cell::getBackground(App::Color &color) const void Cell::setDisplayUnit(const std::string &unit) { DisplayUnit newDisplayUnit; - if (unit.size() > 0) { + if (!unit.empty()) { std::shared_ptr e(ExpressionParser::parseUnit(owner->sheet(), unit.c_str())); if (!e) @@ -641,7 +641,7 @@ bool Cell::getSpans(int &rows, int &columns) const void Cell::setException(const std::string &e, bool silent) { - if(!silent && e.size() && owner && owner->sheet()) { + if(!silent && !e.empty() && owner && owner->sheet()) { FC_ERR(owner->sheet()->getFullName() << '.' << address.toString() << ": " << e); } @@ -651,7 +651,7 @@ void Cell::setException(const std::string &e, bool silent) void Cell::setParseException(const std::string &e) { - if(e.size() && owner && owner->sheet()) { + if(!e.empty() && owner && owner->sheet()) { FC_ERR(owner->sheet()->getFullName() << '.' << address.toString() << ": " << e); } @@ -661,7 +661,7 @@ void Cell::setParseException(const std::string &e) void Cell::setResolveException(const std::string &e) { - if(e.size() && owner && owner->sheet()) { + if(!e.empty() && owner && owner->sheet()) { FC_LOG(owner->sheet()->getFullName() << '.' << address.toString() << ": " << e); } @@ -899,7 +899,7 @@ int Cell::decodeAlignment(const std::string & itemStr, int alignment) alignment = (alignment & ~Cell::ALIGNMENT_VERTICAL) | Cell::ALIGNMENT_VCENTER; else if (itemStr == "bottom") alignment = (alignment & ~Cell::ALIGNMENT_VERTICAL) | Cell::ALIGNMENT_BOTTOM; - else if(itemStr.size()) + else if(!itemStr.empty()) throw Base::ValueError("Invalid alignment."); return alignment; diff --git a/src/Mod/Spreadsheet/App/Cell.h b/src/Mod/Spreadsheet/App/Cell.h index 68d0349758..fb12306bfe 100644 --- a/src/Mod/Spreadsheet/App/Cell.h +++ b/src/Mod/Spreadsheet/App/Cell.h @@ -122,7 +122,7 @@ public: App::CellAddress getAddress() const { return address; } - std::string getFormattedQuantity(void); + std::string getFormattedQuantity(); /* Alignment */ static const int ALIGNMENT_LEFT; diff --git a/src/Mod/Spreadsheet/App/DisplayUnit.h b/src/Mod/Spreadsheet/App/DisplayUnit.h index c0bf22db04..25089e5fa7 100644 --- a/src/Mod/Spreadsheet/App/DisplayUnit.h +++ b/src/Mod/Spreadsheet/App/DisplayUnit.h @@ -35,7 +35,7 @@ public: Base::Unit unit; double scaler; - DisplayUnit(const std::string _stringRep = "", const Base::Unit _unit = Base::Unit(), double _scaler = 0.0) + explicit DisplayUnit(const std::string _stringRep = "", const Base::Unit _unit = Base::Unit(), double _scaler = 0.0) : stringRep(_stringRep) , unit(_unit) , scaler(_scaler) @@ -52,7 +52,7 @@ public: return !operator==(c); } - bool isEmpty() const { return stringRep.size() == 0; } + bool isEmpty() const { return stringRep.empty(); } }; diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidths.h b/src/Mod/Spreadsheet/App/PropertyColumnWidths.h index abcaf014f6..7426fcc05c 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidths.h +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidths.h @@ -32,7 +32,7 @@ namespace Spreadsheet { class SpreadsheetExport PropertyColumnWidths : public App::Property, std::map { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyColumnWidths(); @@ -51,21 +51,21 @@ public: return i != end() ? i->second : defaultWidth; } - virtual Property *Copy(void) const; + Property *Copy() const override; - virtual void Paste(const Property &from); + void Paste(const Property &from) override; - virtual void Save (Base::Writer & writer) const; + void Save (Base::Writer & writer) const override; - virtual void Restore(Base::XMLReader & reader); + void Restore(Base::XMLReader & reader) override; - bool isDirty() const { return dirty.size() > 0; } + bool isDirty() const { return !dirty.empty(); } void clearDirty() { dirty.clear(); } const std::set & getDirty() const { return dirty; } - PyObject *getPyObject(void); + PyObject *getPyObject() override; void clear(); diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp index 53f97d0a76..57b9e5ebba 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp @@ -32,7 +32,7 @@ using namespace Spreadsheet; // returns a string which represents the object e.g. when printed in python -std::string PropertyColumnWidthsPy::representation(void) const +std::string PropertyColumnWidthsPy::representation() const { return std::string(""); } diff --git a/src/Mod/Spreadsheet/App/PropertyRowHeights.h b/src/Mod/Spreadsheet/App/PropertyRowHeights.h index 23bf24a642..005ca185f4 100644 --- a/src/Mod/Spreadsheet/App/PropertyRowHeights.h +++ b/src/Mod/Spreadsheet/App/PropertyRowHeights.h @@ -32,7 +32,7 @@ namespace Spreadsheet { class SpreadsheetExport PropertyRowHeights : public App::Property, std::map { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertyRowHeights(); @@ -51,13 +51,13 @@ public: return *this; } - virtual App::Property *Copy(void) const; + App::Property *Copy() const override; - virtual void Paste(const App::Property &from); + void Paste(const App::Property &from) override; - virtual void Save (Base::Writer & writer) const; + void Save (Base::Writer & writer) const override; - virtual void Restore(Base::XMLReader & reader); + void Restore(Base::XMLReader & reader) override; bool isDirty() const { return dirty.size() > 0; } @@ -65,7 +65,7 @@ public: const std::set & getDirty() const { return dirty; } - PyObject *getPyObject(void); + PyObject *getPyObject() override; static const int defaultHeight; diff --git a/src/Mod/Spreadsheet/App/PropertySheet.cpp b/src/Mod/Spreadsheet/App/PropertySheet.cpp index f1ffbad298..0604984bda 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.cpp +++ b/src/Mod/Spreadsheet/App/PropertySheet.cpp @@ -126,7 +126,7 @@ bool PropertySheet::isValidAlias(const std::string &candidate) boost::cmatch cm; /* Check if it is used before */ - if (getValueFromAlias(candidate) != nullptr) + if (getValueFromAlias(candidate)) return false; /* Check to make sure it doesn't clash with a predefined unit */ @@ -142,7 +142,7 @@ bool PropertySheet::isValidAlias(const std::string &candidate) const boost::sub_match rowstr = cm[2]; // A valid cell address? - if (App::validRow(rowstr.str()) >= 0 && App::validColumn(colstr.str()) >= 0) + if (App::validRow(rowstr.str()) >= 0 && App::validColumn(colstr.str())) return false; } return true; @@ -578,14 +578,14 @@ Cell * PropertySheet::nonNullCellAt(CellAddress address) void PropertySheet::setContent(CellAddress address, const char *value) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setContent(value); } void PropertySheet::setAlignment(CellAddress address, int _alignment) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); if (cell->address != address) //Reject alignment change for merged cell except top-left one return; cell->setAlignment(_alignment); @@ -594,40 +594,40 @@ void PropertySheet::setAlignment(CellAddress address, int _alignment) void PropertySheet::setStyle(CellAddress address, const std::set &_style) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setStyle(_style); } void PropertySheet::setForeground(CellAddress address, const App::Color &color) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setForeground(color); } void PropertySheet::setBackground(CellAddress address, const App::Color &color) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setBackground(color); } void PropertySheet::setDisplayUnit(CellAddress address, const std::string &unit) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setDisplayUnit(unit); } void PropertySheet::setAlias(CellAddress address, const std::string &alias) { - if (alias.size() > 0 && !isValidAlias(alias)) + if (!alias.empty() && !isValidAlias(alias)) throw Base::ValueError("Invalid alias"); const Cell * aliasedCell = getValueFromAlias(alias); Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); if(aliasedCell == cell) return; @@ -654,7 +654,7 @@ void PropertySheet::setAlias(CellAddress address, const std::string &alias) cell->getAlias(oldAlias); cell->setAlias(alias); - if (oldAlias.size() > 0) { + if (!oldAlias.empty()) { std::map m; App::ObjectIdentifier key(owner, oldAlias); @@ -671,14 +671,14 @@ void PropertySheet::setAlias(CellAddress address, const std::string &alias) void PropertySheet::setComputedUnit(CellAddress address, const Base::Unit &unit) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setComputedUnit(unit); } void PropertySheet::setSpans(CellAddress address, int rows, int columns) { Cell * cell = nonNullCellAt(address); - assert(cell != nullptr); + assert(cell); cell->setSpans(rows, columns); } @@ -1133,7 +1133,7 @@ void PropertySheet::addDependencies(CellAddress key) const Expression * expression = cell->getExpression(); - if (expression == nullptr) + if (!expression) return; for(auto &var : expression->getIdentifiers()) { @@ -1158,7 +1158,7 @@ void PropertySheet::addDependencies(CellAddress key) cellToPropertyNameMap[key].insert(propName); // Also an alias? - if (name.size() && docObj->isDerivedFrom(Sheet::getClassTypeId())) { + if (!name.empty() && docObj->isDerivedFrom(Sheet::getClassTypeId())) { auto other = static_cast(docObj); auto j = other->cells.revAliasProp.find(name); @@ -1219,7 +1219,7 @@ void PropertySheet::removeDependencies(CellAddress key) if (k != documentObjectToCellMap.end()) { k->second.erase(key); - if (k->second.size() == 0) + if (k->second.empty()) documentObjectToCellMap.erase(*j); } @@ -1358,7 +1358,7 @@ void PropertySheet::onRelabeledDocument(const App::Document &doc) void PropertySheet::renameObjectIdentifiers(const std::map &paths) { - RenameObjectIdentifierExpressionVisitor v(*this, paths, *this); + RenameObjectIdentifierExpressionVisitor v {*this, paths, *this}; for(auto &c : data) { c.second->visit(v); if(v.changed()) { diff --git a/src/Mod/Spreadsheet/App/PropertySheet.h b/src/Mod/Spreadsheet/App/PropertySheet.h index c1f2f1eed6..0ca0f362ae 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.h +++ b/src/Mod/Spreadsheet/App/PropertySheet.h @@ -43,35 +43,35 @@ class SpreadsheetExport PropertySheet : public App::PropertyExpressionContainer TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - PropertySheet(Sheet * _owner = nullptr); + explicit PropertySheet(Sheet * _owner = nullptr); - ~PropertySheet(); + ~PropertySheet() override; - virtual std::map getExpressions() const override; - virtual void setExpressions(std::map &&exprs) override; - virtual void onRelabeledDocument(const App::Document &doc) override; + std::map getExpressions() const override; + void setExpressions(std::map &&exprs) override; + void onRelabeledDocument(const App::Document &doc) override; - virtual void updateElementReference( + void updateElementReference( App::DocumentObject *feature,bool reverse=false,bool notify=false) override; - virtual bool referenceChanged() const override; - virtual bool adjustLink(const std::set &inList) override; - virtual Property *CopyOnImportExternal(const std::map &nameMap) const override; - virtual Property *CopyOnLabelChange(App::DocumentObject *obj, + bool referenceChanged() const override; + bool adjustLink(const std::set &inList) override; + Property *CopyOnImportExternal(const std::map &nameMap) const override; + Property *CopyOnLabelChange(App::DocumentObject *obj, const std::string &ref, const char *newLabel) const override; - virtual Property *CopyOnLinkReplace(const App::DocumentObject *parent, + Property *CopyOnLinkReplace(const App::DocumentObject *parent, App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - virtual void breakLink(App::DocumentObject *obj, bool clear) override; + void breakLink(App::DocumentObject *obj, bool clear) override; - virtual void afterRestore() override; - virtual void onContainerRestored() override; + void afterRestore() override; + void onContainerRestored() override; - virtual Property *Copy(void) const override; + Property *Copy(void) const override; - virtual void Paste(const Property &from) override; + void Paste(const Property &from) override; - virtual void Save (Base::Writer & writer) const override; + void Save (Base::Writer & writer) const override; - virtual void Restore(Base::XMLReader & reader) override; + void Restore(Base::XMLReader & reader) override; void copyCells(Base::Writer &writer, const std::vector &ranges) const; @@ -145,7 +145,7 @@ public: void removeColumns(int col, int count); - virtual unsigned int getMemSize (void) const override; + unsigned int getMemSize (void) const override; bool mergeCells(App::CellAddress from, App::CellAddress to); @@ -188,8 +188,8 @@ public: std::string getColumn(int offset=0) const; - virtual void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; - virtual const boost::any getPathValue(const App::ObjectIdentifier & path) const override; + void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; + const boost::any getPathValue(const App::ObjectIdentifier & path) const override; unsigned getBindingBorder(App::CellAddress address) const; @@ -207,11 +207,11 @@ public: App::ObjectIdentifier *pTarget=nullptr) const; protected: - virtual void hasSetValue() override; - virtual void hasSetChildValue(App::Property &prop) override; - virtual void onBreakLink(App::DocumentObject *obj) override; - virtual void onAddDep(App::DocumentObject *obj) override; - virtual void onRemoveDep(App::DocumentObject *obj) override; + void hasSetValue() override; + void hasSetChildValue(App::Property &prop) override; + void onBreakLink(App::DocumentObject *obj) override; + void onAddDep(App::DocumentObject *obj) override; + void onRemoveDep(App::DocumentObject *obj) override; private: diff --git a/src/Mod/Spreadsheet/App/Sheet.cpp b/src/Mod/Spreadsheet/App/Sheet.cpp index b8189e4567..d7016432c7 100644 --- a/src/Mod/Spreadsheet/App/Sheet.cpp +++ b/src/Mod/Spreadsheet/App/Sheet.cpp @@ -208,7 +208,7 @@ bool Sheet::importFromFile(const std::string &filename, char delimiter, char quo tokenizer > tok(line, e); for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) { - if ((*i).size() > 0) + if (!i->empty()) setCell(CellAddress(row, col), (*i).c_str()); col++; } @@ -266,10 +266,11 @@ static void writeEscaped(std::string const& s, char quoteChar, char escapeChar, bool Sheet::exportToFile(const std::string &filename, char delimiter, char quoteChar, char escapeChar) const { - std::ofstream file; + Base::ofstream file; int prevRow = -1, prevCol = -1; - file.open(filename.c_str(), std::ios::out | std::ios::ate | std::ios::binary); + Base::FileInfo fi(filename); + file.open(fi, std::ios::out | std::ios::ate | std::ios::binary); if (!file.is_open()) return false; @@ -368,7 +369,7 @@ Cell *Sheet::getNewCell(CellAddress address) { Cell * cell = getCell(address); - if (cell == nullptr) + if (!cell) cell = cells.createCell(address); return cell; @@ -384,7 +385,7 @@ Cell *Sheet::getNewCell(CellAddress address) void Sheet::setCell(const char * address, const char * contents) { - assert(address != nullptr && contents != nullptr); + assert(address && contents); setCell(CellAddress(address), contents); } @@ -400,7 +401,7 @@ void Sheet::setCell(const char * address, const char * contents) void Sheet::setCell(CellAddress address, const char * value) { - assert(value != nullptr); + assert(value); if (*value == '\0') { @@ -672,7 +673,7 @@ void Sheet::updateProperty(CellAddress key) { Cell * cell = getCell(key); - if (cell != nullptr) { + if (cell) { std::unique_ptr output; const Expression * input = cell->getExpression(); @@ -930,7 +931,7 @@ DocumentObjectExecReturn *Sheet::execute(void) std::map VertexList; std::map VertexIndexList; std::deque workQueue(dirtyCells.begin(),dirtyCells.end()); - while(workQueue.size()) { + while(!workQueue.empty()) { CellAddress currPos = workQueue.front(); workQueue.pop_front(); @@ -978,7 +979,7 @@ DocumentObjectExecReturn *Sheet::execute(void) } // Try to be more user friendly by finding individual loops - while(dirtyCells.size()) { + while(!dirtyCells.empty()) { std::deque workQueue; DependencyList graph; @@ -989,7 +990,7 @@ DocumentObjectExecReturn *Sheet::execute(void) workQueue.push_back(currentAddr); dirtyCells.erase(dirtyCells.begin()); - while (workQueue.size() > 0) { + while (!workQueue.empty()) { CellAddress currPos = workQueue.front(); workQueue.pop_front(); @@ -1057,7 +1058,7 @@ DocumentObjectExecReturn *Sheet::execute(void) rowHeights.clearDirty(); columnWidths.clearDirty(); - if (cellErrors.size() == 0) + if (cellErrors.empty()) return DocumentObject::StdReturn; else return new DocumentObjectExecReturn("One or more cells failed contains errors.", this); @@ -1070,7 +1071,7 @@ DocumentObjectExecReturn *Sheet::execute(void) short Sheet::mustExecute(void) const { - if (cellErrors.size() > 0 || cells.isDirty()) + if (!cellErrors.empty() || cells.isDirty()) return 1; return DocumentObject::mustExecute(); } @@ -1381,13 +1382,13 @@ void Sheet::setAlias(CellAddress address, const std::string &alias) { std::string existingAlias = getAddressFromAlias(alias); - if (existingAlias.size() > 0) { + if (!existingAlias.empty()) { if (existingAlias == address.toString()) // Same as old? return; else throw Base::ValueError("Alias already defined"); } - else if (alias.size() == 0) // Empty? + else if (alias.empty()) // Empty? cells.setAlias(address, ""); else if (isValidAlias(alias)) // Valid? cells.setAlias(address, alias); @@ -1427,7 +1428,7 @@ bool Sheet::isValidAlias(const std::string & candidate) return false; // Existing alias? Then it's ok - if (getAddressFromAlias(candidate).size() > 0 ) + if (!getAddressFromAlias(candidate).empty() ) return true; // Check to see that is does not crash with any other property in the Sheet object. @@ -1633,10 +1634,10 @@ void PropertySpreadsheetQuantity::Paste(const Property &from) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Spreadsheet::SheetPython, Spreadsheet::Sheet) -template<> const char* Spreadsheet::SheetPython::getViewProviderName(void) const { +template<> const char* Spreadsheet::SheetPython::getViewProviderName() const { return "SpreadsheetGui::ViewProviderSheet"; } -template<> PyObject* Spreadsheet::SheetPython::getPyObject(void) { +template<> PyObject* Spreadsheet::SheetPython::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 PythonObject = Py::Object(new FeaturePythonPyT(this),true); diff --git a/src/Mod/Spreadsheet/App/Sheet.h b/src/Mod/Spreadsheet/App/Sheet.h index 0c746c2328..a13e64f8f8 100644 --- a/src/Mod/Spreadsheet/App/Sheet.h +++ b/src/Mod/Spreadsheet/App/Sheet.h @@ -60,27 +60,27 @@ class SheetObserver; */ class SpreadsheetExport PropertySpreadsheetQuantity : public App::PropertyQuantity { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: PropertySpreadsheetQuantity(void){} - virtual ~PropertySpreadsheetQuantity(){} + ~PropertySpreadsheetQuantity() override{} - virtual Property *Copy(void) const; - virtual void Paste(const Property &from); + Property *Copy(void) const override; + void Paste(const Property &from) override; }; class SpreadsheetExport Sheet : public App::DocumentObject { - PROPERTY_HEADER(Spreadsheet::Sheet); + PROPERTY_HEADER_WITH_OVERRIDE(Spreadsheet::Sheet); public: /// Constructor Sheet(); - virtual ~Sheet(); + ~Sheet() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "SpreadsheetGui::ViewProviderSheet"; } @@ -171,19 +171,19 @@ public: void providesTo(App::CellAddress address, std::set & result) const; bool hasCell(const std::vector &ranges) const; - PyObject *getPyObject(); + PyObject *getPyObject() override; PropertySheet *getCells() { return &cells; } - App::Property *getPropertyByName(const char *name) const; + App::Property *getPropertyByName(const char *name) const override; - App::Property *getDynamicPropertyByName(const char* name) const; + App::Property *getDynamicPropertyByName(const char* name) const override; - virtual void getPropertyNamedList(std::vector > &List) const; + void getPropertyNamedList(std::vector > &List) const override; - virtual short mustExecute(void) const; + short mustExecute(void) const override; - App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute(void) override; bool getCellAddress(const App::Property *prop, App::CellAddress &address); @@ -217,7 +217,7 @@ public: void observeDocument(App::Document *document); - virtual void renameObjectIdentifiers(const std::map & paths); + void renameObjectIdentifiers(const std::map & paths) override; void setCopyOrCutRanges(const std::vector &ranges, bool copy=true); const std::vector &getCopyOrCutRange(bool copy=true) const; @@ -225,13 +225,13 @@ public: protected: - virtual void onChanged(const App::Property *prop); + void onChanged(const App::Property *prop) override; void updateColumnsOrRows(bool horizontal, int section, int count) ; std::set providesTo(App::CellAddress address) const; - void onDocumentRestored(); + void onDocumentRestored() override; void recomputeCell(App::CellAddress p); @@ -251,7 +251,7 @@ protected: App::Property *setQuantityProperty(App::CellAddress key, double value, const Base::Unit &unit); - virtual void onSettingDocument(); + void onSettingDocument() override; void updateBindings(); diff --git a/src/Mod/Spreadsheet/App/SheetObserver.cpp b/src/Mod/Spreadsheet/App/SheetObserver.cpp index 4c9a0dc87d..d540998edc 100644 --- a/src/Mod/Spreadsheet/App/SheetObserver.cpp +++ b/src/Mod/Spreadsheet/App/SheetObserver.cpp @@ -75,7 +75,7 @@ void SheetObserver::slotChangedObject(const DocumentObject &Obj, const Property else { const char * name = Obj.getPropertyName(&Prop); - if (name == nullptr) + if (!name) return; if (isUpdating.find(name) != isUpdating.end()) diff --git a/src/Mod/Spreadsheet/App/SheetObserver.h b/src/Mod/Spreadsheet/App/SheetObserver.h index 3b4e855ae4..0a6f7a1547 100644 --- a/src/Mod/Spreadsheet/App/SheetObserver.h +++ b/src/Mod/Spreadsheet/App/SheetObserver.h @@ -33,10 +33,10 @@ class PropertySheet; class SheetObserver : public App::DocumentObserver { public: SheetObserver(App::Document* document, PropertySheet *_sheet); - ~SheetObserver() { } - virtual void slotCreatedObject(const App::DocumentObject& Obj); - virtual void slotDeletedObject(const App::DocumentObject& Obj); - virtual void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop); + ~SheetObserver() override { } + void slotCreatedObject(const App::DocumentObject& Obj) override; + void slotDeletedObject(const App::DocumentObject& Obj) override; + void slotChangedObject(const App::DocumentObject& Obj, const App::Property& Prop) override; void ref(); bool unref(); App::Document* getDocument() const { return App::DocumentObserver::getDocument(); } diff --git a/src/Mod/Spreadsheet/App/SheetPyImp.cpp b/src/Mod/Spreadsheet/App/SheetPyImp.cpp index 217bd8e25a..c17cf1d2f7 100644 --- a/src/Mod/Spreadsheet/App/SheetPyImp.cpp +++ b/src/Mod/Spreadsheet/App/SheetPyImp.cpp @@ -71,7 +71,7 @@ PyObject* SheetPy::set(PyObject *args) std::string cellAddress = sheet->getAddressFromAlias(address).c_str(); /* Check to see if address is really an alias first */ - if (cellAddress.size() > 0) + if (!cellAddress.empty()) sheet->setCell(cellAddress.c_str(), contents); else { Range rangeIter(address); @@ -123,7 +123,7 @@ PyObject* SheetPy::get(PyObject *args) App::Property * prop = this->getSheetPtr()->getPropertyByName(address); - if (prop == nullptr) { + if (!prop) { PyErr_Format(PyExc_ValueError, "Invalid cell address or property: %s",address); return nullptr; @@ -544,7 +544,7 @@ PyObject* SheetPy::getCellFromAlias(PyObject *args) try { std::string address = getSheetPtr()->getAddressFromAlias(alias); - if (address.size() > 0) + if (!address.empty()) return Py::new_reference_to( Py::String( address ) ); else { Py_INCREF(Py_None); @@ -622,7 +622,7 @@ PyObject* SheetPy::setAlignment(PyObject *args) tokenizer > tok(line, e); for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) { - if(i->size()) + if(!i->empty()) alignment = Cell::decodeAlignment(*i, alignment); } } diff --git a/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py b/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py index b04aa569c0..c73e08eddc 100644 --- a/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py +++ b/src/Mod/Spreadsheet/App/Spreadsheet_legacy.py @@ -41,7 +41,7 @@ class MathParser: 'e' : math.e } for var in vars.keys(): - if self.vars.get(var) != None: + if self.vars.get(var) is not None: raise RuntimeError("Cannot redefine the value of " + var) self.vars[var] = vars[var] diff --git a/src/Mod/Spreadsheet/App/Utils.cpp b/src/Mod/Spreadsheet/App/Utils.cpp index f651c9e61f..f20ae7aced 100644 --- a/src/Mod/Spreadsheet/App/Utils.cpp +++ b/src/Mod/Spreadsheet/App/Utils.cpp @@ -74,7 +74,7 @@ std::string Spreadsheet::rowName(int row) void Spreadsheet::createRectangles(std::set > & cells, std::map, std::pair > & rectangles) { - while (cells.size() != 0) { + while (!cells.empty()) { int row, col; int orgRow; int rows = 1; diff --git a/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp b/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp index 321b1c2bef..3dd53f9bd2 100644 --- a/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp +++ b/src/Mod/Spreadsheet/Gui/AppSpreadsheetGui.cpp @@ -71,7 +71,7 @@ public: initialize("This module is the SpreadsheetGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object open(const Py::Tuple& args) diff --git a/src/Mod/Spreadsheet/Gui/CMakeLists.txt b/src/Mod/Spreadsheet/Gui/CMakeLists.txt index 7f0975be55..ae932c3245 100644 --- a/src/Mod/Spreadsheet/Gui/CMakeLists.txt +++ b/src/Mod/Spreadsheet/Gui/CMakeLists.txt @@ -5,6 +5,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) generate_from_xml(ViewProviderSpreadsheetPy) diff --git a/src/Mod/Spreadsheet/Gui/Command.cpp b/src/Mod/Spreadsheet/Gui/Command.cpp index 3e9ed3a5d4..2a6e2e96f1 100644 --- a/src/Mod/Spreadsheet/Gui/Command.cpp +++ b/src/Mod/Spreadsheet/Gui/Command.cpp @@ -87,7 +87,7 @@ void CmdSpreadsheetMergeCells::activated(int iMsg) std::vector ranges = sheetView->selectedRanges(); // Execute mergeCells commands - if (ranges.size() > 0) { + if (!ranges.empty()) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Merge cells")); std::vector::const_iterator i = ranges.begin(); for (; i != ranges.end(); ++i) @@ -311,7 +311,7 @@ void CmdSpreadsheetAlignLeft::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); std::vector ranges = sheetView->selectedRanges(); - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Left-align cell")); @@ -363,7 +363,7 @@ void CmdSpreadsheetAlignCenter::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); std::vector ranges = sheetView->selectedRanges(); - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Center cell")); @@ -415,7 +415,7 @@ void CmdSpreadsheetAlignRight::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); std::vector ranges = sheetView->selectedRanges(); - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Right-align cell")); @@ -467,7 +467,7 @@ void CmdSpreadsheetAlignTop::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); std::vector ranges = sheetView->selectedRanges(); - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Top-align cell")); @@ -519,7 +519,7 @@ void CmdSpreadsheetAlignBottom::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); std::vector ranges = sheetView->selectedRanges(); - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Bottom-align cell")); @@ -571,7 +571,7 @@ void CmdSpreadsheetAlignVCenter::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); std::vector ranges = sheetView->selectedRanges(); - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Vertically center cells")); @@ -623,10 +623,10 @@ void CmdSpreadsheetStyleBold::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); QModelIndexList selection = sheetView->selectedIndexes(); - if (selection.size() > 0) { + if (!selection.empty()) { bool allBold = true; - for (QModelIndexList::const_iterator it = selection.begin(); it != selection.end(); ++it) { + for (QModelIndexList::const_iterator it = selection.cbegin(); it != selection.cend(); ++it) { const Cell * cell = sheet->getCell(CellAddress((*it).row(), (*it).column())); if (cell) { @@ -697,10 +697,10 @@ void CmdSpreadsheetStyleItalic::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); QModelIndexList selection = sheetView->selectedIndexes(); - if (selection.size() > 0) { + if (!selection.empty()) { bool allItalic = true; - for (QModelIndexList::const_iterator it = selection.begin(); it != selection.end(); ++it) { + for (QModelIndexList::const_iterator it = selection.cbegin(); it != selection.cend(); ++it) { const Cell * cell = sheet->getCell(CellAddress((*it).row(), (*it).column())); if (cell) { @@ -771,10 +771,10 @@ void CmdSpreadsheetStyleUnderline::activated(int iMsg) Sheet * sheet = sheetView->getSheet(); QModelIndexList selection = sheetView->selectedIndexes(); - if (selection.size() > 0) { + if (!selection.empty()) { bool allUnderline = true; - for (QModelIndexList::const_iterator it = selection.begin(); it != selection.end(); ++it) { + for (QModelIndexList::const_iterator it = selection.cbegin(); it != selection.cend(); ++it) { const Cell * cell = sheet->getCell(CellAddress((*it).row(), (*it).column())); if (cell) { diff --git a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp index 23c2f4dd57..5d81dbb497 100644 --- a/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp +++ b/src/Mod/Spreadsheet/Gui/DlgBindSheet.cpp @@ -139,7 +139,7 @@ void DlgBindSheet::accept() { bool commandActive = false; try { - const char *ref = ui->comboBox->itemData(ui->comboBox->currentIndex()).toByteArray().constData(); + const char *ref = ui->comboBox->itemData(ui->comboBox->currentIndex()).toByteArray().constData(); // clazy:exclude=returning-data-from-temporary auto obj = sheet; if(ref[0]) { const char *sep = strchr(ref,'#'); diff --git a/src/Mod/Spreadsheet/Gui/DlgBindSheet.h b/src/Mod/Spreadsheet/Gui/DlgBindSheet.h index 51d20e65de..02587dd503 100644 --- a/src/Mod/Spreadsheet/Gui/DlgBindSheet.h +++ b/src/Mod/Spreadsheet/Gui/DlgBindSheet.h @@ -38,9 +38,9 @@ class DlgBindSheet : public QDialog public: explicit DlgBindSheet(Spreadsheet::Sheet *sheet, const std::vector &range, QWidget *parent = nullptr); - ~DlgBindSheet(); + ~DlgBindSheet() override; - void accept(); + void accept() override; public Q_SLOTS: void onDiscard(); diff --git a/src/Mod/Spreadsheet/Gui/DlgSettingsImp.h b/src/Mod/Spreadsheet/Gui/DlgSettingsImp.h index d65e335044..3aa365e81e 100644 --- a/src/Mod/Spreadsheet/Gui/DlgSettingsImp.h +++ b/src/Mod/Spreadsheet/Gui/DlgSettingsImp.h @@ -40,13 +40,13 @@ class DlgSettingsImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgSettingsImp( QWidget* parent = nullptr ); - ~DlgSettingsImp(); + explicit DlgSettingsImp( QWidget* parent = nullptr ); + ~DlgSettingsImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Spreadsheet/Gui/DlgSheetConf.h b/src/Mod/Spreadsheet/Gui/DlgSheetConf.h index 6d20fc5a31..ce2aa42895 100644 --- a/src/Mod/Spreadsheet/Gui/DlgSheetConf.h +++ b/src/Mod/Spreadsheet/Gui/DlgSheetConf.h @@ -38,9 +38,9 @@ class DlgSheetConf : public QDialog public: explicit DlgSheetConf(Spreadsheet::Sheet *sheet, App::Range range, QWidget *parent = nullptr); - ~DlgSheetConf(); + ~DlgSheetConf() override; - void accept(); + void accept() override; App::Property *prepare(App::CellAddress &from, App::CellAddress &to, std::string &rangeConf, App::ObjectIdentifier &path, bool init); diff --git a/src/Mod/Spreadsheet/Gui/LineEdit.h b/src/Mod/Spreadsheet/Gui/LineEdit.h index a2b9ed58ee..8f253f7b09 100644 --- a/src/Mod/Spreadsheet/Gui/LineEdit.h +++ b/src/Mod/Spreadsheet/Gui/LineEdit.h @@ -35,13 +35,13 @@ class LineEdit : public Gui::ExpressionLineEdit public: explicit LineEdit(QWidget *parent = nullptr); - bool event(QEvent *event); + bool event(QEvent *event) override; Q_SIGNALS: void finishedWithKey(int key, Qt::KeyboardModifiers modifiers); private: - bool eventFilter(QObject* object, QEvent* event); + bool eventFilter(QObject* object, QEvent* event) override; private: diff --git a/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp b/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp index 00702f00cd..ccbc7411d1 100644 --- a/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp +++ b/src/Mod/Spreadsheet/Gui/PropertiesDialog.cpp @@ -52,7 +52,7 @@ PropertiesDialog::PropertiesDialog(Sheet *_sheet, const std::vector &_ran Cell * cell = sheet->getNewCell(*range); - assert(cell != nullptr); + assert(cell); (void)cell->getForeground(foregroundColor); (void)cell->getBackground(backgroundColor); @@ -224,7 +224,7 @@ PropertiesDialog::~PropertiesDialog() void PropertiesDialog::apply() { - if (ranges.size() > 0) { + if (!ranges.empty()) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Set cell properties")); std::vector::const_iterator i = ranges.begin(); bool changes = false; diff --git a/src/Mod/Spreadsheet/Gui/PropertiesDialog.h b/src/Mod/Spreadsheet/Gui/PropertiesDialog.h index 6c8acaaa42..e68ceed029 100644 --- a/src/Mod/Spreadsheet/Gui/PropertiesDialog.h +++ b/src/Mod/Spreadsheet/Gui/PropertiesDialog.h @@ -38,7 +38,7 @@ class PropertiesDialog : public QDialog public: explicit PropertiesDialog(Spreadsheet::Sheet *_sheet, const std::vector & _ranges, QWidget *parent = nullptr); - ~PropertiesDialog(); + ~PropertiesDialog() override; void apply(); void selectAlias(); diff --git a/src/Mod/Spreadsheet/Gui/SheetModel.cpp b/src/Mod/Spreadsheet/Gui/SheetModel.cpp index 259faa4808..bcde0eff56 100644 --- a/src/Mod/Spreadsheet/Gui/SheetModel.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetModel.cpp @@ -85,7 +85,7 @@ QVariant SheetModel::data(const QModelIndex &index, int role) const int col = index.column(); const Cell * cell = sheet->getCell(CellAddress(row, col)); - if (cell == nullptr) + if (!cell) cell = emptyCell; //#define DEBUG_DEPS @@ -224,7 +224,7 @@ QVariant SheetModel::data(const QModelIndex &index, int role) const if(cell->getExpression()) { std::string str; if (cell->getStringContent(str)) - if (str.size() > 0 && str[0] == '=') + if (!str.empty() && str[0] == '=') // If this is a real computed value, indicate that a recompute is // needed before we can display it return QVariant(QLatin1String("#PENDING")); @@ -516,7 +516,7 @@ void SheetModel::cellUpdated(CellAddress address) { QModelIndex i = index(address.row(), address.col()); - dataChanged(i, i); + Q_EMIT dataChanged(i, i); } void SheetModel::rangeUpdated(const Range &range) @@ -524,7 +524,7 @@ void SheetModel::rangeUpdated(const Range &range) QModelIndex i = index(range.from().row(), range.from().col()); QModelIndex j = index(range.to().row(), range.to().col()); - dataChanged(i, j); + Q_EMIT dataChanged(i, j); } #include "moc_SheetModel.cpp" diff --git a/src/Mod/Spreadsheet/Gui/SheetModel.h b/src/Mod/Spreadsheet/Gui/SheetModel.h index f30ab5c8e5..dd71b8748c 100644 --- a/src/Mod/Spreadsheet/Gui/SheetModel.h +++ b/src/Mod/Spreadsheet/Gui/SheetModel.h @@ -38,15 +38,15 @@ class SheetModel : public QAbstractTableModel Q_OBJECT public: explicit SheetModel(Spreadsheet::Sheet * _sheet, QObject *parent = nullptr); - ~SheetModel(); + ~SheetModel() override; - SheetModel(QObject *parent); - int rowCount(const QModelIndex &parent = QModelIndex()) const ; - int columnCount(const QModelIndex &parent = QModelIndex()) const; - QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - QVariant headerData(int section, Qt::Orientation orientation, int role) const; - bool setData(const QModelIndex &index, const QVariant &value, int role); - Qt::ItemFlags flags(const QModelIndex &) const; + explicit SheetModel(QObject *parent); + int rowCount(const QModelIndex &parent = QModelIndex()) const override ; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; + Qt::ItemFlags flags(const QModelIndex &) const override; private Q_SLOTS: void setCellData(QModelIndex index, QString str); diff --git a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp index 3b1af956c4..bfea091ed4 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableView.cpp +++ b/src/Mod/Spreadsheet/Gui/SheetTableView.cpp @@ -60,7 +60,7 @@ namespace bp = boost::placeholders; void SheetViewHeader::mouseReleaseEvent(QMouseEvent *event) { QHeaderView::mouseReleaseEvent(event); - resizeFinished(); + Q_EMIT resizeFinished(); } bool SheetViewHeader::viewportEvent(QEvent *e) { @@ -223,7 +223,7 @@ void SheetTableView::onRecompute() { void SheetTableView::onBind() { auto ranges = selectedRanges(); - if(ranges.size()>=1 && ranges.size()<=2) { + if(!ranges.empty() && ranges.size()<=2) { DlgBindSheet dlg(sheet,ranges,this); dlg.exec(); } @@ -308,13 +308,13 @@ QModelIndexList SheetTableView::selectedIndexesRaw() const void SheetTableView::insertRows() { - assert(sheet != nullptr); + assert(sheet); QModelIndexList rows = selectionModel()->selectedRows(); std::vector sortedRows; /* Make sure rows are sorted in ascending order */ - for (QModelIndexList::const_iterator it = rows.begin(); it != rows.end(); ++it) + for (QModelIndexList::const_iterator it = rows.cbegin(); it != rows.cend(); ++it) sortedRows.push_back(it->row()); std::sort(sortedRows.begin(), sortedRows.end()); @@ -345,7 +345,7 @@ void SheetTableView::insertRows() void SheetTableView::insertRowsAfter() { - assert(sheet != nullptr); + assert(sheet); const auto rows = selectionModel()->selectedRows(); const auto & [min, max] = selectedMinMaxRows(rows); assert(max - min == rows.size() - 1); @@ -359,13 +359,13 @@ void SheetTableView::insertRowsAfter() void SheetTableView::removeRows() { - assert(sheet != nullptr); + assert(sheet); QModelIndexList rows = selectionModel()->selectedRows(); std::vector sortedRows; /* Make sure rows are sorted in descending order */ - for (QModelIndexList::const_iterator it = rows.begin(); it != rows.end(); ++it) + for (QModelIndexList::const_iterator it = rows.cbegin(); it != rows.cend(); ++it) sortedRows.push_back(it->row()); std::sort(sortedRows.begin(), sortedRows.end(), std::greater()); @@ -380,13 +380,13 @@ void SheetTableView::removeRows() void SheetTableView::insertColumns() { - assert(sheet != nullptr); + assert(sheet); QModelIndexList cols = selectionModel()->selectedColumns(); std::vector sortedColumns; /* Make sure rows are sorted in ascending order */ - for (QModelIndexList::const_iterator it = cols.begin(); it != cols.end(); ++it) + for (QModelIndexList::const_iterator it = cols.cbegin(); it != cols.cend(); ++it) sortedColumns.push_back(it->column()); std::sort(sortedColumns.begin(), sortedColumns.end()); @@ -418,7 +418,7 @@ void SheetTableView::insertColumns() void SheetTableView::insertColumnsAfter() { - assert(sheet != nullptr); + assert(sheet); const auto columns = selectionModel()->selectedColumns(); const auto& [min, max] = selectedMinMaxColumns(columns); assert(max - min == columns.size() - 1); @@ -432,13 +432,13 @@ void SheetTableView::insertColumnsAfter() void SheetTableView::removeColumns() { - assert(sheet != nullptr); + assert(sheet); QModelIndexList cols = selectionModel()->selectedColumns(); std::vector sortedColumns; /* Make sure rows are sorted in descending order */ - for (QModelIndexList::const_iterator it = cols.begin(); it != cols.end(); ++it) + for (QModelIndexList::const_iterator it = cols.cbegin(); it != cols.cend(); ++it) sortedColumns.push_back(it->column()); std::sort(sortedColumns.begin(), sortedColumns.end(), std::greater()); @@ -599,7 +599,7 @@ void SheetTableView::deleteSelection() { QModelIndexList selection = selectionModel()->selectedIndexes(); - if (selection.size() > 0) { + if (!selection.empty()) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Clear cell(s)")); std::vector ranges = selectedRanges(); std::vector::const_iterator i = ranges.begin(); @@ -672,7 +672,7 @@ void SheetTableView::pasteClipboard() ranges = sheet->getCopyOrCutRange(copy); } - if(ranges.size()) + if(!ranges.empty()) _copySelection(ranges, copy); const QMimeData* mimeData = QApplication::clipboard()->mimeData(); @@ -694,13 +694,13 @@ void SheetTableView::pasteClipboard() Range range = ranges.back(); if (!mimeData->hasFormat(_SheetMime)) { CellAddress current = range.from(); - QStringList cells; QString text = mimeData->text(); + QStringList cells = text.split(QLatin1Char('\n')); int i=0; - for (auto it : text.split(QLatin1Char('\n'))) { + for (const auto& it : cells) { QStringList cols = it.split(QLatin1Char('\t')); int j=0; - for (auto jt : cols) { + for (const auto& jt : cols) { QModelIndex index = model()->index(current.row()+i, current.col()+j); model()->setData(index, jt); j++; @@ -1004,7 +1004,7 @@ void SheetTableView::contextMenuEvent(QContextMenuEvent *) } auto ranges = selectedRanges(); - actionBind->setEnabled(ranges.size()>=1 && ranges.size()<=2); + actionBind->setEnabled(!ranges.empty() && ranges.size()<=2); contextMenu->exec(QCursor::pos()); } diff --git a/src/Mod/Spreadsheet/Gui/SheetTableView.h b/src/Mod/Spreadsheet/Gui/SheetTableView.h index b26c676e39..90164e4a81 100644 --- a/src/Mod/Spreadsheet/Gui/SheetTableView.h +++ b/src/Mod/Spreadsheet/Gui/SheetTableView.h @@ -42,8 +42,8 @@ public: Q_SIGNALS: void resizeFinished(); protected: - void mouseReleaseEvent(QMouseEvent * event); - bool viewportEvent(QEvent *e); + void mouseReleaseEvent(QMouseEvent * event) override; + bool viewportEvent(QEvent *e) override; private: QTableView *owner; }; @@ -53,7 +53,7 @@ class SheetTableView : public QTableView Q_OBJECT public: explicit SheetTableView(QWidget *parent = nullptr); - ~SheetTableView(); + ~SheetTableView() override; void edit(const QModelIndex &index); void setSheet(Spreadsheet::Sheet *_sheet); @@ -72,7 +72,7 @@ public Q_SLOTS: void ModifyBlockSelection(int targetRow, int targetColumn); protected Q_SLOTS: - void commitData(QWidget *editor); + void commitData(QWidget *editor) override; void updateCellSpan(App::CellAddress address); void insertRows(); void insertRowsAfter(); @@ -86,13 +86,13 @@ protected Q_SLOTS: void onConfSetup(); protected: - bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event); - bool event(QEvent *event); - void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint); - void mousePressEvent(QMouseEvent* event); - void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); + bool edit(const QModelIndex &index, EditTrigger trigger, QEvent *event) override; + bool event(QEvent *event) override; + void closeEditor(QWidget *editor, QAbstractItemDelegate::EndEditHint hint) override; + void mousePressEvent(QMouseEvent* event) override; + void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override; - void contextMenuEvent (QContextMenuEvent * e); + void contextMenuEvent (QContextMenuEvent * e) override; void _copySelection(const std::vector &ranges, bool copy); diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h b/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h index d7cb3f2ebe..8d388c1375 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetDelegate.h @@ -39,13 +39,13 @@ class SpreadsheetDelegate : public QStyledItemDelegate public: explicit SpreadsheetDelegate(Spreadsheet::Sheet * sheet, QWidget *parent = nullptr); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, - const QModelIndex &index) const; - void setEditorData(QWidget *editor, const QModelIndex &index) const; + const QModelIndex &index) const override; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const; + const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const override; Q_SIGNALS: void finishedWithKey(int key, Qt::KeyboardModifiers modifiers); diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp b/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp index 8b0d104c7c..24e94b7881 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetView.cpp @@ -118,11 +118,11 @@ SheetView::SheetView(Gui::Document *pcDocument, App::DocumentObject *docObj, QWi ui->cells->setPalette(palette); QList bgList = Gui::getMainWindow()->findChildren(QString::fromLatin1("Spreadsheet_BackgroundColor")); - if (bgList.size() > 0) + if (!bgList.empty()) bgList[0]->setCurrentColor(palette.color(QPalette::Base)); QList fgList = Gui::getMainWindow()->findChildren(QString::fromLatin1("Spreadsheet_ForegroundColor")); - if (fgList.size() > 0) + if (!fgList.empty()) fgList[0]->setCurrentColor(palette.color(QPalette::Text)); // Set document object to create auto completer @@ -133,7 +133,9 @@ SheetView::SheetView(Gui::Document *pcDocument, App::DocumentObject *docObj, QWi SheetView::~SheetView() { Gui::Application::Instance->detachView(this); - //delete delegate; + delete ui; + delete model; + delete delegate; } bool SheetView::onMsg(const char *pMsg, const char **) @@ -310,7 +312,7 @@ void SheetView::updateAliasLine() void SheetView::columnResizeFinished() { - if (newColumnSizes.size() == 0) + if (newColumnSizes.empty()) return; blockSignals(true); @@ -322,7 +324,7 @@ void SheetView::columnResizeFinished() void SheetView::rowResizeFinished() { - if (newRowSizes.size() == 0) + if (newRowSizes.empty()) return; blockSignals(true); @@ -581,7 +583,7 @@ Py::Object SheetViewPy::getattr(const char * attr) if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); - for (auto it : dict_base) { + for (const auto& it : dict_base) { dict_self.setItem(it.first, it.second); } return dict_self; diff --git a/src/Mod/Spreadsheet/Gui/SpreadsheetView.h b/src/Mod/Spreadsheet/Gui/SpreadsheetView.h index 9c72c454c0..445a87b0fc 100644 --- a/src/Mod/Spreadsheet/Gui/SpreadsheetView.h +++ b/src/Mod/Spreadsheet/Gui/SpreadsheetView.h @@ -55,23 +55,23 @@ class SpreadsheetGuiExport SheetView : public Gui::MDIView { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: SheetView(Gui::Document* pcDocument, App::DocumentObject* docObj, QWidget* parent); - ~SheetView(); + ~SheetView() override; - const char *getName(void) const {return "SheetView";} + const char *getName(void) const override {return "SheetView";} - bool onMsg(const char* pMsg,const char** ppReturn); - bool onHasMsg(const char* pMsg) const; + bool onMsg(const char* pMsg,const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; /** @name Printing */ //@{ - void print(); - void printPdf(); - void printPreview(); - void print(QPrinter*); + void print() override; + void printPdf() override; + void printPreview() override; + void print(QPrinter*) override; //@} void updateCell(const App::Property * prop); @@ -93,9 +93,9 @@ public: void deleteSelection(); - PyObject *getPyObject(void); + PyObject *getPyObject(void) override; - virtual void deleteSelf(); + void deleteSelf() override; protected Q_SLOTS: void editingFinishedWithKey(int key, Qt::KeyboardModifiers modifiers); @@ -133,11 +133,11 @@ public: using BaseType = Py::PythonExtension; static void init_type(); - SheetViewPy(SheetView *mdi); - ~SheetViewPy(); + explicit SheetViewPy(SheetView *mdi); + ~SheetViewPy() override; - Py::Object repr(); - Py::Object getattr(const char *); + Py::Object repr() override; + Py::Object getattr(const char *) override; Py::Object getSheet(const Py::Tuple&); Py::Object cast_to_base(const Py::Tuple&); diff --git a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp index 5bef28a45a..25abd9bb3d 100644 --- a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp +++ b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.cpp @@ -82,7 +82,7 @@ void ViewProviderSheet::setDisplayMode(const char* ModeName) std::vector ViewProviderSheet::getDisplayModes(void) const { std::vector StrList; - StrList.push_back("Spreadsheet"); + StrList.emplace_back("Spreadsheet"); return StrList; } diff --git a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.h b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.h index 565aac1fca..85f5ab2213 100644 --- a/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.h +++ b/src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.h @@ -48,26 +48,26 @@ public: ViewProviderSheet(); /// destructor. - ~ViewProviderSheet(); + ~ViewProviderSheet() override; void setDisplayMode(const char* ModeName) override; - virtual bool useNewSelectionModel(void) const override {return false;} + bool useNewSelectionModel(void) const override {return false;} std::vector getDisplayModes() const override; - virtual bool doubleClicked(void) override; + bool doubleClicked(void) override; void setupContextMenu(QMenu* menu, QObject* receiver, const char* member) override; Spreadsheet::Sheet* getSpreadsheetObject() const; - virtual void beforeDelete() override; + void beforeDelete() override; QIcon getIcon() const override; - virtual bool setEdit(int ModNum) override; + bool setEdit(int ModNum) override; - virtual bool isShow(void) const override { return true; } + bool isShow(void) const override { return true; } - virtual Gui::MDIView *getMDIView() const override; + Gui::MDIView *getMDIView() const override; inline SheetView* getView() const { return view; } diff --git a/src/Mod/Spreadsheet/Gui/Workbench.cpp b/src/Mod/Spreadsheet/Gui/Workbench.cpp index b7c2a4a978..2d3a92271a 100644 --- a/src/Mod/Spreadsheet/Gui/Workbench.cpp +++ b/src/Mod/Spreadsheet/Gui/Workbench.cpp @@ -78,7 +78,7 @@ void Workbench::activated() QPalette palette = Gui::getMainWindow()->palette(); QList fgList = Gui::getMainWindow()->findChildren(QString::fromLatin1("Spreadsheet_ForegroundColor")); - if (fgList.size() > 0) + if (!fgList.empty()) foregroundColor = fgList[0]; else { foregroundColor = new QtColorPicker(); @@ -93,7 +93,7 @@ void Workbench::activated() bar->addWidget(foregroundColor); QList bgList = Gui::getMainWindow()->findChildren(QString::fromLatin1("Spreadsheet_BackgroundColor")); - if (bgList.size() > 0) + if (!bgList.empty()) backgroundColor = bgList[0]; else { backgroundColor = new QtColorPicker(); @@ -125,7 +125,7 @@ void WorkbenchHelper::setForegroundColor(const QColor & color) std::vector ranges = sheetView->selectedRanges(); // Execute mergeCells commands - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Set foreground color")); @@ -152,7 +152,7 @@ void WorkbenchHelper::setBackgroundColor(const QColor & color) std::vector ranges = sheetView->selectedRanges(); // Execute mergeCells commands - if (ranges.size() > 0) { + if (!ranges.empty()) { std::vector::const_iterator i = ranges.begin(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Set background color")); diff --git a/src/Mod/Spreadsheet/Gui/Workbench.h b/src/Mod/Spreadsheet/Gui/Workbench.h index 06a0388c28..67d9807bb9 100644 --- a/src/Mod/Spreadsheet/Gui/Workbench.h +++ b/src/Mod/Spreadsheet/Gui/Workbench.h @@ -47,21 +47,21 @@ protected Q_SLOTS: class SpreadsheetGuiExport Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); - void activated(); + ~Workbench() override; + void activated() override; private: bool initialized; std::unique_ptr workbenchHelper; protected: - Gui::MenuItem *setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; - Gui::ToolBarItem* setupCommandBars() const; + Gui::MenuItem *setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; + Gui::ToolBarItem* setupCommandBars() const override; }; } // namespace SpreadsheetModGui diff --git a/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp b/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp index 2ec41dba04..0c68f186f1 100644 --- a/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp +++ b/src/Mod/Spreadsheet/Gui/qtcolorpicker.cpp @@ -152,14 +152,14 @@ signals: void clicked(); protected: - void mousePressEvent(QMouseEvent *e); - void mouseMoveEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void keyPressEvent(QKeyEvent *e); - void keyReleaseEvent(QKeyEvent *e); - void paintEvent(QPaintEvent *e); - void focusInEvent(QFocusEvent *e); - void focusOutEvent(QFocusEvent *e); + void mousePressEvent(QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; + void keyPressEvent(QKeyEvent *e) override; + void keyReleaseEvent(QKeyEvent *e) override; + void paintEvent(QPaintEvent *e) override; + void focusInEvent(QFocusEvent *e) override; + void focusOutEvent(QFocusEvent *e) override; }; /* @@ -172,7 +172,7 @@ class ColorPickerItem : public QFrame public: ColorPickerItem(const QColor &color = Qt::white, const QString &text = QString(), QWidget *parent = nullptr); - ~ColorPickerItem(); + ~ColorPickerItem() override; QColor color() const; QString text() const; @@ -187,10 +187,10 @@ public Q_SLOTS: void setColor(const QColor &color, const QString &text = QString()); protected: - void mousePressEvent(QMouseEvent *e); - void mouseReleaseEvent(QMouseEvent *e); - void mouseMoveEvent(QMouseEvent *e); - void paintEvent(QPaintEvent *e); + void mousePressEvent(QMouseEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; + void mouseMoveEvent(QMouseEvent *e) override; + void paintEvent(QPaintEvent *e) override; private: QColor c; @@ -208,7 +208,7 @@ class ColorPickerPopup : public QFrame public: ColorPickerPopup(int width, bool withColorDialog, QWidget *parent = nullptr); - ~ColorPickerPopup(); + ~ColorPickerPopup() override; void insertColor(const QColor &col, const QString &text, int index); void exec(); @@ -233,10 +233,10 @@ protected Q_SLOTS: void updateSelected(); protected: - void keyPressEvent(QKeyEvent *e); - void showEvent(QShowEvent *e); - void hideEvent(QHideEvent *e); - void mouseReleaseEvent(QMouseEvent *e); + void keyPressEvent(QKeyEvent *e) override; + void showEvent(QShowEvent *e) override; + void hideEvent(QHideEvent *e) override; + void mouseReleaseEvent(QMouseEvent *e) override; void regenerateGrid(); diff --git a/src/Mod/Spreadsheet/Gui/qtcolorpicker.h b/src/Mod/Spreadsheet/Gui/qtcolorpicker.h index 6122183b17..391435839d 100644 --- a/src/Mod/Spreadsheet/Gui/qtcolorpicker.h +++ b/src/Mod/Spreadsheet/Gui/qtcolorpicker.h @@ -76,13 +76,13 @@ class QT_QTCOLORPICKER_EXPORT QtColorPicker : public QPushButton { Q_OBJECT - Q_PROPERTY(bool colorDialog READ colorDialogEnabled WRITE setColorDialogEnabled) + Q_PROPERTY(bool colorDialog READ colorDialogEnabled WRITE setColorDialogEnabled) // clazy:exclude=qproperty-without-notify public: QtColorPicker(QWidget *parent = nullptr, int columns = -1, bool enableColorDialog = true); - ~QtColorPicker(); + ~QtColorPicker() override; void insertColor(const QColor &color, const QString &text = QString(), int index = -1); @@ -105,7 +105,7 @@ Q_SIGNALS: void colorSet(const QColor &); protected: - void paintEvent(QPaintEvent *e); + void paintEvent(QPaintEvent *e) override; private Q_SLOTS: void buttonPressed(bool toggled); diff --git a/src/Mod/Spreadsheet/InitGui.py b/src/Mod/Spreadsheet/InitGui.py index dda6423eb7..8a8b7b2a1e 100644 --- a/src/Mod/Spreadsheet/InitGui.py +++ b/src/Mod/Spreadsheet/InitGui.py @@ -45,4 +45,4 @@ class SpreadsheetWorkbench ( Workbench ): Gui.addWorkbench(SpreadsheetWorkbench()) # Append the open handler -FreeCAD.EndingAdd("Spreadsheet formats (*.csv)","SpreadsheetGui") +FreeCAD.addImportType("Spreadsheet formats (*.csv)","SpreadsheetGui") diff --git a/src/Mod/Spreadsheet/importXLSX.py b/src/Mod/Spreadsheet/importXLSX.py index d628edc492..4d333a91b4 100644 --- a/src/Mod/Spreadsheet/importXLSX.py +++ b/src/Mod/Spreadsheet/importXLSX.py @@ -56,7 +56,6 @@ known issues: import zipfile import xml.dom.minidom import FreeCAD as App -import sys try: import FreeCADGui except ValueError: gui = False @@ -322,10 +321,7 @@ def getText(nodelist): for node in nodelist: if node.nodeType == node.TEXT_NODE: rc.append(node.data) - if sys.version_info.major >= 3: - return ''.join(rc) - else: - return ''.join(rc).encode('utf8') + return ''.join(rc) def handleWorkSheet(theDom, actSheet, strList): diff --git a/src/Mod/Start/App/AppStart.cpp b/src/Mod/Start/App/AppStart.cpp index e442d3b55e..97e1d95d72 100644 --- a/src/Mod/Start/App/AppStart.cpp +++ b/src/Mod/Start/App/AppStart.cpp @@ -36,7 +36,7 @@ public: initialize("This module is the Start module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Start/Gui/AppStartGui.cpp b/src/Mod/Start/Gui/AppStartGui.cpp index 489a9160c7..ae16fa3665 100644 --- a/src/Mod/Start/Gui/AppStartGui.cpp +++ b/src/Mod/Start/Gui/AppStartGui.cpp @@ -34,7 +34,7 @@ // use a different name to CreateCommand() -void CreateStartCommands(void); +void CreateStartCommands(); void loadStartResource() { @@ -52,7 +52,7 @@ public: initialize("This module is the StartGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: }; diff --git a/src/Mod/Start/Gui/CMakeLists.txt b/src/Mod/Start/Gui/CMakeLists.txt index 10b91ef91e..caa6a64e1d 100644 --- a/src/Mod/Start/Gui/CMakeLists.txt +++ b/src/Mod/Start/Gui/CMakeLists.txt @@ -4,6 +4,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) set(StartGui_LIBS diff --git a/src/Mod/Start/Gui/Command.cpp b/src/Mod/Start/Gui/Command.cpp index 96c243c25e..72ba20b8af 100644 --- a/src/Mod/Start/Gui/Command.cpp +++ b/src/Mod/Start/Gui/Command.cpp @@ -51,7 +51,7 @@ void CmdStartPage::activated(int iMsg) } -void CreateStartCommands(void) +void CreateStartCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Start/Gui/DlgStartPreferencesImp.h b/src/Mod/Start/Gui/DlgStartPreferencesImp.h index 67b93dd233..f65a5283c9 100644 --- a/src/Mod/Start/Gui/DlgStartPreferencesImp.h +++ b/src/Mod/Start/Gui/DlgStartPreferencesImp.h @@ -34,13 +34,13 @@ namespace StartGui { Q_OBJECT public: - DlgStartPreferencesImp( QWidget* parent = nullptr ); - ~DlgStartPreferencesImp(); + explicit DlgStartPreferencesImp( QWidget* parent = nullptr ); + ~DlgStartPreferencesImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/Start/Gui/Workbench.h b/src/Mod/Start/Gui/Workbench.h index 074036e7f1..8b545f3a9d 100644 --- a/src/Mod/Start/Gui/Workbench.h +++ b/src/Mod/Start/Gui/Workbench.h @@ -33,28 +33,28 @@ namespace StartGui { */ class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; /** Defines the standard context menu. */ - virtual void setupContextMenu(const char* recipient,Gui::MenuItem*) const; + void setupContextMenu(const char* recipient,Gui::MenuItem*) const override; /** Run some actions when the workbench gets activated. */ - virtual void activated(); + void activated() override; static void loadStartPage(); protected: /** Defines the standard menus. */ - virtual Gui::MenuItem* setupMenuBar() const; + Gui::MenuItem* setupMenuBar() const override; /** Defines the standard toolbars. */ - virtual Gui::ToolBarItem* setupToolBars() const; + Gui::ToolBarItem* setupToolBars() const override; /** Defines the standard command bars. */ - virtual Gui::ToolBarItem* setupCommandBars() const; + Gui::ToolBarItem* setupCommandBars() const override; /** Returns a DockWindowItems structure of dock windows this workbench. */ - virtual Gui::DockWindowItems* setupDockWindows() const; + Gui::DockWindowItems* setupDockWindows() const override; }; // namespace StartGui diff --git a/src/Mod/Surface/App/AppSurface.cpp b/src/Mod/Surface/App/AppSurface.cpp index 22ceb69343..02349b5af6 100644 --- a/src/Mod/Surface/App/AppSurface.cpp +++ b/src/Mod/Surface/App/AppSurface.cpp @@ -24,38 +24,42 @@ #include #include -#include "FeatureFilling.h" -#include "FeatureSewing.h" + +#include "Blending/BlendCurvePy.h" +#include "Blending/BlendPointPy.h" +#include "Blending/FeatureBlendCurve.h" #include "FeatureCut.h" -#include "FeatureGeomFillSurface.h" #include "FeatureExtend.h" +#include "FeatureFilling.h" +#include "FeatureGeomFillSurface.h" #include "FeatureSections.h" +#include "FeatureSewing.h" #include #include -namespace Surface { -class Module : public Py::ExtensionModule +namespace Surface +{ +class Module: public Py::ExtensionModule { public: Module() : Py::ExtensionModule("Surface") { - initialize("This module is the Surface module."); // register with Python + initialize("This module is the Surface module.");// register with Python } - virtual ~Module() {} + ~Module() override {} private: }; -PyObject* initModule() +PyObject *initModule() { return Base::Interpreter().addModule(new Module); } -} // namespace Surface - +}// namespace Surface /* Python entry */ PyMOD_INIT_FUNC(Surface) @@ -63,21 +67,24 @@ PyMOD_INIT_FUNC(Surface) try { Base::Interpreter().runString("import Part"); } - catch(const Base::Exception& e) { + catch (const Base::Exception &e) { PyErr_SetString(PyExc_ImportError, e.what()); PyMOD_Return(nullptr); } - PyObject* mod = Surface::initModule(); + PyObject *mod = Surface::initModule(); Base::Console().Log("Loading Surface module... done\n"); + Base::Interpreter().addType(&Surface::BlendPointPy::Type, mod, "BlendPoint"); + Base::Interpreter().addType(&Surface::BlendCurvePy::Type, mod, "BlendCurve"); // Add types to module - Surface::Filling ::init(); - Surface::Sewing ::init(); - Surface::Cut ::init(); - Surface::GeomFillSurface ::init(); - Surface::Extend ::init(); - Surface::Sections ::init(); + Surface::Filling ::init(); + Surface::Sewing ::init(); + Surface::Cut ::init(); + Surface::GeomFillSurface ::init(); + Surface::Extend ::init(); + Surface::FeatureBlendCurve ::init(); + Surface::Sections ::init(); PyMOD_Return(mod); } diff --git a/src/Mod/Surface/App/Blending/BlendCurve.cpp b/src/Mod/Surface/App/Blending/BlendCurve.cpp new file mode 100644 index 0000000000..7af7a67ab0 --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendCurve.cpp @@ -0,0 +1,143 @@ +/*************************************************************************** + * Copyright (c) 2022 Matteo Grellier * + * * + * * + * 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 +#include +#include +#include +#include +#include +#include +#endif +#include "Blending/BlendCurve.h" +#include "Blending/BlendCurvePy.h" +#include +#include + +using namespace Surface; + +BlendCurve::BlendCurve(const std::vector& blendPointsList) +{ + // Retrieve number of blendPoints and push them into blendPoints. + size_t nb_pts = blendPointsList.size(); + + if (nb_pts > 2) { + throw Base::NotImplementedError("Not implemented"); + } + + if (nb_pts < 2) { + throw Base::ValueError("Need two points for working"); + } + + blendPoints = blendPointsList; +} + +Handle(Geom_BezierCurve) BlendCurve::compute() +{ + size_t nb_pts = blendPoints.size(); + try { + // Uniform Parametrization + TColStd_Array1OfReal params(1, nb_pts); + for (size_t i = 0; i < nb_pts; ++i) { + params(i + 1) = (double)i / ((double)nb_pts - 1); + } + + int num_poles = 0; + for (size_t i = 0; i < nb_pts; ++i) { + num_poles += blendPoints[i].nbVectors(); + } + + Handle(Geom_BezierCurve) curve; + if (num_poles > (curve->MaxDegree() + 1))// use Geom_BezierCurve max degree + Standard_Failure::Raise("number of constraints exceeds bezier curve capacity"); + + TColStd_Array1OfReal knots(1, 2 * num_poles); + for (int i = 1; i <= num_poles; ++i) { + knots(i) = params(1); + knots(num_poles + i) = params(nb_pts); + } + + math_Matrix OCCmatrix(1, num_poles, 1, num_poles, 0.0); + math_Vector res_x(1, num_poles, 0.0); + math_Vector res_y(1, num_poles, 0.0); + math_Vector res_z(1, num_poles, 0.0); + int row_idx = 1; + int cons_idx = 1; + for (size_t i = 0; i < nb_pts; ++i) { + math_Matrix bezier_eval(1, blendPoints[i].nbVectors(), 1, num_poles, 0.0); + Standard_Integer first_non_zero; + BSplCLib::EvalBsplineBasis(blendPoints[i].nbVectors() - 1, num_poles, knots, params(cons_idx), first_non_zero, bezier_eval, Standard_False); + int idx2 = 1; + for (int it2 = 0; it2 < blendPoints[i].nbVectors(); ++it2) { + OCCmatrix.SetRow(row_idx, bezier_eval.Row(idx2)); + Base::Vector3d pnt = blendPoints[i].vectors[it2]; + res_x(row_idx) = pnt.x; + res_y(row_idx) = pnt.y; + res_z(row_idx) = pnt.z; + idx2++; + row_idx++; + } + cons_idx++; + } + math_Gauss gauss(OCCmatrix); + gauss.Solve(res_x); + if (!gauss.IsDone()) + Standard_Failure::Raise("Failed to solve equations"); + gauss.Solve(res_y); + if (!gauss.IsDone()) + Standard_Failure::Raise("Failed to solve equations"); + gauss.Solve(res_z); + if (!gauss.IsDone()) + Standard_Failure::Raise("Failed to solve equations"); + + TColgp_Array1OfPnt poles(1, num_poles); + for (int idx = 1; idx <= num_poles; ++idx) { + poles.SetValue(idx, gp_Pnt(res_x(idx), res_y(idx), res_z(idx))); + } + Handle(Geom_BezierCurve) bezier = new Geom_BezierCurve(poles); + return bezier; + } + catch (Standard_Failure &) { + PyErr_SetString(Base::PyExc_FC_CADKernelError, "Failed to compute bezier curve"); + } + return nullptr; +} + +void BlendCurve::setSize(int i, double f, bool relative) +{ + double size = f; + try { + if (relative) { + double nb_poles = blendPoints.front().nbVectors() + blendPoints[1].nbVectors(); + Base::Vector3d diff = blendPoints[1].vectors[0] - blendPoints[0].vectors[0]; + size = size * diff.Length() / nb_poles; + } + blendPoints[i].setSize(size); + } + catch (Standard_Failure &e) { + PyErr_SetString(Base::PyExc_FC_CADKernelError, e.GetMessageString()); + } +} diff --git a/src/Mod/Surface/App/Blending/BlendCurve.h b/src/Mod/Surface/App/Blending/BlendCurve.h new file mode 100644 index 0000000000..f3da60cf3b --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendCurve.h @@ -0,0 +1,63 @@ +/*************************************************************************** + * Copyright (c) 2022 Matteo Grellier * + * * + * 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 SURFACE_BLEND_CURVE_H +#define SURFACE_BLEND_CURVE_H + +#include +#include +#include + +namespace Surface +{ +/*! +* Create a BezierCurve interpolating a list of BlendPoints +*/ +class SurfaceExport BlendCurve +{ +public: + std::vector blendPoints; + + BlendCurve() = default; + /*! + * Constructor + *\param std::vector + */ + explicit BlendCurve(const std::vector& blendPointsList); + ~BlendCurve() = default; + /*! + * Perform the interpolate algorithm + *\return the BezierCurve + */ + Handle(Geom_BezierCurve) compute(); + /*! + * Set the size of the first derivative of a BlendPoint + *\param int index of the BlendPoint to modify + *\param double new size + *\param bool interpret new size relative to chordlength + */ + void setSize(int, double, bool); +}; +}// namespace Surface + +#endif + diff --git a/src/Mod/Surface/App/Blending/BlendCurvePy.xml b/src/Mod/Surface/App/Blending/BlendCurvePy.xml new file mode 100644 index 0000000000..a1938d25e6 --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendCurvePy.xml @@ -0,0 +1,41 @@ + + + + + + + + + Create a BlendCurve that interpolate 2 BlendPoints. + curve = BlendCurve(BlendPoint1, BlendPoint2) + + + + + + Return the BezierCurve that interpolate the input BlendPoints. + + + + + + + Set the tangent size of the blendpoint at given index. + If relative is true, the size is considered relative to the distance between the two blendpoints. + myBlendCurve.setSize(idx, size, relative) + + + + + diff --git a/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp b/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp new file mode 100644 index 0000000000..46a3de3b7d --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendCurvePyImp.cpp @@ -0,0 +1,97 @@ +///*************************************************************************** +// * Copyright (c) 2022 Matteo Grellier * +// * * +// * 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 "Blending/BlendCurvePy.h" +#include "Blending/BlendCurvePy.cpp" +#include "Blending/BlendPointPy.h" +#include +#include + +using namespace Surface; + +std::string BlendCurvePy::representation() const +{ + return "BlendCurve"; +} + +PyObject *BlendCurvePy::PyMake(struct _typeobject *, PyObject *, PyObject *)// Python wrapper +{ + // create a new instance of BlendCurvePy + return new BlendCurvePy(new BlendCurve); +} + +int BlendCurvePy::PyInit(PyObject *args, PyObject * /*kwds*/) +{ + PyObject *b1; + PyObject *b2; + + if (!PyArg_ParseTuple(args, "O!O!", &(Surface::BlendPointPy::Type), &b1, &(Surface::BlendPointPy::Type), &b2)) + return -1; + + std::vector bpList; + BlendPoint *geom1 = static_cast(b1)->getBlendPointPtr(); + BlendPoint *geom2 = static_cast(b2)->getBlendPointPtr(); + bpList.emplace_back(*geom1); + bpList.emplace_back(*geom2); + this->getBlendCurvePtr()->blendPoints = bpList; + return 0; +} + +PyObject *BlendCurvePy::compute(PyObject * args) +{ + if (!PyArg_ParseTuple(args, "")) + return nullptr; + + BlendCurve *bc = getBlendCurvePtr(); + Handle(Geom_BezierCurve) gc = bc->compute(); + return new Part::BezierCurvePy(new Part::GeomBezierCurve(gc)); +} + +PyObject *BlendCurvePy::setSize(PyObject *args) +{ + int i; + double size; + PyObject *relative = Py_True; + if (!PyArg_ParseTuple(args, "idO!", &i, &size, &PyBool_Type, &relative)) { + return nullptr; + } + try { + getBlendCurvePtr()->setSize(i, size, Base::asBoolean(relative)); + Py_Return; + } + catch (Standard_Failure &e) { + PyErr_SetString(Base::PyExc_FC_CADKernelError, e.GetMessageString()); + return nullptr; + } +} + +PyObject *BlendCurvePy::getCustomAttributes(const char * /*attr*/) const +{ + return nullptr; +} + +int BlendCurvePy::setCustomAttributes(const char * /*attr*/, PyObject * /*obj*/) +{ + return 0; +} diff --git a/src/Mod/Surface/App/Blending/BlendPoint.cpp b/src/Mod/Surface/App/Blending/BlendPoint.cpp new file mode 100644 index 0000000000..62a4d7b128 --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendPoint.cpp @@ -0,0 +1,70 @@ +/*************************************************************************** + * Copyright (c) 2022 Matteo Grellier * + * * + * * + * 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 "Blending/BlendPoint.h" +#include "Blending/BlendPointPy.h" + + +using namespace Surface; + +BlendPoint::BlendPoint(const std::vector& vectorList) + : vectors{vectorList} +{ +} + +BlendPoint::BlendPoint() +{ + vectors.emplace_back(Base::Vector3d(0, 0, 0)); +} + +void BlendPoint::multiply(double f) +{ + for (int i = 0; i < nbVectors(); i++) { + vectors[i] *= Pow(f, i); + } +} + +void BlendPoint::setSize(double f) +{ + if (nbVectors() > 1) { + double il = vectors[1].Length(); + if (il > Precision::Confusion()) { + multiply(f / il); + } + } +} + +int BlendPoint::getContinuity() +{ + return vectors.size() - 1; +} + +int BlendPoint::nbVectors() +{ + return vectors.size(); +} diff --git a/src/Mod/Surface/App/Blending/BlendPoint.h b/src/Mod/Surface/App/Blending/BlendPoint.h new file mode 100644 index 0000000000..20b12706a0 --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendPoint.h @@ -0,0 +1,76 @@ +/*************************************************************************** + * Copyright (c) 2014 Matteo Grellier * + * * + * 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 SURFACE_BLEND_POINT_H +#define SURFACE_BLEND_POINT_H + + +#include +#include +#include + + +namespace Surface +{ + +/*! +* Create a list of vectors formed by a point and some derivatives +* obtained from a curve or surface +*/ +class SurfaceExport BlendPoint +{ +public: + std::vector vectors; + + BlendPoint(); + /*! + * Constructor + *\param std::vector + */ + explicit BlendPoint(const std::vector& vectorList); + ~BlendPoint() = default; + /*! + * Scale the blendpoint vectors + *\param double scaling factor + */ + void multiply(double f); + /*! + * Resize the blendpoint vectors + * by setting the size of the first derivative + *\param double new size + */ + void setSize(double f); + /*! + *\return continuity of this BlendPoint + */ + int getContinuity(); + /*! + *\return Number of vectors of this BlendPoint + */ + int nbVectors(); + +private: +}; +}// namespace Surface + +#endif + diff --git a/src/Mod/Surface/App/Blending/BlendPointPy.xml b/src/Mod/Surface/App/Blending/BlendPointPy.xml new file mode 100644 index 0000000000..8024dc3c99 --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendPointPy.xml @@ -0,0 +1,57 @@ + + + + + + + + + Create BlendPoint from a point and some derivatives. + myBlendPoint = BlendPoint([Point, D1, D2, ..., DN]) + BlendPoint can also be constructed from an edge + myBlendPoint = BlendPoint(Edge, parameter = float, continuity = int) + + + + + The list of vectors of this BlendPoint. + + + + + + + Return BlendPoint first derivative length. + + + + + + + Resizes the BlendPoint vectors, + by setting the length of the first derivative. + theBlendPoint.setSize(new_size) + + + + + + + Set the vectors of BlendPoint. + BlendPoint.setvectors([Point, D1, D2, ..., DN]) + + + + + diff --git a/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp b/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp new file mode 100644 index 0000000000..6183142a3a --- /dev/null +++ b/src/Mod/Surface/App/Blending/BlendPointPyImp.cpp @@ -0,0 +1,195 @@ +///*************************************************************************** +// * Copyright (c) 2022 Matteo Grellier * +// * * +// * 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 "Blending/BlendPoint.h" +#include "Blending/BlendPointPy.h" +#include "Blending/BlendPointPy.cpp" +#include +#include +#include + + +using namespace Surface; + +std::string BlendPointPy::representation() const +{ + std::stringstream str; + str << "G" << getBlendPointPtr()->getContinuity() << " BlendPoint"; + + if (getBlendPointPtr()->vectors.empty()) { + Base::Vector3d bp = getBlendPointPtr()->vectors[0]; + str << " at (" << bp.x << ", " << bp.y << ", " << bp.z << "), "; + } + return str.str(); +} + +PyObject *BlendPointPy::PyMake(struct _typeobject *, PyObject *, PyObject *)// Python wrapper +{ + // create a new instance of BlendPointPy + return new BlendPointPy(new BlendPoint); +} + +int BlendPointPy::PyInit(PyObject *args, PyObject *) +{ + PyObject *plist; + std::vector vecs; + if (PyArg_ParseTuple(args, "O", &plist)) { + Py::Sequence list(plist); + if (list.size() == 0) { + vecs.emplace_back(Base::Vector3d(0, 0, 0)); + } + else { + for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { + Py::Vector v(*it); + Base::Vector3d vec = v.toVector(); + vecs.emplace_back(vec); + } + } + this->getBlendPointPtr()->vectors = vecs; + return 0; + } + + PyErr_Clear(); + if (PyArg_ParseTuple(args, "")) { + vecs.emplace_back(Base::Vector3d(0, 0, 0)); + this->getBlendPointPtr()->vectors = vecs; + return 0; + } + + double param; + int cont; + PyObject *pcObj; + PyErr_Clear(); + // Create a curve with an edge, parameter and continiuity. + if (PyArg_ParseTuple(args, "O!di", &(Part::TopoShapePy::Type), &pcObj, ¶m, &cont)) { + try { + gp_Pnt Pt; + TopoDS_Shape shape = static_cast(pcObj)->getTopoShapePtr()->getShape(); + const TopoDS_Edge &e = TopoDS::Edge(shape); + 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()); + } + + adapt.D0(param, Pt); + Base::Vector3d bv(Pt.X(), Pt.Y(), Pt.Z()); + vecs.emplace_back(bv); + + for (int i = 1; i <= cont; i++) { + gp_Vec v1 = adapt.DN(param, i); + Base::Vector3d bbv1(v1.X(), v1.Y(), v1.Z()); + vecs.emplace_back(bbv1); + } + this->getBlendPointPtr()->vectors = vecs; + return 0; + } + catch (const std::exception &e) { + PyErr_SetString(PyExc_RuntimeError, e.what()); + return -1; + } + } + + PyErr_SetString(PyExc_TypeError, "supported signatures:\n" + "BlendPoint()\n" + "BlendPoint(list of Vector)\n" + "BlendPoint(edge, parameter and continiuity)\n"); + return -1; +} + +PyObject *BlendPointPy::setSize(PyObject *args) +{ + double size = 1.0; + + if (!PyArg_ParseTuple(args, "d", &size)) + return nullptr; + try { + getBlendPointPtr()->setSize(size); + Py_Return; + } + catch (Standard_Failure &e) { + PyErr_SetString(Base::PyExc_FC_CADKernelError, "Failed to set size"); + return nullptr; + } +} + +PyObject *BlendPointPy::getSize(PyObject *args) +{ + if (!PyArg_ParseTuple(args, "")) + return nullptr; + int nb = getBlendPointPtr()->nbVectors(); + if (nb >= 2) { + double bpTangentLength = getBlendPointPtr()->vectors[1].Length(); + return Py_BuildValue("d", bpTangentLength); + } + + PyErr_SetString(PyExc_RuntimeError, "Cannot determine size"); + return nullptr; +} + +Py::List BlendPointPy::getVectors() const +{ + BlendPoint *bp = getBlendPointPtr(); + Py::List vecs; + for (const auto& p : bp->vectors) { + Base::VectorPy *vec = new Base::VectorPy(p); + vecs.append(Py::asObject(vec)); + } + return vecs; +} + +PyObject *BlendPointPy::setvectors(PyObject *args) +{ + PyObject *plist; + if (!PyArg_ParseTuple(args, "O", &plist)) { + PyErr_SetString(PyExc_TypeError, "List of vectors required."); + return nullptr; + } + + Py::Sequence list(plist); + std::vector vecs; + for (Py::Sequence::iterator it = list.begin(); it != list.end(); ++it) { + Py::Vector v(*it); + Base::Vector3d pole = v.toVector(); + vecs.emplace_back(pole); + } + + BlendPoint *bp = getBlendPointPtr(); + bp->vectors = vecs; + Py_Return; +} + +PyObject *BlendPointPy::getCustomAttributes(const char * /*attr*/) const +{ + return nullptr; +} + +int BlendPointPy::setCustomAttributes(const char * /*attr*/, PyObject * /*obj*/) +{ + return 0; +} diff --git a/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp b/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp new file mode 100644 index 0000000000..b3c63c53a5 --- /dev/null +++ b/src/Mod/Surface/App/Blending/FeatureBlendCurve.cpp @@ -0,0 +1,180 @@ +/*************************************************************************** + * Copyright (c) 2022 Matteo Grellier * + * * + * * + * 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 +#include +#include +#include +#include +#include +#include +#endif +#include "FeatureBlendCurve.h" +#include "Mod/Surface/App/Blending/BlendCurve.h" +#include "Mod/Surface/App/Blending/BlendPoint.h" + +using namespace Surface; + +const App::PropertyFloatConstraint::Constraints StartParameterConstraint = {0.0, 1.0, 0.05}; +const App::PropertyFloatConstraint::Constraints EndParameterConstraint = {0.0, 1.0, 0.05}; +const App::PropertyIntegerConstraint::Constraints StartContinuityConstraint = {0, 25, 1}; +const App::PropertyIntegerConstraint::Constraints EndContinuityConstraint = {0, 25, 1}; + +PROPERTY_SOURCE(Surface::FeatureBlendCurve, Part::Spline) + +FeatureBlendCurve::FeatureBlendCurve() : lockOnChangeMutex(false) +{ + ADD_PROPERTY_TYPE(StartEdge, (nullptr), "FirstEdge", App::Prop_None, ""); + ADD_PROPERTY_TYPE(StartContinuity, (2), "FirstEdge", App::Prop_None, ""); + StartContinuity.setConstraints(&StartContinuityConstraint); + ADD_PROPERTY_TYPE(StartParameter, (0.0f), "FirstEdge", App::Prop_None, ""); + StartParameter.setConstraints(&StartParameterConstraint); + ADD_PROPERTY_TYPE(StartSize, (1.0f), "FirstEdge", App::Prop_None, ""); + + ADD_PROPERTY_TYPE(EndEdge, (nullptr), "SecondEdge", App::Prop_None, ""); + ADD_PROPERTY_TYPE(EndContinuity, (2), "SecondEdge", App::Prop_None, ""); + EndContinuity.setConstraints(&EndContinuityConstraint); + ADD_PROPERTY_TYPE(EndParameter, (0.0f), "SecondEdge", App::Prop_None, ""); + EndParameter.setConstraints(&EndParameterConstraint); + ADD_PROPERTY_TYPE(EndSize, (1.0f), "SecondEdge", App::Prop_None, ""); + Handle(Geom_BezierCurve) maxDegreeCurve; + maxDegree = maxDegreeCurve->MaxDegree(); +} + +short FeatureBlendCurve::mustExecute() const +{ + if (StartEdge.isTouched()) + return 1; + if (StartParameter.isTouched()) + return 1; + if (StartContinuity.isTouched()) + return 1; + if (StartSize.isTouched()) + return 1; + if (EndEdge.isTouched()) + return 1; + if (EndParameter.isTouched()) + return 1; + if (EndContinuity.isTouched()) + return 1; + if (EndSize.isTouched()) + return 1; + return 0; +} + +BlendPoint FeatureBlendCurve::GetBlendPoint(App::PropertyLinkSub &link, App::PropertyFloatConstraint ¶m, App::PropertyIntegerConstraint &continuity) +{ + auto linked = link.getValue(); + + TopoDS_Shape axEdge; + if (link.getSubValues().size() > 0 && link.getSubValues()[0].length() > 0) { + axEdge = Feature::getTopoShape(linked, link.getSubValues()[0].c_str(), true /*need element*/).getShape(); + } + else { + axEdge = Feature::getShape(linked); + } + + if (axEdge.IsNull()) + throw Base::ValueError("DirLink shape is null"); + if (axEdge.ShapeType() != TopAbs_EDGE) + throw Base::TypeError("DirLink shape is not an edge"); + const TopoDS_Edge &e = TopoDS::Edge(axEdge); + BRepAdaptor_Curve adapt(e); + double fp = adapt.FirstParameter(); + double lp = adapt.LastParameter(); + + double RealPar = RelativeToRealParameters(param.getValue(), fp, lp); + + std::vector constraints; + gp_Pnt Pt; + + adapt.D0(RealPar, Pt); + Base::Vector3d bv(Pt.X(), Pt.Y(), Pt.Z()); + constraints.emplace_back(bv); + + for (int i = 1; i <= continuity.getValue(); i++) { + gp_Vec v1 = adapt.DN(RealPar, i); + Base::Vector3d bbv1(v1.X(), v1.Y(), v1.Z()); + constraints.emplace_back(bbv1); + } + + BlendPoint bp(constraints); + + return bp; +} + +App::DocumentObjectExecReturn *FeatureBlendCurve::execute(void) +{ + BlendPoint bp1 = GetBlendPoint(StartEdge, StartParameter, StartContinuity); + BlendPoint bp2 = GetBlendPoint(EndEdge, EndParameter, EndContinuity); + + std::vector blendPointsList; + + blendPointsList.emplace_back(bp1); + blendPointsList.emplace_back(bp2); + + BlendCurve curve(blendPointsList); + curve.setSize(0, StartSize.getValue(), true); + curve.setSize(1, EndSize.getValue(), true); + + Handle(Geom_BezierCurve) bc(curve.compute()); + BRepBuilderAPI_MakeEdge mkEdge(bc); + + Shape.setValue(mkEdge.Edge()); + + return StdReturn; +} + +double FeatureBlendCurve::RelativeToRealParameters(double relativeValue, double fp, double lp) +{ + return fp + relativeValue * (lp - fp); +} + + +void FeatureBlendCurve::onChanged(const App::Property *prop) +{ + // using a mutex and lock to protect a recursive calling when setting the new values + if (lockOnChangeMutex) + return; + Base::StateLocker lock(lockOnChangeMutex); + + if (prop == &StartContinuity) { + auto changedStartProp = dynamic_cast(prop); + + if (changedStartProp->getValue() > (maxDegree - 2 - EndContinuity.getValue())) { + + StartContinuity.setValue(maxDegree - 2 - EndContinuity.getValue()); + } + } + else if (prop == &EndContinuity) { + auto changedEndProp = dynamic_cast(prop); + + if (changedEndProp->getValue() > (maxDegree - 2 - StartContinuity.getValue())) { + EndContinuity.setValue(maxDegree - 2 - StartContinuity.getValue()); + } + } + Part::Spline::onChanged(prop); +} diff --git a/src/Mod/Surface/App/Blending/FeatureBlendCurve.h b/src/Mod/Surface/App/Blending/FeatureBlendCurve.h new file mode 100644 index 0000000000..6ff4329a32 --- /dev/null +++ b/src/Mod/Surface/App/Blending/FeatureBlendCurve.h @@ -0,0 +1,74 @@ +/*************************************************************************** + * Copyright (c) 2014 Matteo Grellier * + * * + * 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 FEATURE_BLEND_CURVE_H +#define FEATURE_BLEND_CURVE_H + +#include +#include +#include +#include +#include +#include + +namespace Surface +{ + +class SurfaceExport FeatureBlendCurve: public Part::Spline +{ + PROPERTY_HEADER_WITH_OVERRIDE(Surface::FeatureBlendCurve); + +public: + + FeatureBlendCurve(); + + App::PropertyLinkSub StartEdge; + App::PropertyFloatConstraint StartParameter; + App::PropertyIntegerConstraint StartContinuity; + App::PropertyFloat StartSize; + + App::PropertyLinkSub EndEdge; + App::PropertyFloatConstraint EndParameter; + App::PropertyIntegerConstraint EndContinuity; + App::PropertyFloat EndSize; + + Standard_Integer maxDegree; + + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + const char *getViewProviderName() const override + { + return "SurfaceGui::ViewProviderBlendCurve"; + } + +private: + BlendPoint GetBlendPoint(App::PropertyLinkSub &link, App::PropertyFloatConstraint ¶m, App::PropertyIntegerConstraint &Continuity); + double RelativeToRealParameters(double, double, double); + bool lockOnChangeMutex; + +protected: + void onChanged(const App::Property *prop) override; +}; + +}//Namespace Surface + +#endif diff --git a/src/Mod/Surface/App/CMakeLists.txt b/src/Mod/Surface/App/CMakeLists.txt index df574bca63..02010eaffe 100644 --- a/src/Mod/Surface/App/CMakeLists.txt +++ b/src/Mod/Surface/App/CMakeLists.txt @@ -1,37 +1,88 @@ if(MSVC) - add_definitions(-DHAVE_ACOSH -DHAVE_ASINH -DHAVE_ATANH) + add_definitions(-DHAVE_ACOSH -DHAVE_ASINH -DHAVE_ATANH) else(MSVC) - add_definitions(-DHAVE_LIMITS_H -DHAVE_CONFIG_H) + add_definitions(-DHAVE_LIMITS_H -DHAVE_CONFIG_H) endif(MSVC) include_directories( - ${Boost_INCLUDE_DIRS} - ${OCC_INCLUDE_DIR} - ${PYTHON_INCLUDE_DIRS} - ${ZLIB_INCLUDE_DIR} + ${CMAKE_BINARY_DIR} + ${CMAKE_BINARY_DIR}/src + ${CMAKE_SOURCE_DIR}/src + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR} + ${Boost_INCLUDE_DIRS} + ${OCC_INCLUDE_DIR} + ${PYTHON_INCLUDE_DIRS} + ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} + ${FREETYPE_INCLUDE_DIRS} ) +link_directories(${OCC_LIBRARY_DIR}) + +file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Blending) + +generate_from_xml(Blending/BlendPointPy) +generate_from_xml(Blending/BlendCurvePy) + set(Surface_LIBS - FreeCADApp - Part + FreeCADApp + Part +) + +# BlendPoint Wrapper +SET(BlendingPy_SRCS + Blending/BlendPointPy.xml + Blending/BlendPointPyImp.cpp + Blending/BlendCurvePy.xml + Blending/BlendCurvePyImp.cpp +) +SOURCE_GROUP("Blending" FILES ${BlendingPy_SRCS}) + +SET(Blending_SRCS + Blending/FeatureBlendCurve.cpp + Blending/FeatureBlendCurve.h + Blending/BlendPoint.cpp + Blending/BlendPoint.h + Blending/BlendCurve.cpp + Blending/BlendCurve.h +) + +SET(BlendingPy_SRCS + Blending/BlendPointPy.xml + Blending/BlendPointPyImp.cpp + Blending/BlendCurvePy.xml + Blending/BlendCurvePyImp.cpp +) +SOURCE_GROUP("Blending" FILES ${BlendingPy_SRCS}) + +SET(Blending_SRCS + Blending/FeatureBlendCurve.cpp + Blending/FeatureBlendCurve.h + Blending/BlendPoint.cpp + Blending/BlendPoint.h + Blending/BlendCurve.cpp + Blending/BlendCurve.h ) SET(Surface_SRCS - AppSurface.cpp - PreCompiled.cpp - PreCompiled.h - FeatureExtend.cpp - FeatureExtend.h - FeatureGeomFillSurface.cpp - FeatureGeomFillSurface.h - FeatureFilling.cpp - FeatureFilling.h - FeatureSections.cpp - FeatureSections.h - FeatureSewing.cpp - FeatureSewing.h - FeatureCut.cpp - FeatureCut.h + ${Blending_SRCS} + ${BlendingPy_SRCS} + AppSurface.cpp + PreCompiled.cpp + PreCompiled.h + FeatureExtend.cpp + FeatureExtend.h + FeatureGeomFillSurface.cpp + FeatureGeomFillSurface.h + FeatureFilling.cpp + FeatureFilling.h + FeatureSections.cpp + FeatureSections.h + FeatureSewing.cpp + FeatureSewing.h + FeatureCut.cpp + FeatureCut.h ) link_directories(${OCC_LIBRARY_DIR}) diff --git a/src/Mod/Surface/App/FeatureCut.cpp b/src/Mod/Surface/App/FeatureCut.cpp index 7e617e4224..fbc7711a6e 100644 --- a/src/Mod/Surface/App/FeatureCut.cpp +++ b/src/Mod/Surface/App/FeatureCut.cpp @@ -56,7 +56,7 @@ short Cut::mustExecute() const return 0; } -App::DocumentObjectExecReturn *Cut::execute(void) +App::DocumentObjectExecReturn *Cut::execute() { //Perform error checking diff --git a/src/Mod/Surface/App/FeatureCut.h b/src/Mod/Surface/App/FeatureCut.h index eba82cbfa1..12dfc1fe4a 100644 --- a/src/Mod/Surface/App/FeatureCut.h +++ b/src/Mod/Surface/App/FeatureCut.h @@ -34,7 +34,7 @@ namespace Surface class SurfaceExport Cut : public Part::Feature { - PROPERTY_HEADER(Surface::Cut); + PROPERTY_HEADER_WITH_OVERRIDE(Surface::Cut); public: Cut(); @@ -42,8 +42,8 @@ public: App::PropertyLinkSubList ShapeList; //Shapes to be cut. // recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider // const char* getViewProviderName(void) const { // return "SurfaceGui::ViewProviderCut"; diff --git a/src/Mod/Surface/App/FeatureExtend.cpp b/src/Mod/Surface/App/FeatureExtend.cpp index da53f3415f..87877785d0 100644 --- a/src/Mod/Surface/App/FeatureExtend.cpp +++ b/src/Mod/Surface/App/FeatureExtend.cpp @@ -90,7 +90,7 @@ short Extend::mustExecute() const return 0; } -App::DocumentObjectExecReturn *Extend::execute(void) +App::DocumentObjectExecReturn *Extend::execute() { App::DocumentObject* part = Face.getValue(); if (!part || !part->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) diff --git a/src/Mod/Surface/App/FeatureExtend.h b/src/Mod/Surface/App/FeatureExtend.h index e23917ae35..b682531a25 100644 --- a/src/Mod/Surface/App/FeatureExtend.h +++ b/src/Mod/Surface/App/FeatureExtend.h @@ -38,7 +38,7 @@ class SurfaceExport Extend : public Part::Spline public: Extend(); - ~Extend(); + ~Extend() override; App::PropertyLinkSub Face; App::PropertyFloatConstraint Tolerance; @@ -52,16 +52,16 @@ public: App::PropertyIntegerConstraint SampleV; // recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "SurfaceGui::ViewProviderExtend"; } protected: - virtual void onChanged(const App::Property* prop) override; - virtual void handleChangedPropertyName(Base::XMLReader &reader, + void onChanged(const App::Property* prop) override; + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; diff --git a/src/Mod/Surface/App/FeatureFilling.cpp b/src/Mod/Surface/App/FeatureFilling.cpp index 946bcaea43..eee6ef5476 100644 --- a/src/Mod/Surface/App/FeatureFilling.cpp +++ b/src/Mod/Surface/App/FeatureFilling.cpp @@ -245,12 +245,12 @@ void Filling::addConstraints(BRepFill_Filling& builder, const App::PropertyLinkSubList& pointsList) { auto points = pointsList.getSubListValues(); - for (auto it : points) { + for (const auto& it : points) { App::DocumentObject* obj = it.first; std::vector sub = it.second; if (obj && obj->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { const Part::TopoShape& shape = static_cast(obj)->Shape.getShape(); - for (auto jt : sub) { + for (const auto& jt : sub) { TopoDS_Shape subShape = shape.getSubShape(jt.c_str()); if (!subShape.IsNull() && subShape.ShapeType() == TopAbs_VERTEX) { gp_Pnt pnt = BRep_Tool::Pnt(TopoDS::Vertex(subShape)); @@ -261,7 +261,7 @@ void Filling::addConstraints(BRepFill_Filling& builder, } } -App::DocumentObjectExecReturn *Filling::execute(void) +App::DocumentObjectExecReturn *Filling::execute() { //Assign Variables unsigned int degree = Degree.getValue(); @@ -288,7 +288,7 @@ App::DocumentObjectExecReturn *Filling::execute(void) if (initFace && initFace->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { const Part::TopoShape& shape = static_cast(initFace)->Shape.getShape(); std::vector subNames = InitialFace.getSubValues(); - for (auto it : subNames) { + for (const auto& it : subNames) { TopoDS_Shape subShape = shape.getSubShape(it.c_str()); if (!subShape.IsNull() && subShape.ShapeType() == TopAbs_FACE) { builder.LoadInitSurface(TopoDS::Face(subShape)); diff --git a/src/Mod/Surface/App/FeatureFilling.h b/src/Mod/Surface/App/FeatureFilling.h index b5173e9832..f757918d9a 100644 --- a/src/Mod/Surface/App/FeatureFilling.h +++ b/src/Mod/Surface/App/FeatureFilling.h @@ -36,7 +36,7 @@ namespace Surface class SurfaceExport Filling : public Part::Spline { - PROPERTY_HEADER(Surface::Filling); + PROPERTY_HEADER_WITH_OVERRIDE(Surface::Filling); public: Filling(); @@ -66,10 +66,10 @@ public: App::PropertyInteger MaximumSegments; //Maximum number of segments // recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "SurfaceGui::ViewProviderFilling"; } diff --git a/src/Mod/Surface/App/FeatureGeomFillSurface.cpp b/src/Mod/Surface/App/FeatureGeomFillSurface.cpp index 4ccddc1635..0171a01fc2 100644 --- a/src/Mod/Surface/App/FeatureGeomFillSurface.cpp +++ b/src/Mod/Surface/App/FeatureGeomFillSurface.cpp @@ -63,7 +63,7 @@ ShapeValidator::ShapeValidator() initValidator(); } -void ShapeValidator::initValidator(void) +void ShapeValidator::initValidator() { willBezier = true; edgeCount = 0; @@ -94,7 +94,7 @@ void ShapeValidator::checkEdge(const TopoDS_Shape& shape) void ShapeValidator::checkAndAdd(const TopoDS_Shape &shape, Handle(ShapeExtend_WireData) *aWD) { checkEdge(shape); - if (aWD != nullptr) { + if (aWD) { BRepBuilderAPI_Copy copier(shape); // make a copy of the shape and the underlying geometry to avoid to affect the input shapes (*aWD)->Add(TopoDS::Edge(copier.Shape())); @@ -104,7 +104,7 @@ void ShapeValidator::checkAndAdd(const TopoDS_Shape &shape, Handle(ShapeExtend_W void ShapeValidator::checkAndAdd(const Part::TopoShape &ts, const char *subName, Handle(ShapeExtend_WireData) *aWD) { try { - if (subName != nullptr && *subName != '\0') { + if (subName && *subName != '\0') { //we want only the subshape which is linked checkAndAdd(ts.getSubShape(subName), aWD); } @@ -162,7 +162,7 @@ void GeomFillSurface::onChanged(const App::Property* prop) Part::Spline::onChanged(prop); } -App::DocumentObjectExecReturn *GeomFillSurface::execute(void) +App::DocumentObjectExecReturn *GeomFillSurface::execute() { try { TopoDS_Wire aWire; @@ -218,7 +218,7 @@ bool GeomFillSurface::getWire(TopoDS_Wire& aWire) App::PropertyLinkSubList::SubSet set = boundary[i]; if (set.first->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) { - for (auto jt: set.second) { + for (const auto& jt: set.second) { const Part::TopoShape &ts = static_cast(set.first)->Shape.getShape(); validator.checkAndAdd(ts, jt.c_str(), &aWD); } diff --git a/src/Mod/Surface/App/FeatureGeomFillSurface.h b/src/Mod/Surface/App/FeatureGeomFillSurface.h index 781b66257d..908ef9413c 100644 --- a/src/Mod/Surface/App/FeatureGeomFillSurface.h +++ b/src/Mod/Surface/App/FeatureGeomFillSurface.h @@ -45,7 +45,7 @@ protected: public: ShapeValidator(); - void initValidator(void); + void initValidator(); void checkEdge(const TopoDS_Shape& shape); void checkAndAdd(const TopoDS_Shape &shape, Handle(ShapeExtend_WireData) *aWD = nullptr); void checkAndAdd(const Part::TopoShape &ts, const char *subName, Handle(ShapeExtend_WireData) *aWire = nullptr); @@ -60,7 +60,7 @@ public: class GeomFillSurface : public Part::Spline { - PROPERTY_HEADER(Surface::GeomFillSurface); + PROPERTY_HEADER_WITH_OVERRIDE(Surface::GeomFillSurface); public: GeomFillSurface(); @@ -68,12 +68,12 @@ public: App::PropertyBoolList ReversedList; // Booleans to handle orientation of the curves App::PropertyEnumeration FillType; // Fill method (1, 2, or 3 for Stretch, Coons, and Curved) - short mustExecute() const; - void onChanged(const App::Property*); - App::DocumentObjectExecReturn *execute(void); + short mustExecute() const override; + void onChanged(const App::Property*) override; + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "SurfaceGui::ViewProviderGeomFillSurface"; } diff --git a/src/Mod/Surface/App/FeatureSections.cpp b/src/Mod/Surface/App/FeatureSections.cpp index 7aeccce826..313569784d 100644 --- a/src/Mod/Surface/App/FeatureSections.cpp +++ b/src/Mod/Surface/App/FeatureSections.cpp @@ -53,7 +53,7 @@ Sections::~Sections() { } -App::DocumentObjectExecReturn *Sections::execute(void) +App::DocumentObjectExecReturn *Sections::execute() { TColGeom_SequenceOfCurve curveSeq; auto edge_obj = NSections.getValues(); diff --git a/src/Mod/Surface/App/FeatureSections.h b/src/Mod/Surface/App/FeatureSections.h index e9e42f9213..250af07359 100644 --- a/src/Mod/Surface/App/FeatureSections.h +++ b/src/Mod/Surface/App/FeatureSections.h @@ -38,14 +38,14 @@ class SurfaceExport Sections : public Part::Spline public: Sections(); - ~Sections(); + ~Sections() override; App::PropertyLinkSubList NSections; // recalculate the feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; /// returns the type name of the view provider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "SurfaceGui::ViewProviderSections"; } }; diff --git a/src/Mod/Surface/App/FeatureSewing.cpp b/src/Mod/Surface/App/FeatureSewing.cpp index c9971dd147..0c6be1a676 100644 --- a/src/Mod/Surface/App/FeatureSewing.cpp +++ b/src/Mod/Surface/App/FeatureSewing.cpp @@ -65,7 +65,7 @@ short Sewing::mustExecute() const return 0; } -App::DocumentObjectExecReturn *Sewing::execute(void) +App::DocumentObjectExecReturn *Sewing::execute() { //Assign Variables double atol = Tolerance.getValue(); @@ -86,7 +86,7 @@ App::DocumentObjectExecReturn *Sewing::execute(void) Part::TopoShape ts = static_cast(it->first)->Shape.getShape(); //we want only the subshape which is linked - for (auto jt: it->second) { + for (const auto& jt: it->second) { TopoDS_Shape sub = ts.getSubShape(jt.c_str()); builder.Add(sub); } diff --git a/src/Mod/Surface/App/FeatureSewing.h b/src/Mod/Surface/App/FeatureSewing.h index 239c2ee054..1f0b7a0f92 100644 --- a/src/Mod/Surface/App/FeatureSewing.h +++ b/src/Mod/Surface/App/FeatureSewing.h @@ -34,7 +34,7 @@ namespace Surface class SurfaceExport Sewing : public Part::Feature { - PROPERTY_HEADER(Surface::Sewing); + PROPERTY_HEADER_WITH_OVERRIDE(Surface::Sewing); public: Sewing(); @@ -48,8 +48,8 @@ public: App::PropertyBool Nonmanifold; //Option for non-manifold processing // recalculate the feature - App::DocumentObjectExecReturn *execute(void); - short mustExecute() const; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; }; }//Namespace Surface diff --git a/src/Mod/Surface/CMakeLists.txt b/src/Mod/Surface/CMakeLists.txt index ce0575e0f1..a11faa20c0 100644 --- a/src/Mod/Surface/CMakeLists.txt +++ b/src/Mod/Surface/CMakeLists.txt @@ -6,6 +6,12 @@ endif(BUILD_GUI) set(Surface_Scripts Init.py + TestSurfaceApp.py +) + +set(Surface_TestScripts + SurfaceTests/__init__.py + SurfaceTests/TestBlendCurve.py ) if(BUILD_GUI) @@ -13,13 +19,14 @@ if(BUILD_GUI) endif(BUILD_GUI) add_custom_target(SurfaceScripts ALL - SOURCES ${Surface_Scripts} + SOURCES ${Surface_Scripts} ${Surface_TestScripts} ) fc_target_copy_resource(SurfaceScripts ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_BINARY_DIR}/Mod/Surface ${Surface_Scripts} + ${Surface_TestScripts} ) install( @@ -28,3 +35,10 @@ install( DESTINATION Mod/Surface ) + +install( + FILES + ${Surface_TestScripts} + DESTINATION + Mod/Surface/SurfaceTests +) diff --git a/src/Mod/Surface/Gui/AppSurfaceGui.cpp b/src/Mod/Surface/Gui/AppSurfaceGui.cpp index 90849781c0..5bc15816f9 100644 --- a/src/Mod/Surface/Gui/AppSurfaceGui.cpp +++ b/src/Mod/Surface/Gui/AppSurfaceGui.cpp @@ -24,19 +24,20 @@ #include "PreCompiled.h" #include -#include #include +#include #include -#include "Workbench.h" -#include "TaskGeomFillSurface.h" +#include "Blending/ViewProviderBlendCurve.h" #include "TaskFilling.h" +#include "TaskGeomFillSurface.h" #include "TaskSections.h" #include "ViewProviderExtend.h" +#include "Workbench.h" // use a different name to CreateCommand() -void CreateSurfaceCommands(void); +void CreateSurfaceCommands(); namespace SurfaceGui { @@ -45,20 +46,19 @@ class Module : public Py::ExtensionModule public: Module() : Py::ExtensionModule("SurfaceGui") { - initialize("This module is the SurfaceGui module."); // register with Python + initialize("This module is the SurfaceGui module.");// register with Python } - virtual ~Module() {} + ~Module() override {} private: }; -PyObject* initModule() -{ +PyObject *initModule() { return Base::Interpreter().addModule(new Module); } -} // namespace SurfaceGui +}// namespace SurfaceGui /* Python entry */ PyMOD_INIT_FUNC(SurfaceGui) @@ -78,10 +78,11 @@ PyMOD_INIT_FUNC(SurfaceGui) SurfaceGui::ViewProviderGeomFillSurface ::init(); SurfaceGui::ViewProviderFilling ::init(); SurfaceGui::ViewProviderSections ::init(); - SurfaceGui::ViewProviderExtend::init(); + SurfaceGui::ViewProviderExtend ::init(); + SurfaceGui::ViewProviderBlendCurve ::init(); // SurfaceGui::ViewProviderCut::init(); - PyObject* mod = SurfaceGui::initModule(); + PyObject *mod = SurfaceGui::initModule(); Base::Console().Log("Loading GUI of Surface module... done\n"); PyMOD_Return(mod); } diff --git a/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp b/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp new file mode 100644 index 0000000000..333c4c6051 --- /dev/null +++ b/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.cpp @@ -0,0 +1,38 @@ +/*************************************************************************** + * Copyright (c) 2022 Matteo Grellier * + * * + * 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 "ViewProviderBlendCurve.h" + +PROPERTY_SOURCE(SurfaceGui::ViewProviderBlendCurve, PartGui::ViewProviderSpline) + +namespace SurfaceGui +{ + +QIcon ViewProviderBlendCurve::getIcon() const +{ + return Gui::BitmapFactory().pixmap("BlendCurve"); +} + +}//namespace SurfaceGui diff --git a/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.h b/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.h new file mode 100644 index 0000000000..09e4b70c89 --- /dev/null +++ b/src/Mod/Surface/Gui/Blending/ViewProviderBlendCurve.h @@ -0,0 +1,41 @@ +/*************************************************************************** + * Copyright (c) 2022 Matteo Grellier * + * * + * 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 SURFACEGUI_VIEWPROVIDERBLENDCURVE_H +#define SURFACEGUI_VIEWPROVIDERBLENDCURVE_H + +#include + +namespace SurfaceGui +{ + +class ViewProviderBlendCurve: public PartGui::ViewProviderSpline +{ + PROPERTY_HEADER(SurfaceGui::ViewProviderBlendCurve); + +public: + QIcon getIcon() const; +}; + +}//namespace SurfaceGui + +#endif// SURFACEGUI_VIEWPROVIDEREXTEND_H diff --git a/src/Mod/Surface/Gui/CMakeLists.txt b/src/Mod/Surface/Gui/CMakeLists.txt index 83aec1ddb2..1764c167dc 100644 --- a/src/Mod/Surface/Gui/CMakeLists.txt +++ b/src/Mod/Surface/Gui/CMakeLists.txt @@ -9,10 +9,12 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY_DIR}/src ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_SOURCE_DIR} ${Boost_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ) @@ -36,6 +38,11 @@ SET(SurfaceGui_UIC_SRCS TaskSections.ui ) +SET(BlendingGui_SRCS + Blending/ViewProviderBlendCurve.cpp + Blending/ViewProviderBlendCurve.h +) + if (BUILD_QT5) qt5_wrap_ui(SurfaceGui_UIC_HDRS ${SurfaceGui_UIC_SRCS}) else() @@ -45,6 +52,7 @@ endif() SET(SurfaceGui_SRCS ${SurfaceGui_QRC_SRCS} ${SurfaceGui_UIC_HDRS} + ${BlendingGui_SRCS} TaskFilling.cpp TaskFilling.h TaskFillingEdge.cpp diff --git a/src/Mod/Surface/Gui/Command.cpp b/src/Mod/Surface/Gui/Command.cpp index 68aff54c08..c163af04fd 100644 --- a/src/Mod/Surface/Gui/Command.cpp +++ b/src/Mod/Surface/Gui/Command.cpp @@ -61,6 +61,8 @@ #include #include #include "Mod/Part/App/PartFeature.h" +#include +#include //=========================================================================== @@ -151,7 +153,7 @@ void CmdSurfaceFilling::activated(int iMsg) doCommand(Doc, "Gui.ActiveDocument.setEdit('%s',0)", FeatName.c_str()); } -bool CmdSurfaceFilling::isActive(void) +bool CmdSurfaceFilling::isActive() { return hasActiveDocument(); } @@ -173,7 +175,7 @@ CmdSurfaceGeomFillSurface::CmdSurfaceGeomFillSurface() sPixmap = "Surface_GeomFillSurface"; } -bool CmdSurfaceGeomFillSurface::isActive(void) +bool CmdSurfaceGeomFillSurface::isActive() { return hasActiveDocument(); } @@ -189,6 +191,8 @@ void CmdSurfaceGeomFillSurface::activated(int iMsg) } + + DEF_STD_CMD_A(CmdSurfaceCurveOnMesh) CmdSurfaceCurveOnMesh::CmdSurfaceCurveOnMesh() @@ -204,13 +208,15 @@ CmdSurfaceCurveOnMesh::CmdSurfaceCurveOnMesh() sPixmap = "Surface_CurveOnMesh"; } + + void CmdSurfaceCurveOnMesh::activated(int) { - doCommand(Doc,"import MeshPartGui, FreeCADGui\n" - "FreeCADGui.runCommand('MeshPart_CurveOnMesh')\n"); + doCommand(Doc, "import MeshPartGui, FreeCADGui\n" + "FreeCADGui.runCommand('MeshPart_CurveOnMesh')\n"); } -bool CmdSurfaceCurveOnMesh::isActive(void) +bool CmdSurfaceCurveOnMesh::isActive() { if (Gui::Control().activeDialog()) return false; @@ -224,6 +230,118 @@ bool CmdSurfaceCurveOnMesh::isActive(void) return false; } +//=========================================================================== +// CmdBlendSurface THIS IS THE BLEND SURFACE COMMAND +//=========================================================================== +DEF_STD_CMD_A(CmdBlendSurface) + +CmdBlendSurface::CmdBlendSurface() + : Command("Surface_BlendSurface") +{ + sAppModule = "Surface"; + sGroup = QT_TR_NOOP("Surface"); + sMenuText = QT_TR_NOOP("Blend Surface"); + sToolTipText = QT_TR_NOOP("This is the blend Surface feature"); + sStatusTip = sToolTipText; + sWhatsThis = "BlendSurface"; + sPixmap = "BlendSurface"; +} + +void CmdBlendSurface::activated(int) +{ + +} + +bool CmdBlendSurface::isActive() +{ + return true; +} + + + + + +//=========================================================================== +// CmdBlendCurve THIS IS THE BLEND CURVE COMMAND +//=========================================================================== +DEF_STD_CMD_A(CmdBlendCurve) + +CmdBlendCurve::CmdBlendCurve() + : Command("Surface_BlendCurve") +{ + sAppModule = "Surface"; + sGroup = QT_TR_NOOP("Surface"); + sMenuText = QT_TR_NOOP("Blend Curve"); + sToolTipText = QT_TR_NOOP("Join two edges with high continuity"); + sStatusTip = sToolTipText; + sWhatsThis = "BlendCurve"; + sPixmap = "BlendCurve"; +} + +void CmdBlendCurve::activated(int) +{ + // To do add pickpoints to parameters + std::string docName = App::GetApplication().getActiveDocument()->getName(); + std::string objName[2]; + std::string edge[2]; + std::string featName = getUniqueObjectName("BlendCurve"); + std::vector sel = getSelection().getSelectionEx(0, Part::Feature::getClassTypeId()); + //std::vector pickedPoints = sel[0].getPickedPoints(); + //App::DocumentObject *obj1 = sel[0].getObject(); + //App::DocumentObject *obj2 = sel[1].getObject(); + //std::vector edge1SubName = sel[0].getSubNames(); + //std::vector edge2SubName = sel[1].getSubNames(); + + //TopoDS_Shape edge1 = static_cast(obj1) + // ->Shape.getShape() + // .getSubShape(edge1SubName[0].c_str()); + //if (edge1.IsNull() || edge1.ShapeType() != TopAbs_EDGE) + // return; + //TopoDS_Shape edge2 = static_cast(obj2) + // ->Shape.getShape() + // .getSubShape(edge2SubName[0].c_str()); + //if (edge2.IsNull() || edge2.ShapeType() != TopAbs_EDGE) + // return; + + //const TopoDS_Edge &e1 = TopoDS::Edge(edge1); + //BRepAdaptor_Curve adapt1(e1); + //gp_Pnt pnt1(pickedPoints[0].x, pickedPoints[0].y, pickedPoints[0].z); + + //GeomAdaptor_Curve geomCurve = adapt1.Curve(); + //GeomAPI_ProjectPointOnCurve geomAPI(pnt1, geomCurve.Curve()); + //double par = geomAPI.LowerDistanceParameter(); + + //edge2.Curve.closestParameter(vec, par) + + objName[0] = sel[0].getFeatName(); + edge[0] = sel[0].getSubNames()[0]; + + if (sel.size() == 1) { + objName[1] = sel[0].getFeatName(); + edge[1] = sel[0].getSubNames()[1]; + } + else { + objName[1] = sel[1].getFeatName(); + edge[1] = sel[1].getSubNames()[0]; + } + openCommand(QT_TRANSLATE_NOOP("Command", "Blend Curve")); + doCommand(Doc, "App.ActiveDocument.addObject(\"Surface::FeatureBlendCurve\",\"%s\")", featName.c_str()); + doCommand(Doc, "App.ActiveDocument.%s.StartEdge = (App.getDocument('%s').getObject('%s'),['%s'])", featName.c_str(), docName.c_str(), objName[0].c_str(), edge[0].c_str()); + doCommand(Doc, "App.ActiveDocument.%s.EndEdge = (App.getDocument('%s').getObject('%s'),['%s'])", featName.c_str(), docName.c_str(), objName[1].c_str(), edge[1].c_str()); + updateActive(); + commitCommand(); +} + +bool CmdBlendCurve::isActive() +{ + Gui::SelectionFilter edgeFilter("SELECT Part::Feature SUBELEMENT Edge COUNT 2"); + return edgeFilter.match(); +} + + + + + DEF_STD_CMD_A(CmdSurfaceExtendFace) CmdSurfaceExtendFace::CmdSurfaceExtendFace() @@ -249,7 +367,7 @@ void CmdSurfaceExtendFace::activated(int) std::string FeatName = getUniqueObjectName("Surface"); std::string supportString = faceFilter.Result[0][0].getAsPropertyLinkSubString(); doCommand(Doc, "App.ActiveDocument.addObject(\"Surface::Extend\",\"%s\")", FeatName.c_str()); - doCommand(Doc, "App.ActiveDocument.%s.Face = %s",FeatName.c_str(),supportString.c_str()); + doCommand(Doc, "App.ActiveDocument.%s.Face = %s", FeatName.c_str(), supportString.c_str()); updateActive(); commitCommand(); } @@ -261,7 +379,7 @@ void CmdSurfaceExtendFace::activated(int) } } -bool CmdSurfaceExtendFace::isActive(void) +bool CmdSurfaceExtendFace::isActive() { return Gui::Selection().countObjectsOfType(Part::Feature::getClassTypeId()) == 1; } @@ -290,12 +408,12 @@ void CmdSurfaceSections::activated(int iMsg) doCommand(Doc, "Gui.ActiveDocument.setEdit('%s',0)", FeatName.c_str()); } -bool CmdSurfaceSections::isActive(void) +bool CmdSurfaceSections::isActive() { return hasActiveDocument(); } -void CreateSurfaceCommands(void) +void CreateSurfaceCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); /* @@ -306,4 +424,6 @@ void CreateSurfaceCommands(void) rcCmdMgr.addCommand(new CmdSurfaceSections()); rcCmdMgr.addCommand(new CmdSurfaceExtendFace()); rcCmdMgr.addCommand(new CmdSurfaceCurveOnMesh()); + rcCmdMgr.addCommand(new CmdBlendCurve()); + rcCmdMgr.addCommand(new CmdBlendSurface()); } diff --git a/src/Mod/Surface/Gui/Resources/Surface.qrc b/src/Mod/Surface/Gui/Resources/Surface.qrc index 7af306fa62..a0840c7967 100644 --- a/src/Mod/Surface/Gui/Resources/Surface.qrc +++ b/src/Mod/Surface/Gui/Resources/Surface.qrc @@ -4,6 +4,7 @@ icons/Surface_BSplineSurface.svg icons/Surface_CurveOnMesh.svg icons/Surface_Cut.svg + icons/BlendCurve.svg icons/Surface_ExtendFace.svg icons/Surface_Filling.svg icons/Surface_GeomFillSurface.svg @@ -11,6 +12,7 @@ icons/Surface_Sewing.svg icons/Surface_Surface.svg icons/Surface_Workbench.svg + icons/BlendSurface.svg diff --git a/src/Mod/Surface/Gui/Resources/icons/BlendCurve.svg b/src/Mod/Surface/Gui/Resources/icons/BlendCurve.svg new file mode 100644 index 0000000000..aeac6de070 --- /dev/null +++ b/src/Mod/Surface/Gui/Resources/icons/BlendCurve.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Mod/Surface/Gui/Resources/icons/BlendSurface.svg b/src/Mod/Surface/Gui/Resources/icons/BlendSurface.svg new file mode 100644 index 0000000000..7411c1dcc6 --- /dev/null +++ b/src/Mod/Surface/Gui/Resources/icons/BlendSurface.svg @@ -0,0 +1,191 @@ + + + Surface_Sewing + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + Surface_Sewing + + + [bitacovir] + + + Part_Shape_from_Mesh + 2020/10/03 + http://www.freecadweb.org/wiki/index.php?title=Artwork + + + FreeCAD + + + + + + FreeCAD LGPL2+ + + + https://www.gnu.org/copyleft/lesser.html + + + + + + + + surface + + + + + + + + + + + + + + + + + diff --git a/src/Mod/Surface/Gui/TaskFilling.cpp b/src/Mod/Surface/Gui/TaskFilling.cpp index e0d0c86ff7..4c01b677a2 100644 --- a/src/Mod/Surface/Gui/TaskFilling.cpp +++ b/src/Mod/Surface/Gui/TaskFilling.cpp @@ -95,14 +95,14 @@ void ViewProviderFilling::unsetEdit(int ModNum) PartGui::ViewProviderSpline::unsetEdit(ModNum); } -QIcon ViewProviderFilling::getIcon(void) const +QIcon ViewProviderFilling::getIcon() const { return Gui::BitmapFactory().pixmap("Surface_Filling"); } void ViewProviderFilling::highlightReferences(ShapeType type, const References& refs, bool on) { - for (auto it : refs) { + for (const auto& it : refs) { Part::Feature* base = dynamic_cast(it.first); if (base) { PartGui::ViewProviderPartExt* svp = dynamic_cast( @@ -116,7 +116,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& TopExp::MapShapes(base->Shape.getValue(), TopAbs_VERTEX, vMap); colors.resize(vMap.Extent(), svp->PointColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { // check again that the index is in range because it's possible that the // sub-names are invalid std::size_t idx = static_cast(std::stoi(jt.substr(6)) - 1); @@ -137,7 +137,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); colors.resize(eMap.Extent(), svp->LineColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that the // sub-names are invalid @@ -158,7 +158,7 @@ void ViewProviderFilling::highlightReferences(ShapeType type, const References& TopExp::MapShapes(base->Shape.getValue(), TopAbs_FACE, fMap); colors.resize(fMap.Extent(), svp->ShapeColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that the // sub-names are invalid @@ -189,14 +189,14 @@ public: , editedObject(editedObject) { } - ~ShapeSelection() + ~ShapeSelection() override { mode = FillingPanel::None; } /** * Allow the user to pick only edges. */ - bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) + bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) override { // don't allow references to itself if (pObj == editedObject) @@ -234,9 +234,9 @@ private: return false; auto links = editedObject->BoundaryEdges.getSubListValues(); - for (auto it : links) { + for (const auto& it : links) { if (it.first == pObj) { - for (auto jt : it.second) { + for (const auto& jt : it.second) { if (jt == sSubName) return !appendEdges; } @@ -295,8 +295,8 @@ void FillingPanel::setEditedObject(Surface::Filling* fea) const std::vector& subList = editedObject->InitialFace.getSubValues(); if (initFace && subList.size() == 1) { QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(initFace->Label.getValue())) - .arg(QString::fromStdString(subList.front())); + .arg(QString::fromUtf8(initFace->Label.getValue()), + QString::fromStdString(subList.front())); ui->lineInitFaceName->setText(text); } @@ -329,8 +329,8 @@ void FillingPanel::setEditedObject(Surface::Filling* fea) ui->listBoundary->addItem(item); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(obj->Label.getValue())) - .arg(QString::fromStdString(edge)); + .arg(QString::fromUtf8(obj->Label.getValue()), + QString::fromStdString(edge)); item->setText(text); // The user data field of a list widget item @@ -373,8 +373,8 @@ void FillingPanel::open() // highlight the referenced face std::vector links; - links.push_back(std::make_pair(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues())); + links.emplace_back(editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, true); Gui::Selection().clearSelection(); @@ -420,8 +420,8 @@ void FillingPanel::slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) // unhighlight the referenced face std::vector links; - links.push_back(std::make_pair(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues())); + links.emplace_back(editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); } } @@ -444,8 +444,8 @@ bool FillingPanel::accept() // unhighlight the referenced face std::vector links; - links.push_back(std::make_pair(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues())); + links.emplace_back(editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); return true; @@ -458,8 +458,8 @@ bool FillingPanel::reject() // unhighlight the referenced face std::vector links; - links.push_back(std::make_pair(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues())); + links.emplace_back(editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); selectionMode = None; @@ -475,8 +475,8 @@ void FillingPanel::on_lineInitFaceName_textChanged(const QString& text) // unhighlight the referenced face std::vector links; - links.push_back(std::make_pair(editedObject->InitialFace.getValue(), - editedObject->InitialFace.getSubValues())); + links.emplace_back(editedObject->InitialFace.getValue(), + editedObject->InitialFace.getSubValues()); this->vp->highlightReferences(ViewProviderFilling::Face, links, false); editedObject->InitialFace.setValue(nullptr); @@ -581,17 +581,17 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) if (selectionMode == InitFace) { Gui::SelectionObject sel(msg); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(sel.getObject()->Label.getValue())) - .arg(QString::fromLatin1(msg.pSubName)); + .arg(QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName)); ui->lineInitFaceName->setText(text); std::vector subList; - subList.push_back(msg.pSubName); + subList.emplace_back(msg.pSubName); editedObject->InitialFace.setValue(sel.getObject(), subList); // highlight the referenced face std::vector links; - links.push_back(std::make_pair(sel.getObject(), subList)); + links.emplace_back(sel.getObject(), subList); this->vp->highlightReferences(ViewProviderFilling::Face, links, true); Gui::Selection().rmvSelectionGate(); @@ -603,8 +603,8 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) Gui::SelectionObject sel(msg); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(sel.getObject()->Label.getValue())) - .arg(QString::fromLatin1(msg.pSubName)); + .arg(QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName)); item->setText(text); QList data; @@ -619,7 +619,7 @@ void FillingPanel::onSelectionChanged(const Gui::SelectionChanges& msg) std::size_t count = objects.size(); objects.push_back(sel.getObject()); auto element = editedObject->BoundaryEdges.getSubValues(); - element.push_back(msg.pSubName); + element.emplace_back(msg.pSubName); editedObject->BoundaryEdges.setValues(objects, element); // extend faces and continuities lists if needed diff --git a/src/Mod/Surface/Gui/TaskFilling.h b/src/Mod/Surface/Gui/TaskFilling.h index c069187adc..9ac5a02530 100644 --- a/src/Mod/Surface/Gui/TaskFilling.h +++ b/src/Mod/Surface/Gui/TaskFilling.h @@ -42,15 +42,15 @@ class Ui_TaskFilling; class ViewProviderFilling : public PartGui::ViewProviderSpline { - PROPERTY_HEADER(SurfaceGui::ViewProviderFilling); + PROPERTY_HEADER_WITH_OVERRIDE(SurfaceGui::ViewProviderFilling); typedef std::vector References; public: enum ShapeType {Vertex, Edge, Face}; - virtual void setupContextMenu(QMenu*, QObject*, const char*); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - QIcon getIcon(void) const; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; + QIcon getIcon() const override; void highlightReferences(ShapeType type, const References& refs, bool on); }; @@ -73,7 +73,7 @@ private: public: FillingPanel(ViewProviderFilling* vp, Surface::Filling* obj); - ~FillingPanel(); + ~FillingPanel() override; void open(); void checkOpenCommand(); @@ -82,14 +82,14 @@ public: void setEditedObject(Surface::Filling* obj); protected: - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; /** Notifies on undo */ - virtual void slotUndoDocument(const Gui::Document& Doc); + void slotUndoDocument(const Gui::Document& Doc) override; /** Notifies on redo */ - virtual void slotRedoDocument(const Gui::Document& Doc); + void slotRedoDocument(const Gui::Document& Doc) override; /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; void modifyBoundary(bool); private Q_SLOTS: @@ -100,7 +100,7 @@ private Q_SLOTS: void on_listBoundary_itemDoubleClicked(QListWidgetItem*); void on_buttonAccept_clicked(); void on_buttonIgnore_clicked(); - void onDeleteEdge(void); + void onDeleteEdge(); void onIndexesMoved(); void clearSelection(); }; @@ -111,16 +111,16 @@ class TaskFilling : public Gui::TaskView::TaskDialog public: TaskFilling(ViewProviderFilling* vp, Surface::Filling* obj); - ~TaskFilling(); + ~TaskFilling() override; void setEditedObject(Surface::Filling* obj); public: - void open(); - void closed(); - bool accept(); - bool reject(); + void open() override; + void closed() override; + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Surface/Gui/TaskFillingEdge.cpp b/src/Mod/Surface/Gui/TaskFillingEdge.cpp index 0f5db36719..58e6b7fdb5 100644 --- a/src/Mod/Surface/Gui/TaskFillingEdge.cpp +++ b/src/Mod/Surface/Gui/TaskFillingEdge.cpp @@ -61,14 +61,14 @@ public: , editedObject(editedObject) { } - ~ShapeSelection() + ~ShapeSelection() override { mode = FillingEdgePanel::None; } /** * Allow the user to pick only edges. */ - bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) + bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) override { // don't allow references to itself if (pObj == editedObject) @@ -97,9 +97,9 @@ private: return false; auto links = editedObject->UnboundEdges.getSubListValues(); - for (auto it : links) { + for (const auto& it : links) { if (it.first == pObj) { - for (auto jt : it.second) { + for (const auto& jt : it.second) { if (jt == sSubName) return !appendEdges; } @@ -179,8 +179,8 @@ void FillingEdgePanel::setEditedObject(Surface::Filling* fea) ui->listUnbound->addItem(item); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(obj->Label.getValue())) - .arg(QString::fromStdString(edge)); + .arg(QString::fromUtf8(obj->Label.getValue()), + QString::fromStdString(edge)); item->setText(text); // The user data field of a list widget item @@ -381,8 +381,8 @@ void FillingEdgePanel::onSelectionChanged(const Gui::SelectionChanges& msg) Gui::SelectionObject sel(msg); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(sel.getObject()->Label.getValue())) - .arg(QString::fromLatin1(msg.pSubName)); + .arg(QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName)); item->setText(text); QList data; @@ -397,7 +397,7 @@ void FillingEdgePanel::onSelectionChanged(const Gui::SelectionChanges& msg) std::size_t count = objects.size(); objects.push_back(sel.getObject()); auto element = editedObject->UnboundEdges.getSubValues(); - element.push_back(msg.pSubName); + element.emplace_back(msg.pSubName); editedObject->UnboundEdges.setValues(objects, element); // extend faces and continuities lists if needed diff --git a/src/Mod/Surface/Gui/TaskFillingEdge.h b/src/Mod/Surface/Gui/TaskFillingEdge.h index 4c66b5f120..53fd2146b5 100644 --- a/src/Mod/Surface/Gui/TaskFillingEdge.h +++ b/src/Mod/Surface/Gui/TaskFillingEdge.h @@ -59,7 +59,7 @@ private: public: FillingEdgePanel(ViewProviderFilling* vp, Surface::Filling* obj); - ~FillingEdgePanel(); + ~FillingEdgePanel() override; void open(); void checkOpenCommand(); @@ -68,14 +68,14 @@ public: void setEditedObject(Surface::Filling* obj); protected: - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; /** Notifies on undo */ - virtual void slotUndoDocument(const Gui::Document& Doc); + void slotUndoDocument(const Gui::Document& Doc) override; /** Notifies on redo */ - virtual void slotRedoDocument(const Gui::Document& Doc); + void slotRedoDocument(const Gui::Document& Doc) override; /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; void modifyBoundary(bool); private Q_SLOTS: @@ -84,7 +84,7 @@ private Q_SLOTS: void on_listUnbound_itemDoubleClicked(QListWidgetItem*); void on_buttonUnboundAccept_clicked(); void on_buttonUnboundIgnore_clicked(); - void onDeleteUnboundEdge(void); + void onDeleteUnboundEdge(); void clearSelection(); }; diff --git a/src/Mod/Surface/Gui/TaskFillingVertex.cpp b/src/Mod/Surface/Gui/TaskFillingVertex.cpp index 59ea024c37..7d9a606796 100644 --- a/src/Mod/Surface/Gui/TaskFillingVertex.cpp +++ b/src/Mod/Surface/Gui/TaskFillingVertex.cpp @@ -60,14 +60,14 @@ public: , editedObject(editedObject) { } - ~VertexSelection() + ~VertexSelection() override { mode = FillingVertexPanel::None; } /** * Allow the user to pick only edges. */ - bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) + bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) override { // don't allow references to itself if (pObj == editedObject) @@ -96,9 +96,9 @@ private: return false; auto links = editedObject->Points.getSubListValues(); - for (auto it : links) { + for (const auto& it : links) { if (it.first == pObj) { - for (auto jt : it.second) { + for (const auto& jt : it.second) { if (jt == sSubName) return !appendVertex; } @@ -160,8 +160,8 @@ void FillingVertexPanel::setEditedObject(Surface::Filling* obj) ui->listFreeVertex->addItem(item); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8((*it)->Label.getValue())) - .arg(QString::fromStdString(*jt)); + .arg(QString::fromUtf8((*it)->Label.getValue()), + QString::fromStdString(*jt)); item->setText(text); QList data; @@ -259,8 +259,8 @@ void FillingVertexPanel::onSelectionChanged(const Gui::SelectionChanges& msg) Gui::SelectionObject sel(msg); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(sel.getObject()->Label.getValue())) - .arg(QString::fromLatin1(msg.pSubName)); + .arg(QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName)); item->setText(text); QList data; @@ -272,7 +272,7 @@ void FillingVertexPanel::onSelectionChanged(const Gui::SelectionChanges& msg) auto objects = editedObject->Points.getValues(); objects.push_back(sel.getObject()); auto element = editedObject->Points.getSubValues(); - element.push_back(msg.pSubName); + element.emplace_back(msg.pSubName); editedObject->Points.setValues(objects, element); this->vp->highlightReferences(ViewProviderFilling::Vertex, editedObject->Points.getSubListValues(), true); diff --git a/src/Mod/Surface/Gui/TaskFillingVertex.h b/src/Mod/Surface/Gui/TaskFillingVertex.h index 7b67493425..bbc1052c5a 100644 --- a/src/Mod/Surface/Gui/TaskFillingVertex.h +++ b/src/Mod/Surface/Gui/TaskFillingVertex.h @@ -58,7 +58,7 @@ private: public: FillingVertexPanel(ViewProviderFilling* vp, Surface::Filling* obj); - ~FillingVertexPanel(); + ~FillingVertexPanel() override; void open(); void reject(); @@ -66,19 +66,19 @@ public: void setEditedObject(Surface::Filling* obj); protected: - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; /** Notifies on undo */ - virtual void slotUndoDocument(const Gui::Document& Doc); + void slotUndoDocument(const Gui::Document& Doc) override; /** Notifies on redo */ - virtual void slotRedoDocument(const Gui::Document& Doc); + void slotRedoDocument(const Gui::Document& Doc) override; /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; private Q_SLOTS: void on_buttonVertexAdd_clicked(); void on_buttonVertexRemove_clicked(); - void onDeleteVertex(void); + void onDeleteVertex(); void clearSelection(); }; diff --git a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp index d14029663d..f04494a796 100644 --- a/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp +++ b/src/Mod/Surface/Gui/TaskGeomFillSurface.cpp @@ -97,7 +97,7 @@ void ViewProviderGeomFillSurface::unsetEdit(int ModNum) } } -QIcon ViewProviderGeomFillSurface::getIcon(void) const +QIcon ViewProviderGeomFillSurface::getIcon() const { return Gui::BitmapFactory().pixmap("Surface_BSplineSurface"); } @@ -106,7 +106,7 @@ void ViewProviderGeomFillSurface::highlightReferences(bool on) { Surface::GeomFillSurface* surface = static_cast(getObject()); auto bounds = surface->BoundaryList.getSubListValues(); - for (auto it : bounds) { + for (const auto& it : bounds) { Part::Feature* base = dynamic_cast(it.first); if (base) { PartGui::ViewProviderPartExt* svp = dynamic_cast( @@ -118,7 +118,7 @@ void ViewProviderGeomFillSurface::highlightReferences(bool on) TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); colors.resize(eMap.Extent(), svp->LineColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); assert (idx < colors.size()); colors[idx] = App::Color(1.0,0.0,1.0); // magenta @@ -148,7 +148,7 @@ public: /** * Allow the user to pick only edges. */ - bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName); + bool allow(App::Document* pDoc, App::DocumentObject* pObj, const char* sSubName) override; private: bool appendEdges; @@ -171,9 +171,9 @@ bool GeomFillSurface::EdgeSelection::allow(App::Document* , App::DocumentObject* return false; auto links = editedObject->BoundaryList.getSubListValues(); - for (auto it : links) { + for (const auto& it : links) { if (it.first == pObj) { - for (auto jt : it.second) { + for (const auto& jt : it.second) { if (jt == sSubName) return !appendEdges; } @@ -258,8 +258,8 @@ void GeomFillSurface::setEditedObject(Surface::GeomFillSurface* obj) ui->listWidget->addItem(item); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8((*it)->Label.getValue())) - .arg(QString::fromStdString(*jt)); + .arg(QString::fromUtf8((*it)->Label.getValue()), + QString::fromStdString(*jt)); item->setText(text); QList data; @@ -424,8 +424,8 @@ void GeomFillSurface::onSelectionChanged(const Gui::SelectionChanges& msg) Gui::SelectionObject sel(msg); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(sel.getObject()->Label.getValue())) - .arg(QString::fromLatin1(msg.pSubName)); + .arg(QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName)); item->setText(text); QList data; @@ -437,7 +437,7 @@ void GeomFillSurface::onSelectionChanged(const Gui::SelectionChanges& msg) auto objects = editedObject->BoundaryList.getValues(); objects.push_back(sel.getObject()); auto element = editedObject->BoundaryList.getSubValues(); - element.push_back(msg.pSubName); + element.emplace_back(msg.pSubName); editedObject->BoundaryList.setValues(objects, element); auto booleans = editedObject->ReversedList.getValues(); booleans.push_back(false); diff --git a/src/Mod/Surface/Gui/TaskGeomFillSurface.h b/src/Mod/Surface/Gui/TaskGeomFillSurface.h index 90d7aa1ea7..ba83cd2835 100644 --- a/src/Mod/Surface/Gui/TaskGeomFillSurface.h +++ b/src/Mod/Surface/Gui/TaskGeomFillSurface.h @@ -41,12 +41,12 @@ class Ui_GeomFillSurface; class ViewProviderGeomFillSurface : public PartGui::ViewProviderSpline { - PROPERTY_HEADER(SurfaceGui::ViewProviderGeomFillSurface); + PROPERTY_HEADER_WITH_OVERRIDE(SurfaceGui::ViewProviderGeomFillSurface); public: - virtual void setupContextMenu(QMenu*, QObject*, const char*); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - QIcon getIcon(void) const; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; + QIcon getIcon() const override; void highlightReferences(bool on); }; @@ -69,7 +69,7 @@ private: public: GeomFillSurface(ViewProviderGeomFillSurface* vp, Surface::GeomFillSurface* obj); - ~GeomFillSurface(); + ~GeomFillSurface() override; void open(); void checkOpenCommand(); @@ -78,14 +78,14 @@ public: void setEditedObject(Surface::GeomFillSurface* obj); protected: - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; /** Notifies on undo */ - virtual void slotUndoDocument(const Gui::Document& Doc); + void slotUndoDocument(const Gui::Document& Doc) override; /** Notifies on redo */ - virtual void slotRedoDocument(const Gui::Document& Doc); + void slotRedoDocument(const Gui::Document& Doc) override; /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; void changeFillType(GeomFill_FillingStyle); void flipOrientation(QListWidgetItem*); @@ -96,7 +96,7 @@ private Q_SLOTS: void on_buttonEdgeAdd_clicked(); void on_buttonEdgeRemove_clicked(); void on_listWidget_itemDoubleClicked(QListWidgetItem*); - void onDeleteEdge(void); + void onDeleteEdge(); void onFlipOrientation(); void clearSelection(); }; @@ -107,15 +107,15 @@ class TaskGeomFillSurface : public Gui::TaskView::TaskDialog public: TaskGeomFillSurface(ViewProviderGeomFillSurface* vp, Surface::GeomFillSurface* obj); - ~TaskGeomFillSurface(); + ~TaskGeomFillSurface() override; void setEditedObject(Surface::GeomFillSurface* obj); public: - void open(); - bool accept(); - bool reject(); + void open() override; + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Surface/Gui/TaskSections.cpp b/src/Mod/Surface/Gui/TaskSections.cpp index 6182253a28..349710ff0c 100644 --- a/src/Mod/Surface/Gui/TaskSections.cpp +++ b/src/Mod/Surface/Gui/TaskSections.cpp @@ -99,14 +99,14 @@ void ViewProviderSections::unsetEdit(int ModNum) } } -QIcon ViewProviderSections::getIcon(void) const +QIcon ViewProviderSections::getIcon() const { return Gui::BitmapFactory().pixmap("Surface_Sections"); } void ViewProviderSections::highlightReferences(ShapeType type, const References& refs, bool on) { - for (auto it : refs) { + for (const auto& it : refs) { Part::Feature* base = dynamic_cast(it.first); if (base) { PartGui::ViewProviderPartExt* svp = dynamic_cast( @@ -120,7 +120,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& TopExp::MapShapes(base->Shape.getValue(), TopAbs_VERTEX, vMap); colors.resize(vMap.Extent(), svp->PointColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { // check again that the index is in range because it's possible that the // sub-names are invalid std::size_t idx = static_cast(std::stoi(jt.substr(6)) - 1); @@ -141,7 +141,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& TopExp::MapShapes(base->Shape.getValue(), TopAbs_EDGE, eMap); colors.resize(eMap.Extent(), svp->LineColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that the // sub-names are invalid @@ -162,7 +162,7 @@ void ViewProviderSections::highlightReferences(ShapeType type, const References& TopExp::MapShapes(base->Shape.getValue(), TopAbs_FACE, fMap); colors.resize(fMap.Extent(), svp->ShapeColor.getValue()); - for (auto jt : it.second) { + for (const auto& jt : it.second) { std::size_t idx = static_cast(std::stoi(jt.substr(4)) - 1); // check again that the index is in range because it's possible that the // sub-names are invalid @@ -193,14 +193,14 @@ public: , editedObject(editedObject) { } - ~ShapeSelection() + ~ShapeSelection() override { mode = SectionsPanel::None; } /** * Allow the user to pick only edges. */ - bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) + bool allow(App::Document*, App::DocumentObject* pObj, const char* sSubName) override { // don't allow references to itself if (pObj == editedObject) @@ -229,9 +229,9 @@ private: return false; auto links = editedObject->NSections.getSubListValues(); - for (auto it : links) { + for (const auto& it : links) { if (it.first == pObj) { - for (auto jt : it.second) { + for (const auto& jt : it.second) { if (jt == sSubName) return !appendEdges; } @@ -295,8 +295,8 @@ void SectionsPanel::setEditedObject(Surface::Sections* fea) ui->listSections->addItem(item); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(obj->Label.getValue())) - .arg(QString::fromStdString(edge)); + .arg(QString::fromUtf8(obj->Label.getValue()), + QString::fromStdString(edge)); item->setText(text); // The user data field of a list widget item @@ -428,8 +428,8 @@ void SectionsPanel::onSelectionChanged(const Gui::SelectionChanges& msg) Gui::SelectionObject sel(msg); QString text = QString::fromLatin1("%1.%2") - .arg(QString::fromUtf8(sel.getObject()->Label.getValue())) - .arg(QString::fromLatin1(msg.pSubName)); + .arg(QString::fromUtf8(sel.getObject()->Label.getValue()), + QString::fromLatin1(msg.pSubName)); item->setText(text); QList data; diff --git a/src/Mod/Surface/Gui/TaskSections.h b/src/Mod/Surface/Gui/TaskSections.h index 03f1c5635c..afb97bbca6 100644 --- a/src/Mod/Surface/Gui/TaskSections.h +++ b/src/Mod/Surface/Gui/TaskSections.h @@ -41,15 +41,15 @@ class Ui_Sections; class ViewProviderSections : public PartGui::ViewProviderSpline { - PROPERTY_HEADER(SurfaceGui::ViewProviderSections); + PROPERTY_HEADER_WITH_OVERRIDE(SurfaceGui::ViewProviderSections); typedef std::vector References; public: enum ShapeType {Vertex, Edge, Face}; - virtual void setupContextMenu(QMenu*, QObject*, const char*); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - QIcon getIcon(void) const; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool setEdit(int ModNum) override; + void unsetEdit(int ModNum) override; + QIcon getIcon() const override; void highlightReferences(ShapeType type, const References& refs, bool on); }; @@ -72,7 +72,7 @@ private: public: SectionsPanel(ViewProviderSections* vp, Surface::Sections* obj); - ~SectionsPanel(); + ~SectionsPanel() override; void open(); void checkOpenCommand(); @@ -81,19 +81,19 @@ public: void setEditedObject(Surface::Sections* obj); protected: - void changeEvent(QEvent *e); - virtual void onSelectionChanged(const Gui::SelectionChanges& msg); + void changeEvent(QEvent *e) override; + void onSelectionChanged(const Gui::SelectionChanges& msg) override; /** Notifies on undo */ - virtual void slotUndoDocument(const Gui::Document& Doc); + void slotUndoDocument(const Gui::Document& Doc) override; /** Notifies on redo */ - virtual void slotRedoDocument(const Gui::Document& Doc); + void slotRedoDocument(const Gui::Document& Doc) override; /** Notifies when the object is about to be removed. */ - virtual void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj); + void slotDeletedObject(const Gui::ViewProviderDocumentObject& Obj) override; private Q_SLOTS: void on_buttonEdgeAdd_clicked(); void on_buttonEdgeRemove_clicked(); - void onDeleteEdge(void); + void onDeleteEdge(); void clearSelection(); void onIndexesMoved(); @@ -108,15 +108,15 @@ class TaskSections : public Gui::TaskView::TaskDialog public: TaskSections(ViewProviderSections* vp, Surface::Sections* obj); - ~TaskSections(); + ~TaskSections() override; void setEditedObject(Surface::Sections* obj); public: - void open(); - bool accept(); - bool reject(); + void open() override; + bool accept() override; + bool reject() override; - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } private: diff --git a/src/Mod/Surface/Gui/ViewProviderExtend.h b/src/Mod/Surface/Gui/ViewProviderExtend.h index 2c8b6824ea..7f5f18c415 100644 --- a/src/Mod/Surface/Gui/ViewProviderExtend.h +++ b/src/Mod/Surface/Gui/ViewProviderExtend.h @@ -31,10 +31,10 @@ namespace SurfaceGui class ViewProviderExtend : public PartGui::ViewProviderSpline { - PROPERTY_HEADER(SurfaceGui::ViewProviderExtend); + PROPERTY_HEADER_WITH_OVERRIDE(SurfaceGui::ViewProviderExtend); public: - QIcon getIcon(void) const; + QIcon getIcon() const override; }; } //namespace SurfaceGui diff --git a/src/Mod/Surface/Gui/Workbench.cpp b/src/Mod/Surface/Gui/Workbench.cpp index f24b7f5ba6..a16839b6f4 100644 --- a/src/Mod/Surface/Gui/Workbench.cpp +++ b/src/Mod/Surface/Gui/Workbench.cpp @@ -44,40 +44,42 @@ Workbench::~Workbench() { } -Gui::MenuItem* Workbench::setupMenuBar() const +Gui::MenuItem *Workbench::setupMenuBar() const { - Gui::MenuItem* root = StdWorkbench::setupMenuBar(); - Gui::MenuItem* item = root->findItem( "&Windows" ); + Gui::MenuItem *root = StdWorkbench::setupMenuBar(); + Gui::MenuItem *item = root->findItem("&Windows"); - Gui::MenuItem* surface = new Gui::MenuItem; - root->insertItem( item, surface ); + Gui::MenuItem *surface = new Gui::MenuItem; + root->insertItem(item, surface); surface->setCommand("Surface"); *surface << "Surface_Filling" << "Surface_GeomFillSurface" << "Surface_Sections" << "Surface_ExtendFace" - << "Surface_CurveOnMesh"; -/* + << "Surface_CurveOnMesh" + << "Surface_BlendCurve"; + /* *surface << "Surface_Cut"; -*/ + */ return root; } -Gui::ToolBarItem* Workbench::setupToolBars() const +Gui::ToolBarItem *Workbench::setupToolBars() const { - Gui::ToolBarItem* root = StdWorkbench::setupToolBars(); + Gui::ToolBarItem *root = StdWorkbench::setupToolBars(); - Gui::ToolBarItem* surface = new Gui::ToolBarItem(root); + Gui::ToolBarItem *surface = new Gui::ToolBarItem(root); surface->setCommand("Surface"); *surface << "Surface_Filling" << "Surface_GeomFillSurface" << "Surface_Sections" << "Surface_ExtendFace" - << "Surface_CurveOnMesh"; -/* + << "Surface_CurveOnMesh" + << "Surface_BlendCurve"; + /* *surface << "Surface_Cut"; -*/ + */ return root; } diff --git a/src/Mod/Surface/Gui/Workbench.h b/src/Mod/Surface/Gui/Workbench.h index d82b2a203b..6f384806a4 100644 --- a/src/Mod/Surface/Gui/Workbench.h +++ b/src/Mod/Surface/Gui/Workbench.h @@ -30,15 +30,15 @@ namespace SurfaceGui { class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; protected: - Gui::MenuItem* setupMenuBar() const; - Gui::ToolBarItem* setupToolBars() const; + Gui::MenuItem* setupMenuBar() const override; + Gui::ToolBarItem* setupToolBars() const override; }; } // namespace SurfaceGui diff --git a/src/Mod/Surface/Init.py b/src/Mod/Surface/Init.py index 0fa131610a..605013d32d 100644 --- a/src/Mod/Surface/Init.py +++ b/src/Mod/Surface/Init.py @@ -1,2 +1,4 @@ # FreeCAD init script of the Surface module # (c) 2001 Juergen Riegel LGPL + +FreeCAD.__unit_test__ += ["TestSurfaceApp"] diff --git a/src/Mod/Surface/SurfaceTests/TestBlendCurve.py b/src/Mod/Surface/SurfaceTests/TestBlendCurve.py new file mode 100644 index 0000000000..0840ec8db8 --- /dev/null +++ b/src/Mod/Surface/SurfaceTests/TestBlendCurve.py @@ -0,0 +1,75 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 Werner Mayer * +# * * +# * 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__ = "Surface unit tests" +__author__ = "Werner Mayer" +__url__ = "https://www.freecadweb.org" + +import sys +import unittest +from os.path import join + +import FreeCAD +from FreeCAD import Base +import Surface + +vec = Base.Vector + + +class TestBlendCurve(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + def assertAlmostCoincide(self, pt1, pt2, places=None, msg=None, delta=None): + self.assertAlmostEqual(pt1.x, pt2.x, places, msg, delta) + self.assertAlmostEqual(pt1.y, pt2.y, places, msg, delta) + self.assertAlmostEqual(pt1.z, pt2.z, places, msg, delta) + + def test_blend_curve(self): + # Create C0 BlendPoint at origin + b1 = Surface.BlendPoint() + # Create G1 BlendPoint + b2 = Surface.BlendPoint([vec(10,3,6), vec(2,5,6)]) + # BlendCurve between the two BlendPoints + bc = Surface.BlendCurve(b1, b2) + # Compute the interpolating BezierCurve + curve1 = bc.compute() + + # Create G2 BlendPoint at the end of previous BlendCurve + b1 = Surface.BlendPoint(curve1.toShape(), 1, 2) + # Create G1 BlendPoint + b2 = Surface.BlendPoint([vec(5,6,2), vec(2,5,6)]) + + bc = Surface.BlendCurve(b1, b2) + # Compute the interpolating BezierCurve + curve2 = bc.compute() + + d1 = curve1.getD2(1) + d2 = curve2.getD2(0) + + self.assertEqual(len(d1), len(d2)) + self.assertAlmostCoincide(d1[0], d2[0]) + self.assertAlmostCoincide(d1[1], d2[1]) + self.assertAlmostCoincide(d1[2], d2[2]) diff --git a/src/Mod/Surface/SurfaceTests/__init__.py b/src/Mod/Surface/SurfaceTests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/Mod/Surface/TestSurfaceApp.py b/src/Mod/Surface/TestSurfaceApp.py new file mode 100644 index 0000000000..2b77c3fee5 --- /dev/null +++ b/src/Mod/Surface/TestSurfaceApp.py @@ -0,0 +1,24 @@ +# *************************************************************************** +# * * +# * Copyright (c) 2022 Werner Mayer * +# * * +# * 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 * +# * * +# *************************************************************************** + +# Unit test for the Surface module +from SurfaceTests.TestBlendCurve import TestBlendCurve diff --git a/src/Mod/TechDraw/App/AppTechDrawPy.cpp b/src/Mod/TechDraw/App/AppTechDrawPy.cpp index 8f6d6c3b10..264a6105fa 100644 --- a/src/Mod/TechDraw/App/AppTechDrawPy.cpp +++ b/src/Mod/TechDraw/App/AppTechDrawPy.cpp @@ -119,7 +119,7 @@ void copy(Py::Dict sourceRange, OutputIt targetIt) string key; string value; - for (auto keyPy : sourceRange.keys()) { + for (const auto& keyPy : sourceRange.keys()) { key = Py::String(keyPy); value = Py::String(sourceRange[keyPy]); *targetIt = {key, value}; @@ -191,10 +191,10 @@ public: ); initialize("This is a module for making drawings"); // register with Python } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) + Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); @@ -392,7 +392,7 @@ private: if(ew.perform()) { std::vector rw = ew.getResultNoDups(); std::vector sortedWires = ew.sortStrip(rw,true); - if(sortedWires.size()) { + if(!sortedWires.empty()) { outerWire = new TopoShapeWirePy(new TopoShape(*sortedWires.begin())); success = true; } @@ -556,7 +556,7 @@ private: if (dvp->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())) { TechDraw::DrawProjGroupItem* dpgi = static_cast(dvp); TechDraw::DrawProjGroup* dpg = dpgi->getPGroup(); - if (dpg != nullptr) { + if (dpg) { offX = dpg->X.getValue(); offY = dpg->Y.getValue(); } @@ -710,7 +710,7 @@ private: } else if (v->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())) { DrawViewDimension* dvd = static_cast(v); TechDraw::DrawViewPart* dvp = dvd->getViewPart(); - if (dvp == nullptr) { + if (!dvp) { continue; } double grandParentX = 0.0; @@ -718,7 +718,7 @@ private: if (dvp->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())) { TechDraw::DrawProjGroupItem* dpgi = static_cast(dvp); TechDraw::DrawProjGroup* dpg = dpgi->getPGroup(); - if (dpg == nullptr) { + if (!dpg) { continue; } grandParentX = dpg->X.getValue(); @@ -1212,7 +1212,7 @@ private: throw Py::Exception(); std::string svg(svgcode); - std::string empty = ""; + std::string empty; std::string endline = "--endOfLine--"; std::string linebreak = "\\n"; // removing linebreaks for regex to work diff --git a/src/Mod/TechDraw/App/ArrowPropEnum.h b/src/Mod/TechDraw/App/ArrowPropEnum.h index c6acebd1ec..49a2540270 100644 --- a/src/Mod/TechDraw/App/ArrowPropEnum.h +++ b/src/Mod/TechDraw/App/ArrowPropEnum.h @@ -23,6 +23,8 @@ #ifndef _ARROWENUMS_H_ #define _ARROWENUMS_H_ +#include + #include #include #include diff --git a/src/Mod/TechDraw/App/CMakeLists.txt b/src/Mod/TechDraw/App/CMakeLists.txt index ca5088c48c..adc4cd507a 100644 --- a/src/Mod/TechDraw/App/CMakeLists.txt +++ b/src/Mod/TechDraw/App/CMakeLists.txt @@ -15,14 +15,26 @@ include_directories( ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ${QT_QTCORE_INCLUDE_DIR} ) +set(TechDrawLIBS + Measure + Part + Spreadsheet + Import +) + if(BUILD_QT5) include_directories( ${Qt5XmlPatterns_INCLUDE_DIRS} + ${Qt5Concurrent_INCLUDE_DIRS} ) set(QtXmlPatternsLib ${Qt5XmlPatterns_LIBRARIES}) + list(APPEND TechDrawLIBS + ${Qt5Concurrent_LIBRARIES} + ) else(BUILD_QT5) include_directories( ${QT_QTXMLPATTERNS_INCLUDE_DIR} @@ -32,13 +44,6 @@ endif(BUILD_QT5) link_directories(${OCC_LIBRARY_DIR}) -set(TechDrawLIBS - Measure - Part - Spreadsheet - Import -) - generate_from_xml(DrawPagePy) generate_from_xml(DrawViewPy) generate_from_xml(DrawViewPartPy) @@ -258,7 +263,7 @@ ADD_CUSTOM_COMMAND(TARGET TechDraw COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/src/Mod/TechDraw/Patterns ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_DATADIR}/Mod/TechDraw/Patterns -) +) ADD_CUSTOM_COMMAND(TARGET TechDraw POST_BUILD @@ -272,7 +277,7 @@ ADD_CUSTOM_COMMAND(TARGET TechDraw COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/src/Mod/TechDraw/Symbols ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_DATADIR}/Mod/TechDraw/Symbols -) +) SET_BIN_DIR(TechDraw TechDraw /Mod/TechDraw) SET_PYTHON_PREFIX_SUFFIX(TechDraw) diff --git a/src/Mod/TechDraw/App/CenterLinePyImp.cpp b/src/Mod/TechDraw/App/CenterLinePyImp.cpp index 756bc0aedf..f7f20bfa7a 100644 --- a/src/Mod/TechDraw/App/CenterLinePyImp.cpp +++ b/src/Mod/TechDraw/App/CenterLinePyImp.cpp @@ -35,7 +35,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string CenterLinePy::representation(void) const +std::string CenterLinePy::representation() const { std::stringstream ss; ss << " at " << std::hex << this; @@ -110,7 +110,7 @@ PyObject* CenterLinePy::copy(PyObject *args) return cpy; } -Py::Object CenterLinePy::getFormat(void) const +Py::Object CenterLinePy::getFormat() const { TechDraw::CenterLine* cl = this->getCenterLinePtr(); @@ -160,20 +160,20 @@ void CenterLinePy::setFormat(Py::Object arg) } } -Py::String CenterLinePy::getTag(void) const +Py::String CenterLinePy::getTag() const { std::string tmp = boost::uuids::to_string(getCenterLinePtr()->getTag()); return Py::String(tmp); } -Py::Long CenterLinePy::getType(void) const +Py::Long CenterLinePy::getType() const { int tmp = getCenterLinePtr()->m_type; return Py::Long(tmp); } -Py::Long CenterLinePy::getMode(void) const +Py::Long CenterLinePy::getMode() const { int tmp = getCenterLinePtr()->m_mode; return Py::Long(tmp); @@ -192,7 +192,7 @@ void CenterLinePy::setMode(Py::Long arg) } } -Py::Float CenterLinePy::getHorizShift(void) const +Py::Float CenterLinePy::getHorizShift() const { double shift = getCenterLinePtr()->getHShift(); return Py::asObject(PyFloat_FromDouble(shift)); @@ -212,7 +212,7 @@ void CenterLinePy::setHorizShift(Py::Float arg) } } -Py::Float CenterLinePy::getVertShift(void) const +Py::Float CenterLinePy::getVertShift() const { double shift = getCenterLinePtr()->getVShift(); return Py::asObject(PyFloat_FromDouble(shift)); @@ -232,7 +232,7 @@ void CenterLinePy::setVertShift(Py::Float arg) } } -Py::Float CenterLinePy::getRotation(void) const +Py::Float CenterLinePy::getRotation() const { double rot = getCenterLinePtr()->getRotate(); return Py::asObject(PyFloat_FromDouble(rot)); @@ -251,7 +251,7 @@ void CenterLinePy::setRotation(Py::Float arg) } } -Py::Float CenterLinePy::getExtension(void) const +Py::Float CenterLinePy::getExtension() const { double rot = getCenterLinePtr()->getExtend(); return Py::asObject(PyFloat_FromDouble(rot)); @@ -270,7 +270,7 @@ void CenterLinePy::setExtension(Py::Float arg) } } -Py::Boolean CenterLinePy::getFlip(void) const +Py::Boolean CenterLinePy::getFlip() const { bool flip = getCenterLinePtr()->getFlip(); return Py::Boolean(flip); @@ -292,7 +292,7 @@ void CenterLinePy::setFlip(Py::Boolean arg) } } -Py::Object CenterLinePy::getEdges(void) const +Py::Object CenterLinePy::getEdges() const { // Base::Console().Message("CLP::getEdges()\n"); TechDraw::CenterLine* cl = this->getCenterLinePtr(); @@ -331,7 +331,7 @@ void CenterLinePy::setEdges(Py::Object arg) Base::Console().Error("CLPI::setEdges - input not a list!\n"); } } -Py::Object CenterLinePy::getFaces(void) const +Py::Object CenterLinePy::getFaces() const { // Base::Console().Message("CLP::getFaces()\n"); TechDraw::CenterLine* cl = this->getCenterLinePtr(); @@ -371,7 +371,7 @@ void CenterLinePy::setFaces(Py::Object arg) } } -Py::Object CenterLinePy::getPoints(void) const +Py::Object CenterLinePy::getPoints() const { // Base::Console().Message("CLP::getPoints()\n"); TechDraw::CenterLine* cl = this->getCenterLinePtr(); diff --git a/src/Mod/TechDraw/App/Cosmetic.cpp b/src/Mod/TechDraw/App/Cosmetic.cpp index 35b4cd8c73..696f01b02f 100644 --- a/src/Mod/TechDraw/App/Cosmetic.cpp +++ b/src/Mod/TechDraw/App/Cosmetic.cpp @@ -1,5 +1,6 @@ /*************************************************************************** * Copyright (c) 2019 WandererFan * + * Copyright (c) 2022 Benjamin Bræstrup Sayoc * * * * This file is part of the FreeCAD CAx development system. * * * @@ -73,18 +74,10 @@ using namespace std; #define COSMETICEDGE 1 #define CENTERLINE 2 -LineFormat::LineFormat() -{ - m_style = getDefEdgeStyle(); - m_weight = getDefEdgeWidth(); - m_color = getDefEdgeColor(); - m_visible = true; -} - LineFormat::LineFormat(int style, double weight, App::Color color, - bool visible ) : + bool visible) : m_style(style), m_weight(weight), m_color(color), @@ -98,7 +91,7 @@ void LineFormat::dump(const char* title) Base::Console().Message("LF::dump - %s \n",toString().c_str()); } -std::string LineFormat::toString(void) const +std::string LineFormat::toString() const { std::stringstream ss; ss << m_style << "," << @@ -111,12 +104,7 @@ std::string LineFormat::toString(void) const //static preference getters. double LineFormat::getDefEdgeWidth() { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - - double width = lg->getWeight("Graphic"); - delete lg; - return width; + return TechDraw::LineGroup::getDefaultWidth("Graphic"); } App::Color LineFormat::getDefEdgeColor() @@ -143,7 +131,7 @@ CosmeticVertex::CosmeticVertex() : TechDraw::Vertex() linkGeom = -1; color = Preferences::vertexColor(); size = Preferences::vertexScale() * - LineGroup::getDefaultWidth("Thick", Preferences::lineGroup()); + LineGroup::getDefaultWidth("Thick"); style = 1; visible = true; hlrVisible = true; @@ -172,7 +160,7 @@ CosmeticVertex::CosmeticVertex(Base::Vector3d loc) : TechDraw::Vertex(loc) linkGeom = -1; color = Preferences::vertexColor(); size = Preferences::vertexScale() * - LineGroup::getDefaultWidth("Thick", Preferences::lineGroup()); + LineGroup::getDefaultWidth("Thick"); style = 1; //TODO: implement styled vertexes visible = true; hlrVisible = true; @@ -192,7 +180,7 @@ void CosmeticVertex::moveRelative(Base::Vector3d movement) permaPoint += movement; } -std::string CosmeticVertex::toString(void) const +std::string CosmeticVertex::toString() const { std::stringstream ss; ss << permaPoint.x << "," << @@ -217,7 +205,7 @@ std::string CosmeticVertex::toString(void) const } // Persistence implementers -unsigned int CosmeticVertex::getMemSize (void) const +unsigned int CosmeticVertex::getMemSize () const { return 1; } @@ -269,19 +257,17 @@ void CosmeticVertex::Restore(Base::XMLReader &reader) Base::Vector3d CosmeticVertex::scaled(double factor) { - pnt = permaPoint * factor; - return pnt; -} + return permaPoint * factor; +} boost::uuids::uuid CosmeticVertex::getTag() const { return tag; } -std::string CosmeticVertex::getTagAsString(void) const +std::string CosmeticVertex::getTagAsString() const { - std::string tmp = boost::uuids::to_string(getTag()); - return tmp; + return boost::uuids::to_string(getTag()); } void CosmeticVertex::createNewTag() @@ -307,14 +293,13 @@ void CosmeticVertex::assignTag(const TechDraw::CosmeticVertex * cv) throw Base::TypeError("CosmeticVertex tag can not be assigned as types do not match."); } -CosmeticVertex* CosmeticVertex::copy(void) const +CosmeticVertex* CosmeticVertex::copy() const { // Base::Console().Message("CV::copy()\n"); - CosmeticVertex* newCV = new CosmeticVertex(this); - return newCV; + return new CosmeticVertex(this); } -CosmeticVertex* CosmeticVertex::clone(void) const +CosmeticVertex* CosmeticVertex::clone() const { // Base::Console().Message("CV::clone()\n"); CosmeticVertex* cpy = this->copy(); @@ -322,7 +307,7 @@ CosmeticVertex* CosmeticVertex::clone(void) const return cpy; } -PyObject* CosmeticVertex::getPyObject(void) +PyObject* CosmeticVertex::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -364,41 +349,22 @@ CosmeticEdge::CosmeticEdge(CosmeticEdge* ce) initialize(); } -CosmeticEdge::CosmeticEdge(Base::Vector3d pt1, Base::Vector3d pt2) +CosmeticEdge::CosmeticEdge(Base::Vector3d pt1, Base::Vector3d pt2) : +// 🠓 returns TopoDS_Edge + CosmeticEdge::CosmeticEdge(TopoDS_EdgeFromVectors(pt1, pt2)) { -// 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); - gp_Pnt gp2(p2.x,p2.y,p2.z); - TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); - m_geometry = TechDraw::BaseGeom::baseFactory(e); - permaStart = p1; - permaEnd = p2; - initialize(); } -CosmeticEdge::CosmeticEdge(TopoDS_Edge e) +// 🠓 returns TechDraw::BaseGeomPtr +CosmeticEdge::CosmeticEdge(TopoDS_Edge e) : CosmeticEdge(TechDraw::BaseGeom::baseFactory(e)) { -// Base::Console().Message("CE::CE(TopoDS_Edge)\n"); - m_geometry = TechDraw::BaseGeom::baseFactory(e); - //we assume input edge is already in Yinverted coordinates - permaStart = m_geometry->getStartPoint(); - permaEnd = m_geometry->getEndPoint(); - if ((m_geometry->geomType == TechDraw::GeomType::CIRCLE) || - (m_geometry->geomType == TechDraw::GeomType::ARCOFCIRCLE) ) { - TechDraw::CirclePtr circ = std::static_pointer_cast(m_geometry); - permaStart = circ->center; - permaEnd = circ->center; - permaRadius = circ->radius; - } - initialize(); } CosmeticEdge::CosmeticEdge(TechDraw::BaseGeomPtr g) { // Base::Console().Message("CE::CE(bg)\n"); m_geometry = g; + //we assume input edge is already in Yinverted coordinates permaStart = m_geometry->getStartPoint(); permaEnd = m_geometry->getEndPoint(); if ((g->geomType == TechDraw::GeomType::CIRCLE) || @@ -411,12 +377,12 @@ CosmeticEdge::CosmeticEdge(TechDraw::BaseGeomPtr g) initialize(); } -CosmeticEdge::~CosmeticEdge(void) +CosmeticEdge::~CosmeticEdge() { //shared pointer will delete m_geometry when ref count goes to zero. } -void CosmeticEdge::initialize(void) +void CosmeticEdge::initialize() { m_geometry->classOfEdge = ecHARD; m_geometry->hlrVisible = true; @@ -427,13 +393,23 @@ void CosmeticEdge::initialize(void) m_geometry->setCosmeticTag(getTagAsString()); } +TopoDS_Edge CosmeticEdge::TopoDS_EdgeFromVectors(Base::Vector3d pt1, Base::Vector3d pt2) +{ + // 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); + gp_Pnt gp2(p2.x,p2.y,p2.z); + TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); + return e; +} + TechDraw::BaseGeomPtr CosmeticEdge::scaledGeometry(double scale) { - TechDraw::BaseGeomPtr newGeom = nullptr; TopoDS_Edge e = m_geometry->occEdge; TopoDS_Shape s = TechDraw::scaleShape(e, scale); TopoDS_Edge newEdge = TopoDS::Edge(s); - newGeom = TechDraw::BaseGeom::baseFactory(newEdge); + TechDraw::BaseGeomPtr newGeom = TechDraw::BaseGeom::baseFactory(newEdge); newGeom->classOfEdge = ecHARD; newGeom->hlrVisible = true; newGeom->cosmetic = true; @@ -442,11 +418,11 @@ TechDraw::BaseGeomPtr CosmeticEdge::scaledGeometry(double scale) return newGeom; } -std::string CosmeticEdge::toString(void) const +std::string CosmeticEdge::toString() const { std::stringstream ss; ss << getTagAsString() << ", $$$, "; - if (m_geometry != nullptr) { + if (m_geometry) { ss << m_geometry->geomType << ",$$$," << m_geometry->toString() << @@ -463,7 +439,7 @@ void CosmeticEdge::dump(const char* title) } // Persistence implementers -unsigned int CosmeticEdge::getMemSize (void) const +unsigned int CosmeticEdge::getMemSize () const { return 1; } @@ -542,10 +518,9 @@ boost::uuids::uuid CosmeticEdge::getTag() const return tag; } -std::string CosmeticEdge::getTagAsString(void) const +std::string CosmeticEdge::getTagAsString() const { - std::string tmp = boost::uuids::to_string(getTag()); - return tmp; + return boost::uuids::to_string(getTag()); } void CosmeticEdge::createNewTag() @@ -571,7 +546,7 @@ void CosmeticEdge::assignTag(const TechDraw::CosmeticEdge * ce) throw Base::TypeError("CosmeticEdge tag can not be assigned as types do not match."); } -CosmeticEdge* CosmeticEdge::copy(void) const +CosmeticEdge* CosmeticEdge::copy() const { // Base::Console().Message("CE::copy()\n"); CosmeticEdge* newCE = new CosmeticEdge(); @@ -581,7 +556,7 @@ CosmeticEdge* CosmeticEdge::copy(void) const return newCE; } -CosmeticEdge* CosmeticEdge::clone(void) const +CosmeticEdge* CosmeticEdge::clone() const { // Base::Console().Message("CE::clone()\n"); CosmeticEdge* cpy = this->copy(); @@ -589,7 +564,7 @@ CosmeticEdge* CosmeticEdge::clone(void) const return cpy; } -PyObject* CosmeticEdge::getPyObject(void) +PyObject* CosmeticEdge::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -603,7 +578,7 @@ PyObject* CosmeticEdge::getPyObject(void) TYPESYSTEM_SOURCE(TechDraw::CenterLine,Base::Persistence) -CenterLine::CenterLine(void) +CenterLine::CenterLine() { m_start = Base::Vector3d(0.0, 0.0, 0.0); m_end = Base::Vector3d(0.0, 0.0, 0.0); @@ -637,54 +612,15 @@ CenterLine::CenterLine(TechDraw::CenterLine* cl) initialize(); } -CenterLine::CenterLine(TechDraw::BaseGeomPtr bg) -{ - m_start = bg->getStartPoint(); - m_end = bg->getEndPoint(); - m_mode = CLMODE::VERTICAL; - m_hShift = 0.0; - m_vShift = 0.0; - m_rotate = 0.0; - m_extendBy = 0.0; - m_type = CLTYPE::FACE; - m_flip2Line = false; - - m_geometry = bg; - - initialize(); -} - -CenterLine::CenterLine(Base::Vector3d pt1, Base::Vector3d pt2) -{ - m_start = pt1; - m_end = pt2; - m_mode = CLMODE::VERTICAL; - m_hShift = 0.0; - m_vShift = 0.0; - m_rotate = 0.0; - m_extendBy = 0.0; - m_type = CLTYPE::FACE; - m_flip2Line = false; - - Base::Vector3d p1 = DrawUtil::invertY(pt1); - Base::Vector3d p2 = DrawUtil::invertY(pt2); - gp_Pnt gp1(p1.x,p1.y,p1.z); - gp_Pnt gp2(p2.x,p2.y,p2.z); - TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); - m_geometry = TechDraw::BaseGeom::baseFactory(e); - - initialize(); -} - -CenterLine::CenterLine(Base::Vector3d pt1, Base::Vector3d pt2, +CenterLine::CenterLine(TechDraw::BaseGeomPtr bg, int m, double h, double v, double r, double x) { - m_start = pt1; - m_end = pt2; + m_start = bg->getStartPoint(); + m_end = bg->getEndPoint(); m_mode = m; m_hShift = h; m_vShift = v; @@ -693,17 +629,21 @@ CenterLine::CenterLine(Base::Vector3d pt1, Base::Vector3d pt2, m_type = CLTYPE::FACE; m_flip2Line = false; - //not sure this is right? - Base::Vector3d p1 = DrawUtil::invertY(pt1); - Base::Vector3d p2 = DrawUtil::invertY(pt2); - gp_Pnt gp1(p1.x,p1.y,p1.z); - gp_Pnt gp2(p2.x,p2.y,p2.z); - TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); - m_geometry = TechDraw::BaseGeom::baseFactory(e); + m_geometry = bg; initialize(); } +CenterLine::CenterLine(Base::Vector3d pt1, + Base::Vector3d pt2, + int m, + double h, + double v, + double r, + double x) : CenterLine(BaseGeomPtrFromVectors(pt1, pt2), m, h, v, r, x) +{ +} + CenterLine::~CenterLine() { } @@ -719,6 +659,18 @@ void CenterLine::initialize() m_geometry->setCosmeticTag(getTagAsString()); } +TechDraw::BaseGeomPtr CenterLine::BaseGeomPtrFromVectors(Base::Vector3d pt1, Base::Vector3d pt2) +{ + // 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); + gp_Pnt gp2(p2.x,p2.y,p2.z); + TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); + TechDraw::BaseGeomPtr bg = TechDraw::BaseGeom::baseFactory(e); + return bg; +} + CenterLine* CenterLine::CenterLineBuilder(DrawViewPart* partFeat, std::vector subNames, int mode, @@ -764,7 +716,7 @@ CenterLine* CenterLine::CenterLineBuilder(DrawViewPart* partFeat, return nullptr; } TechDraw::CenterLine* cl = new TechDraw::CenterLine(ends.first, ends.second); - if (cl != nullptr) { + if (cl) { cl->m_type = type; cl->m_mode = mode; cl->m_faces = faces; @@ -813,31 +765,30 @@ TechDraw::BaseGeomPtr CenterLine::scaledGeometry(TechDraw::DrawViewPart* partFea return nullptr; } - TechDraw::BaseGeomPtr newGeom = nullptr; Base::Vector3d p1 = ends.first; Base::Vector3d p2 = ends.second; - if (!p1.IsEqual(p2, 0.00001)) { - gp_Pnt gp1(p1.x,p1.y,p1.z); - gp_Pnt gp2(p2.x,p2.y,p2.z); - TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); - TopoDS_Shape s = TechDraw::scaleShape(e, scale); - TopoDS_Edge newEdge = TopoDS::Edge(s); - newGeom = TechDraw::BaseGeom::baseFactory(newEdge); - newGeom->classOfEdge = ecHARD; - newGeom->hlrVisible = true; - newGeom->cosmetic = true; - newGeom->source(CENTERLINE); - newGeom->setCosmeticTag(getTagAsString()); - } else { + if (p1.IsEqual(p2, 0.00001)) { Base::Console().Warning("Centerline endpoints are equal. Could not draw.\n"); //what to do here? //return current geom? return m_geometry; } + + gp_Pnt gp1(p1.x,p1.y,p1.z); + gp_Pnt gp2(p2.x,p2.y,p2.z); + TopoDS_Edge e = BRepBuilderAPI_MakeEdge(gp1, gp2); + TopoDS_Shape s = TechDraw::scaleShape(e, scale); + TopoDS_Edge newEdge = TopoDS::Edge(s); + TechDraw::BaseGeomPtr newGeom = TechDraw::BaseGeom::baseFactory(newEdge); + newGeom->classOfEdge = ecHARD; + newGeom->hlrVisible = true; + newGeom->cosmetic = true; + newGeom->source(CENTERLINE); + newGeom->setCosmeticTag(getTagAsString()); return newGeom; } -std::string CenterLine::toString(void) const +std::string CenterLine::toString() const { std::stringstream ss; ss << m_start.x << "," << @@ -873,6 +824,24 @@ void CenterLine::dump(const char* title) Base::Console().Message("CL::dump - %s \n",toString().c_str()); } +std::tuple CenterLine::rotatePointsAroundMid(Base::Vector3d p1, Base::Vector3d p2, Base::Vector3d mid, double rotate) { + //rotate p1, p2 about mid + double revRotate = -rotate; + double cosTheta = cos(revRotate * M_PI / 180.0); + double sinTheta = sin(revRotate * M_PI / 180.0); + Base::Vector3d toOrg = p1 - mid; + double xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; + double yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; + Base::Vector3d newp1 = Base::Vector3d(xRot, yRot, 0.0) + mid; + toOrg = p2 - mid; + xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; + yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; + Base::Vector3d newp2 = Base::Vector3d(xRot, yRot, 0.0) + mid; + + return std::make_tuple(newp1, newp2); +} + + //end points for centerline with no geometry reference std::pair CenterLine::calcEndPointsNoRef( Base::Vector3d start, @@ -883,7 +852,6 @@ std::pair CenterLine::calcEndPointsNoRef( double rotate) { // Base::Console().Message("CL::calcEndPointsNoRef()\n"); - std::pair result; Base::Vector3d p1 = start; Base::Vector3d p2 = end; Base::Vector3d mid = (p1 + p2) / 2.0; @@ -897,17 +865,7 @@ std::pair CenterLine::calcEndPointsNoRef( //rotate if (!DrawUtil::fpCompare(rotate, 0.0)) { //rotate p1, p2 about mid point - double revRotate = -rotate; - double cosTheta = cos(revRotate * M_PI / 180.0); - double sinTheta = sin(revRotate * M_PI / 180.0); - Base::Vector3d toOrg = p1 - mid; - double xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - double yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p1 = Base::Vector3d(xRot, yRot, 0.0) + mid; - toOrg = p2 - mid; - xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p2 = Base::Vector3d(xRot, yRot, 0.0) + mid; + tie(p1, p2) = rotatePointsAroundMid(p1, p2, mid, rotate); } //shift @@ -922,6 +880,7 @@ std::pair CenterLine::calcEndPointsNoRef( p2.y = p2.y + vss; } + std::pair result; result.first = p1 / scale; result.second = p2 / scale; return result; @@ -935,10 +894,9 @@ std::pair CenterLine::calcEndPoints(DrawViewPart double rotate) { // Base::Console().Message("CL::calcEndPoints()\n"); - std::pair result; if (faceNames.empty()) { Base::Console().Warning("CL::calcEndPoints - no faces!\n"); - return result; + return std::pair(); } Bnd_Box faceBox; @@ -1003,17 +961,7 @@ std::pair CenterLine::calcEndPoints(DrawViewPart //rotate if (!DrawUtil::fpCompare(rotate, 0.0)) { //rotate p1, p2 about mid point - double revRotate = -rotate; - double cosTheta = cos(revRotate * M_PI / 180.0); - double sinTheta = sin(revRotate * M_PI / 180.0); - Base::Vector3d toOrg = p1 - mid; - double xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - double yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p1 = Base::Vector3d(xRot, yRot, 0.0) + mid; - toOrg = p2 - mid; - xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p2 = Base::Vector3d(xRot, yRot, 0.0) + mid; + tie(p1, p2) = rotatePointsAroundMid(p1, p2, mid, rotate); } //shift @@ -1028,6 +976,7 @@ std::pair CenterLine::calcEndPoints(DrawViewPart p2.y = p2.y + vss; } + std::pair result; result.first = p1 / scale; result.second = p2 / scale; return result; @@ -1059,7 +1008,7 @@ std::pair CenterLine::calcEndPoints2Lines(DrawVi } int idx = TechDraw::DrawUtil::getIndexFromName(en); TechDraw::BaseGeomPtr bg = partFeat->getGeomByIndex(idx); - if (bg != nullptr) { + if (bg) { edges.push_back(bg); } else { Base::Console().Message("CL::calcEndPoints2Lines - no geom for index: %d\n", idx); @@ -1112,17 +1061,7 @@ std::pair CenterLine::calcEndPoints2Lines(DrawVi //rotate if (!DrawUtil::fpCompare(rotate, 0.0)) { //rotate p1, p2 about mid - double revRotate = -rotate; - double cosTheta = cos(revRotate * M_PI / 180.0); - double sinTheta = sin(revRotate * M_PI / 180.0); - Base::Vector3d toOrg = p1 - mid; - double xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - double yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p1 = Base::Vector3d(xRot, yRot, 0.0) + mid; - toOrg = p2 - mid; - xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p2 = Base::Vector3d(xRot, yRot, 0.0) + mid; + tie(p1, p2) = rotatePointsAroundMid(p1, p2, mid, rotate); } //shift @@ -1150,10 +1089,9 @@ std::pair CenterLine::calcEndPoints2Points(DrawV { // Base::Console().Message("CL::calc2Points()\n"); - std::pair result; if (vertNames.empty()) { Base::Console().Warning("CL::calcEndPoints2Points - no points!\n"); - return result; + return std::pair(); } double scale = partFeat->getScale(); @@ -1165,7 +1103,7 @@ std::pair CenterLine::calcEndPoints2Points(DrawV } int idx = TechDraw::DrawUtil::getIndexFromName(vn); TechDraw::VertexPtr v = partFeat->getProjVertexByIndex(idx); - if (v != nullptr) { + if (v) { points.push_back(v); } } @@ -1189,8 +1127,7 @@ std::pair CenterLine::calcEndPoints2Points(DrawV Base::Vector3d p2 = mid - clDir * (length / 2.0); if (flip) { //is flip relevant to 2 point??? - Base::Vector3d temp; - temp = p1; + Base::Vector3d temp = p1; p1 = p2; p2 = temp; } @@ -1213,17 +1150,7 @@ std::pair CenterLine::calcEndPoints2Points(DrawV //rotate if (!DrawUtil::fpCompare(rotate, 0.0)) { //rotate p1, p2 about mid - double revRotate = -rotate; - double cosTheta = cos(revRotate * M_PI / 180.0); - double sinTheta = sin(revRotate * M_PI / 180.0); - Base::Vector3d toOrg = p1 - mid; - double xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - double yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p1 = Base::Vector3d(xRot, yRot, 0.0) + mid; - toOrg = p2 - mid; - xRot = toOrg.x * cosTheta - toOrg.y * sinTheta; - yRot = toOrg.y * cosTheta + toOrg.x * sinTheta; - p2 = Base::Vector3d(xRot, yRot, 0.0) + mid; + tie(p1, p2) = rotatePointsAroundMid(p1, p2, mid, rotate); } //shift @@ -1238,13 +1165,14 @@ std::pair CenterLine::calcEndPoints2Points(DrawV p2.y = p2.y + vss; } + std::pair result; result.first = p1 / scale; result.second = p2 / scale; return result; } // Persistence implementers -unsigned int CenterLine::getMemSize (void) const +unsigned int CenterLine::getMemSize () const { return 1; } @@ -1321,23 +1249,22 @@ void CenterLine::Save(Base::Writer &writer) const writer.Stream() << writer.ind() << "" << endl; //stored geometry - if (m_geometry != nullptr) { - writer.Stream() << writer.ind() << "geomType <<"\"/>" << endl; - if (m_geometry->geomType == TechDraw::GeomType::GENERIC) { - GenericPtr gen = std::static_pointer_cast(m_geometry); - gen->Save(writer); - } else if (m_geometry->geomType == TechDraw::GeomType::CIRCLE) { - TechDraw::CirclePtr circ = std::static_pointer_cast(m_geometry); - circ->Save(writer); - } else if (m_geometry->geomType == TechDraw::GeomType::ARCOFCIRCLE) { - TechDraw::AOCPtr aoc = std::static_pointer_cast(m_geometry); - aoc->Save(writer); - } else { - Base::Console().Message("CL::Save - unimplemented geomType: %d\n", m_geometry->geomType); - } + if (!m_geometry) { + return Base::Console().Error("CL::Save - m_geometry is null\n"); + } + + writer.Stream() << writer.ind() << "geomType <<"\"/>" << endl; + if (m_geometry->geomType == TechDraw::GeomType::GENERIC) { + GenericPtr gen = std::static_pointer_cast(m_geometry); + gen->Save(writer); + } else if (m_geometry->geomType == TechDraw::GeomType::CIRCLE) { + TechDraw::CirclePtr circ = std::static_pointer_cast(m_geometry); + circ->Save(writer); + } else if (m_geometry->geomType == TechDraw::GeomType::ARCOFCIRCLE) { + TechDraw::AOCPtr aoc = std::static_pointer_cast(m_geometry); + aoc->Save(writer); } else { - Base::Console().Error("CL::Save - m_geometry is null\n"); - //TODO: create a placeholder for missing geom??? + Base::Console().Message("CL::Save - unimplemented geomType: %d\n", m_geometry->geomType); } } @@ -1441,7 +1368,7 @@ void CenterLine::Restore(Base::XMLReader &reader) } } -CenterLine* CenterLine::copy(void) const +CenterLine* CenterLine::copy() const { CenterLine* newCL = new CenterLine(); newCL->m_start = m_start; @@ -1471,10 +1398,9 @@ boost::uuids::uuid CenterLine::getTag() const return tag; } -std::string CenterLine::getTagAsString(void) const +std::string CenterLine::getTagAsString() const { - std::string tmp = boost::uuids::to_string(getTag()); - return tmp; + return boost::uuids::to_string(getTag()); } void CenterLine::createNewTag() @@ -1489,6 +1415,7 @@ void CenterLine::createNewTag() } static boost::uuids::basic_random_generator gen(&ran); + tag = gen(); } @@ -1500,7 +1427,7 @@ void CenterLine::assignTag(const TechDraw::CenterLine * ce) throw Base::TypeError("CenterLine tag can not be assigned as types do not match."); } -CenterLine *CenterLine::clone(void) const +CenterLine *CenterLine::clone() const { CenterLine* cpy = this->copy(); cpy->tag = this->tag; @@ -1508,7 +1435,7 @@ CenterLine *CenterLine::clone(void) const return cpy; } -PyObject* CenterLine::getPyObject(void) +PyObject* CenterLine::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -1524,12 +1451,12 @@ void CenterLine::setShifts(double h, double v) m_vShift = v; } -double CenterLine::getHShift(void) +double CenterLine::getHShift() { return m_hShift; } -double CenterLine::getVShift(void) +double CenterLine::getVShift() { return m_vShift; } @@ -1539,7 +1466,7 @@ void CenterLine::setRotate(double r) m_rotate = r; } -double CenterLine::getRotate(void) +double CenterLine::getRotate() { return m_rotate; } @@ -1549,7 +1476,7 @@ void CenterLine::setExtend(double e) m_extendBy = e; } -double CenterLine::getExtend(void) +double CenterLine::getExtend() { return m_extendBy; } @@ -1559,7 +1486,7 @@ void CenterLine::setFlip(bool f) m_flip2Line = f; } -bool CenterLine::getFlip(void) +bool CenterLine::getFlip() { return m_flip2Line; } @@ -1611,7 +1538,7 @@ void GeomFormat::dump(const char* title) const Base::Console().Message("GF::dump - %s \n",toString().c_str()); } -std::string GeomFormat::toString(void) const +std::string GeomFormat::toString() const { std::stringstream ss; ss << m_geomIndex << ",$$$," << @@ -1620,7 +1547,7 @@ std::string GeomFormat::toString(void) const } // Persistence implementer -unsigned int GeomFormat::getMemSize (void) const +unsigned int GeomFormat::getMemSize () const { return 1; } @@ -1661,10 +1588,9 @@ boost::uuids::uuid GeomFormat::getTag() const return tag; } -std::string GeomFormat::getTagAsString(void) const +std::string GeomFormat::getTagAsString() const { - std::string tmp = boost::uuids::to_string(getTag()); - return tmp; + return boost::uuids::to_string(getTag()); } void GeomFormat::createNewTag() @@ -1690,7 +1616,7 @@ void GeomFormat::assignTag(const TechDraw::GeomFormat * ce) throw Base::TypeError("GeomFormat tag can not be assigned as types do not match."); } -GeomFormat *GeomFormat::clone(void) const +GeomFormat *GeomFormat::clone() const { GeomFormat* cpy = this->copy(); cpy->tag = this->tag; @@ -1698,7 +1624,7 @@ GeomFormat *GeomFormat::clone(void) const return cpy; } -GeomFormat* GeomFormat::copy(void) const +GeomFormat* GeomFormat::copy() const { GeomFormat* newFmt = new GeomFormat(); newFmt->m_geomIndex = m_geomIndex; @@ -1709,7 +1635,7 @@ GeomFormat* GeomFormat::copy(void) const return newFmt; } -PyObject* GeomFormat::getPyObject(void) +PyObject* GeomFormat::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -1718,11 +1644,10 @@ PyObject* GeomFormat::getPyObject(void) return Py::new_reference_to(PythonObject); } -bool CosmeticVertex::restoreCosmetic(void) +bool CosmeticVertex::restoreCosmetic() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); - bool result = hGrp->GetBool("restoreCosmetic", true); - return result; + return hGrp->GetBool("restoreCosmetic", true); } diff --git a/src/Mod/TechDraw/App/Cosmetic.h b/src/Mod/TechDraw/App/Cosmetic.h index 934896e242..dc0a5d3ad1 100644 --- a/src/Mod/TechDraw/App/Cosmetic.h +++ b/src/Mod/TechDraw/App/Cosmetic.h @@ -23,6 +23,8 @@ #ifndef TECHDRAW_COSMETIC_H #define TECHDRAW_COSMETIC_H +#include + #include #include @@ -31,7 +33,6 @@ #include "Geometry.h" - class TopoDS_Edge; namespace TechDraw { @@ -42,11 +43,10 @@ class DrawViewPart; class TechDrawExport LineFormat { public: - LineFormat(); - LineFormat(int style, - double weight, - App::Color color, - bool visible ); + LineFormat(int style = getDefEdgeStyle(), + double weight = getDefEdgeWidth(), + App::Color color = getDefEdgeColor(), + bool visible = true); ~LineFormat() = default; int m_style; @@ -65,31 +65,31 @@ public: //********** Cosmetic Vertex *************************************************** class TechDrawExport CosmeticVertex: public Base::Persistence, public TechDraw::Vertex { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: CosmeticVertex(); CosmeticVertex(const CosmeticVertex* cv); CosmeticVertex(Base::Vector3d loc); - virtual ~CosmeticVertex() = default; + ~CosmeticVertex() override = default; void move(Base::Vector3d newPos); void moveRelative(Base::Vector3d movement); - std::string toString(void) const; - void dump(const char* title); + std::string toString() const; + void dump(const char* title) override; Base::Vector3d scaled(double factor); - static bool restoreCosmetic(void); + static bool restoreCosmetic(); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; - virtual PyObject *getPyObject(void); - CosmeticVertex* copy(void) const; - CosmeticVertex* clone(void) const; + PyObject *getPyObject() override; + CosmeticVertex* copy() const; + CosmeticVertex* clone() const; Base::Vector3d permaPoint; //permanent, unscaled value int linkGeom; //connection to corresponding "geom" Vertex (fragile - index based!) @@ -100,7 +100,7 @@ public: bool visible; //base class vertex also has visible property boost::uuids::uuid getTag() const; - virtual std::string getTagAsString(void) const; + std::string getTagAsString() const override; protected: //Uniqueness @@ -114,33 +114,38 @@ protected: }; + + + //********** CosmeticEdge ****************************************************** class TechDrawExport CosmeticEdge : public Base::Persistence, public TechDraw::BaseGeom { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: CosmeticEdge(); + CosmeticEdge(TechDraw::BaseGeomPtr* geometry); CosmeticEdge(CosmeticEdge* ce); CosmeticEdge(Base::Vector3d p1, Base::Vector3d p2); CosmeticEdge(TopoDS_Edge e); CosmeticEdge(TechDraw::BaseGeomPtr g); - virtual ~CosmeticEdge(); + ~CosmeticEdge() override; - void initialize(void); + void initialize(); + TopoDS_Edge TopoDS_EdgeFromVectors(Base::Vector3d pt1, Base::Vector3d pt2); TechDraw::BaseGeomPtr scaledGeometry(double scale); - virtual std::string toString(void) const; + std::string toString() const override; void dump(const char* title); // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; - virtual PyObject *getPyObject(void); - CosmeticEdge* copy(void) const; - CosmeticEdge* clone(void) const; + PyObject *getPyObject() override; + CosmeticEdge* copy() const; + CosmeticEdge* clone() const; Base::Vector3d permaStart; //persistent unscaled start/end points in View coords Base::Vector3d permaEnd; @@ -150,7 +155,7 @@ public: LineFormat m_format; boost::uuids::uuid getTag() const; - virtual std::string getTagAsString(void) const; + std::string getTagAsString() const override; protected: //Uniqueness @@ -166,44 +171,51 @@ protected: class TechDrawExport CenterLine: public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - CenterLine(); - CenterLine(CenterLine* cl); - //set m_faces after using next 3 ctors - CenterLine(TechDraw::BaseGeomPtr bg); - CenterLine(Base::Vector3d p1, Base::Vector3d p2); - CenterLine(Base::Vector3d p1, Base::Vector3d p2, - int m, - double h, - double v, - double r, - double x); - virtual ~CenterLine(); - - enum CLMODE { + enum CLMODE + { VERTICAL, HORIZONTAL, ALIGNED }; - - enum CLTYPE { + enum CLTYPE + { FACE, EDGE, VERTEX }; + CenterLine(); + CenterLine(CenterLine* cl); + //set m_faces after using next 3 ctors + CenterLine(TechDraw::BaseGeomPtr bg, + int m = CLMODE::VERTICAL, + double h = 0.0, + double v = 0.0, + double r = 0.0, + double x = 0.0); + CenterLine(Base::Vector3d p1, Base::Vector3d p2, + int m = CLMODE::VERTICAL, + double h = 0.0, + double v = 0.0, + double r = 0.0, + double x = 0.0); + ~CenterLine() override; + + TechDraw::BaseGeomPtr BaseGeomPtrFromVectors(Base::Vector3d pt1, Base::Vector3d pt2); + // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; - virtual PyObject *getPyObject(void); - CenterLine* copy(void) const; - CenterLine* clone(void) const; + PyObject *getPyObject() override; + CenterLine* copy() const; + CenterLine* clone() const; - std::string toString(void) const; + std::string toString() const; static CenterLine* CenterLineBuilder(TechDraw::DrawViewPart* partFeat, std::vector subs, @@ -211,6 +223,11 @@ public: bool flip = false); TechDraw::BaseGeomPtr scaledGeometry(TechDraw::DrawViewPart* partFeat); + static std::tuple rotatePointsAroundMid( + Base::Vector3d p1, + Base::Vector3d p2, + Base::Vector3d mid, + double rotate); static std::pair calcEndPointsNoRef( Base::Vector3d start, Base::Vector3d end, @@ -238,14 +255,14 @@ public: double rotate, bool flip); void dump(const char* title); void setShifts(double h, double v); - double getHShift(void); - double getVShift(void); + double getHShift(); + double getVShift(); void setRotate(double r); - double getRotate(void); + double getRotate(); void setExtend(double e); - double getExtend(void); + double getExtend(); void setFlip(bool f); - bool getFlip(void); + bool getFlip(); Base::Vector3d m_start; Base::Vector3d m_end; @@ -267,7 +284,7 @@ public: //Uniqueness boost::uuids::uuid getTag() const; - virtual std::string getTagAsString(void) const; + virtual std::string getTagAsString() const; protected: void initialize(); @@ -286,25 +303,25 @@ protected: // format specifier for geometric edges (Edge5) class TechDrawExport GeomFormat: public Base::Persistence { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: GeomFormat(); - GeomFormat(TechDraw::GeomFormat* gf); + explicit GeomFormat(TechDraw::GeomFormat* gf); GeomFormat(int idx, LineFormat fmt); - ~GeomFormat(); + ~GeomFormat() override; // Persistence implementer --------------------- - virtual unsigned int getMemSize(void) const; - virtual void Save(Base::Writer &/*writer*/) const; - virtual void Restore(Base::XMLReader &/*reader*/); + unsigned int getMemSize() const override; + void Save(Base::Writer &/*writer*/) const override; + void Restore(Base::XMLReader &/*reader*/) override; - virtual PyObject *getPyObject(void); - GeomFormat* copy(void) const; - GeomFormat* clone(void) const; + PyObject *getPyObject() override; + GeomFormat* copy() const; + GeomFormat* clone() const; - std::string toString(void) const; + std::string toString() const; void dump(const char* title) const; //std::string linkTag; @@ -313,7 +330,7 @@ public: //Uniqueness boost::uuids::uuid getTag() const; - virtual std::string getTagAsString(void) const; + virtual std::string getTagAsString() const; protected: void createNewTag(); diff --git a/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp b/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp index 30a9eb987d..8890525326 100644 --- a/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp +++ b/src/Mod/TechDraw/App/CosmeticEdgePyImp.cpp @@ -48,7 +48,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string CosmeticEdgePy::representation(void) const +std::string CosmeticEdgePy::representation() const { std::stringstream ss; ss << " at " << std::hex << this; @@ -157,7 +157,7 @@ void CosmeticEdgePy::setFormat(Py::Object arg) } } -Py::Object CosmeticEdgePy::getFormat(void) const +Py::Object CosmeticEdgePy::getFormat() const { TechDraw::CosmeticEdge* ce = this->getCosmeticEdgePtr(); @@ -176,7 +176,7 @@ Py::Object CosmeticEdgePy::getFormat(void) const return Py::asObject(result); } -Py::String CosmeticEdgePy::getTag(void) const +Py::String CosmeticEdgePy::getTag() const { std::string tmp = boost::uuids::to_string(getCosmeticEdgePtr()->getTag()); return Py::String(tmp); @@ -211,7 +211,7 @@ Py::String CosmeticEdgePy::getTag(void) const // } //} -Py::Object CosmeticEdgePy::getStart(void) const +Py::Object CosmeticEdgePy::getStart() const { Base::Vector3d point = getCosmeticEdgePtr()->permaStart; point = DrawUtil::invertY(point); @@ -245,7 +245,7 @@ void CosmeticEdgePy::setStart(Py::Object arg) // delete oldGeom; } -Py::Object CosmeticEdgePy::getEnd(void) const +Py::Object CosmeticEdgePy::getEnd() const { Base::Vector3d point = getCosmeticEdgePtr()->permaEnd; point = DrawUtil::invertY(point); @@ -279,7 +279,7 @@ void CosmeticEdgePy::setEnd(Py::Object arg) // delete oldGeom; } -Py::Object CosmeticEdgePy::getRadius(void) const +Py::Object CosmeticEdgePy::getRadius() const { TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType; if ( (gt != TechDraw::GeomType::CIRCLE) && @@ -322,7 +322,7 @@ void CosmeticEdgePy::setRadius(Py::Object arg) // delete oldGeom; } -Py::Object CosmeticEdgePy::getCenter(void) const +Py::Object CosmeticEdgePy::getCenter() const { TechDraw::GeomType gt = getCosmeticEdgePtr()->m_geometry->geomType; if ( (gt != TechDraw::GeomType::CIRCLE) && @@ -363,7 +363,7 @@ void CosmeticEdgePy::setCenter(Py::Object arg) pNew = DrawUtil::invertY(pNew); auto oldGeom = getCosmeticEdgePtr()->m_geometry; TechDraw::CirclePtr oldCircle = std::dynamic_pointer_cast (oldGeom); - if (oldCircle == nullptr) { + if (!oldCircle) { throw Py::TypeError("Edge geometry is not a circle"); } diff --git a/src/Mod/TechDraw/App/CosmeticExtension.cpp b/src/Mod/TechDraw/App/CosmeticExtension.cpp index bfb89260b0..0a4e98e1d1 100644 --- a/src/Mod/TechDraw/App/CosmeticExtension.cpp +++ b/src/Mod/TechDraw/App/CosmeticExtension.cpp @@ -111,17 +111,14 @@ TechDraw::CosmeticVertex* CosmeticExtension::getCosmeticVertexBySelection(std::s CosmeticVertex* result = nullptr; App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); - if (dvp == nullptr) { + if (!dvp) return result; - } int idx = DrawUtil::getIndexFromName(name); TechDraw::VertexPtr v = dvp->getProjVertexByIndex(idx); - if (v == nullptr) { + if (!v) return result; - } - if (!v->cosmeticTag.empty()) { + if (!v->cosmeticTag.empty()) result = getCosmeticVertex(v->cosmeticTag); - } return result; } @@ -155,14 +152,6 @@ void CosmeticExtension::removeCosmeticVertex(std::vector delTags) } } -bool CosmeticExtension::replaceCosmeticVertex(CosmeticVertex* newCV) -{ - (void) newCV; - Base::Console().Message("CX::replaceCosmeticVertex() - deprecated. do not use.\n"); - bool result = false; - return result; -} - //********** Cosmetic Edge ***************************************************** //returns unique CE id @@ -219,18 +208,15 @@ TechDraw::CosmeticEdge* CosmeticExtension::getCosmeticEdgeBySelection(std::strin CosmeticEdge* result = nullptr; App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); - if (dvp == nullptr) { + if (!dvp) return result; - } int idx = DrawUtil::getIndexFromName(name); TechDraw::BaseGeomPtr base = dvp->getGeomByIndex(idx); - if (base == nullptr) { + if (!base) return result; - } - if (!base->getCosmeticTag().empty()) { + if (!base->getCosmeticTag().empty()) result = getCosmeticEdge(base->getCosmeticTag()); - } return result; } @@ -264,15 +250,6 @@ void CosmeticExtension::removeCosmeticEdge(std::vector delTags) } } - -bool CosmeticExtension::replaceCosmeticEdge(CosmeticEdge* newCE) -{ - (void) newCE; - Base::Console().Message("CX::replaceCosmeticEdge() - deprecated. do not use.\n"); - bool result = false; - return result; -} - //********** Center Line ******************************************************* //returns unique CL id @@ -338,17 +315,14 @@ TechDraw::CenterLine* CosmeticExtension::getCenterLineBySelection(std::string na CenterLine* result = nullptr; App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); - if (dvp == nullptr) { + if (!dvp) return result; - } int idx = DrawUtil::getIndexFromName(name); TechDraw::BaseGeomPtr base = dvp->getGeomByIndex(idx); - if (base == nullptr) { + if (!base) return result; - } - if (!base->getCosmeticTag().empty()) { + if (!base->getCosmeticTag().empty()) result = getCenterLine(base->getCosmeticTag()); - } return result; } @@ -382,14 +356,6 @@ void CosmeticExtension::removeCenterLine(std::vector delTags) } } -bool CosmeticExtension::replaceCenterLine(CenterLine* newCL) -{ - (void) newCL; - Base::Console().Message("CX::replaceCenterLine() - deprecated. do not use.\n"); - bool result = false; - return result; -} - //********** Geometry Formats ************************************************** //returns unique GF id @@ -430,9 +396,8 @@ TechDraw::GeomFormat* CosmeticExtension::getGeomFormatBySelection(std::string na GeomFormat* result = nullptr; App::DocumentObject* extObj = const_cast (getExtendedObject()); TechDraw::DrawViewPart* dvp = dynamic_cast(extObj); - if (dvp == nullptr) { + if (!dvp) return result; - } int idx = DrawUtil::getIndexFromName(name); const std::vector formats = GeomFormats.getValues(); for (auto& gf: formats) { @@ -454,14 +419,6 @@ TechDraw::GeomFormat* CosmeticExtension::getGeomFormatBySelection(int i) const return getGeomFormatBySelection(eName); } -bool CosmeticExtension::replaceGeomFormat(GeomFormat* newGF) -{ - (void) newGF; - Base::Console().Message("CX::replaceGeomFormat() - deprecated. do not use.\n"); - bool result = false; - return result; -} - void CosmeticExtension::removeGeomFormat(std::string delTag) { // Base::Console().Message("DVP::removeCE(%s)\n", delTag.c_str()); diff --git a/src/Mod/TechDraw/App/CosmeticExtension.h b/src/Mod/TechDraw/App/CosmeticExtension.h index 00a643c346..d269e8a884 100644 --- a/src/Mod/TechDraw/App/CosmeticExtension.h +++ b/src/Mod/TechDraw/App/CosmeticExtension.h @@ -23,6 +23,8 @@ #ifndef TECHDRAW_COSMETICEXTENSION_H #define TECHDRAW_COSMETICEXTENSION_H +#include + #include #include #include @@ -40,11 +42,11 @@ class DrawViewPart; class GeometryObject; class TechDrawExport CosmeticExtension : public App::DocumentObjectExtension { - EXTENSION_PROPERTY_HEADER(TechDraw::CosmeticObject); + EXTENSION_PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::CosmeticObject); public: CosmeticExtension(); - virtual ~CosmeticExtension(); + ~CosmeticExtension() override; TechDraw::PropertyCosmeticVertexList CosmeticVertexes; TechDraw::PropertyCosmeticEdgeList CosmeticEdges; @@ -55,7 +57,6 @@ public: virtual CosmeticVertex* getCosmeticVertexBySelection(std::string name) const; virtual CosmeticVertex* getCosmeticVertexBySelection(int i) const; virtual CosmeticVertex* getCosmeticVertex(std::string id) const; - virtual bool replaceCosmeticVertex(CosmeticVertex* newVertex); virtual void removeCosmeticVertex(std::string tag); virtual void removeCosmeticVertex(std::vector delTags); @@ -64,7 +65,6 @@ public: virtual CosmeticEdge* getCosmeticEdgeBySelection(std::string name) const; virtual CosmeticEdge* getCosmeticEdgeBySelection(int i) const; virtual CosmeticEdge* getCosmeticEdge(std::string id) const; - virtual bool replaceCosmeticEdge(CosmeticEdge* newEdge); virtual void removeCosmeticEdge(std::string tag); virtual void removeCosmeticEdge(std::vector delTags); @@ -74,7 +74,6 @@ public: virtual CenterLine* getCenterLineBySelection(std::string name) const; virtual CenterLine* getCenterLineBySelection(int i) const; virtual CenterLine* getCenterLine(std::string tag) const; - virtual bool replaceCenterLine(CenterLine* newLine); virtual void removeCenterLine(std::string tag); virtual void removeCenterLine(std::vector delTags); @@ -82,11 +81,10 @@ public: virtual GeomFormat* getGeomFormatBySelection(std::string name) const; virtual GeomFormat* getGeomFormatBySelection(int i) const; virtual GeomFormat* getGeomFormat(std::string id) const; - virtual bool replaceGeomFormat(TechDraw::GeomFormat* gf); virtual void removeGeomFormat(std::string tag); - PyObject* getExtensionPyObject(void); + PyObject* getExtensionPyObject() override; protected: /* virtual void extHandleChangedPropertyName(Base::XMLReader &reader, */ diff --git a/src/Mod/TechDraw/App/CosmeticExtensionPyImp.cpp b/src/Mod/TechDraw/App/CosmeticExtensionPyImp.cpp index de93599540..615662150d 100644 --- a/src/Mod/TechDraw/App/CosmeticExtensionPyImp.cpp +++ b/src/Mod/TechDraw/App/CosmeticExtensionPyImp.cpp @@ -36,7 +36,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string CosmeticExtensionPy::representation(void) const +std::string CosmeticExtensionPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp b/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp index c9cfd654e9..56864a1a3d 100644 --- a/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp +++ b/src/Mod/TechDraw/App/CosmeticVertexPyImp.cpp @@ -42,7 +42,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string CosmeticVertexPy::representation(void) const +std::string CosmeticVertexPy::representation() const { return ""; } @@ -117,13 +117,13 @@ PyObject* CosmeticVertexPy::copy(PyObject *args) return cpy; } -Py::String CosmeticVertexPy::getTag(void) const +Py::String CosmeticVertexPy::getTag() const { std::string tmp = boost::uuids::to_string(getCosmeticVertexPtr()->getTag()); return Py::String(tmp); } -Py::Object CosmeticVertexPy::getPoint(void) const +Py::Object CosmeticVertexPy::getPoint() const { Base::Vector3d point = getCosmeticVertexPtr()->permaPoint; point = DrawUtil::invertY(point); @@ -150,7 +150,7 @@ void CosmeticVertexPy::setPoint(Py::Object arg) } } -Py::Boolean CosmeticVertexPy::getShow(void) const +Py::Boolean CosmeticVertexPy::getShow() const { bool show = getCosmeticVertexPtr()->visible; return Py::Boolean(show); @@ -168,7 +168,7 @@ void CosmeticVertexPy::setShow(Py::Boolean arg) } } -Py::Object CosmeticVertexPy::getColor(void) const +Py::Object CosmeticVertexPy::getColor() const { App::Color color = getCosmeticVertexPtr()->color; PyObject* pyColor = DrawUtil::colorToPyTuple(color); @@ -192,7 +192,7 @@ void CosmeticVertexPy::setColor(Py::Object arg) } } -Py::Object CosmeticVertexPy::getSize(void) const +Py::Object CosmeticVertexPy::getSize() const { CosmeticVertex* cv = getCosmeticVertexPtr(); double size = cv->size; @@ -215,7 +215,7 @@ void CosmeticVertexPy::setSize(Py::Object arg) cv->size = size; } -Py::Object CosmeticVertexPy::getStyle(void) const +Py::Object CosmeticVertexPy::getStyle() const { CosmeticVertex* cv = getCosmeticVertexPtr(); double style = cv->style; diff --git a/src/Mod/TechDraw/App/DrawDimHelper.cpp b/src/Mod/TechDraw/App/DrawDimHelper.cpp index 2245699552..0a1ff0e248 100644 --- a/src/Mod/TechDraw/App/DrawDimHelper.cpp +++ b/src/Mod/TechDraw/App/DrawDimHelper.cpp @@ -95,7 +95,7 @@ void DrawDimHelper::makeExtentDim(DrawViewPart* dvp, { // Base::Console().Message("DDH::makeExtentDim() - dvp: %s edgeNames: %d\n", // dvp->Label.getValue(), edgeNames.size()); - if (dvp == nullptr) { + if (!dvp) { // Base::Console().Message("DDH::makeExtentDim - dvp: %X\n", dvp); return; } @@ -134,12 +134,10 @@ void DrawDimHelper::makeExtentDim(DrawViewPart* dvp, int idx1 = DrawUtil::getIndexFromName(subElements[1]); v0 = dvp->getProjVertexByIndex(idx0); v1 = dvp->getProjVertexByIndex(idx1); - if ( (v0 != nullptr) && - (!v0->cosmeticTag.empty()) ) { + if (v0 && !v0->cosmeticTag.empty()) { tag0 = v0->cosmeticTag; } - if ( (v1 != nullptr) && - (!v1->cosmeticTag.empty()) ) { + if (v1 && !v1->cosmeticTag.empty()) { tag1 = v1->cosmeticTag; } cvTags.push_back(tag0); @@ -175,7 +173,7 @@ std::pair DrawDimHelper::minMax(DrawViewPart* dv if (!n.empty() && (geomType == "Edge")) { int i = DrawUtil::getIndexFromName(n); BaseGeomPtr bg = dvp->getGeomByIndex(i); - if (bg != nullptr) { + if (bg) { bgList.push_back(bg); } } diff --git a/src/Mod/TechDraw/App/DrawDimHelper.h b/src/Mod/TechDraw/App/DrawDimHelper.h index 28802f97f9..438e009032 100644 --- a/src/Mod/TechDraw/App/DrawDimHelper.h +++ b/src/Mod/TechDraw/App/DrawDimHelper.h @@ -23,6 +23,8 @@ #ifndef _DrawDimHelper_h_ #define _DrawDimHelper_h_ +#include + #include #include diff --git a/src/Mod/TechDraw/App/DrawGeomHatch.cpp b/src/Mod/TechDraw/App/DrawGeomHatch.cpp index 6bea4b036d..0b7d234695 100644 --- a/src/Mod/TechDraw/App/DrawGeomHatch.cpp +++ b/src/Mod/TechDraw/App/DrawGeomHatch.cpp @@ -91,7 +91,7 @@ App::PropertyFloatConstraint::Constraints DrawGeomHatch::scaleRange = {Precision PROPERTY_SOURCE(TechDraw::DrawGeomHatch, App::DocumentObject) -DrawGeomHatch::DrawGeomHatch(void) +DrawGeomHatch::DrawGeomHatch() { static const char *vgroup = "GeomHatch"; @@ -123,15 +123,13 @@ void DrawGeomHatch::onChanged(const App::Property* prop) DrawGeomHatch::execute(); } App::Document* doc = getDocument(); - if ((prop == &FilePattern) && - (doc != nullptr) ) { + if ((prop == &FilePattern) && doc) { if (!FilePattern.isEmpty()) { replacePatIncluded(FilePattern.getValue()); DrawGeomHatch::execute(); //remake the line sets } } - if ((prop == &NamePattern) && - (doc != nullptr)) { + if ((prop == &NamePattern) && doc) { DrawGeomHatch::execute(); //remake the line sets } } else { @@ -161,35 +159,49 @@ short DrawGeomHatch::mustExecute() const } -App::DocumentObjectExecReturn *DrawGeomHatch::execute(void) +App::DocumentObjectExecReturn *DrawGeomHatch::execute() { // Base::Console().Message("DGH::execute()\n"); makeLineSets(); DrawViewPart* parent = getSourceView(); - if (parent != nullptr) { + if (parent) { parent->requestPaint(); } return App::DocumentObject::StdReturn; } -void DrawGeomHatch::makeLineSets(void) +void DrawGeomHatch::makeLineSets() { // Base::Console().Message("DGH::makeLineSets()\n"); if ((!PatIncluded.isEmpty()) && (!NamePattern.isEmpty())) { - std::vector specs = getDecodedSpecsFromFile(); m_lineSets.clear(); - for (auto& hl: specs) { - //hl.dump("hl from file"); - LineSet ls; - ls.setPATLineSpec(hl); - m_lineSets.push_back(ls); - } + m_lineSets = makeLineSets(PatIncluded.getValue(), + NamePattern.getValue()); } } -DrawViewPart* DrawGeomHatch::getSourceView(void) const +/*static*/ +std::vector DrawGeomHatch::makeLineSets(std::string fileSpec, std::string myPattern) +{ + std::vector lineSets; + if (!fileSpec.empty() && + !myPattern.empty()) { + std::vector specs = + DrawGeomHatch::getDecodedSpecsFromFile(fileSpec, + myPattern); + for (auto& hl: specs) { + //hl.dump("hl from section"); + LineSet ls; + ls.setPATLineSpec(hl); + lineSets.push_back(ls); + } + } + return lineSets; +} + +DrawViewPart* DrawGeomHatch::getSourceView() const { App::DocumentObject* obj = Source.getValue(); DrawViewPart* result = dynamic_cast(obj); @@ -334,7 +346,7 @@ std::vector DrawGeomHatch::getTrimmedLines(DrawViewPart* source, int i = 0; for (auto& e: resultEdges) { TechDraw::BaseGeomPtr base = BaseGeom::baseFactory(e); - if (base == nullptr) { + if (!base) { Base::Console().Log("FAIL - DGH::getTrimmedLines - baseFactory failed for edge: %d\n",i); throw Base::ValueError("DGH::getTrimmedLines - baseFactory failed"); } @@ -483,7 +495,7 @@ std::vector DrawGeomHatch::getFaceOverlay(int fdx) int i = 0; for (auto& e: candidates) { TechDraw::BaseGeomPtr base = BaseGeom::baseFactory(e); - if (base == nullptr) { + if (!base) { Base::Console().Log("FAIL - DGH::getFaceOverlay - baseFactory failed for edge: %d\n",i); throw Base::ValueError("DGH::getFaceOverlay - baseFactory failed"); } @@ -538,7 +550,7 @@ TopoDS_Face DrawGeomHatch::extractFace(DrawViewPart* source, int iface ) return result; } -PyObject *DrawGeomHatch::getPyObject(void) +PyObject *DrawGeomHatch::getPyObject() { if (PythonObject.is(Py::_None())) { PythonObject = Py::Object(new DrawGeomHatchPy(this),true); @@ -582,7 +594,7 @@ void DrawGeomHatch::setupObject() App::DocumentObject::setupObject(); } -void DrawGeomHatch::setupPatIncluded(void) +void DrawGeomHatch::setupPatIncluded() { // Base::Console().Message("DGH::setupPatIncluded()\n"); App::Document* doc = getDocument(); @@ -603,18 +615,18 @@ void DrawGeomHatch::setupPatIncluded(void) } } -void DrawGeomHatch::unsetupObject(void) +void DrawGeomHatch::unsetupObject() { // Base::Console().Message("DGH::unsetupObject() - status: %lu removing: %d \n", getStatus(), isRemoving()); App::DocumentObject* source = Source.getValue(); DrawView* dv = dynamic_cast(source); - if (dv != nullptr) { + if (dv) { dv->requestPaint(); } App::DocumentObject::unsetupObject(); } -std::string DrawGeomHatch::prefGeomHatchFile(void) +std::string DrawGeomHatch::prefGeomHatchFile() { return Preferences::patFile(); } @@ -647,7 +659,7 @@ App::Color DrawGeomHatch::prefGeomHatchColor() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawGeomHatchPython, TechDraw::DrawGeomHatch) -template<> const char* TechDraw::DrawGeomHatchPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawGeomHatchPython::getViewProviderName() const { return "TechDrawGui::ViewProviderGeomHatch"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawGeomHatch.h b/src/Mod/TechDraw/App/DrawGeomHatch.h index bb740cafba..d29a01173d 100644 --- a/src/Mod/TechDraw/App/DrawGeomHatch.h +++ b/src/Mod/TechDraw/App/DrawGeomHatch.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_DrawGeomHatch_h_ #define _TechDraw_DrawGeomHatch_h_ +#include + #include #include #include @@ -91,7 +93,7 @@ public: static std::string prefGeomHatchFile(void); static std::string prefGeomHatchName(); static App::Color prefGeomHatchColor(); - + static std::vector makeLineSets(std::string fileSpec, std::string myPattern); protected: virtual void onDocumentRestored() override; diff --git a/src/Mod/TechDraw/App/DrawGeomHatchPyImp.cpp b/src/Mod/TechDraw/App/DrawGeomHatchPyImp.cpp index fc2b268dc0..95f4580d28 100644 --- a/src/Mod/TechDraw/App/DrawGeomHatchPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawGeomHatchPyImp.cpp @@ -29,7 +29,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawGeomHatchPy::representation(void) const +std::string DrawGeomHatchPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawHatch.cpp b/src/Mod/TechDraw/App/DrawHatch.cpp index 4e68af8700..3dd6995aca 100644 --- a/src/Mod/TechDraw/App/DrawHatch.cpp +++ b/src/Mod/TechDraw/App/DrawHatch.cpp @@ -80,8 +80,7 @@ void DrawHatch::onChanged(const App::Property* prop) DrawHatch::execute(); } App::Document* doc = getDocument(); - if ((prop == &HatchPattern) && - (doc != nullptr) ) { + if ((prop == &HatchPattern) && doc) { if (!HatchPattern.isEmpty()) { replaceFileIncluded(HatchPattern.getValue()); } @@ -267,7 +266,7 @@ void DrawHatch::unsetupObject(void) // Base::Console().Message("DH::unsetupObject() - status: %lu removing: %d \n", getStatus(), isRemoving()); App::DocumentObject* source = Source.getValue(); DrawView* dv = dynamic_cast(source); - if (dv != nullptr) { + if (dv) { dv->requestPaint(); } App::DocumentObject::unsetupObject(); diff --git a/src/Mod/TechDraw/App/DrawHatch.h b/src/Mod/TechDraw/App/DrawHatch.h index c17da8eec6..1afbbd3afd 100644 --- a/src/Mod/TechDraw/App/DrawHatch.h +++ b/src/Mod/TechDraw/App/DrawHatch.h @@ -44,40 +44,40 @@ class TechDrawExport DrawHatch : public App::DocumentObject public: DrawHatch(); - virtual ~DrawHatch(); + ~DrawHatch() override; App::PropertyLinkSub Source; // the dvp & face this hatch belongs to App::PropertyFile HatchPattern; App::PropertyFileIncluded SvgIncluded; - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderHatch"; } - virtual void unsetupObject(void) override; + void unsetupObject() override; //return PyObject as DrawHatchPy - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - DrawViewPart* getSourceView(void) const; + DrawViewPart* getSourceView() const; bool affectsFace(int i); bool removeSub(std::string toRemove); bool removeSub(int i); - bool empty(void); + bool empty(); static bool faceIsHatched(int i,std::vector hatchObjs); - static std::string prefSvgHatch(void); - static App::Color prefSvgHatchColor(void); + static std::string prefSvgHatch(); + static App::Color prefSvgHatchColor(); - bool isSvgHatch(void) const; - bool isBitmapHatch(void) const; + bool isSvgHatch() const; + bool isBitmapHatch() const; protected: void onChanged(const App::Property* prop) override; - virtual void onDocumentRestored() override; - virtual void setupObject() override; - void setupFileIncluded(void); + void onDocumentRestored() override; + void setupObject() override; + void setupFileIncluded(); void replaceFileIncluded(std::string newSvgFile); private: diff --git a/src/Mod/TechDraw/App/DrawHatchPyImp.cpp b/src/Mod/TechDraw/App/DrawHatchPyImp.cpp index 5f0d4dca95..6b18bffcef 100644 --- a/src/Mod/TechDraw/App/DrawHatchPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawHatchPyImp.cpp @@ -31,7 +31,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawHatchPy::representation(void) const +std::string DrawHatchPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawLeaderLine.cpp b/src/Mod/TechDraw/App/DrawLeaderLine.cpp index bd37419a1d..4cc2f7b0d6 100644 --- a/src/Mod/TechDraw/App/DrawLeaderLine.cpp +++ b/src/Mod/TechDraw/App/DrawLeaderLine.cpp @@ -68,7 +68,7 @@ PROPERTY_SOURCE(TechDraw::DrawLeaderLine, TechDraw::DrawView) // "NONE" // NULL}; -DrawLeaderLine::DrawLeaderLine(void) +DrawLeaderLine::DrawLeaderLine() { static const char *group = "Leader"; @@ -126,7 +126,7 @@ short DrawLeaderLine::mustExecute() const } const App::DocumentObject* docObj = getBaseObject(); - if (docObj != nullptr) { + if (docObj) { result = docObj->isTouched(); //object property points to is touched } if (result) { @@ -136,44 +136,45 @@ short DrawLeaderLine::mustExecute() const return DrawView::mustExecute(); } -App::DocumentObjectExecReturn *DrawLeaderLine::execute(void) +App::DocumentObjectExecReturn *DrawLeaderLine::execute() { // Base::Console().Message("DLL::execute()\n"); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } - adjustLastSegment(); + adjustLastSegment(); + overrideKeepUpdated(false); return DrawView::execute(); } -DrawView* DrawLeaderLine::getBaseView(void) const +DrawView* DrawLeaderLine::getBaseView() const { DrawView* result = nullptr; App::DocumentObject* baseObj = LeaderParent.getValue(); - if (baseObj != nullptr) { + if (baseObj) { DrawView* cast = dynamic_cast(baseObj); - if (cast != nullptr) { + if (cast) { result = cast; } } return result; } -App::DocumentObject* DrawLeaderLine::getBaseObject(void) const +App::DocumentObject* DrawLeaderLine::getBaseObject() const { App::DocumentObject* result = nullptr; DrawView* view = getBaseView(); - if (view != nullptr) { + if (view) { result = view; } return result; } -bool DrawLeaderLine::keepUpdated(void) +bool DrawLeaderLine::keepUpdated() { bool result = false; DrawView* view = getBaseView(); - if (view != nullptr) { + if (view) { result = view->keepUpdated(); } return result; @@ -181,12 +182,12 @@ bool DrawLeaderLine::keepUpdated(void) //need separate getParentScale()??? -double DrawLeaderLine::getBaseScale(void) const +double DrawLeaderLine::getBaseScale() const { // Base::Console().Message("DLL::getBaseScale()\n"); double result = 1.0; DrawView* parent = getBaseView(); - if (parent != nullptr) { + if (parent) { result = parent->getScale(); } else { //TARFU @@ -195,13 +196,13 @@ double DrawLeaderLine::getBaseScale(void) const return result; } -double DrawLeaderLine::getScale(void) const +double DrawLeaderLine::getScale() const { // Base::Console().Message("DLL::getScale()\n"); double result = 1.0; if (Scalable.getValue()) { DrawView* parent = getBaseView(); - if (parent != nullptr) { + if (parent) { result = parent->getScale(); } else { //TARFU @@ -211,7 +212,7 @@ double DrawLeaderLine::getScale(void) const return result; } -Base::Vector3d DrawLeaderLine::getAttachPoint(void) +Base::Vector3d DrawLeaderLine::getAttachPoint() { Base::Vector3d result(X.getValue(), Y.getValue(), @@ -219,7 +220,7 @@ Base::Vector3d DrawLeaderLine::getAttachPoint(void) return result; } -void DrawLeaderLine::adjustLastSegment(void) +void DrawLeaderLine::adjustLastSegment() { // Base::Console().Message("DLL::adjustLastSegment()\n"); bool adjust = AutoHorizontal.getValue(); @@ -238,7 +239,7 @@ void DrawLeaderLine::adjustLastSegment(void) } //middle of last line segment -Base::Vector3d DrawLeaderLine::getTileOrigin(void) const +Base::Vector3d DrawLeaderLine::getTileOrigin() const { Base::Vector3d result; std::vector wp = WayPoints.getValues(); @@ -253,7 +254,7 @@ Base::Vector3d DrawLeaderLine::getTileOrigin(void) const } //start of last line segment -Base::Vector3d DrawLeaderLine::getKinkPoint(void) const +Base::Vector3d DrawLeaderLine::getKinkPoint() const { Base::Vector3d result; std::vector wp = WayPoints.getValues(); @@ -268,7 +269,7 @@ Base::Vector3d DrawLeaderLine::getKinkPoint(void) const } //end of last line segment -Base::Vector3d DrawLeaderLine::getTailPoint(void) const +Base::Vector3d DrawLeaderLine::getTailPoint() const { Base::Vector3d result; std::vector wp = WayPoints.getValues(); @@ -283,7 +284,7 @@ Base::Vector3d DrawLeaderLine::getTailPoint(void) const } -bool DrawLeaderLine::getDefAuto(void) const +bool DrawLeaderLine::getDefAuto() const { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/LeaderLines"); @@ -292,7 +293,7 @@ bool DrawLeaderLine::getDefAuto(void) const } -PyObject *DrawLeaderLine::getPyObject(void) +PyObject *DrawLeaderLine::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -306,7 +307,7 @@ PyObject *DrawLeaderLine::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawLeaderLinePython, TechDraw::DrawLeaderLine) -template<> const char* TechDraw::DrawLeaderLinePython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawLeaderLinePython::getViewProviderName() const { return "TechDrawGui::ViewProviderLeader"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawLeaderLine.h b/src/Mod/TechDraw/App/DrawLeaderLine.h index 30ab847d06..6d8eb0a398 100644 --- a/src/Mod/TechDraw/App/DrawLeaderLine.h +++ b/src/Mod/TechDraw/App/DrawLeaderLine.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_DrawLeaderLine_h_ #define _TechDraw_DrawLeaderLine_h_ +#include + # include # include # include @@ -39,7 +41,7 @@ class TechDrawExport DrawLeaderLine : public TechDraw::DrawView public: DrawLeaderLine(); - virtual ~DrawLeaderLine(); + ~DrawLeaderLine() override; App::PropertyLink LeaderParent; App::PropertyVectorList WayPoints; @@ -52,30 +54,30 @@ public: App::PropertyBool Scalable; App::PropertyBool AutoHorizontal; - virtual short mustExecute() const override; - virtual App::DocumentObjectExecReturn *execute(void) override; + short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderLeader"; } - virtual PyObject *getPyObject(void) override; - virtual QRectF getRect() const override { return QRectF(0,0,1,1);} + PyObject *getPyObject() override; + QRectF getRect() const override { return QRectF(0,0,1,1);} - Base::Vector3d getAttachPoint(void); - DrawView* getBaseView(void) const; - virtual App::DocumentObject* getBaseObject(void) const; - bool keepUpdated(void) override; - double getScale(void) const override; - double getBaseScale(void) const; - void adjustLastSegment(void); - bool getDefAuto(void) const; + Base::Vector3d getAttachPoint(); + DrawView* getBaseView() const; + virtual App::DocumentObject* getBaseObject() const; + bool keepUpdated() override; + double getScale() const override; + double getBaseScale() const; + void adjustLastSegment(); + bool getDefAuto() const; - Base::Vector3d getTileOrigin(void) const; - Base::Vector3d getKinkPoint(void) const; - Base::Vector3d getTailPoint(void) const; + Base::Vector3d getTileOrigin() const; + Base::Vector3d getKinkPoint() const; + Base::Vector3d getTailPoint() const; protected: - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; private: /* static const char* ArrowTypeEnums[];*/ diff --git a/src/Mod/TechDraw/App/DrawLeaderLinePyImp.cpp b/src/Mod/TechDraw/App/DrawLeaderLinePyImp.cpp index a47bed2c28..a7a19cf6b2 100644 --- a/src/Mod/TechDraw/App/DrawLeaderLinePyImp.cpp +++ b/src/Mod/TechDraw/App/DrawLeaderLinePyImp.cpp @@ -38,7 +38,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawLeaderLinePy::representation(void) const +std::string DrawLeaderLinePy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawPage.cpp b/src/Mod/TechDraw/App/DrawPage.cpp index 96d72bc84c..b09f7d5092 100644 --- a/src/Mod/TechDraw/App/DrawPage.cpp +++ b/src/Mod/TechDraw/App/DrawPage.cpp @@ -136,7 +136,7 @@ void DrawPage::onChanged(const App::Property* prop) const std::vector &vals = Views.getValues(); for(std::vector::const_iterator it = vals.begin(); it < vals.end(); ++it) { TechDraw::DrawView *view = dynamic_cast(*it); - if (view != nullptr && view->ScaleType.isValue("Page")) { + if (view && view->ScaleType.isValue("Page")) { if(std::abs(view->Scale.getValue() - Scale.getValue()) > FLT_EPSILON) { view->Scale.setValue(Scale.getValue()); } @@ -148,7 +148,7 @@ void DrawPage::onChanged(const App::Property* prop) const std::vector &vals = Views.getValues(); for(std::vector::const_iterator it = vals.begin(); it < vals.end(); ++it) { TechDraw::DrawProjGroup *view = dynamic_cast(*it); - if (view != nullptr && view->ProjectionType.isValue("Default")) { + if (view && view->ProjectionType.isValue("Default")) { view->ProjectionType.touch(); } } @@ -287,7 +287,7 @@ int DrawPage::removeView(App::DocumentObject *docObj) return -1; App::Document* doc = docObj->getDocument(); - if (doc == nullptr) { + if (!doc) { return -1; } @@ -300,7 +300,7 @@ int DrawPage::removeView(App::DocumentObject *docObj) std::vector::const_iterator it = currViews.begin(); for (; it != currViews.end(); it++) { App::Document* viewDoc = (*it)->getDocument(); - if (viewDoc == nullptr) { + if (!viewDoc) { continue; } @@ -335,46 +335,34 @@ void DrawPage::redrawCommand() updateAllViews(); forceRedraw(false); } -//should really be called "updateMostViews". can still be problems to due execution order. + void DrawPage::updateAllViews() { // Base::Console().Message("DP::updateAllViews()\n"); - std::vector featViews = getAllViews(); - std::vector::iterator it = featViews.begin(); + std::vector featViews = getAllViews(); //unordered list of views within page + //first, make sure all the Parts have been executed so GeometryObjects exist - for(; it != featViews.end(); ++it) { - TechDraw::DrawViewPart *part = dynamic_cast(*it); - TechDraw::DrawViewCollection *collect = dynamic_cast(*it); - if (part != nullptr) { + for(auto& v: featViews) { + TechDraw::DrawViewPart *part = dynamic_cast(v); + if (part) { + //view, section, detail, dpgi part->recomputeFeature(); - } else if (collect != nullptr) { - collect->recomputeFeature(); } } - //second, make sure all the Dimensions have been executed so Measurements have References - for(it = featViews.begin(); it != featViews.end(); ++it) { - TechDraw::DrawViewDimension *dim = dynamic_cast(*it); - if (dim != nullptr) { - dim->recomputeFeature(); + //second, do the rest of the views that may depend on a part view + //TODO: check if we have 2 layers of dependency (ex. leader > weld > tile?) + for(auto& v: featViews) { + TechDraw::DrawViewPart *part = dynamic_cast(v); + if (part) { + continue; } - } - //third, try to execute all leader lines. may not work if parent DVP isn't ready. - for(it = featViews.begin(); it != featViews.end(); ++it) { - TechDraw::DrawLeaderLine *line = dynamic_cast(*it); - if (line != nullptr) { - line->recomputeFeature(); + TechDraw::DrawView* view = dynamic_cast(v); + if (view) { + view->overrideKeepUpdated(true); + view->recomputeFeature(); } } - - //fourth, try to execute all spreadsheets. - for (it = featViews.begin(); it != featViews.end(); ++it) { - TechDraw::DrawViewSpreadsheet *sheet = dynamic_cast(*it); - if (sheet != nullptr) { - sheet->recomputeFeature(); - } - } - } std::vector DrawPage::getAllViews(void) @@ -385,7 +373,7 @@ std::vector DrawPage::getAllViews(void) allViews.push_back(v); if (v->isDerivedFrom(TechDraw::DrawProjGroup::getClassTypeId())) { TechDraw::DrawProjGroup* dpg = static_cast(v); - if (dpg != nullptr) { //can't really happen! + if (dpg) { //can't really happen! std::vector pgViews = dpg->Views.getValues(); allViews.insert(allViews.end(),pgViews.begin(),pgViews.end()); } @@ -426,7 +414,7 @@ void DrawPage::unsetupObject() } App::DocumentObject* tmp = Template.getValue(); - if (tmp != nullptr) { + if (tmp) { std::string templateName = Template.getValue()->getNameInDocument(); Base::Interpreter().runStringArg("App.getDocument(\"%s\").removeObject(\"%s\")", docName.c_str(), templateName.c_str()); diff --git a/src/Mod/TechDraw/App/DrawPage.h b/src/Mod/TechDraw/App/DrawPage.h index db1671bd1b..dc5d0b8860 100644 --- a/src/Mod/TechDraw/App/DrawPage.h +++ b/src/Mod/TechDraw/App/DrawPage.h @@ -22,7 +22,9 @@ #ifndef _DrawPage_h_ #define _DrawPage_h_ - + +#include + #include #include @@ -39,8 +41,8 @@ class TechDrawExport DrawPage: public App::DocumentObject PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawPage); public: - DrawPage(void); - virtual ~DrawPage(); + DrawPage(); + ~DrawPage() override; App::PropertyLinkList Views; App::PropertyLink Template; @@ -54,9 +56,9 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} - virtual void handleChangedPropertyType( + void handleChangedPropertyType( Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; int addView(App::DocumentObject *docObj); @@ -65,11 +67,11 @@ public: boost::signals2::signal signalGuiPaint; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderPage"; } - PyObject *getPyObject(void) override; + PyObject *getPyObject() override; //App::DocumentObjectExecReturn * recompute(void); @@ -89,18 +91,18 @@ public: */ double getPageHeight() const; const char* getPageOrientation() const; - bool isUnsetting(void) { return nowUnsetting; } - void requestPaint(void); - std::vector getAllViews(void) ; + bool isUnsetting() { return nowUnsetting; } + void requestPaint(); + std::vector getAllViews() ; DrawViewPart *balloonParent; //could be many balloons on page? - int getNextBalloonIndex(void); + int getNextBalloonIndex(); - void updateAllViews(void); - static bool GlobalUpdateDrawings(void); - static bool AllowPageOverride(void); + void updateAllViews(); + static bool GlobalUpdateDrawings(); + static bool AllowPageOverride(); void forceRedraw(bool b) { m_forceRedraw = b; } - bool forceRedraw(void) { return m_forceRedraw; } + bool forceRedraw() { return m_forceRedraw; } void redrawCommand(); bool canUpdate() const; @@ -108,8 +110,8 @@ public: protected: void onBeforeChange(const App::Property* prop) override; void onChanged(const App::Property* prop) override; - virtual void onDocumentRestored() override; - virtual void unsetupObject() override; + void onDocumentRestored() override; + void unsetupObject() override; bool m_forceRedraw; diff --git a/src/Mod/TechDraw/App/DrawPagePyImp.cpp b/src/Mod/TechDraw/App/DrawPagePyImp.cpp index 882ef4fb05..20798c73bf 100644 --- a/src/Mod/TechDraw/App/DrawPagePyImp.cpp +++ b/src/Mod/TechDraw/App/DrawPagePyImp.cpp @@ -21,7 +21,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawPagePy::representation(void) const +std::string DrawPagePy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawParametricTemplate.cpp b/src/Mod/TechDraw/App/DrawParametricTemplate.cpp index e8ab8ce479..00728cecef 100644 --- a/src/Mod/TechDraw/App/DrawParametricTemplate.cpp +++ b/src/Mod/TechDraw/App/DrawParametricTemplate.cpp @@ -48,7 +48,7 @@ using namespace std; PROPERTY_SOURCE(TechDraw::DrawParametricTemplate, TechDraw::DrawTemplate) -DrawParametricTemplate::DrawParametricTemplate(void) +DrawParametricTemplate::DrawParametricTemplate() { static const char *group = "Page"; ADD_PROPERTY_TYPE(Template ,(""),group, (App::PropertyType) App::Prop_None,"Template script"); @@ -59,7 +59,7 @@ DrawParametricTemplate::~DrawParametricTemplate() } -PyObject *DrawParametricTemplate::getPyObject(void) +PyObject *DrawParametricTemplate::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -68,7 +68,7 @@ PyObject *DrawParametricTemplate::getPyObject(void) return Py::new_reference_to(PythonObject); } -unsigned int DrawParametricTemplate::getMemSize(void) const +unsigned int DrawParametricTemplate::getMemSize() const { return 0; } @@ -94,7 +94,7 @@ void DrawParametricTemplate::onChanged(const App::Property* prop) App::DocumentObject::onChanged(prop); } -App::DocumentObjectExecReturn *DrawParametricTemplate::execute(void) +App::DocumentObjectExecReturn *DrawParametricTemplate::execute() { std::string temp = Template.getValue(); if (!temp.empty()) { @@ -139,7 +139,7 @@ int DrawParametricTemplate::clearGeometry() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawParametricTemplatePython, TechDraw::DrawParametricTemplate) -template<> const char* TechDraw::DrawParametricTemplatePython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawParametricTemplatePython::getViewProviderName() const { return "TechDrawGui::ViewProviderPython"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawParametricTemplate.h b/src/Mod/TechDraw/App/DrawParametricTemplate.h index f82d4b00a2..033edf9d12 100644 --- a/src/Mod/TechDraw/App/DrawParametricTemplate.h +++ b/src/Mod/TechDraw/App/DrawParametricTemplate.h @@ -22,6 +22,8 @@ #ifndef _TECHDRAW_DrawParametricTemplate_h_ #define _TECHDRAW_DrawParametricTemplate_h_ + +#include #include #include @@ -53,20 +55,20 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void); + virtual App::DocumentObjectExecReturn *execute(); //@} short mustExecute() const; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + virtual const char* getViewProviderName() const { return "TechDrawGui::ViewProviderTemplate"; } // from base class - virtual PyObject *getPyObject(void); - virtual unsigned int getMemSize(void) const; + virtual PyObject *getPyObject(); + virtual unsigned int getMemSize() const; public: std::vector getGeometry() { return geom; } diff --git a/src/Mod/TechDraw/App/DrawProjGroup.cpp b/src/Mod/TechDraw/App/DrawProjGroup.cpp index 43cd573a3e..f74ffd80aa 100644 --- a/src/Mod/TechDraw/App/DrawProjGroup.cpp +++ b/src/Mod/TechDraw/App/DrawProjGroup.cpp @@ -62,8 +62,7 @@ const char* DrawProjGroup::ProjectionTypeEnums[] = {"First Angle", PROPERTY_SOURCE(TechDraw::DrawProjGroup, TechDraw::DrawViewCollection) -DrawProjGroup::DrawProjGroup(void) : - m_lockScale(false) +DrawProjGroup::DrawProjGroup() { static const char *group = "Base"; static const char *agroup = "Distribute"; @@ -71,7 +70,7 @@ DrawProjGroup::DrawProjGroup(void) : Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); bool autoDist = hGrp->GetBool("AutoDist",true); - + ADD_PROPERTY_TYPE(Source, (nullptr), group, App::Prop_None, "Shape to view"); Source.setScope(App::LinkScope::Global); Source.setAllowExternal(true); @@ -97,7 +96,7 @@ DrawProjGroup::~DrawProjGroup() } //TODO: this duplicates code in DVP -std::vector DrawProjGroup::getAllSources(void) const +std::vector DrawProjGroup::getAllSources() const { // Base::Console().Message("DPG::getAllSources()\n"); const std::vector links = Source.getValues(); @@ -115,91 +114,101 @@ void DrawProjGroup::onChanged(const App::Property* prop) { //TODO: For some reason, when the projection type is changed, the isometric views show change appropriately, but the orthographic ones don't... Or vice-versa. WF: why would you change from 1st to 3rd in mid drawing? //if group hasn't been added to page yet, can't scale or distribute projItems + if (isRestoring() || !getPage()) { + return TechDraw::DrawViewCollection::onChanged(prop); + } + TechDraw::DrawPage *page = getPage(); - if (!isRestoring() && page) { - if (prop == &Scale) { - if (!m_lockScale) { + + if (prop == &Scale) { + updateChildrenScale(); + recomputeChildren(); + return; + } + + if (prop == &ProjectionType) { + updateChildrenEnforce(); + return; + } + + if ( prop == &Source || + prop == &XSource ) { + updateChildrenSource(); + return; + } + + if ( prop == &spacingX || + prop == &spacingY ) { + updateChildrenEnforce(); + return; + } + + if (prop == &LockPosition) { + updateChildrenLock(); + return; + } + + if (prop == &ScaleType) { + if (ScaleType.isValue("Page")) { + double newScale = page->Scale.getValue(); + if(std::abs(getScale() - newScale) > FLT_EPSILON) { + Scale.setValue(newScale); updateChildrenScale(); - updateChildrenEnforce(); } } + } - if (prop == &ProjectionType) { - updateChildrenEnforce(); - } +// if ( ScaleType.isValue("Automatic") || +// ScaleType.isValue("Custom") ){ +// //just documenting that nothing is required here +// //DrawView::onChanged will sort out Scale hidden/readonly/etc +// } - if ( (prop == &Source) || - (prop == &XSource) ) { - updateChildrenSource(); - } - - if ((prop == &spacingX) || (prop == &spacingY)) { - updateChildrenEnforce(); - } - - if (prop == &LockPosition) { - updateChildrenLock(); - } - - if (prop == &ScaleType) { - if (ScaleType.isValue("Automatic")) { - //Nothing in particular - } else if (ScaleType.isValue("Page")) { - double newScale = page->Scale.getValue(); - if(std::abs(getScale() - newScale) > FLT_EPSILON) { - Scale.setValue(newScale); - } - } - updateChildrenScale(); - } - if (prop == &Rotation) { - if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { - Rotation.setValue(0.0); - purgeTouched(); - Base::Console().Log("DPG: Projection Groups do not rotate. Change ignored.\n"); - } + if (prop == &Rotation) { + if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { + Rotation.setValue(0.0); + purgeTouched(); + Base::Console().Log("DPG: Projection Groups do not rotate. Change ignored.\n"); } + return; } TechDraw::DrawViewCollection::onChanged(prop); } -App::DocumentObjectExecReturn *DrawProjGroup::execute(void) +App::DocumentObjectExecReturn *DrawProjGroup::execute() { -// Base::Console().Message("DPG::execute() - %s\n", getNameInDocument()); - if (!keepUpdated()) { +// Base::Console().Message("DPG::execute() - %s - waitingForChildren: %d\n", +// getNameInDocument(), waitingForChildren()); + if (!keepUpdated()) return App::DocumentObject::StdReturn; - } //if group hasn't been added to page yet, can't scale or distribute projItems - TechDraw::DrawPage *page = getPage(); - if (!page) { + if (!getPage()) return DrawViewCollection::execute(); - } - std::vector docObjs = getAllSources(); - if (docObjs.empty()) { - return DrawViewCollection::execute(); - } - - App::DocumentObject* docObj = Anchor.getValue(); - if (docObj == nullptr) { + if (!Anchor.getValue()) //no anchor yet. nothing to do. return DrawViewCollection::execute(); + + if (waitingForChildren()) { + return DrawViewCollection::execute(); } - if (ScaleType.isValue("Automatic")) { - if (!checkFit()) { - double newScale = autoScale(); - m_lockScale = true; - Scale.setValue(newScale); - Scale.purgeTouched(); - updateChildrenScale(); - m_lockScale = false; + if (ScaleType.isValue("Automatic") && !checkFit()) { + if (!DrawUtil::fpCompare(getScale(), autoScale(), 0.00001)) { + Scale.setValue(autoScale()); + //don't bother repositioning children since they will be + //recomputed at new scale + overrideKeepUpdated(false); + return DrawViewCollection::execute(); } } - autoPositionChildren(); + if (AutoDistribute.getValue()) { + autoPositionChildren(); + } + overrideKeepUpdated(false); return DrawViewCollection::execute(); } @@ -224,121 +233,121 @@ short DrawProjGroup::mustExecute() const return TechDraw::DrawViewCollection::mustExecute(); } -Base::BoundBox3d DrawProjGroup::getBoundingBox() const +void DrawProjGroup::reportReady() { - Base::BoundBox3d bbox; - - std::vector views = Views.getValues(); - TechDraw::DrawProjGroupItem *anchorView = dynamic_cast(Anchor.getValue()); - if (anchorView == nullptr) { - //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Log("PROBLEM - DPG::getBoundingBox - non DPGI entry in Views! %s\n", - getNameInDocument()); - throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); +// Base::Console().Message("DPG::reportReady - waitingForChildren: %d\n", waitingForChildren()); + if (waitingForChildren()) { + //not ready yet + return; } - for (std::vector::const_iterator it = views.begin(); it != views.end(); ++it) { - if ((*it)->getTypeId().isDerivedFrom(DrawViewPart::getClassTypeId())) { - DrawViewPart *part = static_cast(*it); - Base::BoundBox3d bb = part->getBoundingBox(); - - bb.ScaleX(1. / part->getScale()); - bb.ScaleY(1. / part->getScale()); - bb.ScaleZ(1. / part->getScale()); - - // X and Y of dependent views are relative to the anchorView - if (part != anchorView) { - bb.MoveX(part->X.getValue()); - bb.MoveY(part->Y.getValue()); - } - - bbox.Add(bb); - } + //all the secondary views are ready so we can now figure out alignment + if (AutoDistribute.getValue()) { + recomputeFeature(); } - return bbox; } -TechDraw::DrawPage * DrawProjGroup::getPage(void) const +bool DrawProjGroup::waitingForChildren() const +{ + for(const auto v : Views.getValues()) { + DrawProjGroupItem* dpgi = static_cast(v); + if (dpgi->waitingForHlr() || //dpgi is still thinking + dpgi->isTouched()) { //dpgi needs to execute + return true; + } + } + return false; +} + +TechDraw::DrawPage * DrawProjGroup::getPage() const { return findParentPage(); } -// obs? replaced by autoscale? -// Function provided by Joe Dowsett, 2014 -double DrawProjGroup::calculateAutomaticScale() const +//does the unscaled DPG fit on the page? +bool DrawProjGroup::checkFit() const { - TechDraw::DrawPage *page = getPage(); - if (page == nullptr) - throw Base::RuntimeError("No page is assigned to this feature"); - - DrawProjGroupItem *viewPtrs[10]; - - arrangeViewPointers(viewPtrs); - double width, height; - minimumBbViews(viewPtrs, width, height); //get SCALED boxes! - // if Page.keepUpdated is false, and DrawViews have never been executed, - // bb's will be 0x0 and this routine will return 0!!! - // if we return 1.0, AutoScale will sort itself out once bb's are non-zero. - double bbFudge = 1.2; - width *= bbFudge; - height *= bbFudge; - - // C++ Standard says casting bool to int gives 0 or 1 - int numVertSpaces = (viewPtrs[0] || viewPtrs[3] || viewPtrs[7]) + - (viewPtrs[2] || viewPtrs[5] || viewPtrs[9]) + - (viewPtrs[6] != nullptr); - int numHorizSpaces = (viewPtrs[0] || viewPtrs[1] || viewPtrs[2]) + - (viewPtrs[7] || viewPtrs[8] || viewPtrs[9]); - - double availableX = page->getPageWidth(); - double availableY = page->getPageHeight(); - double xWhite = spacingX.getValue() * (numVertSpaces + 1); - double yWhite = spacingY.getValue() * (numHorizSpaces + 1); - width += xWhite; - height += yWhite; - double scale_x = availableX / width; - double scale_y = availableY / height; - - double scaleFudge = 0.80; - float working_scale = scaleFudge * std::min(scale_x, scale_y); - double result = DrawUtil::sensibleScale(working_scale); - if (!(result > 0.0)) { - Base::Console().Log("DPG - %s - bad scale found (%.3f) using 1.0\n",getNameInDocument(),result); - result = 1.0; +// 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; } - - return result; + auto page = findParentPage(); + if (!page) + throw Base::RuntimeError("No page is assigned to this feature"); + return checkFit(page); } -//returns the (scaled) bounding rectangle of all the views. -QRectF DrawProjGroup::getRect() const //this is current rect, not potential rect +bool DrawProjGroup::checkFit(DrawPage* page) const +{ +// Base::Console().Message("DPG::checkFit(page) - %s\n", getNameInDocument()); + if (waitingForChildren()) { + return true; + } + + QRectF bigBox = getRect(false); + if ( bigBox.width() <= page->getPageWidth() && + bigBox.height() <= page->getPageHeight() ) { + return true; + } + return false; +} + +//calculate a scale that fits all views on page +double DrawProjGroup::autoScale() const +{ +// Base::Console().Message("DPG::autoScale() - %s\n", getNameInDocument()); + auto page = findParentPage(); + if (!page) { + throw Base::RuntimeError("No page is assigned to this feature"); + } + return autoScale(page->getPageWidth(), page->getPageHeight()); +} + +double DrawProjGroup::autoScale(double w, double h) const +{ +// 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 + + double xScale = w / bigBox.width(); // > 1 page bigger than figure + double yScale = h / bigBox.height(); // < 1 page is smaller than figure + + double newScale = std::min(xScale,yScale); + return DrawUtil::sensibleScale(newScale); +} + +//returns the bounding rectangle of all the views in the current scale +QRectF DrawProjGroup::getRect() const +{ + return getRect(true); +} + +QRectF DrawProjGroup::getRect(bool scaled) const { // Base::Console().Message("DPG::getRect - views: %d\n", Views.getValues().size()); DrawProjGroupItem *viewPtrs[10]; arrangeViewPointers(viewPtrs); - double width, height; - minimumBbViews(viewPtrs, width, height); //this is scaled! - double xSpace = spacingX.getValue() * 3.0 * std::max(1.0, getScale()); - double ySpace = spacingY.getValue() * 2.0 * std::max(1.0, getScale()); - double rectW = 0.0; - double rectH = 0.0; - if ( !(DrawUtil::fpCompare(width, 0.0) && - DrawUtil::fpCompare(height, 0.0)) ) { - rectW = width + xSpace; - rectH = height + ySpace; - } - double fudge = 1.3; //make rect a little big to make sure it fits + double totalWidth, totalHeight; + getViewArea(viewPtrs, totalWidth, totalHeight, scaled); + double xSpace = spacingX.getValue() * 3.0; + double ySpace = spacingY.getValue() * 2.0; + double rectW = totalWidth + xSpace; + double rectH = totalHeight + ySpace; + double fudge = 1.2; //make rect a little big to make sure it fits rectW *= fudge; rectH *= fudge; + return QRectF(0,0,rectW,rectH); } -//find area consumed by Views only in current scale -void DrawProjGroup::minimumBbViews(DrawProjGroupItem *viewPtrs[10], - double &width, double &height) const +//find area consumed by Views only - scaled or unscaled +void DrawProjGroup::getViewArea(DrawProjGroupItem *viewPtrs[10], + double &width, double &height, + bool scaled) const { - // Get bounding boxes in object scale + // Get the child view bounding boxes Base::BoundBox3d bboxes[10]; - makeViewBbs(viewPtrs, bboxes, true); //true => scaled + makeViewBbs(viewPtrs, bboxes, scaled); //TODO: note that TLF/TRF/BLF,BRF extend a bit farther than a strict row/col arrangement would suggest. //get widest view in each row/column @@ -359,7 +368,7 @@ App::DocumentObject * DrawProjGroup::getProjObj(const char *viewProjType) const { for( auto it : Views.getValues() ) { auto projPtr( dynamic_cast(it) ); - if (projPtr == nullptr) { + if (!projPtr) { //if an element in Views is not a DPGI, something really bad has happened somewhere Base::Console().Log("PROBLEM - DPG::getProjObj - non DPGI entry in Views! %s / %s\n", getNameInDocument(),viewProjType); @@ -376,8 +385,7 @@ DrawProjGroupItem* DrawProjGroup::getProjItem(const char *viewProjType) const { App::DocumentObject* docObj = getProjObj(viewProjType); auto result( dynamic_cast(docObj) ); - if ( (result == nullptr) && - (docObj != nullptr) ) { + if (!result && docObj) { //should never have a item in DPG that is not a DPGI. Base::Console().Log("PROBLEM - DPG::getProjItem finds non-DPGI in Group %s / %s\n", getNameInDocument(),viewProjType); @@ -410,7 +418,7 @@ bool DrawProjGroup::hasProjection(const char *viewProjType) const { for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { //should never have a item in DPG that is not a DPGI. Base::Console().Log("PROBLEM - DPG::hasProjection finds non-DPGI in Group %s / %s\n", getNameInDocument(),viewProjType); @@ -430,23 +438,21 @@ App::DocumentObject * DrawProjGroup::addProjection(const char *viewProjType) std::pair vecs; DrawPage* dp = findParentPage(); - if (dp == nullptr) { + if (!dp) Base::Console().Error("DPG:addProjection - %s - DPG is not on a page!\n",getNameInDocument()); - } if ( checkViewProjType(viewProjType) && !hasProjection(viewProjType) ) { std::string FeatName = getDocument()->getUniqueObjectName("ProjItem"); auto docObj( getDocument()->addObject( "TechDraw::DrawProjGroupItem", //add to Document FeatName.c_str() ) ); view = dynamic_cast(docObj); - if ( (view == nullptr) && - (docObj != nullptr) ) { + if (!view && docObj) { //should never happen that we create a DPGI that isn't a DPGI!! Base::Console().Log("PROBLEM - DPG::addProjection - created a non DPGI! %s / %s\n", getNameInDocument(),viewProjType); throw Base::TypeError("Error: new projection is not a DPGI!"); } - if (view != nullptr) { //coverity CID 151722 + if (view) { //coverity CID 151722 // the label must be set before the view is added view->Label.setValue(viewProjType); addView(view); //from DrawViewCollection @@ -484,16 +490,16 @@ App::DocumentObject * DrawProjGroup::addProjection(const char *viewProjType) int DrawProjGroup::removeProjection(const char *viewProjType) { // TODO: shouldn't be able to delete "Front" unless deleting whole group - if ( checkViewProjType(viewProjType) ) { - if( !hasProjection(viewProjType) ) { + if (checkViewProjType(viewProjType)) { + if (!hasProjection(viewProjType)) { throw Base::RuntimeError("The projection doesn't exist in the group"); } // Iterate through the child views and find the projection type - for( auto it : Views.getValues() ) { + for (auto it : Views.getValues()) { auto projPtr( dynamic_cast(it) ); - if( projPtr != nullptr) { - if ( strcmp(viewProjType, projPtr->Type.getValueAsString()) == 0 ) { + if (projPtr) { + if (strcmp(viewProjType, projPtr->Type.getValueAsString()) == 0) { removeView(projPtr); // Remove from collection getDocument()->removeObject( it->getNameInDocument() ); // Remove from the document return Views.getValues().size(); @@ -508,7 +514,7 @@ int DrawProjGroup::removeProjection(const char *viewProjType) } return -1; -} +} //removes all DPGI - used when deleting DPG int DrawProjGroup::purgeProjections() @@ -518,7 +524,7 @@ int DrawProjGroup::purgeProjections() DrawProjGroupItem* dpgi; DocumentObject* dObj = views.back(); dpgi = dynamic_cast(dObj); - if (dpgi != nullptr) { + if (dpgi) { std::string itemName = dpgi->Type.getValueAsString(); removeProjection(itemName.c_str()); } else { @@ -529,7 +535,7 @@ int DrawProjGroup::purgeProjections() } } auto page = findParentPage(); - if (page != nullptr) { + if (page) { page->requestPaint(); } @@ -551,7 +557,7 @@ std::pair DrawProjGroup::getDirsFromFront(std::st Base::Vector3d projDir, rotVec; DrawProjGroupItem* anch = getAnchor(); - if (anch == nullptr) { + if (!anch) { Base::Console().Warning("DPG::getDirsFromFront - %s - No Anchor!\n",Label.getValue()); throw Base::RuntimeError("Project Group missing Anchor projection item"); } @@ -570,7 +576,7 @@ std::pair DrawProjGroup::getDirsFromFront(std::st gp_Ax2 newCS; gp_Dir gNewDir; gp_Dir gNewXDir; - + double angle = M_PI / 2.0; //90* if (viewType == "Right") { @@ -793,7 +799,7 @@ int DrawProjGroup::getViewIndex(const char *viewTypeCStr) const const char* projType; DrawPage* dp = findParentPage(); if (ProjectionType.isValue("Default")) { - if (dp != nullptr) { + if (dp) { projType = dp->ProjectionType.getValueAsString(); } else { Base::Console().Warning("DPG: %s - can not find parent page. Using default Projection Type. (1)\n", @@ -855,7 +861,7 @@ void DrawProjGroup::arrangeViewPointers(DrawProjGroupItem *viewPtrs[10]) const const char* projType; if (ProjectionType.isValue("Default")) { DrawPage* dp = findParentPage(); - if (dp != nullptr) { + if (dp) { projType = dp->ProjectionType.getValueAsString(); } else { Base::Console().Error("DPG:arrangeViewPointers - %s - DPG is not on a page!\n", @@ -883,7 +889,7 @@ void DrawProjGroup::arrangeViewPointers(DrawProjGroupItem *viewPtrs[10]) const bool thirdAngle = (strcmp(projType, "Third Angle") == 0); for (auto it : Views.getValues()) { auto oView( dynamic_cast(it) ); - if (oView == nullptr) { + if (!oView) { //if an element in Views is not a DPGI, something really bad has happened somewhere Base::Console().Log("PROBLEM - DPG::arrangeViewPointers - non DPGI in Views! %s\n", getNameInDocument()); @@ -926,16 +932,16 @@ void DrawProjGroup::arrangeViewPointers(DrawProjGroupItem *viewPtrs[10]) const void DrawProjGroup::makeViewBbs(DrawProjGroupItem *viewPtrs[10], Base::BoundBox3d bboxes[10], - bool documentScale) const + bool scaled) const { Base::BoundBox3d empty(Base::Vector3d(0.0, 0.0, 0.0), 0.0); for (int i = 0; i < 10; ++i) { bboxes[i] = empty; if (viewPtrs[i]) { bboxes[i] = viewPtrs[i]->getBoundingBox(); -// bboxes[i] = viewPtrs[i]->getBoundingBox(viewPtrs[i]->getProjectionCS(Base::Vector3d(0.0, 0.0, 0.0))); - if (!documentScale) { + if (!scaled) { double scale = 1.0 / viewPtrs[i]->getScale(); //convert bbx to 1:1 scale +// double scale = 1.0 / viewPtrs[i]->getLastScale(); //convert bbx to 1:1 scale bboxes[i].ScaleX(scale); bboxes[i].ScaleY(scale); bboxes[i].ScaleZ(scale); @@ -944,12 +950,12 @@ void DrawProjGroup::makeViewBbs(DrawProjGroupItem *viewPtrs[10], } } -void DrawProjGroup::recomputeChildren(void) +void DrawProjGroup::recomputeChildren() { -// Base::Console().Message("DPG::recomputeChildren()\n"); +// Base::Console().Message("DPG::recomputeChildren() - waiting: %d\n", waitingForChildren()); for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } else { view->recomputeFeature(); @@ -957,11 +963,14 @@ void DrawProjGroup::recomputeChildren(void) } } -void DrawProjGroup::autoPositionChildren(void) +void DrawProjGroup::autoPositionChildren() { +// Base::Console().Message("DPG::autoPositionChildren() - %s - waiting: %d\n", +// getNameInDocument(), waitingForChildren()); for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { + //if an element in Views is not a DPGI, something really bad has happened somewhere throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } else { view->autoPosition(); @@ -972,18 +981,18 @@ void DrawProjGroup::autoPositionChildren(void) /*! * tell children DPGIs that parent DPG has changed Scale */ -void DrawProjGroup::updateChildrenScale(void) +void DrawProjGroup::updateChildrenScale() { -// Base::Console().Message("DPG::updateChildrenScale\n"); +// Base::Console().Message("DPG::updateChildrenScale() - waiting: %d\n", waitingForChildren()); for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Log("PROBLEM - DPG::updateChildrenScale - non DPGI entry in Views! %s\n", - getNameInDocument()); throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); } else { view->Scale.setValue(getScale()); + view->Scale.purgeTouched(); + view->purgeTouched(); } } } @@ -991,11 +1000,11 @@ void DrawProjGroup::updateChildrenScale(void) /*! * tell children DPGIs that parent DPG has changed Source */ -void DrawProjGroup::updateChildrenSource(void) +void DrawProjGroup::updateChildrenSource() { for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere Base::Console().Log("PROBLEM - DPG::updateChildrenSource - non DPGI entry in Views! %s\n", getNameInDocument()); @@ -1015,11 +1024,11 @@ void DrawProjGroup::updateChildrenSource(void) * tell children DPGIs that parent DPG has changed LockPosition * (really for benefit of QGIV on Gui side) */ -void DrawProjGroup::updateChildrenLock(void) +void DrawProjGroup::updateChildrenLock() { for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere Base::Console().Log("PROBLEM - DPG::updateChildrenLock - non DPGI entry in Views! %s\n", getNameInDocument()); @@ -1030,26 +1039,11 @@ void DrawProjGroup::updateChildrenLock(void) } } -void DrawProjGroup::updateViews(void) { - // this is intended to update the views in general, e.g. when the spacing changed - for (const auto it : Views.getValues()) { - auto view(dynamic_cast(it)); - if (view == nullptr) { - //if an element in Views is not a DPGI, something really bad has happened somewhere - Base::Console().Log("PROBLEM - DPG::updateViews - non DPGI entry in Views! %s\n", - getNameInDocument()); - throw Base::TypeError("Error: projection in DPG list is not a DPGI!"); - } - else // the views are OK - view->recomputeFeature(); - } -} - void DrawProjGroup::updateChildrenEnforce(void) { for( const auto it : Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view == nullptr) { + if (!view) { //if an element in Views is not a DPGI, something really bad has happened somewhere Base::Console().Log("PROBLEM - DPG::updateChildrenEnforce - non DPGI entry in Views! %s\n", getNameInDocument()); @@ -1060,34 +1054,34 @@ void DrawProjGroup::updateChildrenEnforce(void) } } -App::Enumeration DrawProjGroup::usedProjectionType(void) +App::Enumeration DrawProjGroup::usedProjectionType() { //TODO: Would've been nice to have an Enumeration(const PropertyEnumeration &) constructor App::Enumeration ret(ProjectionTypeEnums, ProjectionType.getValueAsString()); if (ret.isValue("Default")) { TechDraw::DrawPage * page = getPage(); - if ( page != nullptr ) { + if (page) { ret.setValue(page->ProjectionType.getValueAsString()); } } return ret; } -bool DrawProjGroup::hasAnchor(void) +bool DrawProjGroup::hasAnchor() { bool result = false; App::DocumentObject* docObj = Anchor.getValue(); - if (docObj != nullptr) { + if (docObj) { result = true; } return result; } -TechDraw::DrawProjGroupItem* DrawProjGroup::getAnchor(void) +TechDraw::DrawProjGroupItem* DrawProjGroup::getAnchor() { DrawProjGroupItem* result = nullptr; App::DocumentObject* docObj = Anchor.getValue(); - if (docObj != nullptr) { + if (docObj) { result = static_cast(docObj); } return result; @@ -1100,11 +1094,11 @@ void DrawProjGroup::setAnchorDirection(const Base::Vector3d dir) item->Direction.setValue(dir); } -Base::Vector3d DrawProjGroup::getAnchorDirection(void) +Base::Vector3d DrawProjGroup::getAnchorDirection() { Base::Vector3d result; App::DocumentObject* docObj = Anchor.getValue(); - if (docObj != nullptr) { + if (docObj) { DrawProjGroupItem* item = static_cast(docObj); result = item->Direction.getValue(); } else { @@ -1245,7 +1239,7 @@ std::vector DrawProjGroup::getViewsAsDPGI() return result; } -int DrawProjGroup::getDefProjConv(void) const +int DrawProjGroup::getDefProjConv() const { return Preferences::projectionAngle(); } @@ -1269,7 +1263,7 @@ void DrawProjGroup::dumpISO(const char * title) } } -PyObject *DrawProjGroup::getPyObject(void) +PyObject *DrawProjGroup::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 diff --git a/src/Mod/TechDraw/App/DrawProjGroup.h b/src/Mod/TechDraw/App/DrawProjGroup.h index 33a64e60d5..7f738f4e8a 100644 --- a/src/Mod/TechDraw/App/DrawProjGroup.h +++ b/src/Mod/TechDraw/App/DrawProjGroup.h @@ -23,6 +23,8 @@ #ifndef _TECHDRAW_FEATUREVIEWGROUP_H_ #define _TECHDRAW_FEATUREVIEWGROUP_H_ +#include + #include # include @@ -53,7 +55,7 @@ class TechDrawExport DrawProjGroup : public TechDraw::DrawViewCollection public: /// Constructor DrawProjGroup(); - ~DrawProjGroup(); + ~DrawProjGroup() override; App::PropertyLinkList Source; App::PropertyXLinkList XSource; @@ -69,9 +71,11 @@ public: App::PropertyLink Anchor; /// Anchor Element to align views to - Base::BoundBox3d getBoundingBox() const; - double calculateAutomaticScale() const; - virtual QRectF getRect(void) const override; + double autoScale() const override; + double autoScale(double w, double h) const override; + QRectF getRect() const override; //always scaled + QRectF getRect(bool scaled) const; //scaled or unscaled + /// Check if container has a view of a specific type bool hasProjection(const char *viewProjType) const; @@ -97,44 +101,50 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderProjGroup"; } //return PyObject as DrawProjGroupPy - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; /// Determines either "First Angle" or "Third Angle". - App::Enumeration usedProjectionType(void); + App::Enumeration usedProjectionType(); /// Allowed projection types - either Document, First Angle or Third Angle static const char* ProjectionTypeEnums[]; - bool hasAnchor(void); + bool hasAnchor(); void setAnchorDirection(Base::Vector3d dir); - Base::Vector3d getAnchorDirection(void); - TechDraw::DrawProjGroupItem* getAnchor(void); - std::pair getDirsFromFront(DrawProjGroupItem* view); - std::pair getDirsFromFront(std::string viewType); + Base::Vector3d getAnchorDirection(); + TechDraw::DrawProjGroupItem* getAnchor(); + std::pair getDirsFromFront(DrawProjGroupItem* view); + std::pair getDirsFromFront(std::string viewType); void updateSecondaryDirs(); void rotate(const std::string &rotationdirection); void spin(const std::string &spindirection); - + void dumpISO(const char * title); std::vector getViewsAsDPGI(); - void recomputeChildren(void); - void updateChildrenScale(void); - void autoPositionChildren(void); - void updateChildrenEnforce(void); + void recomputeChildren(); + void updateChildrenScale(); + void autoPositionChildren(); + void updateChildrenEnforce(); - std::vector getAllSources(void) const; + std::vector getAllSources() const; + bool checkFit() const override; + bool checkFit(DrawPage* p) const override; + bool waitingForChildren() const; + void reportReady(); + + void dumpTouchedProps(); protected: void onChanged(const App::Property* prop) override; @@ -155,30 +165,29 @@ protected: */ void makeViewBbs(DrawProjGroupItem *viewPtrs[10], Base::BoundBox3d bboxes[10], - bool documentScale = true) const; + bool scaled = true) const; /// Helper for calculateAutomaticScale /*! * Returns a width and height in object-space scale, for the enabled views * without accounting for their actual X and Y positions or borders. */ - void minimumBbViews(DrawProjGroupItem *viewPtrs[10], - double &width, double &height) const; + void getViewArea(DrawProjGroupItem *viewPtrs[10], + double &width, double &height, + bool scaled = true) const; /// Returns pointer to our page, or NULL if it couldn't be located - TechDraw::DrawPage * getPage(void) const; + TechDraw::DrawPage * getPage() const; + + void updateChildrenSource(); + void updateChildrenLock(); - void updateChildrenSource(void); - void updateChildrenLock(void); - void updateViews(void); int getViewIndex(const char *viewTypeCStr) const; - int getDefProjConv(void) const; + int getDefProjConv() const; Base::Vector3d dir2vec(gp_Dir d); gp_Dir vec2dir(Base::Vector3d v); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; - - bool m_lockScale; + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; }; } //namespace TechDraw diff --git a/src/Mod/TechDraw/App/DrawProjGroupItem.cpp b/src/Mod/TechDraw/App/DrawProjGroupItem.cpp index fd9de502d1..e681d357f7 100644 --- a/src/Mod/TechDraw/App/DrawProjGroupItem.cpp +++ b/src/Mod/TechDraw/App/DrawProjGroupItem.cpp @@ -81,18 +81,7 @@ DrawProjGroupItem::~DrawProjGroupItem() short DrawProjGroupItem::mustExecute() const { - short result = 0; - if (!isRestoring()) { - result = (Direction.isTouched() || - XDirection.isTouched() || - Source.isTouched() || - XSource.isTouched() || - Scale.isTouched()); - } - - if (result) { - return result; - } + //there is nothing unique about dpgi vs dvp return TechDraw::DrawViewPart::mustExecute(); } @@ -101,7 +90,7 @@ void DrawProjGroupItem::onChanged(const App::Property *prop) if ((prop == &X) || (prop == &Y)) { DrawProjGroup* parent = getPGroup(); - if (parent != nullptr) { + if (parent) { parent->touch(false); } } @@ -121,7 +110,7 @@ bool DrawProjGroupItem::showLock(void) const bool result = DrawView::showLock(); DrawProjGroup* parent = getPGroup(); bool parentLock = false; - if (parent != nullptr) { + if (parent) { parentLock = parent->LockPosition.getValue(); } @@ -135,9 +124,13 @@ bool DrawProjGroupItem::showLock(void) const App::DocumentObjectExecReturn *DrawProjGroupItem::execute(void) { -// Base::Console().Message("DPGI::execute(%s)\n",Label.getValue()); +// Base::Console().Message("DPGI::execute() - %s / %s\n", getNameInDocument(), Label.getValue()); if (!keepUpdated()) { - return App::DocumentObject::StdReturn; + return DrawView::execute(); + } + + if (waitingForHlr()) { + return DrawView::execute(); } bool haveX = checkXDirection(); @@ -154,9 +147,19 @@ App::DocumentObjectExecReturn *DrawProjGroupItem::execute(void) return new App::DocumentObjectExecReturn("DPGI: Direction and XDirection are parallel"); } - App::DocumentObjectExecReturn* ret = DrawViewPart::execute(); + return DrawViewPart::execute(); +} + +void DrawProjGroupItem::postHlrTasks(void) +{ +// Base::Console().Message("DPGI::postHlrTasks() - %s\n", getNameInDocument()); + DrawViewPart::postHlrTasks(); + + //DPGI has no geometry until HLR has finished, and the DPG can not properly + //AutoDistibute until all its items have geometry. autoPosition(); - return ret; + + getPGroup()->reportReady(); //tell the parent DPG we are ready } void DrawProjGroupItem::autoPosition() @@ -165,16 +168,14 @@ void DrawProjGroupItem::autoPosition() if (LockPosition.getValue()) { return; } - auto pgroup = getPGroup(); Base::Vector3d newPos; - if (pgroup != nullptr) { - if (pgroup->AutoDistribute.getValue()) { - newPos = pgroup->getXYPosition(Type.getValueAsString()); - X.setValue(newPos.x); - Y.setValue(newPos.y); - requestPaint(); - purgeTouched(); //prevents "still touched after recompute" message - } + if (getPGroup() && getPGroup()->AutoDistribute.getValue()) { + newPos = getPGroup()->getXYPosition(Type.getValueAsString()); + X.setValue(newPos.x); + Y.setValue(newPos.y); + requestPaint(); + purgeTouched(); //prevents "still touched after recompute" message + getPGroup()->purgeTouched(); //changing dpgi x,y marks parent dpg as touched } } @@ -203,15 +204,10 @@ DrawProjGroup* DrawProjGroupItem::getPGroup() const bool DrawProjGroupItem::isAnchor(void) const { - bool result = false; - auto group = getPGroup(); - if (group != nullptr) { - DrawProjGroupItem* anchor = group->getAnchor(); - if (anchor == this) { - result = true; - } + if (getPGroup() && (getPGroup()->getAnchor() == this) ) { + return true; } - return result; + return false; } /// get a coord system aligned with Direction and Rotation Vector @@ -253,11 +249,11 @@ Base::Vector3d DrawProjGroupItem::getXDirection(void) const // 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 != nullptr) { + if (prop) { Base::Vector3d propVal = XDirection.getValue(); if (DrawUtil::fpCompare(propVal.Length(), 0.0)) { //have XDirection property, but not set prop = getPropertyByName("RotationVector"); - if (prop != nullptr) { + if (prop) { result = RotationVector.getValue(); //use RotationVector if we have it } else { result = DrawViewPart::getXDirection(); //over complex. @@ -268,7 +264,7 @@ Base::Vector3d DrawProjGroupItem::getXDirection(void) const } else { //not sure this branch can actually happen Base::Console().Message("DPGI::getXDirection - unexpected branch taken!\n"); prop = getPropertyByName("RotationVector"); - if (prop != nullptr) { + if (prop) { result = RotationVector.getValue(); } else { @@ -285,7 +281,7 @@ Base::Vector3d DrawProjGroupItem::getLegacyX(const Base::Vector3d& pt, // Base::Console().Message("DPGI::getLegacyX() - %s\n", Label.getValue()); Base::Vector3d result(1.0, 0.0, 0.0); App::Property* prop = getPropertyByName("RotationVector"); - if (prop != nullptr) { + if (prop) { result = RotationVector.getValue(); if (DrawUtil::fpCompare(result.Length(), 0.0)) { //have RotationVector property, but not set gp_Ax2 va = getViewAxis(pt, @@ -336,7 +332,7 @@ double DrawProjGroupItem::getScale(void) const { double result = 1.0; auto pgroup = getPGroup(); - if (pgroup != nullptr) { + if (pgroup) { result = pgroup->getScale(); if (!(result > 0.0)) { Base::Console().Log("DPGI - %s - bad scale found (%.3f) using 1.0\n",getNameInDocument(),Scale.getValue()); @@ -348,16 +344,23 @@ double DrawProjGroupItem::getScale(void) const void DrawProjGroupItem::unsetupObject() { - if (getPGroup() != nullptr) { - if (getPGroup()->hasProjection(Type.getValueAsString()) ) { - if ((getPGroup()->getAnchor() == this) && - !getPGroup()->isUnsetting() ) { - 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 - } - } + if (!getPGroup()) { + DrawViewPart::unsetupObject(); + return; } + + if (!getPGroup()->hasProjection(Type.getValueAsString()) ) { + DrawViewPart::unsetupObject(); + return; + } + + if ( getPGroup()->getAnchor() == this && + !getPGroup()->isUnsetting() ) { + 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 + } + DrawViewPart::unsetupObject(); } @@ -365,7 +368,7 @@ void DrawProjGroupItem::unsetupObject() int DrawProjGroupItem::countParentPages() const { DrawProjGroup* dpg = getPGroup(); - if (dpg != nullptr) { + if (dpg) { int count = dpg->countParentPages(); return count; } @@ -375,7 +378,7 @@ int DrawProjGroupItem::countParentPages() const DrawPage* DrawProjGroupItem::findParentPage() const { DrawProjGroup* dpg = getPGroup(); - if (dpg != nullptr) { + if (dpg) { DrawPage* dp = dpg->findParentPage(); return dp; } @@ -385,7 +388,7 @@ DrawPage* DrawProjGroupItem::findParentPage() const std::vector DrawProjGroupItem::findAllParentPages() const { DrawProjGroup* dpg = getPGroup(); - if (dpg != nullptr) { + if (dpg) { std::vector dps = dpg->findAllParentPages(); return dps; } diff --git a/src/Mod/TechDraw/App/DrawProjGroupItem.h b/src/Mod/TechDraw/App/DrawProjGroupItem.h index 964c5dc693..390fb979c4 100644 --- a/src/Mod/TechDraw/App/DrawProjGroupItem.h +++ b/src/Mod/TechDraw/App/DrawProjGroupItem.h @@ -23,6 +23,8 @@ #ifndef _DrawProjGroupItem_h_ #define _DrawProjGroupItem_h_ +#include + #include #include @@ -45,7 +47,7 @@ enum ProjItemType{ Front, FrontTopRight, FrontBottomLeft, FrontBottomRight }; - + class DrawProjGroup; class TechDrawExport DrawProjGroupItem : public TechDraw::DrawViewPart @@ -55,50 +57,52 @@ class TechDrawExport DrawProjGroupItem : public TechDraw::DrawViewPart public: /// Constructor DrawProjGroupItem(); - virtual ~DrawProjGroupItem(); + ~DrawProjGroupItem() override; App::PropertyEnumeration Type; App::PropertyVector RotationVector; //this is superseded by dvp xdirection short mustExecute() const override; - virtual void onDocumentRestored() override; - virtual void unsetupObject() override; + void onDocumentRestored() override; + void unsetupObject() override; - DrawProjGroup* getPGroup(void) const; + void postHlrTasks(void) override; + + DrawProjGroup* getPGroup() const; double getRotateAngle(); - virtual Base::Vector3d getXDirection(void) const override; - virtual Base::Vector3d getLegacyX(const Base::Vector3d& pt, - const Base::Vector3d& axis, - const bool flip = true) const override; + Base::Vector3d getXDirection() const override; + Base::Vector3d getLegacyX(const Base::Vector3d& pt, + const Base::Vector3d& axis, + const bool flip = true) const override; - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual const char* getViewProviderName(void) const override { + App::DocumentObjectExecReturn *execute() override; + + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderProjGroupItem"; } //return PyObject as DrawProjGroupItemPy - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - //this doesn't override for dvp pointer?? - virtual gp_Ax2 getViewAxis(const Base::Vector3d& pt, - const Base::Vector3d& direction, - const bool flip=true) const override; + gp_Ax2 getViewAxis(const Base::Vector3d& pt, + const Base::Vector3d& direction, + const bool flip=true) const override; - virtual double getScale(void) const override; - void autoPosition(void); - bool isAnchor(void) const; + double getScale() const override; + void autoPosition(); + bool isAnchor() const; //DPGI always fits on page since DPG handles scaling - virtual bool checkFit(void) const override { return true; } - virtual bool checkFit(DrawPage*) const override { return true; } + bool checkFit() const override { return true; } + bool checkFit(DrawPage*) const override { return true; } - virtual int countParentPages() const override; - virtual DrawPage* findParentPage() const override; - virtual std::vector findAllParentPages() const override; + int countParentPages() const override; + DrawPage* findParentPage() const override; + std::vector findAllParentPages() const override; protected: void onChanged(const App::Property* prop) override; - virtual bool isLocked(void) const override; - virtual bool showLock(void) const override; + bool isLocked() const override; + bool showLock() const override; private: static const char* TypeEnums[]; diff --git a/src/Mod/TechDraw/App/DrawProjGroupItemPyImp.cpp b/src/Mod/TechDraw/App/DrawProjGroupItemPyImp.cpp index 661ed5b08b..1bb04e721e 100644 --- a/src/Mod/TechDraw/App/DrawProjGroupItemPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawProjGroupItemPyImp.cpp @@ -10,7 +10,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawProjGroupItemPy::representation(void) const +std::string DrawProjGroupItemPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawProjGroupPyImp.cpp b/src/Mod/TechDraw/App/DrawProjGroupPyImp.cpp index b61f33707c..57555c81d6 100644 --- a/src/Mod/TechDraw/App/DrawProjGroupPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawProjGroupPyImp.cpp @@ -37,7 +37,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawProjGroupPy::representation(void) const +std::string DrawProjGroupPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawProjectSplit.cpp b/src/Mod/TechDraw/App/DrawProjectSplit.cpp index 3b35c6b294..e5a78a7942 100644 --- a/src/Mod/TechDraw/App/DrawProjectSplit.cpp +++ b/src/Mod/TechDraw/App/DrawProjectSplit.cpp @@ -446,7 +446,7 @@ std::vector DrawProjectSplit::removeDuplicateEdges(std::vector DrawProjectSplit::sortEdges(std::vector& //************************* //* edgeSortItem Methods //************************* -std::string edgeSortItem::dump(void) +std::string edgeSortItem::dump() { std::string result; std::stringstream builder; diff --git a/src/Mod/TechDraw/App/DrawProjectSplit.h b/src/Mod/TechDraw/App/DrawProjectSplit.h index fc550a7777..668f0e6d17 100644 --- a/src/Mod/TechDraw/App/DrawProjectSplit.h +++ b/src/Mod/TechDraw/App/DrawProjectSplit.h @@ -23,6 +23,8 @@ #ifndef _DrawProjectSplit_h_ #define _DrawProjectSplit_h_ +#include + #include #include @@ -65,7 +67,7 @@ public: static bool edgeLess(const edgeSortItem& e1, const edgeSortItem& e2); static bool edgeEqual(const edgeSortItem& e1, const edgeSortItem& e2); - std::string dump(void); + std::string dump(); }; class TechDrawExport DrawProjectSplit { diff --git a/src/Mod/TechDraw/App/DrawRichAnno.cpp b/src/Mod/TechDraw/App/DrawRichAnno.cpp index 58d52f6091..fb7aa68cdf 100644 --- a/src/Mod/TechDraw/App/DrawRichAnno.cpp +++ b/src/Mod/TechDraw/App/DrawRichAnno.cpp @@ -43,7 +43,7 @@ using namespace TechDraw; PROPERTY_SOURCE(TechDraw::DrawRichAnno, TechDraw::DrawView) -DrawRichAnno::DrawRichAnno(void) +DrawRichAnno::DrawRichAnno() { static const char *group = "Text Block"; @@ -71,48 +71,59 @@ void DrawRichAnno::onChanged(const App::Property* prop) requestPaint(); } } + DrawView::onChanged(prop); } +//NOTE: DocumentObject::mustExecute returns 1/0 and not true/false short DrawRichAnno::mustExecute() const { - bool result = 0; if (!isRestoring()) { - result = (AnnoText.isTouched()); - } - if (result) { - return result; + if (AnnoText.isTouched() || + AnnoParent.isTouched()) { + return 1; + } } return DrawView::mustExecute(); } -App::DocumentObjectExecReturn *DrawRichAnno::execute(void) +App::DocumentObjectExecReturn *DrawRichAnno::execute() { // Base::Console().Message("DRA::execute() - @ (%.3f, %.3f)\n", X.getValue(), Y.getValue()); if (!keepUpdated()) { return App::DocumentObject::StdReturn; } + overrideKeepUpdated(false); return DrawView::execute(); } -DrawView* DrawRichAnno::getBaseView(void) const +DrawView* DrawRichAnno::getBaseView() const { // Base::Console().Message("DRA::getBaseView() - %s\n", getNameInDocument()); - DrawView* result = nullptr; - App::DocumentObject* baseObj = AnnoParent.getValue(); - if (baseObj != nullptr) { - DrawView* cast = dynamic_cast(baseObj); - if (cast != nullptr) { - result = cast; - } - } - return result; + return dynamic_cast(AnnoParent.getValue()); } +//finds the first DrawPage in this Document that claims to own this DrawRichAnno +//note that it is possible to manipulate the Views property of DrawPage so that +//more than 1 DrawPage claims a DrawRichAnno. +DrawPage* DrawRichAnno::findParentPage() const +{ +// Base::Console().Message("DRA::findParentPage()\n"); + if (!AnnoParent.getValue()) { + return DrawView::findParentPage(); + } -PyObject *DrawRichAnno::getPyObject(void) + DrawView* parent = dynamic_cast(AnnoParent.getValue()); + if (parent) { + return parent->findParentPage(); + } + + return nullptr; +} + +PyObject *DrawRichAnno::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -126,7 +137,7 @@ PyObject *DrawRichAnno::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawRichAnnoPython, TechDraw::DrawRichAnno) -template<> const char* TechDraw::DrawRichAnnoPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawRichAnnoPython::getViewProviderName() const { return "TechDrawGui::ViewProviderRichAnno"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawRichAnno.h b/src/Mod/TechDraw/App/DrawRichAnno.h index 1562783aa1..aeb11ba5a4 100644 --- a/src/Mod/TechDraw/App/DrawRichAnno.h +++ b/src/Mod/TechDraw/App/DrawRichAnno.h @@ -23,40 +23,43 @@ #ifndef _TechDraw_DrawRichAnno_h_ #define _TechDraw_DrawRichAnno_h_ +#include + # include # include #include "DrawView.h" - namespace TechDraw { class TechDrawExport DrawRichAnno : public TechDraw::DrawView { - PROPERTY_HEADER(TechDraw::DrawRichAnno); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawRichAnno); public: DrawRichAnno(); - virtual ~DrawRichAnno(); + ~DrawRichAnno() override; App::PropertyLink AnnoParent; App::PropertyString AnnoText; App::PropertyBool ShowFrame; App::PropertyFloat MaxWidth; - virtual short mustExecute() const; - virtual App::DocumentObjectExecReturn *execute(void); + short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderRichAnno"; } - virtual PyObject *getPyObject(void); - virtual QRectF getRect() const { return QRectF(0,0,1,1);} - DrawView* getBaseView(void) const; + PyObject *getPyObject() override; + QRectF getRect() const override { return QRectF(0,0,1,1);} + DrawView* getBaseView() const; + + DrawPage* findParentPage() const override; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: }; diff --git a/src/Mod/TechDraw/App/DrawRichAnnoPyImp.cpp b/src/Mod/TechDraw/App/DrawRichAnnoPyImp.cpp index 3897903f88..34920a8f64 100644 --- a/src/Mod/TechDraw/App/DrawRichAnnoPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawRichAnnoPyImp.cpp @@ -38,7 +38,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawRichAnnoPy::representation(void) const +std::string DrawRichAnnoPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawSVGTemplate.cpp b/src/Mod/TechDraw/App/DrawSVGTemplate.cpp index 3a78e202f4..ab79410fce 100644 --- a/src/Mod/TechDraw/App/DrawSVGTemplate.cpp +++ b/src/Mod/TechDraw/App/DrawSVGTemplate.cpp @@ -85,7 +85,7 @@ DrawSVGTemplate::~DrawSVGTemplate() { } -PyObject *DrawSVGTemplate::getPyObject(void) +PyObject *DrawSVGTemplate::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -94,7 +94,7 @@ PyObject *DrawSVGTemplate::getPyObject(void) return Py::new_reference_to(PythonObject); } -unsigned int DrawSVGTemplate::getMemSize(void) const +unsigned int DrawSVGTemplate::getMemSize() const { return 0; } @@ -132,7 +132,7 @@ void DrawSVGTemplate::onChanged(const App::Property* prop) TechDraw::DrawTemplate::onChanged(prop); } -App::DocumentObjectExecReturn * DrawSVGTemplate::execute(void) +App::DocumentObjectExecReturn * DrawSVGTemplate::execute() { std::string templateFilename = Template.getValue(); if (templateFilename.empty()) @@ -330,7 +330,7 @@ std::map DrawSVGTemplate::getEditableTextsFromTemplate namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawSVGTemplatePython, TechDraw::DrawSVGTemplate) -template<> const char* TechDraw::DrawSVGTemplatePython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawSVGTemplatePython::getViewProviderName() const { return "TechDrawGui::ViewProviderPython"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawSVGTemplate.h b/src/Mod/TechDraw/App/DrawSVGTemplate.h index 0d018976a2..bafa365dc5 100644 --- a/src/Mod/TechDraw/App/DrawSVGTemplate.h +++ b/src/Mod/TechDraw/App/DrawSVGTemplate.h @@ -22,6 +22,8 @@ #ifndef _TECHDRAW_DrawSVGTemplate_h_ #define _TECHDRAW_DrawSVGTemplate_h_ + +#include #include #include diff --git a/src/Mod/TechDraw/App/DrawSVGTemplatePyImp.cpp b/src/Mod/TechDraw/App/DrawSVGTemplatePyImp.cpp index 15bd483952..f7885a9ea0 100644 --- a/src/Mod/TechDraw/App/DrawSVGTemplatePyImp.cpp +++ b/src/Mod/TechDraw/App/DrawSVGTemplatePyImp.cpp @@ -31,7 +31,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawSVGTemplatePy::representation(void) const +std::string DrawSVGTemplatePy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawTemplate.cpp b/src/Mod/TechDraw/App/DrawTemplate.cpp index bbd17b98ce..6e28a5bd3c 100644 --- a/src/Mod/TechDraw/App/DrawTemplate.cpp +++ b/src/Mod/TechDraw/App/DrawTemplate.cpp @@ -52,7 +52,7 @@ const char* DrawTemplate::OrientationEnums[]= {"Portrait", -DrawTemplate::DrawTemplate(void) +DrawTemplate::DrawTemplate() { const char *group = "Page Properties"; @@ -74,7 +74,7 @@ DrawTemplate::~DrawTemplate() } -PyObject *DrawTemplate::getPyObject(void) +PyObject *DrawTemplate::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -83,7 +83,7 @@ PyObject *DrawTemplate::getPyObject(void) return Py::new_reference_to(PythonObject); } -unsigned int DrawTemplate::getMemSize(void) const +unsigned int DrawTemplate::getMemSize() const { return 0; } @@ -109,7 +109,7 @@ void DrawTemplate::onChanged(const App::Property* prop) App::DocumentObject::onChanged(prop); } -App::DocumentObjectExecReturn *DrawTemplate::execute(void) +App::DocumentObjectExecReturn *DrawTemplate::execute() { DrawPage *page = nullptr; std::vector parent = getInList(); @@ -143,7 +143,7 @@ DrawPage* DrawTemplate::getParentPage() const namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawTemplatePython, TechDraw::DrawTemplate) -template<> const char* TechDraw::DrawTemplatePython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawTemplatePython::getViewProviderName() const { return "TechDrawGui::ViewProviderPython"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawTemplate.h b/src/Mod/TechDraw/App/DrawTemplate.h index 171131dd55..53f5679e7f 100644 --- a/src/Mod/TechDraw/App/DrawTemplate.h +++ b/src/Mod/TechDraw/App/DrawTemplate.h @@ -22,6 +22,8 @@ #ifndef _TECHDRAW_DrawTemplate_h_ #define _TECHDRAW_DrawTemplate_h_ + +#include #include #include diff --git a/src/Mod/TechDraw/App/DrawTemplatePyImp.cpp b/src/Mod/TechDraw/App/DrawTemplatePyImp.cpp index bdc53afe9a..219eaf5010 100644 --- a/src/Mod/TechDraw/App/DrawTemplatePyImp.cpp +++ b/src/Mod/TechDraw/App/DrawTemplatePyImp.cpp @@ -34,7 +34,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawTemplatePy::representation(void) const +std::string DrawTemplatePy::representation() const { return ""; } diff --git a/src/Mod/TechDraw/App/DrawTile.cpp b/src/Mod/TechDraw/App/DrawTile.cpp index f492cad0c7..b93b663061 100644 --- a/src/Mod/TechDraw/App/DrawTile.cpp +++ b/src/Mod/TechDraw/App/DrawTile.cpp @@ -43,7 +43,7 @@ using namespace TechDraw; PROPERTY_SOURCE(TechDraw::DrawTile, App::DocumentObject) -DrawTile::DrawTile(void) +DrawTile::DrawTile() { static const char *group = "Tile"; @@ -80,7 +80,7 @@ short DrawTile::mustExecute() const return DocumentObject::mustExecute(); } -App::DocumentObjectExecReturn *DrawTile::execute(void) +App::DocumentObjectExecReturn *DrawTile::execute() { // Base::Console().Message("DT::execute()\n"); return DocumentObject::execute(); @@ -98,21 +98,13 @@ void DrawTile::handleChangedPropertyType(Base::XMLReader &reader, const char *Ty } } -DrawView* DrawTile::getParent(void) const +DrawView* DrawTile::getParent() const { // Base::Console().Message("DT::getParent() - %s\n", getNameInDocument()); - DrawView* result = nullptr; - App::DocumentObject* baseObj = TileParent.getValue(); - if (baseObj != nullptr) { - DrawView* cast = dynamic_cast(baseObj); - if (cast != nullptr) { - result = cast; - } - } - return result; + return dynamic_cast(TileParent.getValue()); } -PyObject *DrawTile::getPyObject(void) +PyObject *DrawTile::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -126,7 +118,7 @@ PyObject *DrawTile::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawTilePython, TechDraw::DrawTile) -template<> const char* TechDraw::DrawTilePython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawTilePython::getViewProviderName() const { return "TechDrawGui::ViewProviderTile"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawTile.h b/src/Mod/TechDraw/App/DrawTile.h index 221a35782d..8112e1c56e 100644 --- a/src/Mod/TechDraw/App/DrawTile.h +++ b/src/Mod/TechDraw/App/DrawTile.h @@ -22,6 +22,8 @@ #ifndef _TechDraw_DrawTile_h_ #define _TechDraw_DrawTile_h_ + +#include # include # include @@ -33,29 +35,29 @@ namespace TechDraw class TechDrawExport DrawTile : public App::DocumentObject { - PROPERTY_HEADER(TechDraw::DrawTile); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawTile); public: DrawTile(); - virtual ~DrawTile(); + ~DrawTile() override; App::PropertyLink TileParent; //eg DrawWeldSymbol App::PropertyIntegerConstraint TileRow; App::PropertyIntegerConstraint::Constraints TileRowConstraints; App::PropertyInteger TileColumn; - virtual short mustExecute() const; - virtual App::DocumentObjectExecReturn *execute(void); + short mustExecute() const override; + App::DocumentObjectExecReturn *execute(void) override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName(void) const override { return "TechDrawGui::ViewProviderTile"; } - virtual PyObject *getPyObject(void); + PyObject *getPyObject(void) override; virtual DrawView* getParent(void) const; protected: - virtual void onChanged(const App::Property* prop); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + void onChanged(const App::Property* prop) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; private: }; diff --git a/src/Mod/TechDraw/App/DrawTilePyImp.cpp b/src/Mod/TechDraw/App/DrawTilePyImp.cpp index a5048328d3..04f1b7b758 100644 --- a/src/Mod/TechDraw/App/DrawTilePyImp.cpp +++ b/src/Mod/TechDraw/App/DrawTilePyImp.cpp @@ -38,7 +38,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawTilePy::representation(void) const +std::string DrawTilePy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawTileWeld.cpp b/src/Mod/TechDraw/App/DrawTileWeld.cpp index 2982fe3fa0..5badce1767 100644 --- a/src/Mod/TechDraw/App/DrawTileWeld.cpp +++ b/src/Mod/TechDraw/App/DrawTileWeld.cpp @@ -48,7 +48,7 @@ using namespace TechDraw; PROPERTY_SOURCE(TechDraw::DrawTileWeld, TechDraw::DrawTile) -DrawTileWeld::DrawTileWeld(void) +DrawTileWeld::DrawTileWeld() { static const char *group = "TileWeld"; @@ -74,8 +74,7 @@ void DrawTileWeld::onChanged(const App::Property* prop) { if (!isRestoring()) { App::Document* doc = getDocument(); - if ((prop == &SymbolFile) && - (doc != nullptr) ) { + if ((prop == &SymbolFile) && doc) { if (!SymbolFile.isEmpty()) { Base::FileInfo fi(SymbolFile.getValue()); if (fi.isReadable()) { @@ -93,7 +92,7 @@ short DrawTileWeld::mustExecute() const return DrawTile::mustExecute(); } -App::DocumentObjectExecReturn *DrawTileWeld::execute(void) +App::DocumentObjectExecReturn *DrawTileWeld::execute() { // Base::Console().Message("DTW::execute()\n"); return DrawTile::execute(); @@ -136,7 +135,7 @@ void DrawTileWeld::setupObject() DrawTile::setupObject(); } -void DrawTileWeld::setupSymbolIncluded(void) +void DrawTileWeld::setupSymbolIncluded() { // Base::Console().Message("DTW::setupSymbolIncluded()\n"); App::Document* doc = getDocument(); @@ -162,14 +161,14 @@ void DrawTileWeld::setupSymbolIncluded(void) } //standard preference getter (really a default in this case) -std::string DrawTileWeld::prefSymbol(void) +std::string DrawTileWeld::prefSymbol() { std::string defaultDir = App::Application::getResourceDir() + "Mod/TechDraw/Symbols/Welding/"; std::string defaultFileName = defaultDir + "blankTile.svg"; return defaultFileName; } -PyObject *DrawTileWeld::getPyObject(void) +PyObject *DrawTileWeld::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -183,7 +182,7 @@ PyObject *DrawTileWeld::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawTileWeldPython, TechDraw::DrawTileWeld) -template<> const char* TechDraw::DrawTileWeldPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawTileWeldPython::getViewProviderName() const { return "TechDrawGui::ViewProviderTile"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawTileWeld.h b/src/Mod/TechDraw/App/DrawTileWeld.h index 90435aafdd..206f7c37fb 100644 --- a/src/Mod/TechDraw/App/DrawTileWeld.h +++ b/src/Mod/TechDraw/App/DrawTileWeld.h @@ -22,6 +22,8 @@ #ifndef _TechDraw_DrawTileWeld_h_ #define _TechDraw_DrawTileWeld_h_ + +#include #include #include @@ -36,11 +38,11 @@ namespace TechDraw class TechDrawExport DrawTileWeld : public TechDraw::DrawTile { - PROPERTY_HEADER(TechDraw::DrawTileWeld); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawTileWeld); public: DrawTileWeld(); - virtual ~DrawTileWeld(); + ~DrawTileWeld() override; App::PropertyString LeftText; App::PropertyString RightText; @@ -48,25 +50,25 @@ public: App::PropertyFile SymbolFile; App::PropertyFileIncluded SymbolIncluded; - virtual short mustExecute() const; - virtual App::DocumentObjectExecReturn *execute(void); - virtual void onDocumentRestored(); - virtual void setupObject(); + short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; + void onDocumentRestored() override; + void setupObject() override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderTile"; } - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; virtual QRectF getRect() const { return QRectF(0,0,1,1);} void replaceSymbolIncluded(std::string newSymbolFile); - void setupSymbolIncluded(void); + void setupSymbolIncluded(); // void replaceSymbol(std::string newSymbolFile); - std::string prefSymbol(void); + std::string prefSymbol(); protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: }; diff --git a/src/Mod/TechDraw/App/DrawUtil.cpp b/src/Mod/TechDraw/App/DrawUtil.cpp index 2fabb84ff1..b5f8a825d9 100644 --- a/src/Mod/TechDraw/App/DrawUtil.cpp +++ b/src/Mod/TechDraw/App/DrawUtil.cpp @@ -67,7 +67,9 @@ #include #include #include +#include #include +#include #include #include @@ -82,52 +84,53 @@ using namespace TechDraw; /*static*/ int DrawUtil::getIndexFromName(std::string geomName) { // 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; + boost::regex re("\\d+$"); // one of more digits at end of string + boost::match_results what; + boost::match_flag_type flags = boost::match_default; // char* endChar; - std::string::const_iterator begin = geomName.begin(); - auto pos = geomName.rfind('.'); - if(pos!=std::string::npos) - begin += pos+1; - std::string::const_iterator end = geomName.end(); - std::stringstream ErrorMsg; + std::string::const_iterator begin = geomName.begin(); + auto pos = geomName.rfind('.'); + if(pos!=std::string::npos) + begin += pos+1; + std::string::const_iterator end = geomName.end(); + std::stringstream ErrorMsg; - if (!geomName.empty()) { - if (boost::regex_search(begin, end, what, re, flags)) { - return int (std::stoi(what.str())); - } else { - ErrorMsg << "getIndexFromName: malformed geometry name - " << geomName; - throw Base::ValueError(ErrorMsg.str()); - } - } else { - Base::Console().Log("DU::getIndexFromName(%s) - empty geometry name\n",geomName.c_str()); - throw Base::ValueError("getIndexFromName - empty geometry name"); - } + if (geomName.empty()) { + Base::Console().Log("DU::getIndexFromName(%s) - empty geometry name\n",geomName.c_str()); + throw Base::ValueError("getIndexFromName - empty geometry name"); + } + + + if (boost::regex_search(begin, end, what, re, flags)) { + return int (std::stoi(what.str())); + } else { + ErrorMsg << "getIndexFromName: malformed geometry name - " << geomName; + throw Base::ValueError(ErrorMsg.str()); + } } std::string DrawUtil::getGeomTypeFromName(std::string geomName) { - boost::regex re("^[a-zA-Z]*"); //one or more letters at start of string - boost::match_results what; - boost::match_flag_type flags = boost::match_default; - std::string::const_iterator begin = geomName.begin(); - auto pos = geomName.rfind('.'); - if(pos!=std::string::npos) - begin += pos+1; - std::string::const_iterator end = geomName.end(); - std::stringstream ErrorMsg; + boost::regex re("^[a-zA-Z]*"); //one or more letters at start of string + boost::match_results what; + boost::match_flag_type flags = boost::match_default; + std::string::const_iterator begin = geomName.begin(); + auto pos = geomName.rfind('.'); + if(pos!=std::string::npos) + begin += pos+1; + std::string::const_iterator end = geomName.end(); + std::stringstream ErrorMsg; - if (!geomName.empty()) { - if (boost::regex_search(begin, end, what, re, flags)) { - return what.str(); //TODO: use std::stoi() in c++11 - } else { - ErrorMsg << "In getGeomTypeFromName: malformed geometry name - " << geomName; - throw Base::ValueError(ErrorMsg.str()); - } - } else { - throw Base::ValueError("getGeomTypeFromName - empty geometry name"); - } + if (geomName.empty()) { + throw Base::ValueError("getGeomTypeFromName - empty geometry name"); + } + + if (boost::regex_search(begin, end, what, re, flags)) { + return what.str(); //TODO: use std::stoi() in c++11 + } else { + ErrorMsg << "In getGeomTypeFromName: malformed geometry name - " << geomName; + throw Base::ValueError(ErrorMsg.str()); + } } std::string DrawUtil::makeGeomName(std::string geomType, int index) @@ -140,35 +143,31 @@ std::string DrawUtil::makeGeomName(std::string geomType, int index) //! true if v1 and v2 are the same geometric point within tolerance bool DrawUtil::isSamePoint(TopoDS_Vertex v1, TopoDS_Vertex v2, double tolerance) { - bool result = false; gp_Pnt p1 = BRep_Tool::Pnt(v1); gp_Pnt p2 = BRep_Tool::Pnt(v2); if (p1.IsEqual(p2,tolerance)) { - result = true; + return true; } - return result; + return false; } bool DrawUtil::isZeroEdge(TopoDS_Edge e, double tolerance) { TopoDS_Vertex vStart = TopExp::FirstVertex(e); TopoDS_Vertex vEnd = TopExp::LastVertex(e); - bool result = isSamePoint(vStart,vEnd, tolerance); - if (result) { + if (isSamePoint(vStart,vEnd, tolerance)) { //closed edge will have same V's but non-zero length GProp_GProps props; BRepGProp::LinearProperties(e, props); double len = props.Mass(); if (len > tolerance) { - result = false; + return false; } } - return result; + return false; } double DrawUtil::simpleMinDist(TopoDS_Shape s1, TopoDS_Shape s2) { - Standard_Real minDist = -1; - BRepExtrema_DistShapeShape extss(s1, s2); if (!extss.IsDone()) { Base::Console().Message("DU::simpleMinDist - BRepExtrema_DistShapeShape failed"); @@ -176,18 +175,16 @@ double DrawUtil::simpleMinDist(TopoDS_Shape s1, TopoDS_Shape s2) } int count = extss.NbSolution(); if (count != 0) { - minDist = extss.Value(); + return extss.Value(); } else { - minDist = -1; + return -1; } - return minDist; } //! assumes 2d on XY //! quick angle for straight edges double DrawUtil::angleWithX(TopoDS_Edge e, bool reverse) { - double result = 0; gp_Pnt gstart = BRep_Tool::Pnt(TopExp::FirstVertex(e)); Base::Vector3d start(gstart.X(),gstart.Y(),gstart.Z()); gp_Pnt gend = BRep_Tool::Pnt(TopExp::LastVertex(e)); @@ -198,7 +195,7 @@ double DrawUtil::angleWithX(TopoDS_Edge e, bool reverse) } else { u = end - start; } - result = atan2(u.y,u.x); + double result = atan2(u.y,u.x); if (result < 0) { result += 2.0 * M_PI; } @@ -209,7 +206,6 @@ double DrawUtil::angleWithX(TopoDS_Edge e, bool reverse) //! find angle of edge with x-Axis at First/LastVertex double DrawUtil::angleWithX(TopoDS_Edge e, TopoDS_Vertex v, double tolerance) { - double result = 0; double param = 0; //find tangent @ v @@ -248,7 +244,7 @@ double DrawUtil::angleWithX(TopoDS_Edge e, TopoDS_Vertex v, double tolerance) //throw ?????? } } - result = atan2(uVec.y,uVec.x); + double result = atan2(uVec.y,uVec.x); if (result < 0) { //map from [-PI:PI] to [0:2PI] result += 2.0 * M_PI; } @@ -257,31 +253,28 @@ double DrawUtil::angleWithX(TopoDS_Edge e, TopoDS_Vertex v, double tolerance) bool DrawUtil::isFirstVert(TopoDS_Edge e, TopoDS_Vertex v, double tolerance) { - bool result = false; TopoDS_Vertex first = TopExp::FirstVertex(e); if (isSamePoint(first,v, tolerance)) { - result = true; + return true; } - return result; + return false; } bool DrawUtil::isLastVert(TopoDS_Edge e, TopoDS_Vertex v, double tolerance) { - bool result = false; TopoDS_Vertex last = TopExp::LastVertex(e); if (isSamePoint(last,v, tolerance)) { - result = true; + return true; } - return result; + return false; } bool DrawUtil::fpCompare(const double& d1, const double& d2, double tolerance) { - bool result = false; if (std::fabs(d1 - d2) < tolerance) { - result = true; + return true; } - return result; + return false; } //brute force intersection points of line(point, dir) with box(xRange, yRange) @@ -348,106 +341,89 @@ std::pair DrawUtil::boxIntersect2d(Base::Vector3 Base::Vector3d DrawUtil::vertex2Vector(const TopoDS_Vertex& v) { gp_Pnt gp = BRep_Tool::Pnt(v); - Base::Vector3d result(gp.X(),gp.Y(),gp.Z()); - return result; + return Base::Vector3d(gp.X(),gp.Y(),gp.Z()); } std::string DrawUtil::formatVector(const Base::Vector3d& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.x << "," << v.y << "," << v.z << ") "; // builder << " (" << setw(6) << v.x << "," << setw(6) << v.y << "," << setw(6) << v.z << ") "; - result = builder.str(); - return result; + return builder.str(); } std::string DrawUtil::formatVector(const gp_Dir& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.X() << "," << v.Y() << "," << v.Z() << ") "; - result = builder.str(); - return result; + return builder.str(); } std::string DrawUtil::formatVector(const gp_Dir2d& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.X() << "," << v.Y() << ") "; - result = builder.str(); - return result; + return builder.str(); } std::string DrawUtil::formatVector(const gp_Vec& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.X() << "," << v.Y() << "," << v.Z() << ") "; - result = builder.str(); - return result; + return builder.str(); } std::string DrawUtil::formatVector(const gp_Pnt& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.X() << "," << v.Y() << "," << v.Z() << ") "; - result = builder.str(); - return result; + return builder.str(); } std::string DrawUtil::formatVector(const gp_Pnt2d& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.X() << "," << v.Y() << ") "; - result = builder.str(); - return result; + return builder.str(); } std::string DrawUtil::formatVector(const QPointF& v) { - std::string result; std::stringstream builder; builder << std::fixed << std::setprecision(3) ; builder << " (" << v.x() << "," << v.y() << ") "; - result = builder.str(); - return result; + return builder.str(); } //! compare 2 vectors for sorting - true if v1 < v2 bool DrawUtil::vectorLess(const Base::Vector3d& v1, const Base::Vector3d& v2) { - bool result = false; if ((v1 - v2).Length() > Precision::Confusion()) { //ie v1 != v2 if (!DrawUtil::fpCompare(v1.x,v2.x)) { - result = v1.x < v2.x; + return v1.x < v2.x; } else if (!DrawUtil::fpCompare(v1.y,v2.y)) { - result = v1.y < v2.y; + return v1.y < v2.y; } else { - result = v1.z < v2.z; + return v1.z < v2.z; } } - return result; + return false; } //!convert fromPoint in coordinate system fromSystem to reference coordinate system Base::Vector3d DrawUtil::toR3(const gp_Ax2& fromSystem, const Base::Vector3d& fromPoint) { gp_Pnt gFromPoint(fromPoint.x,fromPoint.y,fromPoint.z); - gp_Pnt gToPoint; gp_Trsf T; gp_Ax3 gRef; gp_Ax3 gFrom(fromSystem); T.SetTransformation (gFrom, gRef); - gToPoint = gFromPoint.Transformed(T); + gp_Pnt gToPoint = gFromPoint.Transformed(T); Base::Vector3d toPoint(gToPoint.X(),gToPoint.Y(),gToPoint.Z()); return toPoint; } @@ -455,13 +431,12 @@ Base::Vector3d DrawUtil::toR3(const gp_Ax2& fromSystem, const Base::Vector3d& fr //! check if two vectors are parallel. Vectors don't have to be unit vectors bool DrawUtil::checkParallel(const Base::Vector3d v1, Base::Vector3d v2, double tolerance) { - bool result = false; double dot = fabs(v1.Dot(v2)); double mag = v1.Length() * v2.Length(); if (DrawUtil::fpCompare(dot,mag,tolerance)) { - result = true; + return true; } - return result; + return false; } //! rotate vector by angle radians around axis through org @@ -470,11 +445,9 @@ Base::Vector3d DrawUtil::vecRotate(Base::Vector3d vec, Base::Vector3d axis, Base::Vector3d org) { - Base::Vector3d result; Base::Matrix4D xForm; xForm.rotLine(org,axis,angle); - result = xForm * (vec); - return result; + return Base::Vector3d(xForm * (vec)); } Base::Vector3d DrawUtil::closestBasis(Base::Vector3d v) @@ -486,18 +459,16 @@ Base::Vector3d DrawUtil::closestBasis(Base::Vector3d v) Base::Vector3d stdXr(-1.0,0.0,0.0); Base::Vector3d stdYr(0.0,-1.0,0.0); Base::Vector3d stdZr(0.0,0.0,-1.0); - double angleX,angleY,angleZ,angleXr,angleYr,angleZr, angleMin; //first check if already a basis - if (checkParallel(v,stdZ)) { - return v; - } else if (checkParallel(v,stdY)) { - return v; - } else if (checkParallel(v,stdX)) { + if (checkParallel(v,stdZ) || + checkParallel(v,stdY) || + checkParallel(v,stdX)) { return v; } //not a basis. find smallest angle with a basis. + double angleX,angleY,angleZ,angleXr,angleYr,angleZr, angleMin; angleX = stdX.GetAngle(v); angleY = stdY.GetAngle(v); angleZ = stdZ.GetAngle(v); @@ -506,36 +477,29 @@ Base::Vector3d DrawUtil::closestBasis(Base::Vector3d v) angleZr = stdZr.GetAngle(v); angleMin = angleX; - result = stdX; if (angleY < angleMin) { - angleMin = angleY; - result = stdY; + return stdY; } if (angleZ < angleMin) { - angleMin = angleZ; - result = stdZ; + return stdZ; } if (angleXr < angleMin) { - angleMin = angleXr; - result = stdXr; + return stdXr; } if (angleYr < angleMin) { - angleMin = angleYr; - result = stdYr; + return stdYr; } if (angleZr < angleMin) { - angleMin = angleZr; - result = stdZr; + return stdZr; } - return result; + return stdX; } //based on Function provided by Joe Dowsett, 2014 double DrawUtil::sensibleScale(double working_scale) { - double result = 1.0; if (!(working_scale > 0.0)) { - return result; + return 1.0; } //which gives the largest scale for which the min_space requirements can be met, but we want a 'sensible' scale, rather than 0.28457239... //eg if working_scale = 0.115, then we want to use 0.1, similarly 7.65 -> 5, and 76.5 -> 50 @@ -555,36 +519,28 @@ double DrawUtil::sensibleScale(double working_scale) i -= 1; //choosing top list if exponent -ve, bottom list for +ve exponent //now have the appropriate scale, reapply the *10^b - result = valid_scales[(exponent >= 0)][i] * pow(10, exponent); - return result; + return valid_scales[(exponent >= 0)][i] * pow(10, exponent); } double DrawUtil::getDefaultLineWeight(std::string lineType) { - int lgNumber = Preferences::lineGroup(); - auto lg = LineGroup::lineGroupFactory(lgNumber); - - double weight = lg->getWeight(lineType); - delete lg; //Coverity CID 174671 - return weight; + return TechDraw::LineGroup::getDefaultWidth(lineType); } bool DrawUtil::isBetween(const Base::Vector3d pt, const Base::Vector3d end1, const Base::Vector3d end2) { - bool result = false; double segLength = (end2 - end1).Length(); double l1 = (pt - end1).Length(); double l2 = (pt - end2).Length(); if (fpCompare(segLength,l1 + l2)) { - result = true; + return true; } - return result; + return false; } Base::Vector3d DrawUtil::Intersect2d(Base::Vector3d p1, Base::Vector3d d1, Base::Vector3d p2, Base::Vector3d d2) { - Base::Vector3d result(0.0, 0.0, 0.0); Base::Vector3d p12(p1.x+d1.x, p1.y+d1.y, 0.0); double A1 = d1.y; double B1 = -d1.x; @@ -598,20 +554,17 @@ Base::Vector3d DrawUtil::Intersect2d(Base::Vector3d p1, Base::Vector3d d1, double det = A1*B2 - A2*B1; if (fpCompare(det, 0.0, Precision::Confusion())) { Base::Console().Message("Lines are parallel\n"); - } else { - double x = (B2*C1 - B1*C2)/det; - double y = (A1*C2 - A2*C1)/det; - result.x = x; - result.y = y; + return Base::Vector3d(0.0, 0.0, 0.0); } - return result; + double x = (B2*C1 - B1*C2)/det; + double y = (A1*C2 - A2*C1)/det; + return Base::Vector3d(x, y, 0.0); } Base::Vector2d DrawUtil::Intersect2d(Base::Vector2d p1, Base::Vector2d d1, Base::Vector2d p2, Base::Vector2d d2) { - Base::Vector2d result(0.0, 0.0); Base::Vector2d p12(p1.x+d1.x, p1.y+d1.y); double A1 = d1.y; double B1 = -d1.x; @@ -625,14 +578,12 @@ Base::Vector2d DrawUtil::Intersect2d(Base::Vector2d p1, Base::Vector2d d1, double det = A1*B2 - A2*B1; if (fpCompare(det, 0.0, Precision::Confusion())) { Base::Console().Message("Lines are parallel\n"); - }else{ - double x = (B2*C1 - B1*C2)/det; - double y = (A1*C2 - A2*C1)/det; - result.x = x; - result.y = y; + return Base::Vector2d(0.0, 0.0); } - return result; + double x = (B2*C1 - B1*C2)/det; + double y = (A1*C2 - A2*C1)/det; + return Base::Vector2d(x, y); } @@ -654,14 +605,12 @@ TopoDS_Shape DrawUtil::shapeFromString(std::string s) Base::Vector3d DrawUtil::invertY(Base::Vector3d v) { - Base::Vector3d result(v.x, -v.y, v.z); - return result; + return Base::Vector3d (v.x, -v.y, v.z); } QPointF DrawUtil::invertY(QPointF v) { - QPointF result(v.x(), -v.y()); - return result; + return QPointF(v.x(), -v.y()); } @@ -701,24 +650,24 @@ App::Color DrawUtil::pyTupleToColor(PyObject* pColor) { // Base::Console().Message("DU::pyTupleToColor()\n"); double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; - App::Color c(red, green, blue, alpha); - if (PyTuple_Check(pColor)) { - int tSize = (int) PyTuple_Size(pColor); - if (tSize > 2) { - PyObject* pRed = PyTuple_GetItem(pColor,0); - red = PyFloat_AsDouble(pRed); - PyObject* pGreen = PyTuple_GetItem(pColor,1); - green = PyFloat_AsDouble(pGreen); - PyObject* pBlue = PyTuple_GetItem(pColor,2); - blue = PyFloat_AsDouble(pBlue); - } - if (tSize > 3) { - PyObject* pAlpha = PyTuple_GetItem(pColor,3); - alpha = PyFloat_AsDouble(pAlpha); - } - c = App::Color(red, green, blue, alpha); + if (!PyTuple_Check(pColor)) { + return App::Color(red, green, blue, alpha); } - return c; + + int tSize = (int) PyTuple_Size(pColor); + if (tSize > 2) { + PyObject* pRed = PyTuple_GetItem(pColor,0); + red = PyFloat_AsDouble(pRed); + PyObject* pGreen = PyTuple_GetItem(pColor,1); + green = PyFloat_AsDouble(pGreen); + PyObject* pBlue = PyTuple_GetItem(pColor,2); + blue = PyFloat_AsDouble(pBlue); + } + if (tSize > 3) { + PyObject* pAlpha = PyTuple_GetItem(pColor,3); + alpha = PyFloat_AsDouble(pAlpha); + } + return App::Color(red, green, blue, alpha); } PyObject* DrawUtil::colorToPyTuple(App::Color color) @@ -741,12 +690,9 @@ PyObject* DrawUtil::colorToPyTuple(App::Color color) //check for crazy edge. This is probably a geometry error of some sort. bool DrawUtil::isCrazy(TopoDS_Edge e) { - bool result = false; - double ratio = 1.0; if (e.IsNull()) { - result = true; - return result; + return true; } Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> @@ -761,13 +707,11 @@ bool DrawUtil::isCrazy(TopoDS_Edge e) double edgeLength = GCPnts_AbscissaPoint::Length(adapt, Precision::Confusion()); if (edgeLength < 0.00001) { //edge is scaled. this is 0.00001 mm on paper Base::Console().Log("DU::isCrazy - edge crazy short: %.7f\n", edgeLength); - result = true; - return result; + return true; } if (edgeLength > 9999.9) { //edge is scaled. this is 10 m on paper. can't be right? Base::Console().Log("DU::isCrazy - edge crazy long: %.3f\n", edgeLength); - result = true; - return result; + return true; } double start = BRepLProp_CurveTool::FirstParameter(adapt); @@ -777,28 +721,27 @@ bool DrawUtil::isCrazy(TopoDS_Edge e) BRepLProp_CLProps propEnd(adapt,end,0,Precision::Confusion()); const gp_Pnt& vEnd = propEnd.Value(); double distance = vStart.Distance(vEnd); - if (adapt.GetType() == GeomAbs_BSplineCurve) { - if (distance > 0.001) { // not a closed loop - ratio = edgeLength / distance; - if (ratio > 9999.9) { // 10,000x - result = true; //this is crazy edge - } - } - } else if (adapt.GetType() == GeomAbs_Ellipse) { + double ratio = edgeLength / distance; + if (adapt.GetType() == GeomAbs_BSplineCurve && + distance > 0.001 && // not a closed loop + ratio > 9999.9) { // 10,000x + return true; //this is crazy edge + } + else if (adapt.GetType() == GeomAbs_Ellipse) { gp_Elips ellp = adapt.Ellipse(); double major = ellp.MajorRadius(); double minor = ellp.MinorRadius(); if (minor < 0.001) { //too narrow Base::Console().Log("DU::isCrazy - ellipse is crazy narrow: %.7f\n", minor); - result = true; + return true; } else if (major > 9999.9) { //too big Base::Console().Log("DU::isCrazy - ellipse is crazy wide: %.3f\n", major); - result = true; + return true; } } -// Base::Console().Message("DU::isCrazy - returns: %d ratio: %.3f\n", result, ratio); - return result; +// Base::Console().Message("DU::isCrazy - returns: %d ratio: %.3f\n", false, ratio); + return false; } //construct a compound shape from a list of edges @@ -810,7 +753,7 @@ TopoDS_Shape DrawUtil::vectorToCompound(std::vector vecIn) for (auto& v : vecIn) { builder.Add(compOut, v); } - return compOut; + return TopoDS_Compound(std::move(compOut)); } //get 3d position of a face's center Base::Vector3d DrawUtil::getFaceCenter(TopoDS_Face f) @@ -824,8 +767,7 @@ Base::Vector3d DrawUtil::getFaceCenter(TopoDS_Face f) double mv = (v1 + v2) / 2.0; BRepLProp_SLProps prop(adapt,mu,mv,0,Precision::Confusion()); const gp_Pnt gv = prop.Value(); - Base::Vector3d v(gv.X(), gv.Y(), gv.Z()); - return v; + return Base::Vector3d(gv.X(), gv.Y(), gv.Z()); } // test the circulation of the triangle A-B-C @@ -908,7 +850,7 @@ unsigned int DrawUtil::intervalMerge(std::vector> &marki unsigned int i = 0; bool last = false; - if (wraps && marking.size() > 0) { + if (wraps && !marking.empty()) { last = marking.back().second; } @@ -1214,15 +1156,18 @@ void DrawUtil::copyFile(std::string inSpec, std::string outSpec) { // Base::Console().Message("DU::copyFile(%s, %s)\n", inSpec.c_str(), outSpec.c_str()); if (inSpec.empty()) { - std::ofstream output(outSpec); + // create an empty file + Base::FileInfo fi(outSpec); + Base::ofstream output(fi); return; } Base::FileInfo fi(inSpec); - if (fi.isReadable()) { - bool rc = fi.copyTo(outSpec.c_str()); - if (!rc) { - Base::Console().Message("DU::copyFile - failed - in: %s out:%s\n", inSpec.c_str(), outSpec.c_str()); - } + if (!fi.isReadable()) { + return; + } + bool rc = fi.copyTo(outSpec.c_str()); + if (!rc) { + Base::Console().Message("DU::copyFile - failed - in: %s out:%s\n", inSpec.c_str(), outSpec.c_str()); } } @@ -1233,8 +1178,7 @@ void DrawUtil::dumpVertexes(const char* text, const TopoDS_Shape& s) { Base::Console().Message("DUMP - %s\n",text); TopExp_Explorer expl(s, TopAbs_VERTEX); - int i; - for (i = 1 ; expl.More(); expl.Next(),i++) { + 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()); @@ -1270,8 +1214,7 @@ void DrawUtil::dumpEdges(const char* text, const TopoDS_Shape& s) { Base::Console().Message("DUMP - %s\n",text); TopExp_Explorer expl(s, TopAbs_EDGE); - int i; - for (i = 1 ; expl.More(); expl.Next(),i++) { + for (int i = 1 ; expl.More(); expl.Next(),i++) { const TopoDS_Edge& e = TopoDS::Edge(expl.Current()); dumpEdge("dumpEdges", i, e); } diff --git a/src/Mod/TechDraw/App/DrawUtil.h b/src/Mod/TechDraw/App/DrawUtil.h index 26549a3669..9c7b208712 100644 --- a/src/Mod/TechDraw/App/DrawUtil.h +++ b/src/Mod/TechDraw/App/DrawUtil.h @@ -23,6 +23,8 @@ #ifndef _DrawUtil_h_ #define _DrawUtil_h_ +#include + #include #include diff --git a/src/Mod/TechDraw/App/DrawView.cpp b/src/Mod/TechDraw/App/DrawView.cpp index 401d73a6f0..390a8e4125 100644 --- a/src/Mod/TechDraw/App/DrawView.cpp +++ b/src/Mod/TechDraw/App/DrawView.cpp @@ -72,9 +72,10 @@ App::PropertyFloatConstraint::Constraints DrawView::scaleRange = {Precision::Con PROPERTY_SOURCE(TechDraw::DrawView, App::DocumentObject) -DrawView::DrawView(void): +DrawView::DrawView(): autoPos(true), - mouseMove(false) + mouseMove(false), + m_overrideKeepUpdated(false) { static const char *group = "Base"; ADD_PROPERTY_TYPE(X, (0.0), group, (App::PropertyType)(App::Prop_Output), "X position"); @@ -96,10 +97,10 @@ DrawView::~DrawView() { } -App::DocumentObjectExecReturn *DrawView::execute(void) +App::DocumentObjectExecReturn *DrawView::execute() { // Base::Console().Message("DV::execute() - %s touched: %d\n", getNameInDocument(), isTouched()); - if (findParentPage() == nullptr) { + if (!findParentPage()) { return App::DocumentObject::execute(); } handleXYLock(); @@ -109,7 +110,7 @@ App::DocumentObjectExecReturn *DrawView::execute(void) return App::DocumentObject::execute(); } -void DrawView::checkScale(void) +void DrawView::checkScale() { TechDraw::DrawPage *page = findParentPage(); if(page) { @@ -131,19 +132,19 @@ void DrawView::onChanged(const App::Property* prop) if (prop == &ScaleType) { auto page = findParentPage(); if (ScaleType.isValue("Page")) { - Scale.setStatus(App::Property::ReadOnly,true); - if (page != nullptr) { + Scale.setStatus(App::Property::ReadOnly, true); + if (page) { if(std::abs(page->Scale.getValue() - getScale()) > FLT_EPSILON) { Scale.setValue(page->Scale.getValue()); } } } else if ( ScaleType.isValue("Custom") ) { //don't change Scale - Scale.setStatus(App::Property::ReadOnly,false); + Scale.setStatus(App::Property::ReadOnly, false); } else if ( ScaleType.isValue("Automatic") ) { - Scale.setStatus(App::Property::ReadOnly,true); + Scale.setStatus(App::Property::ReadOnly, true); if (!checkFit(page)) { - double newScale = autoScale(page->getPageWidth(),page->getPageHeight()); + double newScale = autoScale(page->getPageWidth(), page->getPageHeight()); if(std::abs(newScale - getScale()) > FLT_EPSILON) { //stops onChanged/execute loop Scale.setValue(newScale); } @@ -152,7 +153,7 @@ void DrawView::onChanged(const App::Property* prop) } else if (prop == &LockPosition) { handleXYLock(); requestPaint(); //change lock icon - LockPosition.purgeTouched(); + LockPosition.purgeTouched(); } else if ((prop == &Caption) || (prop == &Label)) { requestPaint(); @@ -164,35 +165,35 @@ void DrawView::onChanged(const App::Property* prop) App::DocumentObject::onChanged(prop); } -bool DrawView::isLocked(void) const +bool DrawView::isLocked() const { return LockPosition.getValue(); } -bool DrawView::showLock(void) const +bool DrawView::showLock() const { return true; } //override this for View inside a group (ex DPGI in DPG) -void DrawView::handleXYLock(void) +void DrawView::handleXYLock() { if (isLocked()) { if (!X.testStatus(App::Property::ReadOnly)) { - X.setStatus(App::Property::ReadOnly,true); + X.setStatus(App::Property::ReadOnly, true); X.purgeTouched(); } if (!Y.testStatus(App::Property::ReadOnly)) { - Y.setStatus(App::Property::ReadOnly,true); + Y.setStatus(App::Property::ReadOnly, true); Y.purgeTouched(); } } else { if (X.testStatus(App::Property::ReadOnly)) { - X.setStatus(App::Property::ReadOnly,false); + X.setStatus(App::Property::ReadOnly, false); X.purgeTouched(); } if (Y.testStatus(App::Property::ReadOnly)) { - Y.setStatus(App::Property::ReadOnly,false); + Y.setStatus(App::Property::ReadOnly, false); Y.purgeTouched(); } } @@ -335,7 +336,7 @@ bool DrawView::isInClip() return false; } -DrawViewClip* DrawView::getClipGroup(void) +DrawViewClip* DrawView::getClipGroup() { std::vector parent = getInList(); App::DocumentObject* obj = nullptr; @@ -351,7 +352,7 @@ DrawViewClip* DrawView::getClipGroup(void) return result; } -double DrawView::autoScale(void) const +double DrawView::autoScale() const { auto page = findParentPage(); double w = page->getPageWidth(); @@ -359,7 +360,7 @@ double DrawView::autoScale(void) const return autoScale(w,h); } -//compare 1:1 rect of view to pagesize(pw,h) +//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()); @@ -373,13 +374,14 @@ double DrawView::autoScale(double pw, double ph) const double vbh = viewBox.height()/getScale(); double xScale = pw/vbw; // > 1 page bigger than figure double yScale = ph/vbh; // < 1 page is smaller than figure - double newScale = std::min(xScale,yScale) * fudgeFactor; + double newScale = std::min(xScale,yScale) * fudgeFactor; double sensibleScale = DrawUtil::sensibleScale(newScale); return sensibleScale; } -bool DrawView::checkFit(void) const +bool DrawView::checkFit() const { +// Base::Console().Message("DV::checkFit() - %s\n", getNameInDocument()); auto page = findParentPage(); return checkFit(page); } @@ -387,6 +389,7 @@ bool DrawView::checkFit(void) 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()); bool result = true; double fudge = 1.1; @@ -424,7 +427,7 @@ void DrawView::setPosition(double x, double y, bool force) } } -double DrawView::getScale(void) const +double DrawView::getScale() const { auto result = Scale.getValue(); if (ScaleType.isValue("Page")) { @@ -454,8 +457,7 @@ std::vector DrawView::getLeaders() const return result; } -void DrawView::handleChangedPropertyType( - Base::XMLReader &reader, const char * TypeName, App::Property * prop) +void DrawView::handleChangedPropertyType(Base::XMLReader &reader, const char * TypeName, App::Property * prop) { if (prop == &Scale) { App::PropertyFloat tmp; @@ -469,7 +471,7 @@ void DrawView::handleChangedPropertyType( Scale.setValue(1.0); } } else { - // has Scale prop that isn't Float! + // has Scale prop that isn't Float! Base::Console().Log("DrawPage::Restore - old Document Scale is Not Float!\n"); // no idea } @@ -481,7 +483,7 @@ void DrawView::handleChangedPropertyType( if (strcmp(glink.getTypeId().getName(), TypeName) == 0) { //property in file is plg glink.setContainer(this); glink.Restore(reader); - if (glink.getValue() != nullptr) { + if (glink.getValue()) { static_cast(prop)->setScope(App::LinkScope::Global); static_cast(prop)->setValue(glink.getValue()); } @@ -489,7 +491,7 @@ void DrawView::handleChangedPropertyType( else if (strcmp(link.getTypeId().getName(), TypeName) == 0) { //property in file is pl link.setContainer(this); link.Restore(reader); - if (link.getValue() != nullptr) { + if (link.getValue()) { static_cast(prop)->setScope(App::LinkScope::Global); static_cast(prop)->setValue(link.getValue()); } @@ -521,7 +523,7 @@ void DrawView::handleChangedPropertyType( Y2Property.Restore(reader); Y.setValue(Y2Property.getValue()); } - + // property Rotation had App::PropertyFloat and was changed to App::PropertyAngle else if (prop == &Rotation && strcmp(TypeName, "App::PropertyFloat") == 0) { App::PropertyFloat RotationProperty; @@ -531,16 +533,17 @@ void DrawView::handleChangedPropertyType( } } -bool DrawView::keepUpdated(void) +bool DrawView::keepUpdated() { // Base::Console().Message("DV::keepUpdated() - %s\n", getNameInDocument()); - bool result = false; - + if (overrideKeepUpdated()) { + return true; + } TechDraw::DrawPage *page = findParentPage(); if(page) { - result = page->canUpdate() || page->forceRedraw(); + return (page->canUpdate() || page->forceRedraw()); } - return result; + return false; } void DrawView::setScaleAttribute() @@ -553,15 +556,15 @@ void DrawView::setScaleAttribute() } } -int DrawView::prefScaleType(void) +int DrawView::prefScaleType() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); - int result = hGrp->GetInt("DefaultScaleType", 0); + int result = hGrp->GetInt("DefaultScaleType", 0); return result; } -double DrawView::prefScale(void) +double DrawView::prefScale() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); @@ -575,12 +578,19 @@ double DrawView::prefScale(void) return result; } -void DrawView::requestPaint(void) +void DrawView::requestPaint() { // Base::Console().Message("DV::requestPaint() - %s\n", getNameInDocument()); signalGuiPaint(this); } +void DrawView::showProgressMessage(std::string featureName, std::string text) +{ + if (Preferences::reportProgress()) { + signalProgressMessage(this, featureName, text); + } +} + PyObject *DrawView::getPyObject(void) { if (PythonObject.is(Py::_None())) { @@ -595,7 +605,7 @@ PyObject *DrawView::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewPython, TechDraw::DrawView) -template<> const char* TechDraw::DrawViewPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewPython::getViewProviderName() const { return "TechDrawGui::ViewProviderDrawingView"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawView.h b/src/Mod/TechDraw/App/DrawView.h index f60534e4b1..287d6b92d2 100644 --- a/src/Mod/TechDraw/App/DrawView.h +++ b/src/Mod/TechDraw/App/DrawView.h @@ -23,15 +23,17 @@ #ifndef _DrawView_h_ #define _DrawView_h_ +#include + #include #include +#include #include #include #include #include -#include namespace TechDraw @@ -51,8 +53,8 @@ class TechDrawExport DrawView : public App::DocumentObject public: /// Constructor - DrawView(void); - virtual ~DrawView(); + DrawView(); + ~DrawView() override; App::PropertyDistance X; App::PropertyDistance Y; @@ -66,57 +68,68 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual void onDocumentRestored() override; - virtual short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; + void onDocumentRestored() override; + short mustExecute() const override; //@} - virtual void handleChangedPropertyType( + void handleChangedPropertyType( Base::XMLReader &reader, const char * TypeName, App::Property * prop) override; bool isInClip(); - DrawViewClip* getClipGroup(void); + DrawViewClip* getClipGroup(); /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderDrawingView"; } //return PyObject as DrawViewPy - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; virtual DrawPage* findParentPage() const; virtual std::vector findAllParentPages() const; virtual int countParentPages() const; virtual QRectF getRect() const; //must be overridden by derived class - virtual double autoScale(void) const; + virtual double autoScale() const; virtual double autoScale(double w, double h) const; - virtual bool checkFit(void) const; + virtual bool checkFit() const; virtual bool checkFit(DrawPage*) const; virtual void setPosition(double x, double y, bool force = false); virtual bool keepUpdated(void); + boost::signals2::signal signalGuiPaint; + boost::signals2::signal signalProgressMessage; + void requestPaint(void); + void showProgressMessage(std::string featureName, std::string text); + virtual double getScale(void) const; void checkScale(void); - void requestPaint(void); + virtual void handleXYLock(void); virtual bool isLocked(void) const; virtual bool showLock(void) const; std::vector getLeaders(void) const; + void setScaleAttribute(); + void overrideKeepUpdated(bool s) { m_overrideKeepUpdated = s; } + bool overrideKeepUpdated(void) { return m_overrideKeepUpdated; } + protected: - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; virtual void validateScale(); std::string pageFeatName; bool autoPos; bool mouseMove; - int prefScaleType(void); - double prefScale(void); + int prefScaleType(); + double prefScale(); private: static const char* ScaleTypeEnums[]; static App::PropertyFloatConstraint::Constraints scaleRange; + + bool m_overrideKeepUpdated; }; typedef App::FeaturePythonT DrawViewPython; diff --git a/src/Mod/TechDraw/App/DrawViewAnnotation.cpp b/src/Mod/TechDraw/App/DrawViewAnnotation.cpp index 45750502e5..8a4de555e0 100644 --- a/src/Mod/TechDraw/App/DrawViewAnnotation.cpp +++ b/src/Mod/TechDraw/App/DrawViewAnnotation.cpp @@ -55,7 +55,7 @@ const char* DrawViewAnnotation::TextStyleEnums[]= {"Normal", "Bold-Italic", nullptr}; -DrawViewAnnotation::DrawViewAnnotation(void) +DrawViewAnnotation::DrawViewAnnotation() { static const char *vgroup = "Annotation"; @@ -118,7 +118,6 @@ void DrawViewAnnotation::handleChangedPropertyType(Base::XMLReader &reader, cons QRectF DrawViewAnnotation::getRect() const { - QRectF result; double tSize = TextSize.getValue(); int lines = Text.getValues().size(); int chars = 1; @@ -129,11 +128,10 @@ QRectF DrawViewAnnotation::getRect() const } int w = chars * std::max(1,(int)tSize); int h = lines * std::max(1,(int)tSize); - result = QRectF(0,0,getScale() * w,getScale() * h); - return result; + return QRectF(0,0,getScale() * w,getScale() * h); } -App::DocumentObjectExecReturn *DrawViewAnnotation::execute(void) +App::DocumentObjectExecReturn *DrawViewAnnotation::execute() { requestPaint(); return TechDraw::DrawView::execute(); @@ -144,7 +142,7 @@ App::DocumentObjectExecReturn *DrawViewAnnotation::execute(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewAnnotationPython, TechDraw::DrawViewAnnotation) -template<> const char* TechDraw::DrawViewAnnotationPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewAnnotationPython::getViewProviderName() const { return "TechDrawGui::ViewProviderAnnotation"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewAnnotation.h b/src/Mod/TechDraw/App/DrawViewAnnotation.h index 976c5ead37..3841e0d9ea 100644 --- a/src/Mod/TechDraw/App/DrawViewAnnotation.h +++ b/src/Mod/TechDraw/App/DrawViewAnnotation.h @@ -24,6 +24,8 @@ #ifndef _DrawViewAnnotation_h_ #define _DrawViewAnnotation_h_ +#include + #include #include #include @@ -37,12 +39,12 @@ namespace TechDraw class TechDrawExport DrawViewAnnotation : public TechDraw::DrawView { - PROPERTY_HEADER(TechDraw::DrawViewAnnotation); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawViewAnnotation); public: /// Constructor - DrawViewAnnotation(void); - virtual ~DrawViewAnnotation(); + DrawViewAnnotation(); + ~DrawViewAnnotation() override; App::PropertyStringList Text; App::PropertyFont Font; @@ -52,22 +54,22 @@ public: App::PropertyEnumeration TextStyle; // Plain,Bold,Italic,Bold-Italic App::PropertyLength MaxWidth; - virtual QRectF getRect() const; + QRectF getRect() const override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderAnnotation"; } protected: - virtual void onChanged(const App::Property* prop); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + void onChanged(const App::Property* prop) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; private: static const char* TextStyleEnums[]; diff --git a/src/Mod/TechDraw/App/DrawViewAnnotationPyImp.cpp b/src/Mod/TechDraw/App/DrawViewAnnotationPyImp.cpp index 3f97b734d4..ac242215af 100644 --- a/src/Mod/TechDraw/App/DrawViewAnnotationPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewAnnotationPyImp.cpp @@ -42,7 +42,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawViewAnnotationPy::representation(void) const +std::string DrawViewAnnotationPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawViewArch.cpp b/src/Mod/TechDraw/App/DrawViewArch.cpp index 19cf844ce6..ac7347ee5f 100644 --- a/src/Mod/TechDraw/App/DrawViewArch.cpp +++ b/src/Mod/TechDraw/App/DrawViewArch.cpp @@ -52,7 +52,7 @@ const char* DrawViewArch::RenderModeEnums[]= {"Wireframe", "Coin mono", nullptr}; -DrawViewArch::DrawViewArch(void) +DrawViewArch::DrawViewArch() { static const char *group = "Arch view"; @@ -75,28 +75,29 @@ DrawViewArch::~DrawViewArch() { } +//NOTE: DocumentObject::mustExecute returns 1/0 and not true/false short DrawViewArch::mustExecute() const { - short result = 0; if (!isRestoring()) { - result = (Source.isTouched() || - AllOn.isTouched() || - RenderMode.isTouched() || - ShowHidden.isTouched() || - ShowFill.isTouched() || - LineWidth.isTouched() || - FontSize.isTouched() || - CutLineWidth.isTouched() || - JoinArch.isTouched()); - } - if ((bool) result) { - return result; + if ( + Source.isTouched() || + AllOn.isTouched() || + RenderMode.isTouched() || + ShowHidden.isTouched() || + ShowFill.isTouched() || + LineWidth.isTouched() || + FontSize.isTouched() || + CutLineWidth.isTouched() || + JoinArch.isTouched() + ) { + return 1; + } } return DrawViewSymbol::mustExecute(); } -App::DocumentObjectExecReturn *DrawViewArch::execute(void) +App::DocumentObjectExecReturn *DrawViewArch::execute() { if (!keepUpdated()) { return App::DocumentObject::StdReturn; @@ -106,7 +107,7 @@ App::DocumentObjectExecReturn *DrawViewArch::execute(void) if (sourceObj) { //if (sourceObj is not ArchSection) return App::Property* proxy = sourceObj->getPropertyByName("Proxy"); - if (proxy == nullptr) { + if (!proxy) { Base::Console().Error("DVA::execute - %s is not an ArchSection\n", sourceObj->Label.getValue()); //this is definitely not an ArchSection return DrawView::execute(); @@ -139,11 +140,11 @@ App::DocumentObjectExecReturn *DrawViewArch::execute(void) Base::Interpreter().runStringArg("App.activeDocument().%s.Symbol = '%s' + svgBody + '%s'", FeatName.c_str(),svgHead.c_str(),svgTail.c_str()); } -// requestPaint(); + overrideKeepUpdated(false); return DrawView::execute(); } -std::string DrawViewArch::getSVGHead(void) +std::string DrawViewArch::getSVGHead() { std::string head = std::string(""; } diff --git a/src/Mod/TechDraw/App/DrawViewArch.h b/src/Mod/TechDraw/App/DrawViewArch.h index 26cde405a3..5ed2198cc2 100644 --- a/src/Mod/TechDraw/App/DrawViewArch.h +++ b/src/Mod/TechDraw/App/DrawViewArch.h @@ -23,6 +23,8 @@ #ifndef _DrawViewArch_h_ #define _DrawViewArch_h_ +#include + #include #include #include @@ -39,8 +41,8 @@ class TechDrawExport DrawViewArch : public TechDraw::DrawViewSymbol public: /// Constructor - DrawViewArch(void); - virtual ~DrawViewArch(); + DrawViewArch(); + ~DrawViewArch() override; App::PropertyLink Source; App::PropertyBool AllOn; @@ -56,22 +58,22 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderArch"; } - virtual short mustExecute() const override; + short mustExecute() const override; protected: /* virtual void onChanged(const App::Property* prop) override;*/ Base::BoundBox3d bbox; - std::string getSVGHead(void); - std::string getSVGTail(void); + std::string getSVGHead(); + std::string getSVGTail(); private: static const char* RenderModeEnums[]; diff --git a/src/Mod/TechDraw/App/DrawViewBalloon.cpp b/src/Mod/TechDraw/App/DrawViewBalloon.cpp index 05ae795ad3..811ec1703f 100644 --- a/src/Mod/TechDraw/App/DrawViewBalloon.cpp +++ b/src/Mod/TechDraw/App/DrawViewBalloon.cpp @@ -90,7 +90,7 @@ const char* DrawViewBalloon::balloonTypeEnums[]= {"Circular", "Line", nullptr}; -DrawViewBalloon::DrawViewBalloon(void) +DrawViewBalloon::DrawViewBalloon() { ADD_PROPERTY_TYPE(Text, (""), "", App::Prop_None, "The text to be displayed"); ADD_PROPERTY_TYPE(SourceView, (nullptr), "", (App::PropertyType)(App::Prop_None), "Source view for balloon"); @@ -197,47 +197,30 @@ void DrawViewBalloon::handleChangedPropertyType(Base::XMLReader &reader, const c } } +//NOTE: DocumentObject::mustExecute returns 1/0 and not true/false short DrawViewBalloon::mustExecute() const { - bool result = 0; - if (!isRestoring()) { - result = Text.isTouched(); - } - - if (result) { - return result; + if (!isRestoring() && Text.isTouched()) { + return 1; } auto dvp = getViewPart(); - if (dvp != nullptr) { - result = dvp->isTouched(); - } - if (result) { - return result; + if (dvp && dvp->isTouched()) { + return 1; } return DrawView::mustExecute(); } -void DrawViewBalloon::handleXYLock(void) { - if (isLocked()) { - if (!OriginX.testStatus(App::Property::ReadOnly)) { - OriginX.setStatus(App::Property::ReadOnly, true); - OriginX.purgeTouched(); - } - if (!OriginY.testStatus(App::Property::ReadOnly)) { - OriginY.setStatus(App::Property::ReadOnly, true); - OriginY.purgeTouched(); - } - } else { - if (OriginX.testStatus(App::Property::ReadOnly)) { - OriginX.setStatus(App::Property::ReadOnly, false); - OriginX.purgeTouched(); - } - if (OriginY.testStatus(App::Property::ReadOnly)) { - OriginY.setStatus(App::Property::ReadOnly, false); - OriginY.purgeTouched(); - } +void DrawViewBalloon::handleXYLock() { + bool on = isLocked(); + if (!OriginX.testStatus(App::Property::ReadOnly)) { + OriginX.setStatus(App::Property::ReadOnly, on); + OriginX.purgeTouched(); + } + if (!OriginY.testStatus(App::Property::ReadOnly)) { + OriginY.setStatus(App::Property::ReadOnly, on); + OriginY.purgeTouched(); } DrawView::handleXYLock(); } @@ -250,7 +233,7 @@ DrawViewPart* DrawViewBalloon::getViewPart() const return result; } -App::DocumentObjectExecReturn *DrawViewBalloon::execute(void) +App::DocumentObjectExecReturn *DrawViewBalloon::execute() { requestPaint(); return App::DocumentObject::execute(); @@ -264,24 +247,22 @@ void DrawViewBalloon::setOrigin(Base::Vector3d newOrigin) origin = QPointF(newOrigin.x, newOrigin.y); } -double DrawViewBalloon::prefKinkLength(void) const +double DrawViewBalloon::prefKinkLength() const { Base::Reference hGrp = App::GetApplication().GetUserParameter(). GetGroup("BaseApp")->GetGroup("Preferences")-> GetGroup("Mod/TechDraw/Dimensions"); - double length = hGrp->GetFloat("BalloonKink", 5.0); - return length; + return hGrp->GetFloat("BalloonKink", 5.0); } -int DrawViewBalloon::prefShape(void) const +int DrawViewBalloon::prefShape() const { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); - int result = hGrp->GetInt("BalloonShape", 0); - return result; + return hGrp->GetInt("BalloonShape", 0); } -int DrawViewBalloon::prefEnd(void) const +int DrawViewBalloon::prefEnd() const { return Preferences::balloonArrow(); } @@ -290,8 +271,7 @@ QPointF DrawViewBalloon::getOrigin() { double x = OriginX.getValue(); double y = OriginY.getValue(); - QPointF result(x, y); - return result; + return QPointF(x, y); } void DrawViewBalloon::setOrigin(QPointF p) diff --git a/src/Mod/TechDraw/App/DrawViewBalloon.h b/src/Mod/TechDraw/App/DrawViewBalloon.h index dcc5d24c6e..7f2415f6c3 100644 --- a/src/Mod/TechDraw/App/DrawViewBalloon.h +++ b/src/Mod/TechDraw/App/DrawViewBalloon.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_DrawViewBalloon_h_ #define _TechDraw_DrawViewBalloon_h_ +#include + #include #include #include @@ -46,7 +48,7 @@ class TechDrawExport DrawViewBalloon : public TechDraw::DrawView public: /// Constructor DrawViewBalloon(); - virtual ~DrawViewBalloon(); + ~DrawViewBalloon() override; App::PropertyLink SourceView; App::PropertyString Text; @@ -68,29 +70,29 @@ public: //virtual PyObject *getPyObject(void); - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderBalloon"; } static const char* balloonTypeEnums[]; - void handleXYLock(void) override; + void handleXYLock() override; - double prefKinkLength(void) const; - int prefShape(void) const; - int prefEnd(void) const; + double prefKinkLength() const; + int prefShape() const; + int prefEnd() const; void setOrigin(Base::Vector3d newOrigin); Base::Vector3d getOriginOffset() const; protected: void onChanged(const App::Property* prop) override; - virtual void handleChangedPropertyType(Base::XMLReader &reader, + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; - virtual void handleChangedPropertyName(Base::XMLReader &reader, + void handleChangedPropertyName(Base::XMLReader &reader, const char * TypeName, const char *PropName) override; diff --git a/src/Mod/TechDraw/App/DrawViewClip.cpp b/src/Mod/TechDraw/App/DrawViewClip.cpp index d9f0fdabe9..3a25ef9393 100644 --- a/src/Mod/TechDraw/App/DrawViewClip.cpp +++ b/src/Mod/TechDraw/App/DrawViewClip.cpp @@ -45,7 +45,7 @@ using namespace std; PROPERTY_SOURCE(TechDraw::DrawViewClip, TechDraw::DrawView) -DrawViewClip::DrawViewClip(void) +DrawViewClip::DrawViewClip() { static const char *group = "Clip Group"; //App::PropertyType hidden = (App::PropertyType)(App::Prop_Hidden); @@ -104,7 +104,7 @@ void DrawViewClip::removeView(DrawView *view) Views.setValues(newViews); } -App::DocumentObjectExecReturn *DrawViewClip::execute(void) +App::DocumentObjectExecReturn *DrawViewClip::execute() { if (!keepUpdated()) { return App::DocumentObject::StdReturn; @@ -119,19 +119,19 @@ App::DocumentObjectExecReturn *DrawViewClip::execute(void) } requestPaint(); + overrideKeepUpdated(false); return DrawView::execute(); } +//NOTE: DocumentObject::mustExecute returns 1/0 and not true/false short DrawViewClip::mustExecute() const { - short result = 0; if (!isRestoring()) { - result = ( Height.isTouched() || - Width.isTouched() || - Views.isTouched()); - } - if (result) { - return result; + if (Height.isTouched() || + Width.isTouched() || + Views.isTouched()) { + return 1; + } } return TechDraw::DrawView::mustExecute(); } @@ -151,17 +151,16 @@ std::vector DrawViewClip::getChildViewNames() bool DrawViewClip::isViewInClip(App::DocumentObject* view) { - bool result = false; std::vector children = Views.getValues(); for (std::vector::iterator it = children.begin(); it != children.end(); ++it) { if ((*it) == view) { - result = true; + return true; } } - return result; + return false; } -PyObject *DrawViewClip::getPyObject(void) +PyObject *DrawViewClip::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -176,7 +175,7 @@ PyObject *DrawViewClip::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewClipPython, TechDraw::DrawViewClip) -template<> const char* TechDraw::DrawViewClipPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewClipPython::getViewProviderName() const { return "TechDrawGui::ViewProviderViewClip"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewClip.h b/src/Mod/TechDraw/App/DrawViewClip.h index e498de1d48..dd2d66fa23 100644 --- a/src/Mod/TechDraw/App/DrawViewClip.h +++ b/src/Mod/TechDraw/App/DrawViewClip.h @@ -24,6 +24,8 @@ #ifndef _DrawViewClip_h_ #define _DrawViewClip_h_ +#include + #include #include #include @@ -37,12 +39,12 @@ namespace TechDraw class TechDrawExport DrawViewClip: public TechDraw::DrawView { - PROPERTY_HEADER(TechDraw::DrawViewClip); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawViewClip); public: /// Constructor - DrawViewClip(void); - virtual ~DrawViewClip(); + DrawViewClip(); + ~DrawViewClip() override; App::PropertyLength Width; App::PropertyLength Height; @@ -51,28 +53,28 @@ public: void addView(DrawView *view); void removeView(DrawView *view); - short mustExecute() const; + short mustExecute() const override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void); + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewClip"; } //return PyObject as DrawViewClipPy - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; std::vector getChildViewNames(); bool isViewInClip(App::DocumentObject* view); - virtual QRectF getRect(void) const { return QRectF(0,0,Width.getValue(),Height.getValue()); } + QRectF getRect() const override { return QRectF(0,0,Width.getValue(),Height.getValue()); } protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; }; typedef App::FeaturePythonT DrawViewClipPython; diff --git a/src/Mod/TechDraw/App/DrawViewClipPyImp.cpp b/src/Mod/TechDraw/App/DrawViewClipPyImp.cpp index 79f7e26f52..a270f43203 100644 --- a/src/Mod/TechDraw/App/DrawViewClipPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewClipPyImp.cpp @@ -36,7 +36,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawViewClipPy::representation(void) const +std::string DrawViewClipPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawViewCollection.cpp b/src/Mod/TechDraw/App/DrawViewCollection.cpp index 9a93f747be..f32b2a00da 100644 --- a/src/Mod/TechDraw/App/DrawViewCollection.cpp +++ b/src/Mod/TechDraw/App/DrawViewCollection.cpp @@ -69,7 +69,7 @@ short DrawViewCollection::mustExecute() const } } -App::DocumentObjectExecReturn *DrawViewCollection::execute(void) +App::DocumentObjectExecReturn *DrawViewCollection::execute() { if (!keepUpdated()) { return App::DocumentObject::StdReturn; @@ -77,6 +77,7 @@ App::DocumentObjectExecReturn *DrawViewCollection::execute(void) lockChildren(); + overrideKeepUpdated(false); return DrawView::execute(); } @@ -155,7 +156,7 @@ void DrawViewCollection::onDocumentRestored() DrawView::execute(); } -void DrawViewCollection::lockChildren(void) +void DrawViewCollection::lockChildren() { // Base::Console().Message("DVC::lockChildren()\n"); for (auto& v:Views.getValues()) { diff --git a/src/Mod/TechDraw/App/DrawViewCollection.h b/src/Mod/TechDraw/App/DrawViewCollection.h index b76046d69f..8d754b0f7e 100644 --- a/src/Mod/TechDraw/App/DrawViewCollection.h +++ b/src/Mod/TechDraw/App/DrawViewCollection.h @@ -24,6 +24,8 @@ #ifndef _TECHDRAW_FEATUREVIEWCOLLECTION_h_ #define _TECHDRAW_FEATUREVIEWCOLLECTION_h_ +#include + #include #include @@ -36,36 +38,36 @@ namespace TechDraw */ class TechDrawExport DrawViewCollection : public DrawView { - PROPERTY_HEADER(TechDraw::DrawViewCollection); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawViewCollection); public: App::PropertyLinkList Views; public: /// Constructor DrawViewCollection(); - virtual ~DrawViewCollection(); - short mustExecute() const; + ~DrawViewCollection() override; + short mustExecute() const override; int addView(DrawView *view); int removeView(DrawView *view); - void rebuildViewList(void); - bool isUnsetting(void) { return nowUnsetting; } + void rebuildViewList(); + bool isUnsetting() { return nowUnsetting; } int countChildren(); - void lockChildren(void); + void lockChildren(); - virtual void onDocumentRestored(); - virtual App::DocumentObjectExecReturn *execute(void); - virtual void unsetupObject(); + void onDocumentRestored() override; + App::DocumentObjectExecReturn *execute() override; + void unsetupObject() override; /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewCollection"; } - virtual QRectF getRect(void) const; + QRectF getRect() const override; protected: - void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; bool nowUnsetting; }; diff --git a/src/Mod/TechDraw/App/DrawViewDetail.cpp b/src/Mod/TechDraw/App/DrawViewDetail.cpp index 07bcf0272c..c21212b826 100644 --- a/src/Mod/TechDraw/App/DrawViewDetail.cpp +++ b/src/Mod/TechDraw/App/DrawViewDetail.cpp @@ -24,35 +24,21 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include - #include -#include #include -#include #include #include #include -#include -#include #include #include #include -#include #include #include -#include -#include #include -#include #include #include #include -#include -#include -#include #include -#include #include #include #include @@ -61,48 +47,48 @@ #include #include #include - #endif #include +#include -# include -# include +#include +#include +#include #include #include #include #include -#include #include +#include #include #include #include -#include "Preferences.h" -#include "Geometry.h" -#include "GeometryObject.h" -#include "Cosmetic.h" -#include "EdgeWalker.h" -#include "DrawProjectSplit.h" -#include "DrawProjGroupItem.h" #include "DrawPage.h" #include "DrawUtil.h" -#include "DrawViewDetail.h" #include "DrawViewSection.h" +#include "Geometry.h" +#include "GeometryObject.h" +#include "Preferences.h" + +#include "DrawViewDetail.h" using namespace TechDraw; using namespace std; - //=========================================================================== // DrawViewDetail //=========================================================================== PROPERTY_SOURCE(TechDraw::DrawViewDetail, TechDraw::DrawViewPart) -DrawViewDetail::DrawViewDetail() +DrawViewDetail::DrawViewDetail() : + m_waitingForDetail(false), + m_saveDvp(nullptr), + m_saveDvs(nullptr) { static const char *dgroup = "Detail"; @@ -123,128 +109,83 @@ DrawViewDetail::DrawViewDetail() 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()); + m_detailFuture.waitForFinished(); + } } short DrawViewDetail::mustExecute() const { - short result = 0; - if (!isRestoring()) { - result = (AnchorPoint.isTouched() || - Radius.isTouched() || - BaseView.isTouched() || - Reference.isTouched()); + if (isRestoring()) { + TechDraw::DrawView::mustExecute(); } - if (result) { - return result; + + if (AnchorPoint.isTouched() || + Radius.isTouched() || + BaseView.isTouched() || + Reference.isTouched()) { + return 1; } + return TechDraw::DrawView::mustExecute(); } void DrawViewDetail::onChanged(const App::Property* prop) { - if (!isRestoring()) { - if (prop == &Reference) { - std::string lblText = "Detail " + - std::string(Reference.getValue()); - Label.setValue(lblText); - } - if ((prop == &Reference) || - (prop == &Radius) || - (prop == &BaseView)) { - requestPaint(); - } - if (prop == &AnchorPoint) { - // to see AnchorPoint changes repainting is not enough, we must recompute - recomputeFeature(true); - } - if (prop == &ScaleType) { - auto page = findParentPage(); - // if ScaleType is "Page", the user cannot change it - if (ScaleType.isValue("Page")) { - Scale.setStatus(App::Property::ReadOnly, true); - // apply the page-wide Scale - if (page != nullptr) { - if (std::abs(page->Scale.getValue() - getScale()) > FLT_EPSILON) { - Scale.setValue(page->Scale.getValue()); - Scale.purgeTouched(); - } - } - } - else if (ScaleType.isValue("Custom")) { - // allow the change Scale - Scale.setStatus(App::Property::ReadOnly, false); - } - else if (ScaleType.isValue("Automatic")) { - Scale.setStatus(App::Property::ReadOnly, true); - // apply a Scale - if (!checkFit(page)) { - double newScale = autoScale(page->getPageWidth(), page->getPageHeight()); - if (std::abs(newScale - getScale()) > FLT_EPSILON) { //stops onChanged/execute loop - Scale.setValue(newScale); - Scale.purgeTouched(); - } - } - } - } + if (isRestoring()) { + DrawView::onChanged(prop); + return; } - DrawView::onChanged(prop); + + if (prop == &Reference) { + std::string lblText = "Detail " + + std::string(Reference.getValue()); + Label.setValue(lblText); + } + if (prop == &Reference || + prop == &Radius || + prop == &BaseView) { + requestPaint(); + } + if (prop == &AnchorPoint) { + // to see AnchorPoint changes repainting is not enough, we must recompute + recomputeFeature(true); + } + + DrawViewPart::onChanged(prop); } -App::DocumentObjectExecReturn *DrawViewDetail::execute(void) +App::DocumentObjectExecReturn *DrawViewDetail::execute() { -// Base::Console().Message("DVD::execute() - %s\n", Label.getValue()); +// Base::Console().Message("DVD::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { - return App::DocumentObject::StdReturn; + return DrawView::execute(); } App::DocumentObject* baseObj = BaseView.getValue(); if (!baseObj) { - bool isRestoring = getDocument()->testStatus(App::Document::Status::Restoring); - if (isRestoring) { - Base::Console().Warning("DVD::execute - No BaseView (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVD::execute - No BaseView(s) linked. - %s\n", - getNameInDocument()); - } return DrawView::execute(); } - DrawViewPart* dvp = nullptr; if (!baseObj->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { - return new App::DocumentObjectExecReturn("BaseView object is not a DrawViewPart object"); - } else { - dvp = static_cast(baseObj); + //this can only happen via scripting? + return DrawView::execute(); } - - DrawProjGroupItem* dpgi = nullptr; - if (dvp->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())) { - dpgi= static_cast(dvp); - } - + + DrawViewPart* dvp = static_cast(baseObj); DrawViewSection* dvs = nullptr; + TopoDS_Shape shape; if (dvp->isDerivedFrom(TechDraw::DrawViewSection::getClassTypeId())) { dvs= static_cast(dvp); - } - - TopoDS_Shape shape; - if (dvs != nullptr) { shape = dvs->getCutShape(); - } else if (dpgi != nullptr) { - shape = dpgi->getSourceShapeFused(); } else { + //getSourceShapeFused will complain if called on section shape = dvp->getSourceShapeFused(); } if (shape.IsNull()) { - bool isRestoring = getDocument()->testStatus(App::Document::Status::Restoring); - if (isRestoring) { - Base::Console().Warning("DVD::execute - source shape is invalid - (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVD::execute - Source shape is Null. - %s\n", - getNameInDocument()); - } return DrawView::execute(); } @@ -260,96 +201,102 @@ App::DocumentObjectExecReturn *DrawViewDetail::execute(void) detailExec(shape, dvp, dvs); addShapes2d(); - //second pass if required - if (ScaleType.isValue("Automatic")) { - if (!checkFit()) { - double newScale = autoScale(); - Scale.setValue(newScale); - Scale.purgeTouched(); - if (geometryObject != nullptr) { - delete geometryObject; - geometryObject = nullptr; - detailExec(shape, dvp, dvs); - } - } - } - dvp->requestPaint(); //to refresh detail highlight! + dvp->requestPaint(); //to refresh detail highlight in base view return DrawView::execute(); } //try to create a detail of the solids & shells in shape //if there are no solids/shells in shape, use the edges in shape -void DrawViewDetail::detailExec(TopoDS_Shape shape, +void DrawViewDetail::detailExec(TopoDS_Shape& shape, DrawViewPart* dvp, DrawViewSection* dvs) { - Base::Vector3d anchor = AnchorPoint.getValue(); //this is a 2D point (in unrotated coords) - Base::Vector3d dirDetail = dvp->Direction.getValue(); + if (waitingForHlr() || + waitingForDetail()) { + return; + } + connectDetailWatcher = QObject::connect(&m_detailWatcher, &QFutureWatcherBase::finished, [this] { + this->onMakeDetailFinished(); + }); + m_detailFuture = QtConcurrent::run(this, &DrawViewDetail::makeDetailShape, shape, dvp, dvs); + m_detailWatcher.setFuture(m_detailFuture); + waitingForDetail(true); +} + +//this runs in a separate thread since it can sometimes take a long time +//make a common of the input shape and a cylinder (or prism depending on +//the matting style) +void DrawViewDetail::makeDetailShape(TopoDS_Shape& shape, + DrawViewPart* dvp, + DrawViewSection* dvs) +{ + showProgressMessage(getNameInDocument(), "is making detail shape"); + + Base::Vector3d dirDetail = dvp->Direction.getValue(); double radius = getFudgeRadius(); - double scale = getScale(); int solidCount = DrawUtil::countSubShapes(shape, TopAbs_SOLID); int shellCount = DrawUtil::countSubShapes(shape, TopAbs_SHELL); + //make a copy of the input shape so we don't inadvertently change it BRepBuilderAPI_Copy BuilderCopy(shape); - TopoDS_Shape myShape = BuilderCopy.Shape(); + TopoDS_Shape copyShape = BuilderCopy.Shape(); + m_saveShape = copyShape; + m_saveDvp = dvp; + m_saveDvs = dvs; - gp_Pnt gpCenter = TechDraw::findCentroid(myShape, + gp_Pnt gpCenter = TechDraw::findCentroid(copyShape, dirDetail); Base::Vector3d shapeCenter = Base::Vector3d(gpCenter.X(),gpCenter.Y(),gpCenter.Z()); m_saveCentroid = shapeCenter; //centroid of original shape - if (dvs != nullptr) { + if (!dvs) { //section cutShape should already be on origin - } else { - myShape = TechDraw::moveShape(myShape, //centre shape on origin + copyShape = TechDraw::moveShape(copyShape, //centre shape on origin -shapeCenter); } shapeCenter = Base::Vector3d(0.0, 0.0, 0.0); - gp_Ax2 viewAxis; - - viewAxis = dvp->getProjectionCS(shapeCenter); - anchor = Base::Vector3d(anchor.x,anchor.y, 0.0); //anchor coord in projection CS - Base::Vector3d anchorOffset3d = DrawUtil::toR3(viewAxis, anchor); //actual anchor coords in R3 + m_viewAxis = dvp->getProjectionCS(shapeCenter); //save the CS for later + Base::Vector3d anchor = AnchorPoint.getValue(); //this is a 2D point in unrotated base view coords + anchor = DrawUtil::toR3(m_viewAxis, anchor); //actual anchor coords in R3 Bnd_Box bbxSource; bbxSource.SetGap(0.0); - BRepBndLib::AddOptimal(myShape, bbxSource); + BRepBndLib::AddOptimal(copyShape, bbxSource); double diag = sqrt(bbxSource.SquareExtent()); - Base::Vector3d toolPlaneOrigin = anchorOffset3d + dirDetail * diag * -1.0; //center tool about anchor + Base::Vector3d toolPlaneOrigin = anchor + dirDetail * diag * -1.0; //center tool about anchor double extrudeLength = 2.0 * toolPlaneOrigin.Length(); gp_Pnt gpnt(toolPlaneOrigin.x,toolPlaneOrigin.y,toolPlaneOrigin.z); gp_Dir gdir(dirDetail.x,dirDetail.y,dirDetail.z); - double hideToolRadius = radius * 1.0; - TopoDS_Face aProjFace; + TopoDS_Face extrusionFace; Base::Vector3d extrudeVec = dirDetail * extrudeLength; - gp_Vec extrudeDir(extrudeVec.x,extrudeVec.y,extrudeVec.z); + gp_Vec extrudeDir(extrudeVec.x, extrudeVec.y, extrudeVec.z); TopoDS_Shape tool; if (Preferences::mattingStyle()) { //square mat gp_Pln gpln(gpnt,gdir); - BRepBuilderAPI_MakeFace mkFace(gpln, -hideToolRadius,hideToolRadius,-hideToolRadius,hideToolRadius); - aProjFace = mkFace.Face(); - if(aProjFace.IsNull()) { - Base::Console().Warning("DVD::detailExec - %s - failed to create tool base face\n", getNameInDocument()); + 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", getNameInDocument()); return; } - tool = BRepPrimAPI_MakePrism(aProjFace, extrudeDir, false, true).Shape(); + tool = BRepPrimAPI_MakePrism(extrusionFace, extrudeDir, false, true).Shape(); if(tool.IsNull()) { - Base::Console().Warning("DVD::detailExec - %s - failed to create tool (prism)\n", getNameInDocument()); + Base::Console().Warning("DVD::makeDetailShape - %s - failed to create tool (prism)\n", getNameInDocument()); return; } } else { //circular mat gp_Ax2 cs(gpnt, gdir); - BRepPrimAPI_MakeCylinder mkTool(cs, hideToolRadius, extrudeLength); + BRepPrimAPI_MakeCylinder mkTool(cs, radius, extrudeLength); tool = mkTool.Shape(); if(tool.IsNull()) { Base::Console().Warning("DVD::detailExec - %s - failed to create tool (cylinder)\n", getNameInDocument()); @@ -357,29 +304,29 @@ void DrawViewDetail::detailExec(TopoDS_Shape shape, } } + //for each solid and shell in the input shape, make a common with the tool and + //add the result to a compound. This avoids issues with some geometry errors in the + //input shape. BRep_Builder builder; TopoDS_Compound pieces; builder.MakeCompound(pieces); if (solidCount > 0) { - TopExp_Explorer expl(myShape, TopAbs_SOLID); + TopExp_Explorer expl(copyShape, TopAbs_SOLID); for (; expl.More(); expl.Next()) { const TopoDS_Solid& s = TopoDS::Solid(expl.Current()); BRepAlgoAPI_Common mkCommon(s,tool); if (!mkCommon.IsDone()) { - // Base::Console().Warning("DVD::execute - %s - detail cut operation failed (1)\n", getNameInDocument()); continue; } if (mkCommon.Shape().IsNull()) { - // Base::Console().Warning("DVD::execute - %s - detail cut operation failed (2)\n", getNameInDocument()); continue; } //this might be overkill for piecewise algo //Did we get at least 1 solid? TopExp_Explorer xp; xp.Init(mkCommon.Shape(),TopAbs_SOLID); - if (!(xp.More() == Standard_True)) { - // Base::Console().Warning("DVD::execute - mkCommon.Shape is not a solid!\n"); + if (xp.More() != Standard_True) { continue; } builder.Add(pieces, mkCommon.Shape()); @@ -387,25 +334,22 @@ void DrawViewDetail::detailExec(TopoDS_Shape shape, } if (shellCount > 0) { - TopExp_Explorer expl(myShape, TopAbs_SHELL); + TopExp_Explorer expl(copyShape, TopAbs_SHELL); for (; expl.More(); expl.Next()) { const TopoDS_Shell& s = TopoDS::Shell(expl.Current()); BRepAlgoAPI_Common mkCommon(s,tool); if (!mkCommon.IsDone()) { - // Base::Console().Warning("DVD::execute - %s - detail cut operation failed (1)\n", getNameInDocument()); continue; } if (mkCommon.Shape().IsNull()) { - // Base::Console().Warning("DVD::execute - %s - detail cut operation failed (2)\n", getNameInDocument()); continue; } //this might be overkill for piecewise algo //Did we get at least 1 shell? TopExp_Explorer xp; xp.Init(mkCommon.Shape(),TopAbs_SHELL); - if (!(xp.More() == Standard_True)) { - // Base::Console().Warning("DVD::execute - mkCommon.Shape is not a shell!\n"); + if (xp.More() != Standard_True) { continue; } builder.Add(pieces, mkCommon.Shape()); @@ -414,91 +358,104 @@ void DrawViewDetail::detailExec(TopoDS_Shape shape, if (debugDetail()) { BRepTools::Write(tool, "DVDTool.brep"); //debug - BRepTools::Write(myShape, "DVDCopy.brep"); //debug + BRepTools::Write(copyShape, "DVDCopy.brep"); //debug BRepTools::Write(pieces, "DVDCommon.brep"); //debug } -//for debugging show compound instead of common -// BRep_Builder builder; -// TopoDS_Compound Comp; -// builder.MakeCompound(Comp); -// builder.Add(Comp, tool); -// builder.Add(Comp, myShape); - gp_Pnt inputCenter; try { //centroid of result inputCenter = TechDraw::findCentroid(pieces, dirDetail); - Base::Vector3d centroid(inputCenter.X(), - inputCenter.Y(), - inputCenter.Z()); - m_saveCentroid += centroid; //center of massaged shape + Base::Vector3d centroid(inputCenter.X(), + inputCenter.Y(), + inputCenter.Z()); + m_saveCentroid += centroid; //center of massaged shape - TopoDS_Shape scaledShape; - if ((solidCount > 0) || - (shellCount > 0)) { - //align shape with detail anchor - TopoDS_Shape centeredShape = TechDraw::moveShape(pieces, - anchorOffset3d * -1.0); - scaledShape = TechDraw::scaleShape(centeredShape, - getScale()); - if (debugDetail()) { - BRepTools::Write(scaledShape, "DVDScaled.brep"); //debug + if ((solidCount > 0) || + (shellCount > 0)) { + //align shape with detail anchor + TopoDS_Shape centeredShape = TechDraw::moveShape(pieces, + anchor * -1.0); + m_scaledShape = TechDraw::scaleShape(centeredShape, + getScale()); + if (debugDetail()) { + BRepTools::Write(m_scaledShape, "DVDScaled.brep"); //debug + } + } else { + //no solids, no shells, do what you can with edges + TopoDS_Shape projectedEdges = projectEdgesOntoFace(copyShape, extrusionFace, gdir); + TopoDS_Shape centeredShape = TechDraw::moveShape(projectedEdges, + anchor * -1.0); + if (debugDetail()) { + BRepTools::Write(projectedEdges, "DVDProjectedEdges.brep"); //debug + BRepTools::Write(centeredShape, "DVDCenteredShape.brep"); //debug + } + m_scaledShape = TechDraw::scaleShape(centeredShape, + getScale()); } - } else { - //no solids, no shells, do what you can with edges - TopoDS_Shape projectedEdges = projectEdgesOntoFace(myShape, aProjFace, gdir); - TopoDS_Shape centeredShape = TechDraw::moveShape(projectedEdges, - anchorOffset3d * -1.0); - if (debugDetail()) { - BRepTools::Write(projectedEdges, "DVDProjectedEdges.brep"); //debug - BRepTools::Write(centeredShape, "DVDCenteredShape.brep"); //debug + + Base::Vector3d stdOrg(0.0,0.0,0.0); + m_viewAxis = dvp->getProjectionCS(stdOrg); + + if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { + m_scaledShape = TechDraw::rotateShape(m_scaledShape, + m_viewAxis, + Rotation.getValue()); } - scaledShape = TechDraw::scaleShape(centeredShape, - getScale()); - } + } //end try block - Base::Vector3d stdOrg(0.0,0.0,0.0); - gp_Ax2 viewAxis = dvp->getProjectionCS(stdOrg); - - if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { - scaledShape = TechDraw::rotateShape(scaledShape, - viewAxis, - Rotation.getValue()); - } - - geometryObject = buildGeometryObject(scaledShape,viewAxis); - geometryObject->pruneVertexGeom(Base::Vector3d(0.0,0.0,0.0), - Radius.getValue() * scale); //remove vertices beyond clipradius - -#if MOD_TECHDRAW_HANDLE_FACES - if (handleFaces()) { - try { - extractFaces(); - } - catch (Standard_Failure& e4) { - Base::Console().Log("LOG - DVD::execute - extractFaces failed for %s - %s **\n",getNameInDocument(),e4.GetMessageString()); - return; - } - } - -#endif //#if MOD_TECHDRAW_HANDLE_FACES - } catch (Standard_Failure& e1) { - Base::Console().Message("LOG - DVD::execute - failed to create detail %s - %s **\n",getNameInDocument(),e1.GetMessageString()); + Base::Console().Message("DVD::makeDetailShape - failed to create detail %s - %s **\n",getNameInDocument(),e1.GetMessageString()); return; } - addCosmeticVertexesToGeom(); - addCosmeticEdgesToGeom(); - addCenterLinesToGeom(); + showProgressMessage(getNameInDocument(), "has finished making detail shape"); +} - addReferencesToGeom(); //what if landmarks are outside detail area?? +void DrawViewDetail::postHlrTasks(void) +{ +// Base::Console().Message("DVD::postHlrTasks()\n"); + geometryObject->pruneVertexGeom(Base::Vector3d(0.0,0.0,0.0), + Radius.getValue() * getScale()); //remove vertices beyond clipradius + DrawViewPart::postHlrTasks(); + + //second pass if required + if (ScaleType.isValue("Automatic") && !checkFit()) { + double newScale = autoScale(); + Scale.setValue(newScale); + Scale.purgeTouched(); + if (geometryObject) { + delete geometryObject; + geometryObject = nullptr; + detailExec(m_saveShape, m_saveDvp, m_saveDvs); + } + } + overrideKeepUpdated(false); +} + +//continue processing after makeDetailShape thread is finished +void DrawViewDetail::onMakeDetailFinished(void) +{ + waitingForDetail(false); + QObject::disconnect(connectDetailWatcher); + + //ancestor's buildGeometryObject will run HLR and face finding in a separate thread + geometryObject = buildGeometryObject(m_scaledShape, m_viewAxis); } -TopoDS_Shape DrawViewDetail::projectEdgesOntoFace(TopoDS_Shape edgeShape, TopoDS_Face projFace, gp_Dir projDir) +bool DrawViewDetail::waitingForResult() const +{ + if (DrawViewPart::waitingForResult() || + waitingForDetail()) { + return true; + } + return false; +} +TopoDS_Shape DrawViewDetail::projectEdgesOntoFace(TopoDS_Shape &edgeShape, + TopoDS_Face &projFace, + gp_Dir& projDir) { BRep_Builder builder; TopoDS_Compound edges; @@ -522,10 +479,9 @@ TopoDS_Shape DrawViewDetail::projectEdgesOntoFace(TopoDS_Shape edgeShape, TopoDS //we don't want to paint detail highlights on top of detail views, //so tell the Gui that there are no details for this view -std::vector DrawViewDetail::getDetailRefs(void) const +std::vector DrawViewDetail::getDetailRefs() const { - std::vector result; - return result; + return std::vector(); } double DrawViewDetail::getFudgeRadius() @@ -533,13 +489,12 @@ double DrawViewDetail::getFudgeRadius() return Radius.getValue() * m_fudge; } -bool DrawViewDetail::debugDetail(void) const +bool DrawViewDetail::debugDetail() const { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/debug"); - bool result = hGrp->GetBool("debugDetail",false); - return result; + return hGrp->GetBool("debugDetail",false); } void DrawViewDetail::unsetupObject() @@ -547,7 +502,7 @@ void DrawViewDetail::unsetupObject() // Base::Console().Message("DVD::unsetupObject()\n"); App::DocumentObject* baseObj = BaseView.getValue(); DrawView* base = dynamic_cast(baseObj); - if (base != nullptr) { + if (base) { base->requestPaint(); } } @@ -561,7 +516,7 @@ void DrawViewDetail::getParameters() namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewDetailPython, TechDraw::DrawViewDetail) -template<> const char* TechDraw::DrawViewDetailPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewDetailPython::getViewProviderName() const { return "TechDrawGui::ViewProviderViewPart"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewDetail.h b/src/Mod/TechDraw/App/DrawViewDetail.h index 37d84ee302..f6e70ba509 100644 --- a/src/Mod/TechDraw/App/DrawViewDetail.h +++ b/src/Mod/TechDraw/App/DrawViewDetail.h @@ -23,6 +23,11 @@ #ifndef _DrawViewDetail_h_ #define _DrawViewDetail_h_ +#include + +#include +#include + #include #include #include @@ -50,37 +55,59 @@ class TechDrawExport DrawViewDetail : public DrawViewPart public: /// Constructor - DrawViewDetail(void); - virtual ~DrawViewDetail(); + DrawViewDetail(); + ~DrawViewDetail() override; App::PropertyLink BaseView; App::PropertyVector AnchorPoint; App::PropertyFloat Radius; App::PropertyString Reference; - virtual short mustExecute() const override; - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual void onChanged(const App::Property* prop) override; - virtual const char* getViewProviderName(void) const override { + short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; + void onChanged(const App::Property* prop) override; + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewPart"; } - virtual void unsetupObject() override; + void unsetupObject() override; - void detailExec(TopoDS_Shape s, + void detailExec(TopoDS_Shape& s, DrawViewPart* baseView, DrawViewSection* sectionAlias); - double getFudgeRadius(void); - TopoDS_Shape projectEdgesOntoFace(TopoDS_Shape edgeShape, TopoDS_Face projFace, gp_Dir projDir); + void makeDetailShape(TopoDS_Shape& shape, + DrawViewPart* dvp, + DrawViewSection* dvs); + void postHlrTasks(void) override; + void waitingForDetail(bool s) { m_waitingForDetail = s; } + bool waitingForDetail(void) const { return m_waitingForDetail; } + bool waitingForResult() const override; - virtual std::vector getDetailRefs() const override; + double getFudgeRadius(void); + TopoDS_Shape projectEdgesOntoFace(TopoDS_Shape& edgeShape, + TopoDS_Face& projFace, + gp_Dir& projDir); + + std::vector getDetailRefs() const override; + +public Q_SLOTS: + void onMakeDetailFinished(void); protected: - Base::Vector3d toR3(const gp_Ax2 fromSystem, const Base::Vector3d fromPoint); void getParameters(void); double m_fudge; - bool debugDetail(void) const; + bool debugDetail() const; + TopoDS_Shape m_scaledShape; + gp_Ax2 m_viewAxis; + + QMetaObject::Connection connectDetailWatcher; + QFutureWatcher m_detailWatcher; + QFuture m_detailFuture; + bool m_waitingForDetail; + + DrawViewPart* m_saveDvp; + DrawViewSection* m_saveDvs; }; typedef App::FeaturePythonT DrawViewDetailPython; diff --git a/src/Mod/TechDraw/App/DrawViewDimExtent.cpp b/src/Mod/TechDraw/App/DrawViewDimExtent.cpp index aae80a15ed..e8c3c1967a 100644 --- a/src/Mod/TechDraw/App/DrawViewDimExtent.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimExtent.cpp @@ -109,13 +109,11 @@ App::DocumentObjectExecReturn *DrawViewDimExtent::execute(void) } App::DocumentObject* docObj = Source.getValue(); - if (docObj == nullptr) { + if (!docObj) return App::DocumentObject::StdReturn; - } DrawViewPart* dvp = dynamic_cast(docObj); - if (dvp == nullptr) { + if (!dvp) return App::DocumentObject::StdReturn; - } double tolerance = 0.00001; std::vector edgeNames = getSubNames(); @@ -128,102 +126,97 @@ App::DocumentObjectExecReturn *DrawViewDimExtent::execute(void) Base::Vector3d refMin = endPoints.first; Base::Vector3d refMax = endPoints.second; - TechDraw::VertexPtr v0 = nullptr; - TechDraw::VertexPtr v1 = nullptr; std::vector cTags = CosmeticTags.getValues(); - if (cTags.size() > 1) { - v0 = dvp->getProjVertexByCosTag(cTags[0]); - v1 = dvp->getProjVertexByCosTag(cTags[1]); - if ( (v0 != nullptr) && - (v1 != nullptr) ) { - double length00 = (v0->pnt - refMin).Length(); - double length11 = (v1->pnt - refMax).Length(); - double length01 = (v0->pnt - refMax).Length(); - double length10 = (v1->pnt - refMin).Length(); - if ( ((length00 < tolerance) && - (length11 < tolerance)) || - ((length01 < tolerance) && - (length10 < tolerance)) ) { - //nothing changed - nop - } else { - //update GV - v0->pnt = refMin; - v1->pnt = refMax; - // v0->occVertex = ??? - // v1->occVertex = ??? - //update CV - double scale = dvp->getScale(); - CosmeticVertex* cvTemp = dvp->getCosmeticVertex(cTags[0]); - cvTemp->permaPoint = refMin / scale; - cvTemp = dvp->getCosmeticVertex(cTags[1]); - cvTemp->permaPoint = refMax / scale; - } - } + if (cTags.size() <= 1) { + return DrawViewDimension::execute(); } + TechDraw::VertexPtr v0 = dvp->getProjVertexByCosTag(cTags[0]); + TechDraw::VertexPtr v1 = dvp->getProjVertexByCosTag(cTags[1]); + if (!v0 || !v1) + return DrawViewDimension::execute(); + + double length00 = (v0->pnt - refMin).Length(); + double length11 = (v1->pnt - refMax).Length(); + double length01 = (v0->pnt - refMax).Length(); + double length10 = (v1->pnt - refMin).Length(); + + if ((length00 >= tolerance || length11 >= tolerance) && + (length01 >= tolerance || length10 >= tolerance)) { // Something has changed + //update GV + v0->pnt = refMin; + v1->pnt = refMax; +// v0->occVertex = ??? +// v1->occVertex = ??? + //update CV + double scale = dvp->getScale(); + CosmeticVertex* cvTemp = dvp->getCosmeticVertex(cTags[0]); + cvTemp->permaPoint = refMin / scale; + cvTemp = dvp->getCosmeticVertex(cTags[1]); + cvTemp->permaPoint = refMax / scale; + } + + overrideKeepUpdated(false); return DrawViewDimension::execute(); } //getSubValues returns a garbage 1st entry if there are no subelements. std::vector DrawViewDimExtent::getSubNames(void) { - std::vector result; std::vector edgeNames = Source.getSubValues(); - if (!edgeNames.empty() && - (edgeNames[0].size() == 0)) { - //garbage first entry - nop - } else { - result = edgeNames; + if (edgeNames.empty() || + !edgeNames[0].empty()) { + return std::vector(); //garbage first entry - nop } - return result; + return edgeNames; } pointPair DrawViewDimExtent::getPointsTwoVerts() { // Base::Console().Message("DVDE::getPointsTwoVerts() - %s\n",getNameInDocument()); - pointPair result; - result.first = Base::Vector3d(0.0, 0.0, 0.0); - result.second = Base::Vector3d(0.0, 0.0, 0.0); - TechDraw::VertexPtr v0 = nullptr; - TechDraw::VertexPtr v1 = nullptr; + pointPair errorValue( + Base::Vector3d(0.0, 0.0, 0.0), + Base::Vector3d(0.0, 0.0, 0.0) + ); + TechDraw::DrawViewPart* dvp = getViewPart(); - if (dvp == nullptr) { - return result; + if (!dvp) { + return errorValue; } std::vector cTags = CosmeticTags.getValues(); - if (cTags.size() > 1) { - v0 = dvp->getProjVertexByCosTag(cTags[0]); - v1 = dvp->getProjVertexByCosTag(cTags[1]); - if ( (v0 != nullptr) && - (v1 != nullptr) ) { - result.first = v0->pnt; - result.second = v1->pnt; - } + if (cTags.empty()) { + return errorValue; } - return result; + + TechDraw::VertexPtr v0 = dvp->getProjVertexByCosTag(cTags[0]); + TechDraw::VertexPtr v1 = dvp->getProjVertexByCosTag(cTags[1]); + if (!v0 || !v1) + return errorValue; + + return pointPair(v0->pnt, v1->pnt); } //! validate 2D references - only checks if the target exists bool DrawViewDimExtent::checkReferences2D() const { // Base::Console().Message("DVDE::checkReFerences2d() - %s\n",getNameInDocument()); - bool result = false; TechDraw::DrawViewPart* dvp = getViewPart(); - if (dvp == nullptr) { - return result; + if (!dvp) { + return false; } std::vector cTags = CosmeticTags.getValues(); - if (cTags.size() > 1) { - CosmeticVertex* cv0 = dvp->getCosmeticVertex(cTags[0]); - CosmeticVertex* cv1 = dvp->getCosmeticVertex(cTags[1]); - if ( (cv0 != nullptr) && - (cv1 != nullptr) ) { - result = true; - } + if (cTags.empty()) { + return false; } - return result; + + CosmeticVertex* cv0 = dvp->getCosmeticVertex(cTags[0]); + CosmeticVertex* cv1 = dvp->getCosmeticVertex(cTags[1]); + if (!cv0 || !cv1) + return false; + + return true; } void DrawViewDimExtent::unsetupObject() diff --git a/src/Mod/TechDraw/App/DrawViewDimExtent.h b/src/Mod/TechDraw/App/DrawViewDimExtent.h index 0571f6dd2f..98a139eea0 100644 --- a/src/Mod/TechDraw/App/DrawViewDimExtent.h +++ b/src/Mod/TechDraw/App/DrawViewDimExtent.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_DrawViewDimExtent_h_ #define _TechDraw_DrawViewDimExtent_h_ +#include + #include #include @@ -35,12 +37,12 @@ namespace TechDraw { class TechDrawExport DrawViewDimExtent : public TechDraw::DrawViewDimension { - PROPERTY_HEADER(TechDraw::DrawViewDimExtent); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawViewDimExtent); public: /// Constructor DrawViewDimExtent(); - virtual ~DrawViewDimExtent(); + ~DrawViewDimExtent() override; App::PropertyLinkSubList Source; //DrawViewPart & SubElements(Edges) //Cosmetic End points are stored in DVD::References2d @@ -48,19 +50,19 @@ public: App::PropertyInteger DirExtent; //Horizontal, Vertical, TBD App::PropertyStringList CosmeticTags; //id of cosmetic end points. - virtual App::DocumentObjectExecReturn *execute(void); - virtual short mustExecute() const; - virtual void unsetupObject(); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + void unsetupObject() override; - virtual bool checkReferences2D(void) const; + bool checkReferences2D() const override; //return PyObject as DrawViewDimExtentPy - virtual PyObject *getPyObject(void); + PyObject *getPyObject() override; protected: - virtual void onChanged(const App::Property* prop); - std::vector getSubNames(void); - virtual pointPair getPointsTwoVerts(); + void onChanged(const App::Property* prop) override; + std::vector getSubNames(); + pointPair getPointsTwoVerts() override; private: }; diff --git a/src/Mod/TechDraw/App/DrawViewDimExtentPyImp.cpp b/src/Mod/TechDraw/App/DrawViewDimExtentPyImp.cpp index 4603b424d4..a1e41873a2 100644 --- a/src/Mod/TechDraw/App/DrawViewDimExtentPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimExtentPyImp.cpp @@ -38,7 +38,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawViewDimExtentPy::representation(void) const +std::string DrawViewDimExtentPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawViewDimension.cpp b/src/Mod/TechDraw/App/DrawViewDimension.cpp index 30f69e073e..c309cfa90f 100644 --- a/src/Mod/TechDraw/App/DrawViewDimension.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimension.cpp @@ -103,7 +103,7 @@ static const App::PropertyQuantityConstraint::Constraints ToleranceConstraint = // constraint to force positive values static const App::PropertyQuantityConstraint::Constraints PositiveConstraint = { 0.0, DBL_MAX, 0.1 }; -DrawViewDimension::DrawViewDimension(void) +DrawViewDimension::DrawViewDimension() { ADD_PROPERTY_TYPE(References2D, (nullptr,nullptr), "", (App::Prop_None), "Projected Geometry References"); References2D.setScope(App::LinkScope::Global); @@ -166,20 +166,20 @@ DrawViewDimension::~DrawViewDimension() measurement = nullptr; } -void DrawViewDimension::resetLinear(void) +void DrawViewDimension::resetLinear() { m_linearPoints.first = Base::Vector3d(0,0,0); m_linearPoints.second = Base::Vector3d(0,0,0); } -void DrawViewDimension::resetAngular(void) +void DrawViewDimension::resetAngular() { m_anglePoints.ends.first = Base::Vector3d(0,0,0); m_anglePoints.ends.second = Base::Vector3d(0,0,0); m_anglePoints.vertex = Base::Vector3d(0,0,0); } -void DrawViewDimension::resetArc(void) +void DrawViewDimension::resetArc() { m_arcPoints.isArc = false; m_arcPoints.center = Base::Vector3d(0,0,0); @@ -205,10 +205,8 @@ void DrawViewDimension::onChanged(const App::Property* prop) clear3DMeasurements(); //Measurement object if (!(References3D.getValues()).empty()) { setAll3DMeasurement(); - } else { - if (MeasureType.isValue("True")) { //empty 3dRefs, but True - MeasureType.touch(); //run MeasureType logic for this case - } + } else if (MeasureType.isValue("True")) { //empty 3dRefs, but True + MeasureType.touch(); //run MeasureType logic for this case } } else if (prop == &Type) { //why?? @@ -343,13 +341,13 @@ void DrawViewDimension::handleChangedPropertyType(Base::XMLReader &reader, const } // Over/Undertolerance were further changed from App::PropertyQuantity to App::PropertyQuantityConstraint - if ((prop == &OverTolerance) && (strcmp(TypeName, "App::PropertyQuantity") == 0)) { + if (prop == &OverTolerance && strcmp(TypeName, "App::PropertyQuantity") == 0) { App::PropertyQuantity OverToleranceProperty; // restore the PropertyQuantity to be able to set its value OverToleranceProperty.Restore(reader); OverTolerance.setValue(OverToleranceProperty.getValue()); } - else if ((prop == &UnderTolerance) && (strcmp(TypeName, "App::PropertyQuantity") == 0)) { + else if (prop == &UnderTolerance && strcmp(TypeName, "App::PropertyQuantity") == 0) { App::PropertyQuantity UnderToleranceProperty; // restore the PropertyQuantity to be able to set its value UnderToleranceProperty.Restore(reader); @@ -360,38 +358,37 @@ void DrawViewDimension::handleChangedPropertyType(Base::XMLReader &reader, const short DrawViewDimension::mustExecute() const { - bool result = 0; if (!isRestoring()) { - result = (References2D.isTouched() || - Type.isTouched() || - FormatSpec.isTouched() || - Arbitrary.isTouched() || - FormatSpecOverTolerance.isTouched() || - FormatSpecUnderTolerance.isTouched() || - ArbitraryTolerances.isTouched() || - MeasureType.isTouched() || - TheoreticalExact.isTouched() || - EqualTolerance.isTouched() || - OverTolerance.isTouched() || - UnderTolerance.isTouched() || - Inverted.isTouched() ); - } - if (result) { - return result; + if ( + References2D.isTouched() || + Type.isTouched() || + FormatSpec.isTouched() || + Arbitrary.isTouched() || + FormatSpecOverTolerance.isTouched() || + FormatSpecUnderTolerance.isTouched() || + ArbitraryTolerances.isTouched() || + MeasureType.isTouched() || + TheoreticalExact.isTouched() || + EqualTolerance.isTouched() || + OverTolerance.isTouched() || + UnderTolerance.isTouched() || + Inverted.isTouched() + ) { + return true; + } } return DrawView::mustExecute(); } -App::DocumentObjectExecReturn *DrawViewDimension::execute(void) +App::DocumentObjectExecReturn *DrawViewDimension::execute() { if (!keepUpdated()) { return App::DocumentObject::StdReturn; } DrawViewPart* dvp = getViewPart(); - if (dvp == nullptr) { + if (!dvp) return App::DocumentObject::StdReturn; - } if (!has2DReferences()) { //too soon? if (isRestoring() || @@ -739,28 +736,23 @@ App::DocumentObjectExecReturn *DrawViewDimension::execute(void) m_hasGeometry = true; } - //TODO: if MeasureType = Projected and the Projected shape changes, the Dimension may become invalid (see tilted Cube example) + overrideKeepUpdated(false); return DrawView::execute(); } -bool DrawViewDimension::isMultiValueSchema(void) const +bool DrawViewDimension::isMultiValueSchema() const { - bool result = false; - bool angularMeasure = false; - if ( (Type.isValue("Angle")) || - (Type.isValue("Angle3Pt")) ) { - angularMeasure = true; - } + bool angularMeasure = (Type.isValue("Angle") || Type.isValue("Angle3Pt")); Base::UnitSystem uniSys = Base::UnitsApi::getSchema(); - if ((uniSys == Base::UnitSystem::ImperialBuilding) && + if (uniSys == Base::UnitSystem::ImperialBuilding && !angularMeasure) { - result = true; - } else if ((uniSys == Base::UnitSystem::ImperialCivil) && + return true; + } else if (uniSys == Base::UnitSystem::ImperialCivil && !angularMeasure) { - result = true; + return true; } - return result; + return false; } std::string DrawViewDimension::getBaseLengthUnit(Base::UnitSystem system) @@ -794,8 +786,6 @@ std::string DrawViewDimension::formatValue(qreal value, int partial, bool isDim) { - std::string result; - QString qUserStringUnits; QString formattedValue; bool angularMeasure = false; @@ -934,10 +924,11 @@ std::string DrawViewDimension::formatValue(qreal value, } } - result = formattedValue.toStdString(); + + std::string formattedValueString = formattedValue.toStdString(); if (partial == 0) { //full text for multi-value schemas - result = Base::Tools::toStdString(formatPrefix) + + return Base::Tools::toStdString(formatPrefix) + Base::Tools::toStdString(qMultiValueStr) + Base::Tools::toStdString(formatSuffix) + Base::Tools::toStdString(qUserStringUnits); @@ -952,26 +943,26 @@ std::string DrawViewDimension::formatValue(qreal value, } if (angularMeasure) { //always insert unit after value - result = Base::Tools::toStdString(formatPrefix) + - result + + return Base::Tools::toStdString(formatPrefix) + + formattedValueString + Base::Tools::toStdString(qUserStringUnits) + Base::Tools::toStdString(formatSuffix); } else if (showUnits()){ if (isDim && haveTolerance()) { //unit will be included in tolerance so don't repeat it here - result = Base::Tools::toStdString(formatPrefix) + - result + + return Base::Tools::toStdString(formatPrefix) + + formattedValueString + Base::Tools::toStdString(formatSuffix); } else { //no tolerance, so we need to include unit - result = Base::Tools::toStdString(formatPrefix) + - result + + return Base::Tools::toStdString(formatPrefix) + + formattedValueString + Base::Tools::toStdString(qUserStringUnits) + Base::Tools::toStdString(formatSuffix); } } else { - result = Base::Tools::toStdString(formatPrefix) + - result + + return Base::Tools::toStdString(formatPrefix) + + formattedValueString + Base::Tools::toStdString(formatSuffix); } } @@ -982,28 +973,27 @@ std::string DrawViewDimension::formatValue(qreal value, QRegExp space(QString::fromUtf8("\\s")); qUserStringUnits.remove(space); } - result = Base::Tools::toStdString(qUserStringUnits); + return Base::Tools::toStdString(qUserStringUnits); } else if (showUnits()) { - result = Base::Tools::toStdString(qUserStringUnits); + return Base::Tools::toStdString(qUserStringUnits); } else { - result = ""; + return ""; } } - return result; + return formattedValueString; } -bool DrawViewDimension::haveTolerance(void) +bool DrawViewDimension::haveTolerance() { - bool result = false; //if a numeric tolerance is specified AND //tolerances are NOT arbitrary if ((!DrawUtil::fpCompare(OverTolerance.getValue(), 0.0) || !DrawUtil::fpCompare(UnderTolerance.getValue(), 0.0)) && !ArbitraryTolerances.getValue()){ - result = true; + return true; } - return result; + return false; } std::string DrawViewDimension::getFormattedToleranceValue(int partial) @@ -1098,22 +1088,21 @@ std::string DrawViewDimension::getFormattedDimensionValue(int partial) 2, false).c_str()); //just the unit QString tolerance = QString::fromStdString(getFormattedToleranceValue(1).c_str()); - QString result; // tolerance might start with a plus sign that we don't want, so cut it off // note plus sign is not at pos = 0! QRegExp plus(QString::fromUtf8("^\\s*\\+")); tolerance.remove(plus); - result = labelText + + return (labelText + QString::fromUtf8(" \xC2\xB1 ") + // +/- symbol - tolerance; + tolerance).toStdString(); if (partial == 2) { - result = unitText; + return unitText.toStdString(); } - return result.toStdString(); + return ""; } //tolerance not specified, so just format dimension value? @@ -1125,17 +1114,14 @@ std::string DrawViewDimension::getFormattedDimensionValue(int partial) QStringList DrawViewDimension::getPrefixSuffixSpec(QString fSpec) { QStringList result; - QString formatPrefix; - QString formatSuffix; //find the %x.y tag in FormatSpec QRegExp rxFormat(QStringLiteral("%[+-]?[0-9]*\\.*[0-9]*[aefgwAEFGW]")); //printf double format spec - QString match; - int pos = 0; - if ((pos = rxFormat.indexIn(fSpec, 0)) != -1) { - match = rxFormat.cap(0); //entire capture of rx - formatPrefix = fSpec.left(pos); + int pos = rxFormat.indexIn(fSpec, 0); + if (pos != -1) { + QString match = rxFormat.cap(0); //entire capture of rx + QString formatPrefix = fSpec.left(pos); result.append(formatPrefix); - formatSuffix = fSpec.right(fSpec.size() - pos - match.size()); + QString formatSuffix = fSpec.right(fSpec.size() - pos - match.size()); result.append(formatSuffix); result.append(match); } else { //printf format not found! @@ -1163,13 +1149,11 @@ double DrawViewDimension::getDimValue() } return result; } - if (getViewPart() == nullptr) { + if (!getViewPart()) return result; - } - if (!getViewPart()->hasGeometry() ) { //happens when loading saved document + if (!getViewPart()->hasGeometry()) //happens when loading saved document return result; - } if (MeasureType.isValue("True")) { // True Values @@ -1217,7 +1201,8 @@ double DrawViewDimension::getDimValue() arcPoints pts = m_arcPoints; result = (pts.radius * 2.0) / getViewPart()->getScale(); //Projected BaseGeom is scaled for drawing - } else if (Type.isValue("Angle")){ + } else if (Type.isValue("Angle") || + Type.isValue("Angle3Pt")) { //same as case "Angle"? anglePoints pts = m_anglePoints; Base::Vector3d vertex = pts.vertex; Base::Vector3d leg0 = pts.ends.first - vertex; @@ -1225,13 +1210,6 @@ double DrawViewDimension::getDimValue() double legAngle = leg0.GetAngle(leg1) * 180.0 / M_PI; result = legAngle; - } else if (Type.isValue("Angle3Pt")){ //same as case "Angle"? - anglePoints pts = m_anglePoints; - Base::Vector3d vertex = pts.vertex; - Base::Vector3d leg0 = pts.ends.first - vertex; - Base::Vector3d leg1 = pts.ends.second - vertex; - double legAngle = leg0.GetAngle(leg1) * 180.0 / M_PI; - result = legAngle; } } @@ -1250,22 +1228,18 @@ double DrawViewDimension::getDimValue() pointPair DrawViewDimension::getPointsOneEdge() { // Base::Console().Message("DVD::getPointsOneEdge() - %s\n",getNameInDocument()); - pointPair result; const std::vector &subElements = References2D.getSubValues(); //TODO: Check for straight line Edge? int idx = DrawUtil::getIndexFromName(subElements[0]); TechDraw::BaseGeomPtr geom = getViewPart()->getGeomByIndex(idx); - TechDraw::GenericPtr gen; - if (geom && geom->geomType == TechDraw::GeomType::GENERIC) { - gen = std::static_pointer_cast(geom); - } else { + if (!geom || geom->geomType != TechDraw::GeomType::GENERIC) { Base::Console().Error("Error: DVD - %s - 2D references are corrupt (1)\n",getNameInDocument()); - return result; + return pointPair(); } - result.first = gen->points[0]; - result.second = gen->points[1]; - return result; + + TechDraw::GenericPtr gen = std::static_pointer_cast(geom); + return pointPair(gen->points[0], gen->points[1]); } pointPair DrawViewDimension::getPointsTwoEdges() @@ -1278,8 +1252,7 @@ pointPair DrawViewDimension::getPointsTwoEdges() int idx1 = DrawUtil::getIndexFromName(subElements[1]); TechDraw::BaseGeomPtr geom0 = getViewPart()->getGeomByIndex(idx0); TechDraw::BaseGeomPtr geom1 = getViewPart()->getGeomByIndex(idx1); - if ((geom0 == nullptr) || - (geom1 == nullptr) ) { + if (!geom0 || !geom1) { Base::Console().Error("Error: DVD - %s - 2D references are corrupt (2)\n",getNameInDocument()); return result; } @@ -1297,8 +1270,7 @@ pointPair DrawViewDimension::getPointsTwoVerts() int idx1 = DrawUtil::getIndexFromName(subElements[1]); TechDraw::VertexPtr v0 = getViewPart()->getProjVertexByIndex(idx0); TechDraw::VertexPtr v1 = getViewPart()->getProjVertexByIndex(idx1); - if ((v0 == nullptr) || - (v1 == nullptr) ) { + if (!v0 || !v1) { Base::Console().Error("Error: DVD - %s - 2D references are corrupt (3)\n",getNameInDocument()); return result; } @@ -1322,7 +1294,7 @@ pointPair DrawViewDimension::getPointsEdgeVert() e = getViewPart()->getGeomByIndex(idx1); v = getViewPart()->getProjVertexByIndex(idx0); } - if ((v == nullptr) || (e == nullptr) ) { + if (!v || !e) { Base::Console().Error("Error: DVD - %s - 2D references are corrupt (4)\n", getNameInDocument()); return result; } @@ -1368,40 +1340,38 @@ int DrawViewDimension::getRefTypeSubElements(const std::vector &sub bool DrawViewDimension::checkReferences2D() const { // Base::Console().Message("DVD::checkReFerences2d() - %s\n",getNameInDocument()); - bool result = true; const std::vector &objects = References2D.getValues(); - if (!objects.empty()) { - const std::vector &subElements = References2D.getSubValues(); - if (!subElements.empty()) { - for (auto& s: subElements) { - if (!s.empty()) { - int idx = DrawUtil::getIndexFromName(s); - if (DrawUtil::getGeomTypeFromName(s) == "Edge") { - TechDraw::BaseGeomPtr geom = getViewPart()->getGeomByIndex(idx); - if (geom == nullptr) { - result = false; - break; - } - } else if (DrawUtil::getGeomTypeFromName(s) == "Vertex") { - TechDraw::VertexPtr v = getViewPart()->getProjVertexByIndex(idx); - if (v == nullptr) { - result = false; - break; - } - } - } else { - result = false; - } - } - } else { - Base::Console().Log("DVD::checkRegerences2d() - %s - subelements empty!\n",getNameInDocument()); - result = false; - } - } else { - Base::Console().Log("DVD::checkRegerences2d() - %s - objects empty!\n",getNameInDocument()); - result = false; + if (objects.empty()) { + Base::Console().Log("DVD::checkReferences2d() - %s - objects empty!\n",getNameInDocument()); + return false; } - return result; + + const std::vector &subElements = References2D.getSubValues(); + if (subElements.empty()) { + Base::Console().Log("DVD::checkRegerences2d() - %s - subelements empty!\n",getNameInDocument()); + return false; + } + + for (auto& s: subElements) { + if (s.empty()) { + return false; + } + + int idx = DrawUtil::getIndexFromName(s); + if (DrawUtil::getGeomTypeFromName(s) == "Edge") { + TechDraw::BaseGeomPtr geom = getViewPart()->getGeomByIndex(idx); + if (!geom) { + return false; + } + } else if (DrawUtil::getGeomTypeFromName(s) == "Vertex") { + TechDraw::VertexPtr v = getViewPart()->getProjVertexByIndex(idx); + if (!v) { + return false; + } + } + } + + return true; } pointPair DrawViewDimension::closestPoints(TopoDS_Shape s1, @@ -1512,7 +1482,7 @@ bool DrawViewDimension::leaderIntersectsArc(Base::Vector3d s, Base::Vector3d poi void DrawViewDimension::saveArrowPositions(const Base::Vector2d positions[]) { - if (positions == nullptr) { + if (!positions) { m_arrowPositions.first = Base::Vector3d(0.0, 0.0, 0.0); m_arrowPositions.second = Base::Vector3d(0.0, 0.0, 0.0); } else { @@ -1524,59 +1494,50 @@ void DrawViewDimension::saveArrowPositions(const Base::Vector2d positions[]) //return position within parent view of dimension arrow heads/dimline endpoints //note positions are in apparent coord (inverted y). -pointPair DrawViewDimension::getArrowPositions(void) +pointPair DrawViewDimension::getArrowPositions() { return m_arrowPositions; } -bool DrawViewDimension::has2DReferences(void) const +bool DrawViewDimension::has2DReferences() const { // Base::Console().Message("DVD::has2DReferences() - %s\n",getNameInDocument()); - bool result = false; - const std::vector &objects = References2D.getValues(); const std::vector &SubNames = References2D.getSubValues(); - if (!objects.empty()) { - App::DocumentObject* testRef = objects.at(0); - if (testRef != nullptr) { - if (!SubNames.empty()) { - result = true; //not empty is good - for (auto& s: SubNames) { //but check individual entries - if (s.empty()) { - result = false; - break; - } - } - } + if (objects.empty() || SubNames.empty()) { + return false; + } + + for (auto& s: SubNames) { // Check individual entries + if (s.empty()) { + return false; } } - return result; + + return true; } -bool DrawViewDimension::has3DReferences(void) const +bool DrawViewDimension::has3DReferences() const { return (References3D.getSize() > 0); } //has arbitrary or nonzero tolerance -bool DrawViewDimension::hasOverUnderTolerance(void) const +bool DrawViewDimension::hasOverUnderTolerance() const { - bool result = false; if (ArbitraryTolerances.getValue() || !DrawUtil::fpCompare(OverTolerance.getValue(), 0.0) || !DrawUtil::fpCompare(UnderTolerance.getValue(), 0.0)) { - result = true; + return true; } - return result; + return false; } bool DrawViewDimension::showUnits() const { - bool result = false; Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Dimensions"); - result = hGrp->GetBool("ShowUnits", false); - return result; + return hGrp->GetBool("ShowUnits", false); } bool DrawViewDimension::useDecimals() const @@ -1586,26 +1547,15 @@ bool DrawViewDimension::useDecimals() const std::string DrawViewDimension::getPrefix() const { - std::string result = ""; - if (Type.isValue("Distance")) { - result = ""; - } else if (Type.isValue("DistanceX")){ - result = ""; - } else if (Type.isValue("DistanceY")){ - result = ""; - } else if (Type.isValue("DistanceZ")){ - result = ""; - } else if (Type.isValue("Radius")){ - result = "R"; + if (Type.isValue("Radius")){ + return "R"; } else if (Type.isValue("Diameter")){ Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Dimensions"); - std::string diamSym = hGrp->GetASCII("DiameterSymbol","\xe2\x8c\x80"); - result = diamSym; - } else if (Type.isValue("Angle")){ - result = ""; + return std::string(hGrp->GetASCII("DiameterSymbol","\xe2\x8c\x80")); // Diameter symbol } - return result; + + return ""; } std::string DrawViewDimension::getDefaultFormatSpec(bool isToleranceFormat) const @@ -1668,7 +1618,7 @@ std::string DrawViewDimension::getDefaultFormatSpec(bool isToleranceFormat) cons // return result; //} -PyObject *DrawViewDimension::getPyObject(void) +PyObject *DrawViewDimension::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 diff --git a/src/Mod/TechDraw/App/DrawViewDimension.h b/src/Mod/TechDraw/App/DrawViewDimension.h index e2225ff140..5a4a2c7543 100644 --- a/src/Mod/TechDraw/App/DrawViewDimension.h +++ b/src/Mod/TechDraw/App/DrawViewDimension.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_DrawViewDimension_h_ #define _TechDraw_DrawViewDimension_h_ +#include + #include #include @@ -59,6 +61,20 @@ struct anglePoints ends.second = Base::Vector3d(0.0,0.0,0.0); vertex = Base::Vector3d(0.0,0.0,0.0); } + + anglePoints(const anglePoints& ap) + : ends(ap.ends) + , vertex(ap.vertex) + { + + } + + anglePoints& operator= (const anglePoints& ap) + { + ends = ap.ends; + vertex = ap.vertex; + return *this; + } }; struct arcPoints @@ -84,6 +100,29 @@ struct arcPoints arcCW = false; } + arcPoints(const arcPoints& ap) + : isArc(ap.isArc) + , radius(ap.radius) + , center(ap.center) + , onCurve(ap.onCurve) + , arcEnds(ap.arcEnds) + , midArc(ap.midArc) + , arcCW(ap.arcCW) + { + + } + + arcPoints& operator= (const arcPoints& ap) + { + isArc = ap.isArc; + radius = ap.radius; + center = ap.center; + onCurve = ap.onCurve; + arcEnds = ap.arcEnds; + midArc = ap.midArc; + arcCW = ap.arcCW; + return *this; + } }; class TechDrawExport DrawViewDimension : public TechDraw::DrawView @@ -93,7 +132,7 @@ class TechDrawExport DrawViewDimension : public TechDraw::DrawView public: /// Constructor DrawViewDimension(); - virtual ~DrawViewDimension(); + ~DrawViewDimension() override; App::PropertyEnumeration MeasureType; //True/Projected App::PropertyLinkSubList References2D; //Points to Projection SubFeatures @@ -126,60 +165,60 @@ public: short mustExecute() const override; - virtual bool has2DReferences(void) const; - virtual bool has3DReferences(void) const; - bool hasOverUnderTolerance(void) const; + virtual bool has2DReferences() const; + virtual bool has3DReferences() const; + bool hasOverUnderTolerance() const; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderDimension"; } //return PyObject as DrawViewDimensionPy - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; virtual std::string getFormattedToleranceValue(int partial); virtual std::pair getFormattedToleranceValues(int partial = 0); virtual std::string getFormattedDimensionValue(int partial = 0); virtual std::string formatValue(qreal value, QString qFormatSpec, int partial = 0, bool isDim = true); - virtual bool haveTolerance(void); + virtual bool haveTolerance(); virtual double getDimValue(); QStringList getPrefixSuffixSpec(QString fSpec); virtual DrawViewPart* getViewPart() const; - virtual QRectF getRect() const override { return QRectF(0,0,1,1);} //pretend dimensions always fit! + QRectF getRect() const override { return QRectF(0,0,1,1);} //pretend dimensions always fit! virtual int getRefType() const; //Vertex-Vertex, Edge, Edge-Edge static int getRefTypeSubElements(const std::vector &); //Vertex-Vertex, Edge, Edge-Edge void setAll3DMeasurement(); - void clear3DMeasurements(void); - virtual bool checkReferences2D(void) const; - pointPair getLinearPoints(void) {return m_linearPoints; } - arcPoints getArcPoints(void) {return m_arcPoints; } - anglePoints getAnglePoints(void) {return m_anglePoints; } + void clear3DMeasurements(); + virtual bool checkReferences2D() const; + pointPair getLinearPoints() {return m_linearPoints; } + arcPoints getArcPoints() {return m_arcPoints; } + anglePoints getAnglePoints() {return m_anglePoints; } bool leaderIntersectsArc(Base::Vector3d s, Base::Vector3d pointOnCircle); - bool isMultiValueSchema(void) const; + bool isMultiValueSchema() const; std::string getBaseLengthUnit(Base::UnitSystem system); - pointPair getArrowPositions(void); + pointPair getArrowPositions(); void saveArrowPositions(const Base::Vector2d positions[]); bool showUnits() const; bool useDecimals() const; protected: - virtual void handleChangedPropertyType(Base::XMLReader &, const char * , App::Property * ) override; - virtual void Restore(Base::XMLReader& reader) override; - virtual void onChanged(const App::Property* prop) override; - virtual void onDocumentRestored() override; + void handleChangedPropertyType(Base::XMLReader &, const char * , App::Property * ) override; + void Restore(Base::XMLReader& reader) override; + void onChanged(const App::Property* prop) override; + void onDocumentRestored() override; std::string getPrefix() const; std::string getDefaultFormatSpec(bool isToleranceFormat = false) const; virtual pointPair getPointsOneEdge(); @@ -198,9 +237,9 @@ protected: pointPair m_linearPoints; pointPair m_arrowPositions; - void resetLinear(void); - void resetAngular(void); - void resetArc(void); + void resetLinear(); + void resetAngular(); + void resetArc(); private: static const char* TypeEnums[]; diff --git a/src/Mod/TechDraw/App/DrawViewDimensionPyImp.cpp b/src/Mod/TechDraw/App/DrawViewDimensionPyImp.cpp index 80aed293cd..e8851ecb5a 100644 --- a/src/Mod/TechDraw/App/DrawViewDimensionPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewDimensionPyImp.cpp @@ -38,7 +38,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawViewDimensionPy::representation(void) const +std::string DrawViewDimensionPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/DrawViewDraft.cpp b/src/Mod/TechDraw/App/DrawViewDraft.cpp index 1a3b1bfb06..ac4ffe4c91 100644 --- a/src/Mod/TechDraw/App/DrawViewDraft.cpp +++ b/src/Mod/TechDraw/App/DrawViewDraft.cpp @@ -47,7 +47,7 @@ using namespace std; PROPERTY_SOURCE(TechDraw::DrawViewDraft, TechDraw::DrawViewSymbol) -DrawViewDraft::DrawViewDraft(void) +DrawViewDraft::DrawViewDraft() { static const char *group = "Draft view"; @@ -69,26 +69,24 @@ DrawViewDraft::~DrawViewDraft() short DrawViewDraft::mustExecute() const { - short result = 0; if (!isRestoring()) { - result = Source.isTouched() || - LineWidth.isTouched() || - FontSize.isTouched() || - Direction.isTouched() || - Color.isTouched() || - LineStyle.isTouched() || - LineSpacing.isTouched() || - OverrideStyle.isTouched(); - } - if ((bool) result) { - return result; + if(Source.isTouched() || + LineWidth.isTouched() || + FontSize.isTouched() || + Direction.isTouched() || + Color.isTouched() || + LineStyle.isTouched() || + LineSpacing.isTouched() || + OverrideStyle.isTouched()) { + return true; + } } return DrawViewSymbol::mustExecute(); } -App::DocumentObjectExecReturn *DrawViewDraft::execute(void) +App::DocumentObjectExecReturn *DrawViewDraft::execute() { // Base::Console().Message("DVDr::execute() \n"); if (!keepUpdated()) { @@ -112,7 +110,7 @@ App::DocumentObjectExecReturn *DrawViewDraft::execute(void) // TODO treat fillstyle here << ",direction=FreeCAD.Vector(" << Direction.getValue().x << "," << Direction.getValue().y << "," << Direction.getValue().z << ")" << ",linestyle=\"" << LineStyle.getValue() << "\"" - << ",color=\"" << col.asCSSString() << "\"" + << ",color=\"" << col.asHexString() << "\"" << ",linespacing=" << LineSpacing.getValue() // We must set techdraw to "true" becausea couple of things behave differently than in Drawing << ",techdraw=True" @@ -128,11 +126,12 @@ App::DocumentObjectExecReturn *DrawViewDraft::execute(void) Base::Interpreter().runStringArg("App.activeDocument().%s.Symbol = '%s' + svgBody + '%s'", FeatName.c_str(),svgHead.c_str(),svgTail.c_str()); } -// requestPaint(); + + overrideKeepUpdated(false); return DrawView::execute(); } -std::string DrawViewDraft::getSVGHead(void) +std::string DrawViewDraft::getSVGHead() { std::string head = std::string(" const char* TechDraw::DrawViewDraftPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewDraftPython::getViewProviderName() const { return "TechDrawGui::ViewProviderDraft"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewDraft.h b/src/Mod/TechDraw/App/DrawViewDraft.h index 81e98ba27e..793ef3ff90 100644 --- a/src/Mod/TechDraw/App/DrawViewDraft.h +++ b/src/Mod/TechDraw/App/DrawViewDraft.h @@ -23,6 +23,8 @@ #ifndef _DrawViewDraft_h_ #define _DrawViewDraft_h_ +#include + #include #include #include @@ -40,8 +42,8 @@ class TechDrawExport DrawViewDraft : public TechDraw::DrawViewSymbol public: /// Constructor - DrawViewDraft(void); - virtual ~DrawViewDraft(); + DrawViewDraft(); + ~DrawViewDraft() override; App::PropertyLink Source; App::PropertyFloat LineWidth; @@ -55,21 +57,21 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderDraft"; } - virtual short mustExecute() const override; + short mustExecute() const override; protected: /* virtual void onChanged(const App::Property* prop) override;*/ Base::BoundBox3d bbox; - std::string getSVGHead(void); - std::string getSVGTail(void); + std::string getSVGHead(); + std::string getSVGTail(); }; typedef App::FeaturePythonT DrawViewDraftPython; diff --git a/src/Mod/TechDraw/App/DrawViewImage.cpp b/src/Mod/TechDraw/App/DrawViewImage.cpp index 71618f0a2f..b62cac2501 100644 --- a/src/Mod/TechDraw/App/DrawViewImage.cpp +++ b/src/Mod/TechDraw/App/DrawViewImage.cpp @@ -50,7 +50,7 @@ using namespace std; PROPERTY_SOURCE(TechDraw::DrawViewImage, TechDraw::DrawView) -DrawViewImage::DrawViewImage(void) +DrawViewImage::DrawViewImage() { static const char *vgroup = "Image"; @@ -73,8 +73,7 @@ void DrawViewImage::onChanged(const App::Property* prop) { App::Document* doc = getDocument(); if (!isRestoring()) { - if ((prop == &ImageFile) && - (doc != nullptr) ) { + if ((prop == &ImageFile) && doc) { if (!ImageFile.isEmpty()) { replaceImageIncluded(ImageFile.getValue()); } @@ -89,19 +88,17 @@ void DrawViewImage::onChanged(const App::Property* prop) short DrawViewImage::mustExecute() const { - short result = 0; if (!isRestoring()) { - result = (Height.isTouched() || - Width.isTouched()); + if (Height.isTouched() || + Width.isTouched()) { + return true; + }; } - if (result) { - return result; - } return App::DocumentObject::mustExecute(); } -App::DocumentObjectExecReturn *DrawViewImage::execute(void) +App::DocumentObjectExecReturn *DrawViewImage::execute() { requestPaint(); return DrawView::execute(); @@ -109,13 +106,12 @@ App::DocumentObjectExecReturn *DrawViewImage::execute(void) QRectF DrawViewImage::getRect() const { - QRectF result(0.0,0.0,Width.getValue(),Height.getValue()); - return result; + return QRectF(0.0,0.0,Width.getValue(), Height.getValue()); } void DrawViewImage::replaceImageIncluded(std::string newFileName) { - Base::Console().Message("DVI::replaceImageIncluded(%s)\n", newFileName.c_str()); +// Base::Console().Message("DVI::replaceImageIncluded(%s)\n", newFileName.c_str()); if (ImageIncluded.isEmpty()) { setupImageIncluded(); } else { @@ -125,9 +121,9 @@ void DrawViewImage::replaceImageIncluded(std::string newFileName) } } -void DrawViewImage::setupImageIncluded(void) +void DrawViewImage::setupImageIncluded() { - Base::Console().Message("DVI::setupImageIncluded()\n"); +// Base::Console().Message("DVI::setupImageIncluded()\n"); App::Document* doc = getDocument(); std::string dir = doc->TransientDir.getValue(); std::string special = getNameInDocument(); @@ -139,14 +135,18 @@ void DrawViewImage::setupImageIncluded(void) DrawUtil::copyFile(std::string(), imageName); ImageIncluded.setValue(imageName.c_str()); - if (!ImageFile.isEmpty()) { - Base::FileInfo fi(ImageFile.getValue()); - if (fi.isReadable()) { - std::string exchName = ImageIncluded.getExchangeTempFile(); - DrawUtil::copyFile(ImageFile.getValue(), exchName); - ImageIncluded.setValue(exchName.c_str(), special.c_str()); - } + if (ImageFile.isEmpty()) { + return; } + + Base::FileInfo fi(ImageFile.getValue()); + if (!fi.isReadable()) { + return; + } + + std::string exchName = ImageIncluded.getExchangeTempFile(); + DrawUtil::copyFile(ImageFile.getValue(), exchName); + ImageIncluded.setValue(exchName.c_str(), special.c_str()); } // Python Drawing feature --------------------------------------------------------- @@ -154,7 +154,7 @@ void DrawViewImage::setupImageIncluded(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewImagePython, TechDraw::DrawViewImage) -template<> const char* TechDraw::DrawViewImagePython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewImagePython::getViewProviderName() const { return "TechDrawGui::ViewProviderImage"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewImage.h b/src/Mod/TechDraw/App/DrawViewImage.h index d9aaa4919f..2d2379dede 100644 --- a/src/Mod/TechDraw/App/DrawViewImage.h +++ b/src/Mod/TechDraw/App/DrawViewImage.h @@ -42,8 +42,8 @@ class TechDrawExport DrawViewImage : public TechDraw::DrawView public: /// Constructor - DrawViewImage(void); - virtual ~DrawViewImage(); + DrawViewImage(); + ~DrawViewImage() override; App::PropertyFile ImageFile; App::PropertyFileIncluded ImageIncluded; @@ -53,19 +53,19 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} short mustExecute() const override; /// returns the type name of the ViewProvider - const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderImage"; } QRectF getRect() const override; protected: - void setupImageIncluded(void); + void setupImageIncluded(); void replaceImageIncluded(std::string newFileName); void onChanged(const App::Property* prop) override; diff --git a/src/Mod/TechDraw/App/DrawViewMulti.cpp b/src/Mod/TechDraw/App/DrawViewMulti.cpp index 6b407f54da..21b4624c76 100644 --- a/src/Mod/TechDraw/App/DrawViewMulti.cpp +++ b/src/Mod/TechDraw/App/DrawViewMulti.cpp @@ -94,13 +94,10 @@ DrawViewMulti::~DrawViewMulti() short DrawViewMulti::mustExecute() const { - short result = 0; - if (!isRestoring()) { - result = (Sources.isTouched()); - } - if (result) { - return result; + if (!isRestoring() && Sources.isTouched()) { + return true; } + return TechDraw::DrawViewPart::mustExecute(); } @@ -119,7 +116,7 @@ void DrawViewMulti::onChanged(const App::Property* prop) DrawViewPart::onChanged(prop); } -App::DocumentObjectExecReturn *DrawViewMulti::execute(void) +App::DocumentObjectExecReturn *DrawViewMulti::execute() { if (!keepUpdated()) { return App::DocumentObject::StdReturn; @@ -171,7 +168,7 @@ App::DocumentObjectExecReturn *DrawViewMulti::execute(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewMultiPython, TechDraw::DrawViewMulti) -template<> const char* TechDraw::DrawViewMultiPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewMultiPython::getViewProviderName() const { return "TechDrawGui::ViewProviderViewProviderViewPart"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewMulti.h b/src/Mod/TechDraw/App/DrawViewMulti.h index 3da1f4017b..5610652393 100644 --- a/src/Mod/TechDraw/App/DrawViewMulti.h +++ b/src/Mod/TechDraw/App/DrawViewMulti.h @@ -25,6 +25,8 @@ #ifndef _DrawViewMulti_h_ #define _DrawViewMulti_h_ +#include + #include #include #include @@ -54,21 +56,21 @@ class TechDrawExport DrawViewMulti : public DrawViewPart public: /// Constructor - DrawViewMulti(void); - virtual ~DrawViewMulti(); + DrawViewMulti(); + ~DrawViewMulti() override; App::PropertyLinkList Sources; - virtual short mustExecute() const override; + short mustExecute() const override; /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual void onChanged(const App::Property* prop) override; + App::DocumentObjectExecReturn *execute() override; + void onChanged(const App::Property* prop) override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewPart"; } diff --git a/src/Mod/TechDraw/App/DrawViewPart.cpp b/src/Mod/TechDraw/App/DrawViewPart.cpp index 9af73f441e..f39a343ee7 100644 --- a/src/Mod/TechDraw/App/DrawViewPart.cpp +++ b/src/Mod/TechDraw/App/DrawViewPart.cpp @@ -26,58 +26,36 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include - #include -#include -#include +#include #include #include #include #include #include #include -#include -#include -#include -#include -#include #include #include -#include -#include -#include #include #include #include #include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include #include #include #include -#include #include #include #include #include -#include - -#include - #endif #include #include #include +#include + +#include #include #include @@ -88,11 +66,11 @@ #include #include #include -#include -#include -#include -#include "Preferences.h" +#include +#include +#include + #include "Cosmetic.h" #include "DrawGeomHatch.h" #include "DrawHatch.h" @@ -102,15 +80,16 @@ #include "DrawViewBalloon.h" #include "DrawViewDetail.h" #include "DrawViewDimension.h" -#include "LandmarkDimension.h" -#include "DrawViewPart.h" #include "DrawViewSection.h" #include "EdgeWalker.h" #include "Geometry.h" #include "GeometryObject.h" +#include "LandmarkDimension.h" #include "LineGroup.h" +#include "Preferences.h" #include "ShapeExtractor.h" +#include "DrawViewPart.h" #include // generated from DrawViewPartPy.xml using namespace TechDraw; @@ -127,7 +106,9 @@ PROPERTY_SOURCE_WITH_EXTENSIONS(TechDraw::DrawViewPart, TechDraw::DrawView) DrawViewPart::DrawViewPart(void) : - geometryObject(nullptr) + geometryObject(nullptr), + m_waitingForFaces(false), + m_waitingForHlr(false) { static const char *group = "Projection"; static const char *sgroup = "HLR Parameters"; @@ -156,10 +137,9 @@ DrawViewPart::DrawViewPart(void) : "Perspective(true) or Orthographic(false) projection"); ADD_PROPERTY_TYPE(Focus,(defDist),group,App::Prop_None,"Perspective view focus distance"); - //properties that control HLR algoaffect Appearance + //properties that control HLR algo bool coarseView = hGrp->GetBool("CoarseView", false); ADD_PROPERTY_TYPE(CoarseView, (coarseView), sgroup, App::Prop_None, "Coarse View on/off"); - //add property for visible outline? ADD_PROPERTY_TYPE(SmoothVisible ,(prefSmoothViz()),sgroup,App::Prop_None,"Show Visible Smooth lines"); ADD_PROPERTY_TYPE(SeamVisible ,(prefSeamViz()),sgroup,App::Prop_None,"Show Visible Seam lines"); ADD_PROPERTY_TYPE(IsoVisible ,(prefIsoViz()),sgroup,App::Prop_None,"Show Visible Iso u,v lines"); @@ -169,18 +149,26 @@ DrawViewPart::DrawViewPart(void) : ADD_PROPERTY_TYPE(IsoHidden ,(prefIsoHid()),sgroup,App::Prop_None,"Show Hidden Iso u,v lines"); ADD_PROPERTY_TYPE(IsoCount ,(prefIsoCount()),sgroup,App::Prop_None,"Number of iso parameters lines"); - geometryObject = nullptr; //initialize bbox to non-garbage bbox = Base::BoundBox3d(Base::Vector3d(0.0, 0.0, 0.0), 0.0); } 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()); + m_hlrFuture.waitForFinished(); + } + if (m_faceFuture.isRunning()) { + Base::Console().Message("%s is waiting for face finding to finish\n", Label.getValue()); + m_faceFuture.waitForFinished(); + } removeAllReferencesFromGeom(); delete geometryObject; } -std::vector DrawViewPart::getSourceShape2d(void) const +std::vector DrawViewPart::getSourceShape2d() const { // Base::Console().Message("DVP::getSourceShape2d()\n"); std::vector result; @@ -189,55 +177,31 @@ std::vector DrawViewPart::getSourceShape2d(void) const return result; } - -TopoDS_Shape DrawViewPart::getSourceShape(void) const +TopoDS_Shape DrawViewPart::getSourceShape() const { // Base::Console().Message("DVP::getSourceShape()\n"); - TopoDS_Shape result; const std::vector& links = getAllSources(); if (links.empty()) { - bool isRestoring = getDocument()->testStatus(App::Document::Status::Restoring); - if (isRestoring) { - Base::Console().Warning("DVP::getSourceShape - No Sources (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVP::getSourceShape - No Source(s) linked. - %s\n", - getNameInDocument()); - } - } else { - result = ShapeExtractor::getShapes(links); + return TopoDS_Shape(); } - return result; + return ShapeExtractor::getShapes(links); } -TopoDS_Shape DrawViewPart::getSourceShapeFused(void) const +TopoDS_Shape DrawViewPart::getSourceShapeFused() const { // Base::Console().Message("DVP::getSourceShapeFused()\n"); - TopoDS_Shape result; -// const std::vector& links = Source.getValues(); const std::vector& links = getAllSources(); if (links.empty()) { - bool isRestoring = getDocument()->testStatus(App::Document::Status::Restoring); - if (isRestoring) { - Base::Console().Warning("DVP::getSourceShape - No Sources (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVP::getSourceShape - No Source(s) linked. - %s\n", - getNameInDocument()); - } - } else { - result = ShapeExtractor::getShapesFused(links); + return TopoDS_Shape(); } - return result; + return ShapeExtractor::getShapesFused(links); } -std::vector DrawViewPart::getAllSources(void) const +std::vector DrawViewPart::getAllSources() const { // Base::Console().Message("DVP::getAllSources()\n"); - const std::vector links = Source.getValues(); + std::vector links = Source.getValues(); std::vector xLinks = XSource.getValues(); -// std::vector xLinks; -// XSource.getLinks(xLinks); std::vector result = links; if (!xLinks.empty()) { @@ -246,140 +210,8 @@ std::vector DrawViewPart::getAllSources(void) const return result; } -App::DocumentObjectExecReturn *DrawViewPart::execute(void) -{ - if (!keepUpdated()) { - return App::DocumentObject::StdReturn; - } - - App::Document* doc = getDocument(); - bool isRestoring = doc->testStatus(App::Document::Status::Restoring); - const std::vector& links = getAllSources(); - if (links.empty()) { - if (isRestoring) { - Base::Console().Warning("DVP::execute - No Sources (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVP::execute - No Source(s) linked. - %s\n", - getNameInDocument()); - } - return App::DocumentObject::StdReturn; - } - - TopoDS_Shape shape = getSourceShape(); - if (shape.IsNull()) { - if (isRestoring) { - Base::Console().Warning("DVP::execute - source shape is invalid - (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVP::execute - Source shape is Null. - %s\n", - getNameInDocument()); - } - return App::DocumentObject::StdReturn; - } - - - bool haveX = checkXDirection(); - if (!haveX) { - //block touch/onChanged stuff - Base::Vector3d newX = getXDirection(); - XDirection.setValue(newX); - XDirection.purgeTouched(); //don't trigger updates! - //unblock - } - - m_saveShape = shape; - partExec(shape); - addShapes2d(); - - //second pass if required - if (ScaleType.isValue("Automatic")) { - if (!checkFit()) { - double newScale = autoScale(); - Scale.setValue(newScale); - Scale.purgeTouched(); - partExec(shape); - } - } - -//#endif //#if MOD_TECHDRAW_HANDLE_FACES - return DrawView::execute(); -} - -short DrawViewPart::mustExecute() const -{ - short result = 0; - if (!isRestoring()) { - result = (Direction.isTouched() || - Source.isTouched() || - XSource.isTouched() || - Perspective.isTouched() || - Focus.isTouched() || - Rotation.isTouched() || - SmoothVisible.isTouched() || - SeamVisible.isTouched() || - IsoVisible.isTouched() || - HardHidden.isTouched() || - SmoothHidden.isTouched() || - SeamHidden.isTouched() || - IsoHidden.isTouched() || - IsoCount.isTouched() || - CoarseView.isTouched() || - CosmeticVertexes.isTouched() || - CosmeticEdges.isTouched() || - CenterLines.isTouched()); - } - - if (result) { - return result; - } - return TechDraw::DrawView::mustExecute(); -} - -void DrawViewPart::onChanged(const App::Property* prop) -{ - // If the user has set PropertyVector Direction to zero, set it along the default value instead (Front View). - // 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)) { - Direction.setValue(Base::Vector3d(0.0, -1.0, 0.0)); - } - - DrawView::onChanged(prop); - -//TODO: when scale changes, any Dimensions for this View sb recalculated. DVD should pick this up subject to topological naming issues. -} - -void DrawViewPart::partExec(TopoDS_Shape shape) -{ -// Base::Console().Message("DVP::partExec()\n"); - if (geometryObject) { - delete geometryObject; - geometryObject = nullptr; - } - geometryObject = makeGeometryForShape(shape); - if (geometryObject == nullptr) { - return; - } - -#if MOD_TECHDRAW_HANDLE_FACES - if (handleFaces() && !geometryObject->usePolygonHLR()) { - try { - extractFaces(); - } - catch (Standard_Failure& e4) { - Base::Console().Log("LOG - DVP::partExec - extractFaces failed for %s - %s **\n",getNameInDocument(),e4.GetMessageString()); - } - } -#endif //#if MOD_TECHDRAW_HANDLE_FACES -// std::vector verts = getVertexGeometry(); - addCosmeticVertexesToGeom(); - addCosmeticEdgesToGeom(); - addCenterLinesToGeom(); - - addReferencesToGeom(); -} - +//pick supported 2d shapes out of the Source properties and +//add them directly to the geometry without going through HLR void DrawViewPart::addShapes2d(void) { std::vector shapes = getSourceShape2d(); @@ -394,7 +226,7 @@ void DrawViewPart::addShapes2d(void) TechDraw::VertexPtr v1(std::make_shared(projected)); geometryObject->addVertex(v1); } else if (s.ShapeType() == TopAbs_EDGE) { - //not supporting edges yet. + //not supporting edges yet. // Base::Console().Message("DVP::add2dShapes - found loose edge - isNull: %d\n", s.IsNull()); // TopoDS_Shape sTrans = TechDraw::moveShape(s, // m_saveCentroid * -1.0); @@ -410,18 +242,109 @@ void DrawViewPart::addShapes2d(void) } } -GeometryObject* DrawViewPart::makeGeometryForShape(TopoDS_Shape shape) +App::DocumentObjectExecReturn *DrawViewPart::execute(void) { +// Base::Console().Message("DVP::execute() - %s\n", getNameInDocument()); + + if (!keepUpdated()) { + return DrawView::execute(); + } + + if (waitingForHlr()) { + return DrawView::execute(); + } + + TopoDS_Shape shape = getSourceShape(); + if (shape.IsNull()) { + Base::Console().Log("DVP::execute - %s - Source shape is Null.\n", + getNameInDocument()); + return DrawView::execute(); + } + + //make sure the XDirection property is valid. Mostly for older models. + if (!checkXDirection()) { + Base::Vector3d newX = getXDirection(); + XDirection.setValue(newX); + XDirection.purgeTouched(); //don't trigger updates! + } + + m_saveShape = shape; + partExec(shape); + + return DrawView::execute(); +} + +short DrawViewPart::mustExecute() const +{ + if (isRestoring()) { + return TechDraw::DrawView::mustExecute(); + } + + if (Direction.isTouched() || + Source.isTouched() || + XSource.isTouched() || + Perspective.isTouched() || + Focus.isTouched() || + Rotation.isTouched() || + SmoothVisible.isTouched() || + SeamVisible.isTouched() || + IsoVisible.isTouched() || + HardHidden.isTouched() || + SmoothHidden.isTouched() || + SeamHidden.isTouched() || + IsoHidden.isTouched() || + IsoCount.isTouched() || + CoarseView.isTouched() || + CosmeticVertexes.isTouched() || + CosmeticEdges.isTouched() || + CenterLines.isTouched()) { + return 1; + } + + return TechDraw::DrawView::mustExecute(); +} + +void DrawViewPart::onChanged(const App::Property* prop) +{ + // If the user has set PropertyVector Direction to zero, set it along the default value instead (Front View). + // 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)) { + Direction.setValue(Base::Vector3d(0.0, -1.0, 0.0)); + } + + DrawView::onChanged(prop); +} + +void DrawViewPart::partExec(TopoDS_Shape& shape) +{ +// Base::Console().Message("DVP::partExec()\n"); + if (waitingForHlr()) { + //finish what we are already doing before starting a new cycle + return; + } + + if (geometryObject) { + delete geometryObject; + geometryObject = nullptr; + } + + geometryObject = makeGeometryForShape(shape); + if (CoarseView.getValue()){ + onHlrFinished(); //poly algo does not run in separate thread, so we need to invoke + //the post hlr processing manually + } +} + +//prepare the shape for HLR processing by centering, scaling and rotating it +GeometryObject* DrawViewPart::makeGeometryForShape(TopoDS_Shape& shape) +{ +// Base::Console().Message("DVP::makeGeometryForShape()\n"); gp_Pnt inputCenter; Base::Vector3d stdOrg(0.0,0.0,0.0); - gp_Ax2 viewAxis = getProjectionCS(stdOrg); - -// BRepTools::Write(shape, "DVPShape.brep"); //debug - inputCenter = TechDraw::findCentroid(shape, viewAxis); - Base::Vector3d centroid(inputCenter.X(), inputCenter.Y(), inputCenter.Z()); @@ -444,93 +367,131 @@ GeometryObject* DrawViewPart::makeGeometryForShape(TopoDS_Shape shape) return go; } -//note: slightly different than routine with same name in DrawProjectSplit -TechDraw::GeometryObject* DrawViewPart::buildGeometryObject(TopoDS_Shape shape, gp_Ax2 viewAxis) +//create a geometry object and trigger the HLR process in another thread +TechDraw::GeometryObject* DrawViewPart::buildGeometryObject(TopoDS_Shape& shape, gp_Ax2& viewAxis) { +// Base::Console().Message("DVP::buildGeometryObject() - %s\n", getNameInDocument()); + showProgressMessage(getNameInDocument(), "is finding hidden lines"); + TechDraw::GeometryObject* go = new TechDraw::GeometryObject(getNameInDocument(), this); go->setIsoCount(IsoCount.getValue()); go->isPerspective(Perspective.getValue()); go->setFocus(Focus.getValue()); go->usePolygonHLR(CoarseView.getValue()); - if (go->usePolygonHLR()){ + if (CoarseView.getValue()){ + //the polygon approximation HLR process runs quickly, so doesn't need to be in a + //separate thread go->projectShapeWithPolygonAlgo(shape, - viewAxis); + viewAxis); + } else { + //projectShape (the HLR process) runs in a separate thread since it can take a long time + connectHlrWatcher = QObject::connect(&m_hlrWatcher, &QFutureWatcherBase::finished, [this] { + this->onHlrFinished();} + ); + m_hlrFuture = QtConcurrent::run(go, &GeometryObject::projectShape, shape, viewAxis); + m_hlrWatcher.setFuture(m_hlrFuture); + waitingForHlr(true); } - else{ - go->projectShape(shape, - viewAxis); - } - - go->extractGeometry(TechDraw::ecHARD, //always show the hard&outline visible lines - true); - go->extractGeometry(TechDraw::ecOUTLINE, - true); - if (SmoothVisible.getValue()) { - go->extractGeometry(TechDraw::ecSMOOTH, - true); - } - if (SeamVisible.getValue()) { - go->extractGeometry(TechDraw::ecSEAM, - true); - } - if ((IsoVisible.getValue()) && (IsoCount.getValue() > 0)) { - go->extractGeometry(TechDraw::ecUVISO, - true); - } - if (HardHidden.getValue()) { - go->extractGeometry(TechDraw::ecHARD, - false); - go->extractGeometry(TechDraw::ecOUTLINE, - false); - } - if (SmoothHidden.getValue()) { - go->extractGeometry(TechDraw::ecSMOOTH, - false); - } - if (SeamHidden.getValue()) { - go->extractGeometry(TechDraw::ecSEAM, - false); - } - if (IsoHidden.getValue() && (IsoCount.getValue() > 0)) { - go->extractGeometry(TechDraw::ecUVISO, - false); - } - - const BaseGeomPtrVector& edges = go->getEdgeGeometry(); - if (edges.empty()) { - Base::Console().Log("DVP::buildGO - NO extracted edges!\n"); - } - bbox = go->calcBoundingBox(); return go; } -//! make faces from the existing edge geometry +//continue processing after hlr thread completes +void DrawViewPart::onHlrFinished(void) +{ +// Base::Console().Message("DVP::onHlrFinished() - %s\n", getNameInDocument()); + //the last hlr related task is to make a bbox of the results + bbox = geometryObject->calcBoundingBox(); + + waitingForHlr(false); + QObject::disconnect(connectHlrWatcher); + showProgressMessage(getNameInDocument(), "has finished finding hidden lines"); + + postHlrTasks(); //application level tasks that depend on HLR/GO being complete + + //start face finding in a separate thread. We don't find faces when using the polygon + //HLR method + if (handleFaces() && !CoarseView.getValue() && !waitingForFaces()) { + try { + connectFaceWatcher = QObject::connect(&m_faceWatcher, &QFutureWatcherBase::finished, [this] { + this->onFacesFinished(); + }); + m_faceFuture = QtConcurrent::run(this, &DrawViewPart::extractFaces); + m_faceWatcher.setFuture(m_faceFuture); + waitingForFaces(true); + } + catch (Standard_Failure& e) { + waitingForFaces(false); + Base::Console().Error("DVP::partExec - %s - extractFaces failed - %s **\n",getNameInDocument(), e.GetMessageString()); + throw Base::RuntimeError("DVP::onHlrFinished - error extracting faces"); + } + } +} + +//run any tasks that need to been done after geometry is available +void DrawViewPart::postHlrTasks(void) +{ +// Base::Console().Message("DVP::postHlrTasks() - %s\n", getNameInDocument()); + //add geometry that doesn't come from HLR + addCosmeticVertexesToGeom(); + addCosmeticEdgesToGeom(); + addCenterLinesToGeom(); + addReferencesToGeom(); + addShapes2d(); + + //dimensions and balloons need to be recomputed here because their + //references will be invalid until the geometry exists + std::vector dims = getDimensions(); + for (auto& d : dims) { + d->recomputeFeature(); + } + std::vector bals = getBalloons(); + for (auto& b : bals) { + b->recomputeFeature(); + } + + //second pass if required + if (ScaleType.isValue("Automatic") && + !checkFit()) { + double newScale = autoScale(); + Scale.setValue(newScale); + Scale.purgeTouched(); + partExec(m_saveShape); + } + + overrideKeepUpdated(false); + + requestPaint(); +} + +//! make faces from the edge geometry void DrawViewPart::extractFaces() { - if (geometryObject == nullptr) { +// Base::Console().Message("DVP::extractFaces()\n"); + if (!geometryObject || + !this->hasGeometry()) { + //no geometry yet so don't bother return; } + + showProgressMessage(getNameInDocument(), "is extracting faces"); + geometryObject->clearFaceGeom(); const std::vector& goEdges = geometryObject->getVisibleFaceEdges(SmoothVisible.getValue(),SeamVisible.getValue()); - std::vector::const_iterator itEdge = goEdges.begin(); //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; - for (;itEdge != goEdges.end(); itEdge++) { - BRepBuilderAPI_Copy copier((*itEdge)->occEdge, true, true); + for (auto& tdEdge: goEdges) { + BRepBuilderAPI_Copy copier(tdEdge->occEdge, true, true); //copy occEdge with its geometry (TShape) and mesh info copyEdges.push_back(TopoDS::Edge(copier.Shape())); } - std::vector faceEdges; std::vector nonZero; for (auto& e:copyEdges) { //drop any zero edges (shouldn't be any by now!!!) if (!DrawUtil::isZeroEdge(e)) { nonZero.push_back(e); - } else { - Base::Console().Log("INFO - DVP::extractFaces for %s found ZeroEdge!\n",getNameInDocument()); } } @@ -539,18 +500,16 @@ void DrawViewPart::extractFaces() std::vector splits; std::vector::iterator itOuter = nonZero.begin(); int iOuter = 0; - for (; itOuter != nonZero.end(); ++itOuter, iOuter++) { //*** itOuter != nonZero.end() - 1 + for (; itOuter != nonZero.end(); ++itOuter, iOuter++) { TopoDS_Vertex v1 = TopExp::FirstVertex((*itOuter)); TopoDS_Vertex v2 = TopExp::LastVertex((*itOuter)); Bnd_Box sOuter; BRepBndLib::AddOptimal(*itOuter, sOuter); sOuter.SetGap(0.1); if (sOuter.IsVoid()) { - Base::Console().Log("DVP::Extract Faces - outer Bnd_Box is void for %s\n",getNameInDocument()); continue; } if (DrawUtil::isZeroEdge(*itOuter)) { - Base::Console().Log("DVP::extractFaces - outerEdge: %d is ZeroEdge\n",iOuter); //this is not finding ZeroEdges continue; //skip zero length edges. shouldn't happen ;) } int iInner = 0; @@ -567,14 +526,13 @@ void DrawViewPart::extractFaces() BRepBndLib::AddOptimal(*itInner, sInner); sInner.SetGap(0.1); if (sInner.IsVoid()) { - Base::Console().Log("INFO - DVP::Extract Faces - inner Bnd_Box is void for %s\n",getNameInDocument()); continue; } if (sOuter.IsOut(sInner)) { //bboxes of edges don't intersect, don't bother continue; } - double param = -1; + double param = -1; //parametric point on edge where the vertex touches if (DrawProjectSplit::isOnEdge((*itInner),v1,param,false)) { gp_Pnt pnt1 = BRep_Tool::Pnt(v1); splitPoint s1; @@ -594,70 +552,84 @@ void DrawViewPart::extractFaces() } //inner loop } //outer loop + //if edge A was touched at the same point by multiple edges B, we only want to split A once std::vector sorted = DrawProjectSplit::sortSplits(splits,true); auto last = std::unique(sorted.begin(), sorted.end(), DrawProjectSplit::splitEqual); //duplicates to back - sorted.erase(last, sorted.end()); //remove dupl splits + sorted.erase(last, sorted.end()); //remove duplicate splits + std::vector newEdges = DrawProjectSplit::splitEdges(nonZero,sorted); if (newEdges.empty()) { - Base::Console().Log("DVP::extractFaces - no newEdges\n"); + Base::Console().Log("DVP::extractFaces - no edges return by splitting process\n"); + waitingForFaces(false); return; } - newEdges = DrawProjectSplit::removeDuplicateEdges(newEdges); //<<< here + //try to remove any duplicated edges since they will confuse the edgeWalker + newEdges = DrawProjectSplit::removeDuplicateEdges(newEdges); //find all the wires in the pile of faceEdges EdgeWalker ew; ew.loadEdges(newEdges); bool success = ew.perform(); if (!success) { - Base::Console().Warning("DVP::extractFaces - %s -Can't make faces from projected edges\n", getNameInDocument()); + Base::Console().Warning("DVP::extractFaces - %s - Can't make faces from projected edges\n", getNameInDocument()); + waitingForFaces(false); return; } std::vector fw = ew.getResultNoDups(); std::vector sortedWires = ew.sortStrip(fw,true); -// int idb = 0; std::vector::iterator itWire = sortedWires.begin(); for (; itWire != sortedWires.end(); itWire++) { //version 1: 1 wire/face - no voids in face -//debug -// std::stringstream ss; -// ss << "DVPSWire" << idb << ".brep"; -// std::string wireName = ss.str(); -// BRepTools::Write((*itWire), wireName.c_str()); //debug -//debug idb++; TechDraw::FacePtr f(std::make_shared()); const TopoDS_Wire& wire = (*itWire); TechDraw::Wire* w = new TechDraw::Wire(wire); f->wires.push_back(w); - geometryObject->addFaceGeom(f); + if (geometryObject) { + //it can happen that a new hlr cycle deletes geometryObject while we are + //extracting faces. if it does happen, a new cycle should fix it. + geometryObject->addFaceGeom(f); + } } } +//continue processing after extractFaces thread completes +void DrawViewPart::onFacesFinished(void) +{ +// Base::Console().Message("DVP::onFacesFinished()\n"); + waitingForFaces(false); + QObject::disconnect(connectFaceWatcher); + showProgressMessage(getNameInDocument(), "has finished extracting faces"); + requestPaint(); +} + +//retrieve all the face hatches associated with this dvp std::vector DrawViewPart::getHatches() const { std::vector result; std::vector children = getInList(); - for (std::vector::iterator it = children.begin(); it != children.end(); ++it) { - if ( ((*it)->getTypeId().isDerivedFrom(DrawHatch::getClassTypeId())) && - (!(*it)->isRemoving()) ) { - TechDraw::DrawHatch* hatch = dynamic_cast(*it); + for (auto& child: children) { + if ( child->getTypeId().isDerivedFrom(DrawHatch::getClassTypeId()) && + !child->isRemoving() ) { + TechDraw::DrawHatch* hatch = dynamic_cast(child); result.push_back(hatch); } } return result; } +//retrieve all the geometric hatches associated with this dvp std::vector DrawViewPart::getGeomHatches() const { std::vector result; std::vector children = getInList(); - for (std::vector::iterator it = children.begin(); it != children.end(); ++it) { - if ( ((*it)->getTypeId().isDerivedFrom(DrawGeomHatch::getClassTypeId())) && - (!(*it)->isRemoving()) ) { - TechDraw::DrawGeomHatch* geom = dynamic_cast(*it); + for (auto& child: children) { + if ( child->getTypeId().isDerivedFrom(DrawGeomHatch::getClassTypeId()) && + !child->isRemoving() ) { + TechDraw::DrawGeomHatch* geom = dynamic_cast(child); result.push_back(geom); } } @@ -665,6 +637,8 @@ std::vector DrawViewPart::getGeomHatches() const } //return *unique* list of Dimensions which reference this DVP +//if the dimension has two references to this dvp, it will appear twice in +//the inlist std::vector DrawViewPart::getDimensions() const { std::vector result; @@ -698,7 +672,7 @@ std::vector DrawViewPart::getBalloons() const const std::vector DrawViewPart::getVertexGeometry() const { std::vector result; - if (geometryObject != nullptr) { + if (geometryObject) { result = geometryObject->getVertexGeometry(); } return result; @@ -707,19 +681,19 @@ const std::vector DrawViewPart::getVertexGeometry() const const std::vector DrawViewPart::getFaceGeometry() const { std::vector result; - if (geometryObject != nullptr) { - result = geometryObject->getFaceGeometry(); + if ( waitingForFaces() || + !geometryObject ) { + return std::vector(); } - return result; + return geometryObject->getFaceGeometry(); } const BaseGeomPtrVector DrawViewPart::getEdgeGeometry() const { - BaseGeomPtrVector result; - if (geometryObject != nullptr) { - result = geometryObject->getEdgeGeometry(); + if (geometryObject) { + return geometryObject->getEdgeGeometry(); } - return result; + return BaseGeomPtrVector(); } //! returns existing BaseGeom of 2D Edge(idx) @@ -727,11 +701,11 @@ TechDraw::BaseGeomPtr DrawViewPart::getGeomByIndex(int idx) const { const std::vector &geoms = getEdgeGeometry(); if (geoms.empty()) { - Base::Console().Log("INFO - getGeomByIndex(%d) - no Edge Geometry. Probably restoring?\n",idx); + Base::Console().Log("DVP::getGeomByIndex(%d) - no Edge Geometry. Probably restoring?\n",idx); return nullptr; } if ((unsigned)idx >= geoms.size()) { - Base::Console().Log("INFO - getGeomByIndex(%d) - invalid index\n",idx); + Base::Console().Error("DVP::getGeomByIndex(%d) - invalid index - size: %d\n", idx, geoms.size()); return nullptr; } return geoms.at(idx); @@ -742,11 +716,11 @@ TechDraw::VertexPtr DrawViewPart::getProjVertexByIndex(int idx) const { const std::vector &geoms = getVertexGeometry(); if (geoms.empty()) { - Base::Console().Log("INFO - getProjVertexByIndex(%d) - no Vertex Geometry. Probably restoring?\n",idx); + Base::Console().Log("DVP::getProjVertexByIndex(%d) - no Vertex Geometry. Probably restoring?\n",idx); return nullptr; } if ((unsigned)idx >= geoms.size()) { - Base::Console().Log("INFO - getProjVertexByIndex(%d) - invalid index\n",idx); + Base::Console().Error("DVP::getProjVertexByIndex(%d) - invalid index\n",idx); return nullptr; } return geoms.at(idx); @@ -817,13 +791,13 @@ Base::BoundBox3d DrawViewPart::getBoundingBox() const return bbox; } -double DrawViewPart::getBoxX(void) const +double DrawViewPart::getBoxX() const { Base::BoundBox3d bbx = getBoundingBox(); //bbox is already scaled & centered! return (bbx.MaxX - bbx.MinX); } -double DrawViewPart::getBoxY(void) const +double DrawViewPart::getBoxY() const { Base::BoundBox3d bbx = getBoundingBox(); return (bbx.MaxY - bbx.MinY); @@ -874,21 +848,33 @@ BaseGeomPtr DrawViewPart::projectEdge(const TopoDS_Edge& e) const return result; } +bool DrawViewPart::waitingForResult() const +{ + if (waitingForHlr() || + waitingForFaces()) { + return true; + } + return false; +} + bool DrawViewPart::hasGeometry(void) const { - bool result = false; - if (geometryObject == nullptr) { - return result; + if (!geometryObject) { + return false; + } + + if (waitingForHlr()) { + return false; } const std::vector &verts = getVertexGeometry(); const std::vector &edges = getEdgeGeometry(); if (verts.empty() && edges.empty() ) { - result = false; + return false; } else { - result = true; + return true; } - return result; + return false; } gp_Ax2 DrawViewPart::getProjectionCS(const Base::Vector3d pt) const @@ -930,12 +916,12 @@ gp_Ax2 DrawViewPart::getViewAxis(const Base::Vector3d& pt, //TODO: make saveShape a property -Base::Vector3d DrawViewPart::getOriginalCentroid(void) const +Base::Vector3d DrawViewPart::getOriginalCentroid() const { return m_saveCentroid; } -Base::Vector3d DrawViewPart::getCurrentCentroid(void) const +Base::Vector3d DrawViewPart::getCurrentCentroid() const { TopoDS_Shape shape = getSourceShape(); gp_Ax2 cs = getProjectionCS(Base::Vector3d(0.0, 0.0, 0.0)); @@ -943,7 +929,7 @@ Base::Vector3d DrawViewPart::getCurrentCentroid(void) const return center; } -std::vector DrawViewPart::getSectionRefs(void) const +std::vector DrawViewPart::getSectionRefs() const { std::vector result; std::vector inObjs = getInList(); @@ -955,7 +941,7 @@ std::vector DrawViewPart::getSectionRefs(void) const return result; } -std::vector DrawViewPart::getDetailRefs(void) const +std::vector DrawViewPart::getDetailRefs() const { std::vector result; std::vector inObjs = getInList(); @@ -974,7 +960,7 @@ const BaseGeomPtrVector DrawViewPart::getVisibleFaceEdges() const return geometryObject->getVisibleFaceEdges(SmoothVisible.getValue(),SeamVisible.getValue()); } -bool DrawViewPart::handleFaces(void) +bool DrawViewPart::handleFaces() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); @@ -1010,7 +996,7 @@ void DrawViewPart::unsetupObject() // Remove Dimensions which reference this DVP // must use page->removeObject first TechDraw::DrawPage* page = findParentPage(); - if (page != nullptr) { + if (page) { std::vector dims = getDimensions(); std::vector::iterator it3 = dims.begin(); for (; it3 != dims.end(); it3++) { @@ -1026,7 +1012,7 @@ void DrawViewPart::unsetupObject() // Remove Balloons which reference this DVP // must use page->removeObject first page = findParentPage(); - if (page != nullptr) { + if (page) { std::vector balloons = getBalloons(); std::vector::iterator it3 = balloons.begin(); for (; it3 != balloons.end(); it3++) { @@ -1041,7 +1027,7 @@ void DrawViewPart::unsetupObject() } //! is this an Isometric projection? -bool DrawViewPart::isIso(void) const +bool DrawViewPart::isIso() const { bool result = false; Base::Vector3d dir = Direction.getValue(); @@ -1052,7 +1038,7 @@ bool DrawViewPart::isIso(void) const return result; } -bool DrawViewPart::checkXDirection(void) const +bool DrawViewPart::checkXDirection() const { // Base::Console().Message("DVP::checkXDirection()\n"); Base::Vector3d xDir = XDirection.getValue(); @@ -1070,12 +1056,12 @@ bool DrawViewPart::checkXDirection(void) const } // -Base::Vector3d DrawViewPart::getXDirection(void) const +Base::Vector3d DrawViewPart::getXDirection() const { // 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 != nullptr) { //have an XDirection property + if (prop) { //have an XDirection property Base::Vector3d propVal = XDirection.getValue(); if (DrawUtil::fpCompare(propVal.Length(), 0.0)) { //but it has no value Base::Vector3d dir = Direction.getValue(); //make a sensible default @@ -1118,7 +1104,7 @@ void DrawViewPart::updateReferenceVert(std::string tag, Base::Vector3d loc2d) } } -void DrawViewPart::addReferencesToGeom(void) +void DrawViewPart::addReferencesToGeom() { // Base::Console().Message("DVP::addReferencesToGeom() - %s\n", getNameInDocument()); std::vector gVerts = getVertexGeometry(); @@ -1183,14 +1169,14 @@ void DrawViewPart::resetReferenceVerts() //* Cosmetics //******** -void DrawViewPart::clearCosmeticVertexes(void) +void DrawViewPart::clearCosmeticVertexes() { std::vector noVerts; CosmeticVertexes.setValues(noVerts); } //add the cosmetic verts to geometry vertex list -void DrawViewPart::addCosmeticVertexesToGeom(void) +void DrawViewPart::addCosmeticVertexesToGeom() { // Base::Console().Message("DVP::addCosmeticVertexesToGeom()\n"); const std::vector cVerts = CosmeticVertexes.getValues(); @@ -1205,7 +1191,7 @@ int DrawViewPart::add1CVToGV(std::string tag) { // Base::Console().Message("DVP::add1CVToGV(%s) 2\n", tag.c_str()); TechDraw::CosmeticVertex* cv = getCosmeticVertex(tag); - if (cv == nullptr) { + if (!cv) { Base::Console().Message("DVP::add1CVToGV 2 - cv %s not found\n", tag.c_str()); return 0; } @@ -1216,7 +1202,7 @@ int DrawViewPart::add1CVToGV(std::string tag) } //update Vertex geometry with current CV's -void DrawViewPart::refreshCVGeoms(void) +void DrawViewPart::refreshCVGeoms() { // Base::Console().Message("DVP::refreshCVGeoms()\n"); @@ -1270,22 +1256,21 @@ int DrawViewPart::getCVIndex(std::string tag) //CosmeticEdges ------------------------------------------------------------------- //for completeness. not actually used anywhere? -void DrawViewPart::clearCosmeticEdges(void) +void DrawViewPart::clearCosmeticEdges() { std::vector noEdges; CosmeticEdges.setValues(noEdges); } //add the cosmetic edges to geometry edge list -void DrawViewPart::addCosmeticEdgesToGeom(void) +void DrawViewPart::addCosmeticEdgesToGeom() { // Base::Console().Message("CEx::addCosmeticEdgesToGeom()\n"); const std::vector cEdges = CosmeticEdges.getValues(); for (auto& ce: cEdges) { TechDraw::BaseGeomPtr scaledGeom = ce->scaledGeometry(getScale()); - if (scaledGeom == nullptr) { + if (!scaledGeom) continue; - } // int iGE = geometryObject->addCosmeticEdge(scaledGeom, ce->getTagAsString()); @@ -1296,7 +1281,7 @@ int DrawViewPart::add1CEToGE(std::string tag) { // Base::Console().Message("CEx::add1CEToGE(%s) 2\n", tag.c_str()); TechDraw::CosmeticEdge* ce = getCosmeticEdge(tag); - if (ce == nullptr) { + if (!ce) { Base::Console().Message("CEx::add1CEToGE 2 - ce %s not found\n", tag.c_str()); return -1; } @@ -1308,7 +1293,7 @@ int DrawViewPart::add1CEToGE(std::string tag) } //update Edge geometry with current CE's -void DrawViewPart::refreshCEGeoms(void) +void DrawViewPart::refreshCEGeoms() { // Base::Console().Message("DVP::refreshCEGeoms()\n"); std::vector gEdges = getEdgeGeometry(); @@ -1324,7 +1309,7 @@ void DrawViewPart::refreshCEGeoms(void) // CenterLines ----------------------------------------------------------------- -void DrawViewPart::clearCenterLines(void) +void DrawViewPart::clearCenterLines() { std::vector noLines; CenterLines.setValues(noLines); @@ -1334,7 +1319,7 @@ int DrawViewPart::add1CLToGE(std::string tag) { // Base::Console().Message("CEx::add1CLToGE(%s) 2\n", tag.c_str()); TechDraw::CenterLine* cl = getCenterLine(tag); - if (cl == nullptr) { + if (!cl) { Base::Console().Message("CEx::add1CLToGE 2 - cl %s not found\n", tag.c_str()); return -1; } @@ -1346,7 +1331,7 @@ int DrawViewPart::add1CLToGE(std::string tag) } //update Edge geometry with current CL's -void DrawViewPart::refreshCLGeoms(void) +void DrawViewPart::refreshCLGeoms() { // Base::Console().Message("DVP::refreshCLGeoms()\n"); std::vector gEdges = getEdgeGeometry(); @@ -1361,13 +1346,13 @@ void DrawViewPart::refreshCLGeoms(void) } //add the center lines to geometry Edges list -void DrawViewPart::addCenterLinesToGeom(void) +void DrawViewPart::addCenterLinesToGeom() { // Base::Console().Message("DVP::addCenterLinesToGeom()\n"); const std::vector lines = CenterLines.getValues(); for (auto& cl: lines) { TechDraw::BaseGeomPtr scaledGeom = cl->scaledGeometry(this); - if (scaledGeom == nullptr) { + if (!scaledGeom) { Base::Console().Error("DVP::addCenterLinesToGeom - scaledGeometry is null\n"); continue; } @@ -1378,7 +1363,7 @@ void DrawViewPart::addCenterLinesToGeom(void) // GeomFormats ----------------------------------------------------------------- -void DrawViewPart::clearGeomFormats(void) +void DrawViewPart::clearGeomFormats() { std::vector noFormats; std::vector fmts = GeomFormats.getValues(); @@ -1392,7 +1377,7 @@ void DrawViewPart::clearGeomFormats(void) void DrawViewPart::dumpVerts(std::string text) { - if (geometryObject == nullptr) { + if (!geometryObject) { Base::Console().Message("no verts to dump yet\n"); return; } @@ -1434,7 +1419,7 @@ void DrawViewPart::onDocumentRestored() DrawView::onDocumentRestored(); } -PyObject *DrawViewPart::getPyObject(void) +PyObject *DrawViewPart::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -1449,7 +1434,7 @@ void DrawViewPart::handleChangedPropertyName(Base::XMLReader &reader, const char DrawView::handleChangedPropertyName(reader, TypeName, PropName); } -bool DrawViewPart::prefHardViz(void) +bool DrawViewPart::prefHardViz() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1457,7 +1442,7 @@ bool DrawViewPart::prefHardViz(void) return result; } -bool DrawViewPart::prefSeamViz(void) +bool DrawViewPart::prefSeamViz() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1465,7 +1450,7 @@ bool DrawViewPart::prefSeamViz(void) return result; } -bool DrawViewPart::prefSmoothViz(void) +bool DrawViewPart::prefSmoothViz() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1473,7 +1458,7 @@ bool DrawViewPart::prefSmoothViz(void) return result; } -bool DrawViewPart::prefIsoViz(void) +bool DrawViewPart::prefIsoViz() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1481,7 +1466,7 @@ bool DrawViewPart::prefIsoViz(void) return result; } -bool DrawViewPart::prefHardHid(void) +bool DrawViewPart::prefHardHid() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1489,7 +1474,7 @@ bool DrawViewPart::prefHardHid(void) return result; } -bool DrawViewPart::prefSeamHid(void) +bool DrawViewPart::prefSeamHid() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1497,7 +1482,7 @@ bool DrawViewPart::prefSeamHid(void) return result; } -bool DrawViewPart::prefSmoothHid(void) +bool DrawViewPart::prefSmoothHid() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1505,7 +1490,7 @@ bool DrawViewPart::prefSmoothHid(void) return result; } -bool DrawViewPart::prefIsoHid(void) +bool DrawViewPart::prefIsoHid() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1513,7 +1498,7 @@ bool DrawViewPart::prefIsoHid(void) return result; } -int DrawViewPart::prefIsoCount(void) +int DrawViewPart::prefIsoCount() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/HLR"); @@ -1521,13 +1506,12 @@ int DrawViewPart::prefIsoCount(void) return result; } - // Python Drawing feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewPartPython, TechDraw::DrawViewPart) -template<> const char* TechDraw::DrawViewPartPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewPartPython::getViewProviderName() const { return "TechDrawGui::ViewProviderViewPart"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewPart.h b/src/Mod/TechDraw/App/DrawViewPart.h index eb474e4035..c0aac00c2e 100644 --- a/src/Mod/TechDraw/App/DrawViewPart.h +++ b/src/Mod/TechDraw/App/DrawViewPart.h @@ -25,6 +25,12 @@ #ifndef _DrawViewPart_h_ #define _DrawViewPart_h_ +#include + +#include +#include +#include + #include #include @@ -80,8 +86,8 @@ class TechDrawExport DrawViewPart : public DrawView, public CosmeticExtension PROPERTY_HEADER_WITH_EXTENSIONS(TechDraw::DrawViewPart); public: - DrawViewPart(void); - virtual ~DrawViewPart(); + DrawViewPart(); + ~DrawViewPart() override; App::PropertyLinkList Source; App::PropertyXLinkList XSource; @@ -103,16 +109,16 @@ public: App::PropertyBool IsoHidden; App::PropertyInteger IsoCount; - virtual short mustExecute() const override; - virtual void onDocumentRestored() override; - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual const char* getViewProviderName(void) const override { + short mustExecute() const override; + void onDocumentRestored() override; + App::DocumentObjectExecReturn *execute() override; + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewPart"; } - virtual PyObject *getPyObject(void) override; + PyObject *getPyObject() override; - std::vector getHatches(void) const; - std::vector getGeomHatches(void) const; + std::vector getHatches() const; + std::vector getGeomHatches() const; std::vector getDimensions() const; std::vector getBalloons() const; @@ -121,8 +127,8 @@ public: const BaseGeomPtrVector getVisibleFaceEdges() const; const std::vector getFaceGeometry() const; - bool hasGeometry(void) const; - TechDraw::GeometryObject* getGeometryObject(void) const { return geometryObject; } + bool hasGeometry() const; + TechDraw::GeometryObject* getGeometryObject() const { return geometryObject; } TechDraw::BaseGeomPtr getGeomByIndex(int idx) const; //get existing geom for edge idx in projection TechDraw::VertexPtr getProjVertexByIndex(int idx) const; //get existing geom for vertex idx in projection @@ -130,9 +136,9 @@ public: std::vector getFaceEdgesByIndex(int idx) const; //get edges for face idx in projection virtual Base::BoundBox3d getBoundingBox() const; - double getBoxX(void) const; - double getBoxY(void) const; - virtual QRectF getRect() const override; + double getBoxX() const; + double getBoxY() const; + QRectF getRect() const override; virtual std::vector getSectionRefs() const; //are there ViewSections based on this ViewPart? virtual std::vector getDetailRefs() const; @@ -145,77 +151,89 @@ public: const Base::Vector3d& direction, const bool flip=true) const; virtual gp_Ax2 getProjectionCS(Base::Vector3d pt) const; - virtual Base::Vector3d getXDirection(void) const; //don't use XDirection.getValue() - virtual Base::Vector3d getOriginalCentroid(void) const; - virtual Base::Vector3d getCurrentCentroid(void) const; + virtual Base::Vector3d getXDirection() const; //don't use XDirection.getValue() + virtual Base::Vector3d getOriginalCentroid() const; + virtual Base::Vector3d getCurrentCentroid() const; virtual Base::Vector3d getLegacyX(const Base::Vector3d& pt, const Base::Vector3d& axis, const bool flip = true) const; - bool handleFaces(void); + bool handleFaces(); - bool isUnsetting(void) { return nowUnsetting; } + bool isUnsetting() { return nowUnsetting; } virtual std::vector getWireForFace(int idx) const; - virtual TopoDS_Shape getSourceShape(void) const; - virtual TopoDS_Shape getSourceShapeFused(void) const; - virtual std::vector getSourceShape2d(void) const; + virtual TopoDS_Shape getSourceShape() const; + virtual TopoDS_Shape getSourceShapeFused() const; + virtual std::vector getSourceShape2d() const; + virtual void postHlrTasks(void); - bool isIso(void) const; + bool isIso() const; - void clearCosmeticVertexes(void); - void refreshCVGeoms(void); - void addCosmeticVertexesToGeom(void); + void clearCosmeticVertexes(); + void refreshCVGeoms(); + void addCosmeticVertexesToGeom(); int add1CVToGV(std::string tag); int getCVIndex(std::string tag); - void clearCosmeticEdges(void); - void refreshCEGeoms(void); - void addCosmeticEdgesToGeom(void); + void clearCosmeticEdges(); + void refreshCEGeoms(); + void addCosmeticEdgesToGeom(); int add1CEToGE(std::string tag); - void clearCenterLines(void); - void refreshCLGeoms(void); - void addCenterLinesToGeom(void); + void clearCenterLines(); + void refreshCLGeoms(); + void addCenterLinesToGeom(); int add1CLToGE(std::string tag); - void clearGeomFormats(void); + void clearGeomFormats(); void dumpVerts(const std::string text); void dumpCosVerts(const std::string text); void dumpCosEdges(const std::string text); std::string addReferenceVertex(Base::Vector3d v); - void addReferencesToGeom(void); + void addReferencesToGeom(); void removeReferenceVertex(std::string tag); void updateReferenceVert(std::string tag, Base::Vector3d loc2d); void removeAllReferencesFromGeom(); void resetReferenceVerts(); - std::vector getAllSources(void) const; + std::vector getAllSources() const; + bool waitingForFaces() const { return m_waitingForFaces; } + void waitingForFaces(bool s) { m_waitingForFaces = s;} + bool waitingForHlr() const { return m_waitingForHlr; } + void waitingForHlr(bool s) { m_waitingForHlr = s; } + virtual bool waitingForResult() const; + + void progressValueChanged(int v); + +public Q_SLOTS: + void onHlrFinished(void); + void onFacesFinished(void); protected: - bool checkXDirection(void) const; + bool checkXDirection() const; TechDraw::GeometryObject *geometryObject; Base::BoundBox3d bbox; - virtual void onChanged(const App::Property* prop) override; - virtual void unsetupObject() override; + void onChanged(const App::Property* prop) override; + void unsetupObject() override; - virtual TechDraw::GeometryObject* buildGeometryObject(TopoDS_Shape shape, gp_Ax2 viewAxis); //const?? - virtual TechDraw::GeometryObject* makeGeometryForShape(TopoDS_Shape shape); //const?? - void partExec(TopoDS_Shape shape); + virtual TechDraw::GeometryObject* buildGeometryObject(TopoDS_Shape& shape, gp_Ax2& viewAxis); + virtual TechDraw::GeometryObject* makeGeometryForShape(TopoDS_Shape& shape); //const?? + void partExec(TopoDS_Shape& shape); virtual void addShapes2d(void); void extractFaces(); Base::Vector3d shapeCentroid; - void getRunControl(void); + void getRunControl(); bool m_handleFaces; @@ -224,20 +242,29 @@ protected: void handleChangedPropertyName(Base::XMLReader &reader, const char* TypeName, const char* PropName) override; - bool prefHardViz(void); - bool prefSeamViz(void); - bool prefSmoothViz(void); - bool prefIsoViz(void); - bool prefHardHid(void); - bool prefSeamHid(void); - bool prefSmoothHid(void); - bool prefIsoHid(void); - int prefIsoCount(void); + bool prefHardViz(); + bool prefSeamViz(); + bool prefSmoothViz(); + bool prefIsoViz(); + bool prefHardHid(); + bool prefSeamHid(); + bool prefSmoothHid(); + bool prefIsoHid(); + int prefIsoCount(); std::vector m_referenceVerts; private: bool nowUnsetting; + bool m_waitingForFaces; + bool m_waitingForHlr; + + QMetaObject::Connection connectHlrWatcher; + QFutureWatcher m_hlrWatcher; + QFuture m_hlrFuture; + QMetaObject::Connection connectFaceWatcher; + QFutureWatcher m_faceWatcher; + QFuture m_faceFuture; }; diff --git a/src/Mod/TechDraw/App/DrawViewPartPy.xml b/src/Mod/TechDraw/App/DrawViewPartPy.xml index 0d741b1a08..52645d1ad9 100644 --- a/src/Mod/TechDraw/App/DrawViewPartPy.xml +++ b/src/Mod/TechDraw/App/DrawViewPartPy.xml @@ -43,11 +43,6 @@ cv = getCosmeticVertexBySelection(name) - returns CosmeticVertex with name (Vertex6). Used in selections.
- - - rc = replaceCosmeticVertex(cv) - replaces CosmeticVertex in View. Returns True/False. - - removeCosmeticVertex(cv) - remove CosmeticVertex from View. Returns None. @@ -88,11 +83,6 @@ ce = getCosmeticEdgeBySelection(name) - returns CosmeticEdge by name (Edge25). Used in selections - - - replaceCosmeticEdge(ce) - replaces CosmeticEdge ce in View. Returns True/False. - - removeCosmeticEdge(ce) - remove CosmeticEdge ce from View. Returns None. @@ -113,11 +103,6 @@ cl = getCenterLineBySelection(name) - returns CenterLine by name (Edge25). Used in selections - - - replaceCenterLine(cl) - replacls CenterLine cl in View. Returns True/False. - - removeCenterLine(cl) - remove CenterLine cl from View. Returns None. diff --git a/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp b/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp index 4c2e67e39e..ca00161fbb 100644 --- a/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewPartPyImp.cpp @@ -67,7 +67,7 @@ using namespace TechDraw; //TODO: errors to PyErrors // returns a string which represents the object e.g. when printed in python -std::string DrawViewPartPy::representation(void) const +std::string DrawViewPartPy::representation() const { return std::string(""); } @@ -200,7 +200,7 @@ PyObject* DrawViewPartPy::getCosmeticVertex(PyObject *args) } DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::CosmeticVertex* cv = dvp->getCosmeticVertex(id); - if (cv != nullptr) { + if (cv) { result = cv->getPyObject(); } else { result = Py_None; @@ -219,7 +219,7 @@ PyObject* DrawViewPartPy::getCosmeticVertexBySelection(PyObject *args) DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::CosmeticVertex* cv = dvp->getCosmeticVertexBySelection(selName); - if (cv != nullptr) { + if (cv) { result = cv->getPyObject(); } else { result = Py_None; @@ -230,9 +230,8 @@ PyObject* DrawViewPartPy::getCosmeticVertexBySelection(PyObject *args) PyObject* DrawViewPartPy::removeCosmeticVertex(PyObject *args) { DrawViewPart* dvp = getDrawViewPartPtr(); - if (dvp == nullptr) { + if (!dvp) return Py_None; - } char* tag; if (PyArg_ParseTuple(args, "s", &tag)) { @@ -276,14 +275,6 @@ PyObject* DrawViewPartPy::removeCosmeticVertex(PyObject *args) return Py_None; } -PyObject* DrawViewPartPy::replaceCosmeticVertex(PyObject *args) -{ - (void) args; - Base::Console().Message("DVPP::replaceCosmeticVertex() - deprecated. do not use.\n"); - return PyBool_FromLong(0l); - -} - //********* Cosmetic Line Routines ********************************************* @@ -308,14 +299,13 @@ PyObject* DrawViewPartPy::makeCosmeticLine(PyObject *args) Base::Vector3d pnt2 = static_cast(pPnt2)->value(); std::string newTag = dvp->addCosmeticEdge(pnt1, pnt2); TechDraw::CosmeticEdge* ce = dvp->getCosmeticEdge(newTag); - if (ce != nullptr) { + if (ce) { ce->m_format.m_style = style; ce->m_format.m_weight = weight; - if (pColor == nullptr) { + if (!pColor) ce->m_format.m_color = defCol; - } else { + else ce->m_format.m_color = DrawUtil::pyTupleToColor(pColor); - } } else { std::string msg = "DVPPI:makeCosmeticLine - line creation failed"; Base::Console().Message("%s\n",msg.c_str()); @@ -356,14 +346,13 @@ PyObject* DrawViewPartPy::makeCosmeticLine3D(PyObject *args) std::string newTag = dvp->addCosmeticEdge(pnt1, pnt2); TechDraw::CosmeticEdge* ce = dvp->getCosmeticEdge(newTag); - if (ce != nullptr) { + if (ce) { ce->m_format.m_style = style; ce->m_format.m_weight = weight; - if (pColor == nullptr) { + if (!pColor) ce->m_format.m_color = defCol; - } else { + else ce->m_format.m_color = DrawUtil::pyTupleToColor(pColor); - } } else { std::string msg = "DVPPI:makeCosmeticLine - line creation failed"; Base::Console().Message("%s\n",msg.c_str()); @@ -395,15 +384,14 @@ PyObject* DrawViewPartPy::makeCosmeticCircle(PyObject *args) TechDraw::BaseGeomPtr bg = std::make_shared (pnt1, radius); std::string newTag = dvp->addCosmeticEdge(bg); TechDraw::CosmeticEdge* ce = dvp->getCosmeticEdge(newTag); - if (ce != nullptr) { + if (ce) { ce->permaRadius = radius; ce->m_format.m_style = style; ce->m_format.m_weight = weight; - if (pColor == nullptr) { + if (!pColor) ce->m_format.m_color = defCol; - } else { + else ce->m_format.m_color = DrawUtil::pyTupleToColor(pColor); - } } else { std::string msg = "DVPPI:makeCosmeticCircle - circle creation failed"; Base::Console().Message("%s\n",msg.c_str()); @@ -438,15 +426,14 @@ PyObject* DrawViewPartPy::makeCosmeticCircleArc(PyObject *args) TechDraw::BaseGeomPtr bg = std::make_shared (pnt1, radius, angle1, angle2); std::string newTag = dvp->addCosmeticEdge(bg); TechDraw::CosmeticEdge* ce = dvp->getCosmeticEdge(newTag); - if (ce != nullptr) { + if (ce) { ce->permaRadius = radius; ce->m_format.m_style = style; ce->m_format.m_weight = weight; - if (pColor == nullptr) { + if (!pColor) ce->m_format.m_color = defCol; - } else { + else ce->m_format.m_color = DrawUtil::pyTupleToColor(pColor); - } } else { std::string msg = "DVPPI:makeCosmeticCircleArc - arc creation failed"; Base::Console().Message("%s\n",msg.c_str()); @@ -470,7 +457,7 @@ PyObject* DrawViewPartPy::getCosmeticEdge(PyObject *args) } DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::CosmeticEdge* ce = dvp->getCosmeticEdge(tag); - if (ce != nullptr) { + if (ce) { result = ce->getPyObject(); } else { Base::Console().Error("DVPPI::getCosmeticEdge - edge %s not found\n", tag); @@ -490,7 +477,7 @@ PyObject* DrawViewPartPy::getCosmeticEdgeBySelection(PyObject *args) DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::CosmeticEdge* ce = dvp->getCosmeticEdgeBySelection(name); - if (ce != nullptr) { + if (ce) { result = ce->getPyObject(); } else { Base::Console().Error("DVPPI::getCosmeticEdgebySelection - edge for name %s not found\n", name); @@ -498,29 +485,6 @@ PyObject* DrawViewPartPy::getCosmeticEdgeBySelection(PyObject *args) return result; } -PyObject* DrawViewPartPy::replaceCosmeticEdge(PyObject *args) -{ - (void) args; - Base::Console().Message("DVPP::replaceCosmeticEdge() - deprecated. do not use.\n"); - return PyBool_FromLong(0l); - -// Base::Console().Message("DVPPI::replaceCosmeticEdge()\n"); -// bool result = false; -// PyObject* pNewCE; -// if (!PyArg_ParseTuple(args, "O!", &(TechDraw::CosmeticEdgePy::Type), &pNewCE)) { -// throw Py::TypeError("expected (CosmeticEdge)"); -// } -// DrawViewPart* dvp = getDrawViewPartPtr(); -// TechDraw::CosmeticEdgePy* cePy = static_cast(pNewCE); -// TechDraw::CosmeticEdge* ce = cePy->getCosmeticEdgePtr(); -// if (ce != nullptr) { -// result = dvp->replaceCosmeticEdge(ce); //<<< -// dvp->refreshCEGeoms(); -// dvp->requestPaint(); -// } -// return PyBool_FromLong((long) result); -} - PyObject* DrawViewPartPy::removeCosmeticEdge(PyObject *args) { // Base::Console().Message("DVPPI::removeCosmeticEdge()\n"); @@ -565,7 +529,7 @@ PyObject* DrawViewPartPy::makeCenterLine(PyObject *args) cl = CenterLine::CenterLineBuilder(dvp, subs, mode); //vert,horiz,align - if (cl != nullptr) { + if (cl) { tag = dvp->addCenterLine(cl); } else { std::string msg = "DVPPI:makeCenterLine - line creation failed"; @@ -589,7 +553,7 @@ PyObject* DrawViewPartPy::getCenterLine(PyObject *args) } DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::CenterLine* cl = dvp->getCenterLine(tag); - if (cl != nullptr) { + if (cl) { result = cl->getPyObject(); } else { Base::Console().Error("DVPPI::getCenterLine - centerLine %s not found\n", tag); @@ -609,7 +573,7 @@ PyObject* DrawViewPartPy::getCenterLineBySelection(PyObject *args) DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::CenterLine* cl = dvp->getCenterLineBySelection(tag); - if (cl != nullptr) { + if (cl) { result = cl->getPyObject(); } else { Base::Console().Error("DVPPI::getCenterLinebySelection - centerLine for tag %s not found\n", tag); @@ -617,26 +581,6 @@ PyObject* DrawViewPartPy::getCenterLineBySelection(PyObject *args) return result; } -PyObject* DrawViewPartPy::replaceCenterLine(PyObject *args) -{ - (void) args; - Base::Console().Message("DVPP::replaceCenterLine() - deprecated. do not use.\n"); - return PyBool_FromLong(0l); - -// Base::Console().Message("DVPPI::replace CenterLine()\n"); -// PyObject* pNewCL; -// if (!PyArg_ParseTuple(args, "O!", &(TechDraw::CenterLinePy::Type), &pNewCL)) { -// throw Py::TypeError("expected (CenterLine)"); -// } -// DrawViewPart* dvp = getDrawViewPartPtr(); -// TechDraw::CenterLinePy* clPy = static_cast(pNewCL); -// TechDraw::CenterLine* cl = clPy->getCenterLinePtr(); -// bool result = dvp->replaceCenterLine(cl); -// dvp->refreshCLGeoms(); -// dvp->requestPaint(); -// return PyBool_FromLong((long) result); -} - PyObject* DrawViewPartPy::removeCenterLine(PyObject *args) { // Base::Console().Message("DVPPI::removeCenterLine()\n"); @@ -669,7 +613,7 @@ PyObject* DrawViewPartPy::formatGeometricEdge(PyObject *args) color = DrawUtil::pyTupleToColor(pColor); DrawViewPart* dvp = getDrawViewPartPtr(); TechDraw::GeomFormat* gf = dvp->getGeomFormatBySelection(idx); - if (gf != nullptr) { + if (gf) { gf->m_format.m_style = style; gf->m_format.m_color = color; gf->m_format.m_weight = weight; @@ -691,17 +635,15 @@ PyObject* DrawViewPartPy::formatGeometricEdge(PyObject *args) PyObject* DrawViewPartPy::getEdgeByIndex(PyObject *args) { int edgeIndex = 0; - if (!PyArg_ParseTuple(args, "i", &edgeIndex)) { + if (!PyArg_ParseTuple(args, "i", &edgeIndex)) throw Py::TypeError("expected (edgeIndex)"); - } DrawViewPart* dvp = getDrawViewPartPtr(); //this is scaled and +Yup //need unscaled and +Ydown TechDraw::BaseGeomPtr geom = dvp->getGeomByIndex(edgeIndex); - if (geom == nullptr) { + if (!geom) throw Py::ValueError("wrong edgeIndex"); - } TopoDS_Shape temp = TechDraw::mirrorShapeVec(geom->occEdge, Base::Vector3d(0.0, 0.0, 0.0), @@ -714,17 +656,15 @@ PyObject* DrawViewPartPy::getEdgeByIndex(PyObject *args) PyObject* DrawViewPartPy::getVertexByIndex(PyObject *args) { int vertexIndex = 0; - if (!PyArg_ParseTuple(args, "i", &vertexIndex)) { + if (!PyArg_ParseTuple(args, "i", &vertexIndex)) throw Py::TypeError("expected (vertIndex)"); - } DrawViewPart* dvp = getDrawViewPartPtr(); //this is scaled and +Yup //need unscaled and +Ydown TechDraw::VertexPtr vert = dvp->getProjVertexByIndex(vertexIndex); - if (vert == nullptr) { + if (!vert) throw Py::ValueError("wrong vertIndex"); - } Base::Vector3d point = DrawUtil::invertY(vert->point()) / dvp->getScale(); gp_Pnt gPoint(point.x, point.y, point.z); @@ -737,9 +677,8 @@ PyObject* DrawViewPartPy::getEdgeBySelection(PyObject *args) { int edgeIndex = 0; char* selName; //Selection routine name - "Edge0" - if (!PyArg_ParseTuple(args, "s", &selName)) { + if (!PyArg_ParseTuple(args, "s", &selName)) throw Py::TypeError("expected (string)"); - } edgeIndex = DrawUtil::getIndexFromName(std::string(selName)); DrawViewPart* dvp = getDrawViewPartPtr(); @@ -747,9 +686,8 @@ PyObject* DrawViewPartPy::getEdgeBySelection(PyObject *args) //this is scaled and +Yup //need unscaled and +Ydown TechDraw::BaseGeomPtr geom = dvp->getGeomByIndex(edgeIndex); - if (geom == nullptr) { + if (!geom) throw Py::ValueError("wrong edgeIndex"); - } TopoDS_Shape temp = TechDraw::mirrorShapeVec(geom->occEdge, Base::Vector3d(0.0, 0.0, 0.0), @@ -773,9 +711,8 @@ PyObject* DrawViewPartPy::getVertexBySelection(PyObject *args) //this is scaled and +Yup //need unscaled and +Ydown TechDraw::VertexPtr vert = dvp->getProjVertexByIndex(vertexIndex); - if (vert == nullptr) { + if (!vert) throw Py::ValueError("wrong vertIndex"); - } Base::Vector3d point = DrawUtil::invertY(vert->point()) / dvp->getScale(); gp_Pnt gPoint(point.x, point.y, point.z); diff --git a/src/Mod/TechDraw/App/DrawViewSection.cpp b/src/Mod/TechDraw/App/DrawViewSection.cpp index 8787615754..ec8388f3ea 100644 --- a/src/Mod/TechDraw/App/DrawViewSection.cpp +++ b/src/Mod/TechDraw/App/DrawViewSection.cpp @@ -26,32 +26,22 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include - #include #include -//#include #include #include #include #include #include -#include #include #include #include -#include #include #include #include #include #include #include -#include -#include -#include -#include -#include #include #include #include @@ -60,13 +50,14 @@ #include #include #include - #endif #include +#include -# include -# include +#include +#include +#include #include #include @@ -115,7 +106,8 @@ const char* DrawViewSection::CutSurfaceEnums[]= {"Hide", PROPERTY_SOURCE(TechDraw::DrawViewSection, TechDraw::DrawViewPart) -DrawViewSection::DrawViewSection() +DrawViewSection::DrawViewSection() : + m_waitingForCut(false) { static const char *sgroup = "Section"; static const char *fgroup = "Cut Surface Format"; @@ -157,170 +149,106 @@ DrawViewSection::DrawViewSection() DrawViewSection::~DrawViewSection() { + //don't destroy this object while it has dependent threads running + if (m_cutFuture.isRunning()) { + Base::Console().Message("%s is waiting for tasks to complete\n", Label.getValue()); + m_cutFuture.waitForFinished(); + } } short DrawViewSection::mustExecute() const { - short result = 0; - if (!isRestoring()) { - result = (Scale.isTouched() || - Direction.isTouched() || - BaseView.isTouched() || - SectionNormal.isTouched() || - SectionOrigin.isTouched() ); + if (isRestoring()) { + return TechDraw::DrawView::mustExecute(); } - if (result) { - return result; + + if (Scale.isTouched() || + Direction.isTouched() || + BaseView.isTouched() || + SectionNormal.isTouched() || + SectionOrigin.isTouched() ) { + return 1; } + return TechDraw::DrawView::mustExecute(); } void DrawViewSection::onChanged(const App::Property* prop) { - App::Document* doc = getDocument(); -// bool docRestoring = getDocument()->testStatus(App::Document::Status::Restoring); -// Base::Console().Message("DVS::onChanged(%s) - obj restoring: %d\n", -// prop->getName(), isRestoring()); - - if (!isRestoring()) { - if (prop == &SectionSymbol) { - std::string lblText = "Section " + - std::string(SectionSymbol.getValue()) + - " - " + - std::string(SectionSymbol.getValue()); - Label.setValue(lblText); - } else if (prop == &SectionOrigin) { - App::DocumentObject* base = BaseView.getValue(); - TechDraw::DrawView* dv = dynamic_cast(base); - if (dv != nullptr) { - dv->requestPaint(); - } - } else if (prop == &CutSurfaceDisplay) { - if (CutSurfaceDisplay.isValue("PatHatch")) { - makeLineSets(); - } - } - - if ((prop == &FileHatchPattern) && - (doc != nullptr) ) { - if (!FileHatchPattern.isEmpty()) { - Base::FileInfo fi(FileHatchPattern.getValue()); - if (fi.isReadable()) { - replaceSvgIncluded(FileHatchPattern.getValue()); - } - } - } - - if ( (prop == &FileGeomPattern) && - (doc != nullptr) ) { - if (!FileGeomPattern.isEmpty()) { - Base::FileInfo fi(FileGeomPattern.getValue()); - if (fi.isReadable()) { - replacePatIncluded(FileGeomPattern.getValue()); - } - } - } + if (isRestoring()) { + DrawViewPart::onChanged(prop); + return; } - if (prop == &FileGeomPattern || + App::Document* doc = getDocument(); + if (!doc) { + //tarfu + DrawViewPart::onChanged(prop); + return; + } + + if (prop == &SectionSymbol) { + std::string lblText = "Section " + + std::string(SectionSymbol.getValue()) + + " - " + + std::string(SectionSymbol.getValue()); + Label.setValue(lblText); + } else if (prop == &CutSurfaceDisplay) { + if (CutSurfaceDisplay.isValue("PatHatch")) { + makeLineSets(); + } + } else if (prop == &FileHatchPattern) { + if (!FileHatchPattern.isEmpty()) { + Base::FileInfo fi(FileHatchPattern.getValue()); + if (fi.isReadable()) { + replaceSvgIncluded(FileHatchPattern.getValue()); + } + } + } else if (prop == &FileGeomPattern) { + if (!FileGeomPattern.isEmpty()) { + Base::FileInfo fi(FileGeomPattern.getValue()); + if (fi.isReadable()) { + replacePatIncluded(FileGeomPattern.getValue()); + } + } + } else if (prop == &FileGeomPattern || prop == &NameGeomPattern ) { makeLineSets(); } + DrawView::onChanged(prop); } -void DrawViewSection::makeLineSets(void) -{ -// Base::Console().Message("DVS::makeLineSets()\n"); - if (!PatIncluded.isEmpty()) { - std::string fileSpec = PatIncluded.getValue(); - Base::FileInfo fi(fileSpec); - std::string ext = fi.extension(); - if (!fi.isReadable()) { - Base::Console().Message("%s can not read hatch file: %s\n", getNameInDocument(), fileSpec.c_str()); - } else { - if ( (ext == "pat") || - (ext == "PAT") ) { - if ((!fileSpec.empty()) && - (!NameGeomPattern.isEmpty())) { - std::vector specs = - DrawGeomHatch::getDecodedSpecsFromFile(fileSpec, - NameGeomPattern.getValue()); - m_lineSets.clear(); - for (auto& hl: specs) { - //hl.dump("hl from section"); - LineSet ls; - ls.setPATLineSpec(hl); - m_lineSets.push_back(ls); - } - } - } - } - } -} - -//this could probably always use FileHatchPattern as input? -void DrawViewSection::replaceSvgIncluded(std::string newSvgFile) -{ -// Base::Console().Message("DVS::replaceSvgHatch(%s)\n", newSvgFile.c_str()); - if (SvgIncluded.isEmpty()) { - setupSvgIncluded(); - } else { - std::string tempName = SvgIncluded.getExchangeTempFile(); - DrawUtil::copyFile(newSvgFile, tempName); - SvgIncluded.setValue(tempName.c_str()); - } -} - -void DrawViewSection::replacePatIncluded(std::string newPatFile) -{ -// Base::Console().Message("DVS::replacePatHatch(%s)\n", newPatFile.c_str()); - if (PatIncluded.isEmpty()) { - setupPatIncluded(); - } else { - std::string tempName = PatIncluded.getExchangeTempFile(); - DrawUtil::copyFile(newPatFile, tempName); - PatIncluded.setValue(tempName.c_str()); - } -} - -App::DocumentObjectExecReturn *DrawViewSection::execute(void) +App::DocumentObjectExecReturn *DrawViewSection::execute() { if (!keepUpdated()) { return App::DocumentObject::StdReturn; } App::DocumentObject* base = BaseView.getValue(); - if (base == nullptr) { + if (!base) { return new App::DocumentObjectExecReturn("BaseView object not found"); } TechDraw::DrawViewPart* dvp = nullptr; if (!base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { + //this can probably only happen with scripting return new App::DocumentObjectExecReturn("BaseView object is not a DrawViewPart object"); } else { dvp = static_cast(base); } - - TopoDS_Shape baseShape; + + TopoDS_Shape baseShape = dvp->getSourceShape(); if (FuseBeforeCut.getValue()) { baseShape = dvp->getSourceShapeFused(); - } else { - baseShape = dvp->getSourceShape(); } if (baseShape.IsNull()) { - bool isRestoring = getDocument()->testStatus(App::Document::Status::Restoring); - if (isRestoring) { - Base::Console().Warning("DVS::execute - base shape is invalid - (but document is restoring) - %s\n", - getNameInDocument()); - } else { - Base::Console().Error("Error: DVS::execute - base shape is Null. - %s\n", - getNameInDocument()); - } - return new App::DocumentObjectExecReturn("BaseView Source object is Null"); + return DrawView::execute(); } + m_saveShape = baseShape; //save shape for 2nd pass + // checkXDirection(); bool haveX = checkXDirection(); if (!haveX) { @@ -334,33 +262,54 @@ App::DocumentObjectExecReturn *DrawViewSection::execute(void) sectionExec(baseShape); addShapes2d(); - //second pass if required - if (ScaleType.isValue("Automatic")) { - if (!checkFit()) { - double newScale = autoScale(); - Scale.setValue(newScale); - Scale.purgeTouched(); - if (geometryObject != nullptr) { - delete geometryObject; - geometryObject = nullptr; - sectionExec(baseShape); - } - } - } - - dvp->requestPaint(); //to refresh section line return DrawView::execute(); } -void DrawViewSection::sectionExec(TopoDS_Shape baseShape) +void DrawViewSection::sectionExec(TopoDS_Shape& baseShape) { +// Base::Console().Message("DVS::sectionExec() - %s baseShape.IsNull: %d\n", +// getNameInDocument(), baseShape.IsNull()); + + if (waitingForHlr() || + waitingForCut()) { + return; + } + + if (baseShape.IsNull()) { + //should be caught before this + return; + } + if (geometryObject) { + delete geometryObject; + geometryObject = nullptr; + } + + try { + connectCutWatcher = QObject::connect(&m_cutWatcher, &QFutureWatcherBase::finished, [this] { + this->onSectionCutFinished(); + }); + m_cutFuture = QtConcurrent::run(this, &DrawViewSection::makeSectionCut, baseShape); + m_cutWatcher.setFuture(m_cutFuture); + waitingForCut(true); + } + catch (...) { + Base::Console().Message("DVS::sectionExec - failed to make section cut"); + return; + } +} + +void DrawViewSection::makeSectionCut(TopoDS_Shape &baseShape) +{ +// Base::Console().Message("DVS::makeSectionCut() - %s - baseShape.IsNull: %d\n", +// getNameInDocument(), baseShape.IsNull()); + + showProgressMessage(getNameInDocument(), "is making section cut"); + // cut base shape with tool //is SectionOrigin valid? Bnd_Box centerBox; BRepBndLib::AddOptimal(baseShape, centerBox); centerBox.SetGap(0.0); - -// make tool gp_Pln pln = getSectionPlane(); gp_Dir gpNormal = pln.Axis().Direction(); Base::Vector3d orgPnt = SectionOrigin.getValue(); @@ -369,6 +318,7 @@ void DrawViewSection::sectionExec(TopoDS_Shape baseShape) Base::Console().Warning("DVS: SectionOrigin doesn't intersect part in %s\n",getNameInDocument()); } + // make cutting tool // Make the extrusion face double dMax = sqrt(centerBox.SquareExtent()); BRepBuilderAPI_MakeFace mkFace(pln, -dMax,dMax,-dMax,dMax); @@ -383,6 +333,7 @@ void DrawViewSection::sectionExec(TopoDS_Shape baseShape) // We need to copy the shape to not modify the BRepstructure BRepBuilderAPI_Copy BuilderCopy(baseShape); TopoDS_Shape myShape = BuilderCopy.Shape(); + m_saveShape = myShape; //save shape for 2nd pass // perform cut BRep_Builder builder; @@ -403,8 +354,10 @@ void DrawViewSection::sectionExec(TopoDS_Shape baseShape) builder.Add(pieces, cut); outdb++; } -// pieces contains result of cutting each subshape in baseShape with tool + + // pieces contains result of cutting each subshape in baseShape with tool TopoDS_Shape rawShape = pieces; + if (debugSection()) { BRepTools::Write(myShape, "DVSCopy.brep"); //debug BRepTools::Write(aProjFace, "DVSFace.brep"); //debug @@ -417,20 +370,19 @@ void DrawViewSection::sectionExec(TopoDS_Shape baseShape) BRepBndLib::AddOptimal(rawShape, testBox); testBox.SetGap(0.0); if (testBox.IsVoid()) { //prism & input don't intersect. rawShape is garbage, don't bother. - Base::Console().Warning("DVS::execute - prism & input don't intersect - %s\n", Label.getValue()); + Base::Console().Warning("DVS::makeSectionCut - prism & input don't intersect - %s\n", Label.getValue()); return; } // build display geometry as in DVP, with minor mods - gp_Ax2 viewAxis; TopoDS_Shape centeredShape; try { Base::Vector3d origin(0.0, 0.0, 0.0); - viewAxis = getProjectionCS(origin); + m_viewAxis = getProjectionCS(origin); gp_Pnt inputCenter; inputCenter = TechDraw::findCentroid(rawShape, - viewAxis); + m_viewAxis); Base::Vector3d centroid(inputCenter.X(), inputCenter.Y(), inputCenter.Z()); @@ -440,104 +392,153 @@ void DrawViewSection::sectionExec(TopoDS_Shape baseShape) m_cutShape = centeredShape; m_saveCentroid = centroid; - TopoDS_Shape scaledShape = TechDraw::scaleShape(centeredShape, - getScale()); + m_scaledShape = TechDraw::scaleShape(centeredShape, + getScale()); if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { - scaledShape = TechDraw::rotateShape(scaledShape, - viewAxis, - Rotation.getValue()); - } - if (debugSection()) { - BRepTools::Write(m_cutShape, "DVSmCutShape.brep"); //debug - BRepTools::Write(scaledShape, "DVSScaled.brep"); //debug -// DrawUtil::dumpCS("DVS::execute - CS to GO", viewAxis); - } - - geometryObject = buildGeometryObject(scaledShape,viewAxis); - -#if MOD_TECHDRAW_HANDLE_FACES - extractFaces(); -#endif //#if MOD_TECHDRAW_HANDLE_FACES - } - catch (Standard_Failure& e1) { - Base::Console().Warning("DVS::execute - failed to build base shape %s - %s **\n", - getNameInDocument(),e1.GetMessageString()); - return; - } -//display geometry for cut shape is in geometryObject as in DVP - -// build section face geometry - TopoDS_Compound faceIntersections = findSectionPlaneIntersections(rawShape); - TopoDS_Shape centeredShapeF = TechDraw::moveShape(faceIntersections, - m_saveCentroid * -1.0); - - TopoDS_Shape scaledSection = TechDraw::scaleShape(centeredShapeF, - getScale()); - if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { - scaledSection = TechDraw::rotateShape(scaledSection, - viewAxis, + m_scaledShape = TechDraw::rotateShape(m_scaledShape, + m_viewAxis, Rotation.getValue()); } if (debugSection()) { - BRepTools::Write(scaledSection, "DVSScaledFaces.brep"); //debug - } -// scaledSection is compound of TopoDS_Face intersections, but aligned to pln(origin, sectionNormal) -// needs to be aligned to pln (origin, stdZ); - gp_Ax3 R3; - gp_Ax2 projCS = getSectionCS(); - gp_Ax3 proj3 = gp_Ax3(gp_Pnt(0.0, 0.0, 0.0), - projCS.Direction(), - projCS.XDirection()); - gp_Trsf fromR3; - fromR3.SetTransformation(R3, proj3); - BRepBuilderAPI_Transform xformer(fromR3); - xformer.Perform(scaledSection, true); - if (xformer.IsDone()) { - sectionFaces = TopoDS::Compound(xformer.Shape()); -// BRepTools::Write(sectionFaces, "DVSXFaces.brep"); //debug - } else { - Base::Console().Message("DVS::sectionExec - face xform failed\n"); + BRepTools::Write(m_cutShape, "DVSmCutShape.brep"); //debug + BRepTools::Write(m_scaledShape, "DVSScaled.brep"); //debug +// DrawUtil::dumpCS("DVS::makeSectionCut - CS to GO", viewAxis); } - sectionFaces = TopoDS::Compound(GeometryObject::invertGeometry(sectionFaces)); //handle Qt -y + m_rawShape = rawShape; //save for section face finding - //turn section faces into something we can draw - tdSectionFaces.clear(); - TopExp_Explorer sectionExpl(sectionFaces, TopAbs_FACE); - int iface = 0; - for (; sectionExpl.More(); sectionExpl.Next()) { - iface++; - const TopoDS_Face& face = TopoDS::Face(sectionExpl.Current()); - TechDraw::FacePtr sectionFace(std::make_shared()); - TopExp_Explorer expFace(face, TopAbs_WIRE); - int iwire = 0; - for ( ; expFace.More(); expFace.Next()) { - iwire++; - TechDraw::Wire* w = new TechDraw::Wire(); - const TopoDS_Wire& wire = TopoDS::Wire(expFace.Current()); - int iedge = 0; - TopExp_Explorer expWire(wire, TopAbs_EDGE); - for ( ; expWire.More(); expWire.Next()) { - iedge++; - const TopoDS_Edge& edge = TopoDS::Edge(expWire.Current()); - TechDraw::BaseGeomPtr e = BaseGeom::baseFactory(edge); - if (e != nullptr) { - w->geoms.push_back(e); - } + } + catch (Standard_Failure& e1) { + Base::Console().Warning("DVS::makeSectionCut - failed to build base shape %s - %s **\n", + getNameInDocument(),e1.GetMessageString()); + return; + } + + waitingForCut(false); +} + +void DrawViewSection::onSectionCutFinished() +{ +// Base::Console().Message("DVS::onSectionCutFinished() - %s\n", getNameInDocument()); + QObject::disconnect(connectCutWatcher); + + showProgressMessage(getNameInDocument(), "has finished making section cut"); + + postSectionCutTasks(); + + //display geometry for cut shape is in geometryObject as in DVP + geometryObject = buildGeometryObject(m_scaledShape, m_viewAxis); +} + +//activities that depend on updated geometry object +void DrawViewSection::postHlrTasks(void) +{ +// Base::Console().Message("DVS::postHlrTasks() - %s\n", getNameInDocument()); + + DrawViewPart::postHlrTasks(); + + //second pass if required + if (ScaleType.isValue("Automatic")) { + if (!checkFit()) { + double newScale = autoScale(); + Scale.setValue(newScale); + Scale.purgeTouched(); + sectionExec(m_saveShape); + } + } + overrideKeepUpdated(false); + + + // build section face geometry + TopoDS_Compound faceIntersections = findSectionPlaneIntersections(m_rawShape); + if (faceIntersections.IsNull()) { + requestPaint(); + return; + } + + TopoDS_Shape centeredShapeF = TechDraw::moveShape(faceIntersections, + m_saveCentroid * -1.0); + + TopoDS_Shape scaledSection = TechDraw::scaleShape(centeredShapeF, + getScale()); + if (!DrawUtil::fpCompare(Rotation.getValue(),0.0)) { + scaledSection = TechDraw::rotateShape(scaledSection, + m_viewAxis, + Rotation.getValue()); + } + if (debugSection()) { + BRepTools::Write(scaledSection, "DVSScaledFaces.brep"); //debug + } + + // scaledSection is compound of TopoDS_Face intersections, but aligned to pln(origin, sectionNormal) + // needs to be aligned to pln (origin, stdZ); + gp_Ax3 R3; + gp_Ax2 projCS = getSectionCS(); + gp_Ax3 proj3 = gp_Ax3(gp_Pnt(0.0, 0.0, 0.0), + projCS.Direction(), + projCS.XDirection()); + gp_Trsf fromR3; + fromR3.SetTransformation(R3, proj3); + BRepBuilderAPI_Transform xformer(fromR3); + xformer.Perform(scaledSection, true); + if (xformer.IsDone()) { + sectionTopoDSFaces = TopoDS::Compound(xformer.Shape()); + } else { + Base::Console().Message("DVS::sectionExec - face xform failed\n"); + } + + sectionTopoDSFaces = TopoDS::Compound(GeometryObject::invertGeometry(sectionTopoDSFaces)); //handle Qt -y + + //turn section faces into TD geometry + tdSectionFaces.clear(); + TopExp_Explorer sectionExpl(sectionTopoDSFaces, TopAbs_FACE); + for (; sectionExpl.More(); sectionExpl.Next()) { + const TopoDS_Face& face = TopoDS::Face(sectionExpl.Current()); + TechDraw::FacePtr sectionFace(std::make_shared()); + TopExp_Explorer expFace(face, TopAbs_WIRE); + for ( ; expFace.More(); expFace.Next()) { + TechDraw::Wire* w = new TechDraw::Wire(); + const TopoDS_Wire& wire = TopoDS::Wire(expFace.Current()); + TopExp_Explorer expWire(wire, TopAbs_EDGE); + for ( ; expWire.More(); expWire.Next()) { + const TopoDS_Edge& edge = TopoDS::Edge(expWire.Current()); + TechDraw::BaseGeomPtr e = BaseGeom::baseFactory(edge); + if (e) { + w->geoms.push_back(e); } - sectionFace->wires.push_back(w); } - tdSectionFaces.push_back(sectionFace); + sectionFace->wires.push_back(w); } + tdSectionFaces.push_back(sectionFace); + } -// add cosmetic entities to view - addCosmeticVertexesToGeom(); - addCosmeticEdgesToGeom(); - addCenterLinesToGeom(); + TechDraw::DrawViewPart* dvp = dynamic_cast(BaseView.getValue()); + if (dvp) { + dvp->requestPaint(); //to refresh section line + } + requestPaint(); +} -// add landmark dim reference points to view - addReferencesToGeom(); +//activities that depend on a valid section cut +void DrawViewSection::postSectionCutTasks() +{ + std::vector children = getInList(); + for (auto& c: children) { + if (c->getTypeId().isDerivedFrom(DrawViewPart::getClassTypeId())) { + //details or sections of this need cut shape + c->recomputeFeature(); + } + } +} + +bool DrawViewSection::waitingForResult() const +{ + if (DrawViewPart::waitingForResult() || + waitingForCut()) { + return true; + } + return false; } gp_Pln DrawViewSection::getSectionPlane() const @@ -548,74 +549,67 @@ gp_Pln DrawViewSection::getSectionPlane() const return gp_Pln(viewAxis3); } - //! tries to find the intersection of the section plane with the shape giving a collection of planar faces TopoDS_Compound DrawViewSection::findSectionPlaneIntersections(const TopoDS_Shape& shape) { -// Base::Console().Message("DVS::findSectionPlaneIntersections()\n"); - TopoDS_Compound result; +// Base::Console().Message("DVS::findSectionPlaneIntersections() - %s\n", getNameInDocument()); if(shape.IsNull()){ - Base::Console().Warning("DrawViewSection::getSectionSurface - Sectional View shape is Empty\n"); - return result; + // this shouldn't happen + Base::Console().Warning("DrawViewSection::findSectionPlaneInter - %s - input shape is Null\n", getNameInDocument()); + return TopoDS_Compound(); } gp_Pln plnSection = getSectionPlane(); BRep_Builder builder; + TopoDS_Compound result; builder.MakeCompound(result); TopExp_Explorer expFaces(shape, TopAbs_FACE); - int i; - int dbAdded = 0; - for (i = 1 ; expFaces.More(); expFaces.Next(), i++) { + for ( ; expFaces.More(); expFaces.Next()) { const TopoDS_Face& face = TopoDS::Face(expFaces.Current()); BRepAdaptor_Surface adapt(face); if (adapt.GetType() == GeomAbs_Plane){ gp_Pln plnFace = adapt.Plane(); - if(plnSection.Contains(plnFace.Location(), Precision::Confusion()) && plnFace.Axis().IsParallel(plnSection.Axis(), Precision::Angular())) { - dbAdded++; builder.Add(result, face); } } } -// BRepTools::Write(result, "DVSIntersect.brep"); //debug return result; } //calculate the ends of the section line in BaseView's coords -std::pair DrawViewSection::sectionLineEnds(void) +std::pair DrawViewSection::sectionLineEnds() { std::pair result; Base::Vector3d stdZ(0.0, 0.0, 1.0); - double baseRotation = getBaseDVP()->Rotation.getValue(); //Qt degrees + double baseRotation = getBaseDVP()->Rotation.getValue(); //Qt degrees are clockwise Base::Rotation rotator(stdZ, baseRotation * M_PI / 180.0); Base::Rotation unrotator(stdZ, - baseRotation * M_PI / 180.0); auto sNorm = SectionNormal.getValue(); - double angle = M_PI / 2.0; auto axis = getBaseDVP()->Direction.getValue(); Base::Vector3d stdOrg(0.0, 0.0, 0.0); - Base::Vector3d sLineDir = DrawUtil::vecRotate(sNorm, angle, axis, stdOrg); - sLineDir.Normalize(); - Base::Vector3d sLineDir2 = - axis.Cross(sNorm); - sLineDir2.Normalize(); - Base::Vector3d sLineOnBase = getBaseDVP()->projectPoint(sLineDir2); - sLineOnBase.Normalize(); + Base::Vector3d sectionLineDir = - axis.Cross(sNorm); + sectionLineDir.Normalize(); + sectionLineDir = getBaseDVP()->projectPoint(sectionLineDir); //convert to base view CS + sectionLineDir.Normalize(); - auto sOrigin = SectionOrigin.getValue(); - Base::Vector3d adjSectionOrg = sOrigin - getBaseDVP()->getOriginalCentroid(); - Base::Vector3d sOrgOnBase = getBaseDVP()->projectPoint(adjSectionOrg); + Base::Vector3d sectionOrg = SectionOrigin.getValue() - getBaseDVP()->getOriginalCentroid(); + sectionOrg = getBaseDVP()->projectPoint(sectionOrg); //convert to base view CS + //get the unscaled X and Y ranges of the base view geometry auto bbx = getBaseDVP()->getBoundingBox(); double xRange = bbx.MaxX - bbx.MinX; xRange /= getBaseDVP()->getScale(); double yRange = bbx.MaxY - bbx.MinY; yRange /= getBaseDVP()->getScale(); - sOrgOnBase = rotator.multVec(sOrgOnBase); - sLineOnBase = rotator.multVec(sLineOnBase); - result = DrawUtil::boxIntersect2d(sOrgOnBase, sLineOnBase, xRange, yRange); //unscaled + sectionOrg = rotator.multVec(sectionOrg); + sectionLineDir = rotator.multVec(sectionLineDir); + + result = DrawUtil::boxIntersect2d(sectionOrg, sectionLineDir, xRange, yRange); //unscaled result.first = unrotator.multVec(result.first); result.second = unrotator.multVec(result.second); @@ -641,31 +635,31 @@ bool DrawViewSection::isReallyInBox (const gp_Pnt p, const Bnd_Box& bb) const return !bb.IsOut(p); } -Base::Vector3d DrawViewSection::getXDirection(void) const +Base::Vector3d DrawViewSection::getXDirection() const { // Base::Console().Message("DVS::getXDirection() - %s\n", Label.getValue()); Base::Vector3d result(1.0, 0.0, 0.0); //default X App::Property* prop = getPropertyByName("XDirection"); - if (prop != nullptr) { //have an XDirection property - Base::Vector3d propVal = XDirection.getValue(); - if (DrawUtil::fpCompare(propVal.Length(), 0.0)) { //but it has no value - std::string sectName = SectionDirection.getValueAsString(); - gp_Ax2 cs = getCSFromBase(sectName); + if (prop) { + //we have an XDirection property + if (DrawUtil::fpCompare(XDirection.getValue().Length(), 0.0)) { + //but it has no value, so we make a value + gp_Ax2 cs = getCSFromBase(SectionDirection.getValueAsString()); gp_Dir gXDir = cs.XDirection(); result = Base::Vector3d(gXDir.X(), gXDir.Y(), gXDir.Z()); } else { - result = propVal; //normal case. XDirection is set. + //XDirection is good, so we use it + result = XDirection.getValue(); } - } else { //no Property. can this happen? - std::string sectName = SectionDirection.getValueAsString(); - gp_Ax2 cs = getCSFromBase(sectName); - gp_Dir gXDir = cs.XDirection(); - result = Base::Vector3d(gXDir.X(), - gXDir.Y(), - gXDir.Z()); - + } else { + //no XDirection property. can this happen? + gp_Ax2 cs = getCSFromBase(SectionDirection.getValueAsString()); + gp_Dir gXDir = cs.XDirection(); + result = Base::Vector3d(gXDir.X(), + gXDir.Y(), + gXDir.Z()); } return result; } @@ -673,14 +667,13 @@ Base::Vector3d DrawViewSection::getXDirection(void) const void DrawViewSection::setCSFromBase(const std::string sectionName) { // Base::Console().Message("DVS::setCSFromBase(%s)\n", sectionName.c_str()); - gp_Ax2 CS = getCSFromBase(sectionName); - gp_Dir gDir = CS.Direction(); + gp_Dir gDir = getCSFromBase(sectionName).Direction(); Base::Vector3d vDir(gDir.X(), gDir.Y(), gDir.Z()); Direction.setValue(vDir); SectionNormal.setValue(vDir); - gp_Dir gxDir = CS.XDirection(); + gp_Dir gxDir = getCSFromBase(sectionName).XDirection(); Base::Vector3d vXDir(gxDir.X(), gxDir.Y(), gxDir.Z()); @@ -739,7 +732,7 @@ gp_Ax2 DrawViewSection::getCSFromBase(const std::string sectionName) const } //returns current section cs -gp_Ax2 DrawViewSection::getSectionCS(void) const +gp_Ax2 DrawViewSection::getSectionCS() const { // Base::Console().Message("DVS::getSectionCS()\n"); Base::Vector3d vNormal = SectionNormal.getValue(); @@ -767,37 +760,20 @@ gp_Ax2 DrawViewSection::getSectionCS(void) const return sectionCS; } -gp_Ax2 DrawViewSection::rotateCSArbitrary(gp_Ax2 oldCS, - Base::Vector3d axis, - double degAngle) const -{ - gp_Ax2 newCS; - - gp_Pnt oldOrg = oldCS.Location(); - - gp_Dir gAxis(axis.x, axis.y, axis.z); - gp_Ax1 rotAxis = gp_Ax1(oldOrg, gAxis); - - double radAngle = degAngle * M_PI / 180.0; - - newCS = oldCS.Rotated(rotAxis, radAngle); - return newCS; -} - std::vector DrawViewSection::getDrawableLines(int i) { // Base::Console().Message("DVS::getDrawableLines(%d) - lineSets: %d\n", i, m_lineSets.size()); std::vector result; result = DrawGeomHatch::getTrimmedLinesSection(this,m_lineSets, - getSectionTFace(i), + getSectionTopoDSFace(i), HatchScale.getValue()); return result; } -TopoDS_Face DrawViewSection::getSectionTFace(int i) +TopoDS_Face DrawViewSection::getSectionTopoDSFace(int i) { TopoDS_Face result; - TopExp_Explorer expl(sectionFaces, TopAbs_FACE); + TopExp_Explorer expl(sectionTopoDSFaces, TopAbs_FACE); int count = 1; for (; expl.More(); expl.Next(), count++) { if (count == i+1) { @@ -807,20 +783,11 @@ TopoDS_Face DrawViewSection::getSectionTFace(int i) return result; } -void DrawViewSection::unsetupObject() -{ - TechDraw::DrawViewPart* base = getBaseDVP(); - if (base != nullptr) { - base->touch(); - } - DrawViewPart::unsetupObject(); -} - TechDraw::DrawViewPart* DrawViewSection::getBaseDVP() const { TechDraw::DrawViewPart* baseDVP = nullptr; App::DocumentObject* base = BaseView.getValue(); - if (base != nullptr) { + if (base) { if (base->getTypeId().isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId())) { baseDVP = static_cast(base); } @@ -832,7 +799,7 @@ TechDraw::DrawProjGroupItem* DrawViewSection::getBaseDPGI() const { TechDraw::DrawProjGroupItem* baseDPGI = nullptr; App::DocumentObject* base = BaseView.getValue(); - if (base != nullptr) { + if (base) { if (base->getTypeId().isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())) { baseDPGI = static_cast(base); } @@ -840,43 +807,17 @@ TechDraw::DrawProjGroupItem* DrawViewSection::getBaseDPGI() const return baseDPGI; } -void DrawViewSection::getParameters() +// setup / tear down routines + +void DrawViewSection::unsetupObject() { -// Base::Console().Message("DVS::getParameters()\n"); - Base::ReferencehGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); - - bool fuseFirst = hGrp->GetBool("SectionFuseFirst", false); - FuseBeforeCut.setValue(fuseFirst); + TechDraw::DrawViewPart* base = getBaseDVP(); + if (base) { + base->touch(); + } + DrawViewPart::unsetupObject(); } -bool DrawViewSection::debugSection(void) const -{ - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/debug"); - - bool result = hGrp->GetBool("debugSection",false); - return result; -} - -int DrawViewSection::prefCutSurface(void) const -{ -// Base::Console().Message("DVS::prefCutSurface()\n"); - Base::ReferencehGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); - - int result = hGrp->GetInt("CutSurfaceDisplay", 2); //default to SvgHatch - return result; -} - -bool DrawViewSection::showSectionEdges(void) -{ - Base::Reference hGrp = App::GetApplication().GetUserParameter() - .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); - return (hGrp->GetBool("ShowSectionEdges", true)); -} - - void DrawViewSection::onDocumentRestored() { // Base::Console().Message("DVS::onDocumentRestored()\n"); @@ -913,6 +854,34 @@ void DrawViewSection::setupObject() DrawViewPart::setupObject(); } +//hatch file routines + +//create geometric hatch lines +void DrawViewSection::makeLineSets(void) +{ +// Base::Console().Message("DVS::makeLineSets()\n"); + if (PatIncluded.isEmpty()) { + return; + } + + std::string fileSpec = PatIncluded.getValue(); + Base::FileInfo fi(fileSpec); + std::string ext = fi.extension(); + if (!fi.isReadable()) { + Base::Console().Message("%s can not read hatch file: %s\n", getNameInDocument(), fileSpec.c_str()); + return; + } + + if ( (ext == "pat") || + (ext == "PAT") ) { + if ((!fileSpec.empty()) && + (!NameGeomPattern.isEmpty())) { + m_lineSets.clear(); + m_lineSets = DrawGeomHatch::makeLineSets(fileSpec, NameGeomPattern.getValue()); + } + } +} + void DrawViewSection::setupSvgIncluded(void) { // Base::Console().Message("DVS::setupSvgIncluded()\n"); @@ -937,7 +906,7 @@ void DrawViewSection::setupSvgIncluded(void) } } -void DrawViewSection::setupPatIncluded(void) +void DrawViewSection::setupPatIncluded() { // Base::Console().Message("DVS::setupPatIncluded()\n"); App::Document* doc = getDocument(); @@ -958,12 +927,73 @@ void DrawViewSection::setupPatIncluded(void) } } +//this could probably always use FileHatchPattern as input? +void DrawViewSection::replaceSvgIncluded(std::string newSvgFile) +{ +// Base::Console().Message("DVS::replaceSvgHatch(%s)\n", newSvgFile.c_str()); + if (SvgIncluded.isEmpty()) { + setupSvgIncluded(); + } else { + std::string tempName = SvgIncluded.getExchangeTempFile(); + DrawUtil::copyFile(newSvgFile, tempName); + SvgIncluded.setValue(tempName.c_str()); + } +} + +void DrawViewSection::replacePatIncluded(std::string newPatFile) +{ +// Base::Console().Message("DVS::replacePatHatch(%s)\n", newPatFile.c_str()); + if (PatIncluded.isEmpty()) { + setupPatIncluded(); + } else { + std::string tempName = PatIncluded.getExchangeTempFile(); + DrawUtil::copyFile(newPatFile, tempName); + PatIncluded.setValue(tempName.c_str()); + } +} + +// Parameter fetching routines + +void DrawViewSection::getParameters() +{ +// Base::Console().Message("DVS::getParameters()\n"); + Base::ReferencehGrp = App::GetApplication().GetUserParameter() + .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + + bool fuseFirst = hGrp->GetBool("SectionFuseFirst", false); + FuseBeforeCut.setValue(fuseFirst); +} + +bool DrawViewSection::debugSection(void) const +{ + Base::Reference hGrp = App::GetApplication().GetUserParameter() + .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/debug"); + + return hGrp->GetBool("debugSection",false); +} + +int DrawViewSection::prefCutSurface(void) const +{ +// Base::Console().Message("DVS::prefCutSurface()\n"); + Base::ReferencehGrp = App::GetApplication().GetUserParameter() + .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); + + return hGrp->GetInt("CutSurfaceDisplay", 2); //default to SvgHatch +} + +bool DrawViewSection::showSectionEdges(void) +{ + Base::Reference hGrp = App::GetApplication().GetUserParameter() + .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); + return (hGrp->GetBool("ShowSectionEdges", true)); +} + // Python Drawing feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewSectionPython, TechDraw::DrawViewSection) -template<> const char* TechDraw::DrawViewSectionPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewSectionPython::getViewProviderName() const { return "TechDrawGui::ViewProviderDrawingView"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewSection.h b/src/Mod/TechDraw/App/DrawViewSection.h index 0ef6f93911..11b9a94d98 100644 --- a/src/Mod/TechDraw/App/DrawViewSection.h +++ b/src/Mod/TechDraw/App/DrawViewSection.h @@ -25,6 +25,11 @@ #ifndef _DrawViewSection_h_ #define _DrawViewSection_h_ +#include + +#include +#include + #include #include #include @@ -32,6 +37,7 @@ #include #include +#include #include "DrawViewPart.h" @@ -61,8 +67,8 @@ class TechDrawExport DrawViewSection : public DrawViewPart PROPERTY_HEADER_WITH_OVERRIDE(Part::DrawViewSection); public: - DrawViewSection(void); - virtual ~DrawViewSection(); + DrawViewSection(); + ~DrawViewSection() override; App::PropertyLink BaseView; App::PropertyVector SectionNormal; @@ -83,68 +89,80 @@ public: bool isReallyInBox (const Base::Vector3d v, const Base::BoundBox3d bb) const; bool isReallyInBox (const gp_Pnt p, const Bnd_Box& bb) const; - virtual App::DocumentObjectExecReturn *execute(void) override; - virtual void onChanged(const App::Property* prop) override; - virtual const char* getViewProviderName(void) const override { + App::DocumentObjectExecReturn *execute() override; + void onChanged(const App::Property* prop) override; + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderViewSection"; } - virtual void unsetupObject() override; - virtual short mustExecute() const override; + void unsetupObject() override; + short mustExecute() const override; - void sectionExec(TopoDS_Shape s); + void sectionExec(TopoDS_Shape& s); + void makeSectionCut(TopoDS_Shape &baseShape); + void postHlrTasks(void) override; + virtual void postSectionCutTasks(); + void waitingForCut(bool s) { m_waitingForCut = s; } + bool waitingForCut(void) const { return m_waitingForCut; } + bool waitingForResult() const override; std::vector getTDFaceGeometry() {return tdSectionFaces;} void setCSFromBase(const std::string sectionName); gp_Ax2 getCSFromBase(const std::string sectionName) const; - gp_Ax2 rotateCSArbitrary(gp_Ax2 oldCS, - Base::Vector3d axis, - double degAngle) const; gp_Ax2 getSectionCS() const; - virtual Base::Vector3d getXDirection(void) const override; //don't use XDirection.getValue() + Base::Vector3d getXDirection() const override; //don't use XDirection.getValue() TechDraw::DrawViewPart* getBaseDVP() const; TechDraw::DrawProjGroupItem* getBaseDPGI() const; - TopoDS_Compound getSectionFaces() { return sectionFaces;} -// std::vector getSectionFaceWires(void) { return sectionFaceWires; } //obs? - TopoDS_Face getSectionTFace(int i); + TopoDS_Compound getSectionTFaces() { return sectionTopoDSFaces;} + TopoDS_Face getSectionTopoDSFace(int i); void makeLineSets(void) ; std::vector getDrawableLines(int i = 0); std::vector getDecodedSpecsFromFile(std::string fileSpec, std::string myPattern); - TopoDS_Shape getCutShape(void) {return m_cutShape;} + TopoDS_Shape getCutShape() {return m_cutShape;} static const char* SectionDirEnums[]; static const char* CutSurfaceEnums[]; - std::pair sectionLineEnds(void); + std::pair sectionLineEnds(); bool showSectionEdges(void); +public Q_SLOTS: + void onSectionCutFinished(void); + protected: - TopoDS_Compound sectionFaces; //tSectionFaces -// std::vector sectionFaceWires; //obs??? getSectionFaceWires + TopoDS_Compound sectionTopoDSFaces; //needed for hatching std::vector m_lineSets; std::vector tdSectionFaces; gp_Pln getSectionPlane() const; TopoDS_Compound findSectionPlaneIntersections(const TopoDS_Shape& shape); - void getParameters(void); - bool debugSection(void) const; - int prefCutSurface(void) const; + void getParameters(); + bool debugSection() const; + int prefCutSurface() const; TopoDS_Shape m_cutShape; - virtual void onDocumentRestored() override; - virtual void setupObject() override; - void setupSvgIncluded(void); - void setupPatIncluded(void); + void onDocumentRestored() override; + void setupObject() override; + void setupSvgIncluded(); + void setupPatIncluded(); void replaceSvgIncluded(std::string newSvgFile); void replacePatIncluded(std::string newPatFile); + TopoDS_Shape m_rawShape; + gp_Ax2 m_viewAxis; + TopoDS_Shape m_scaledShape; + + QMetaObject::Connection connectCutWatcher; + QFutureWatcher m_cutWatcher; + QFuture m_cutFuture; + bool m_waitingForCut; }; diff --git a/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp b/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp index 68202f2f2d..46d6189204 100644 --- a/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp +++ b/src/Mod/TechDraw/App/DrawViewSpreadsheet.cpp @@ -57,7 +57,7 @@ using namespace std; PROPERTY_SOURCE(TechDraw::DrawViewSpreadsheet, TechDraw::DrawViewSymbol) -DrawViewSpreadsheet::DrawViewSpreadsheet(void) +DrawViewSpreadsheet::DrawViewSpreadsheet() { static const char *vgroup = "Spreadsheet"; @@ -81,19 +81,20 @@ DrawViewSpreadsheet::~DrawViewSpreadsheet() short DrawViewSpreadsheet::mustExecute() const { - short result = 0; if (!isRestoring()) { - result = (Source.isTouched() || - CellStart.isTouched() || - CellEnd.isTouched() || - Font.isTouched() || - TextSize.isTouched() || - TextColor.isTouched() || - LineWidth.isTouched() ); - } - if (result) { - return result; + if ( + Source.isTouched() || + CellStart.isTouched() || + CellEnd.isTouched() || + Font.isTouched() || + TextSize.isTouched() || + TextColor.isTouched() || + LineWidth.isTouched() + ) { + return 1; + } } + return TechDraw::DrawView::mustExecute(); } @@ -102,7 +103,7 @@ void DrawViewSpreadsheet::onChanged(const App::Property* prop) TechDraw::DrawView::onChanged(prop); } -App::DocumentObjectExecReturn *DrawViewSpreadsheet::execute(void) +App::DocumentObjectExecReturn *DrawViewSpreadsheet::execute() { App::DocumentObject* link = Source.getValue(); std::string scellstart = CellStart.getValue(); @@ -111,15 +112,16 @@ App::DocumentObjectExecReturn *DrawViewSpreadsheet::execute(void) return new App::DocumentObjectExecReturn("No spreadsheet linked"); if (!link->getTypeId().isDerivedFrom(Spreadsheet::Sheet::getClassTypeId())) return new App::DocumentObjectExecReturn("The linked object is not a spreadsheet"); - if ( (scellstart.empty()) || (scellend.empty()) ) + if (scellstart.empty() || scellend.empty()) return new App::DocumentObjectExecReturn("Empty cell value"); Symbol.setValue(getSheetImage()); - + + overrideKeepUpdated(false); return TechDraw::DrawView::execute(); } -std::vector DrawViewSpreadsheet::getAvailColumns(void) +std::vector DrawViewSpreadsheet::getAvailColumns() { // build a list of available columns: A, B, C, ... AA, AB, ... ZY, ZZ. std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; @@ -139,24 +141,20 @@ std::vector DrawViewSpreadsheet::getAvailColumns(void) return availcolumns; } -std::string DrawViewSpreadsheet::getSVGHead(void) +std::string DrawViewSpreadsheet::getSVGHead() { - std::string head = std::string("\n"); - return head; + return std::string("\n"); } -std::string DrawViewSpreadsheet::getSVGTail(void) +std::string DrawViewSpreadsheet::getSVGTail() { - std::string tail = "\n"; - return tail; + return "\n"; } -std::string DrawViewSpreadsheet::getSheetImage(void) +std::string DrawViewSpreadsheet::getSheetImage() { - std::stringstream result; - App::DocumentObject* link = Source.getValue(); link->recomputeFeature(); //make sure s/s is up to date @@ -177,19 +175,19 @@ std::string DrawViewSpreadsheet::getSheetImage(void) if (boost::regex_search(scellstart, what, re)) { if (what.size() < 3) { Base::Console().Error("%s - start cell (%s) is invalid\n",getNameInDocument(),CellStart.getValue()); - return result.str(); - } else { - colPart = what[1]; - sColStart = colPart; - rowPart = what[2]; - try { - iRowStart = std::stoi(rowPart); - } - catch (...) { - Base::Console().Error("%s - start cell (%s) invalid row\n", - getNameInDocument(), rowPart.c_str()); - return result.str(); - } + return std::string(); + } + + colPart = what[1]; + sColStart = colPart; + rowPart = what[2]; + try { + iRowStart = std::stoi(rowPart); + } + catch (...) { + Base::Console().Error("%s - start cell (%s) invalid row\n", + getNameInDocument(), rowPart.c_str()); + return std::string(); } } @@ -206,7 +204,7 @@ std::string DrawViewSpreadsheet::getSheetImage(void) catch (...) { Base::Console().Error("%s - end cell (%s) invalid row\n", getNameInDocument(), rowPart.c_str()); - return result.str(); + return std::string(); } } } @@ -218,7 +216,7 @@ std::string DrawViewSpreadsheet::getSheetImage(void) if (iAvailColStart < 0) { //not found range start column in availcolumns list Base::Console().Error("DVS - %s - start Column (%s) is invalid\n", getNameInDocument(), sColStart.c_str()); - return result.str(); + return std::string(); } //validate range end column in sheet's available columns @@ -226,14 +224,14 @@ std::string DrawViewSpreadsheet::getSheetImage(void) if (iAvailColEnd < 0) { Base::Console().Error("DVS - %s - end Column (%s) is invalid\n", getNameInDocument(), sColEnd.c_str()); - return result.str(); + return std::string(); } //check for logical range if ( (iAvailColStart > iAvailColEnd) || (iRowStart > iRowEnd) ) { Base::Console().Error("%s - cell range is illogical\n",getNameInDocument()); - return result.str(); + return std::string(); } // build row and column ranges @@ -251,10 +249,11 @@ std::string DrawViewSpreadsheet::getSheetImage(void) } // create the Svg code - std::string ViewName = Label.getValue(); + std::stringstream result; result << getSVGHead(); + std::string ViewName = Label.getValue(); App::Color c = TextColor.getValue(); result << "" << endl; @@ -283,35 +282,33 @@ std::string DrawViewSpreadsheet::getSheetImage(void) App::Property* prop = sheet->getPropertyByName(address.toString().c_str()); std::stringstream field; if (prop && cell) { - if (prop->isDerivedFrom((App::PropertyQuantity::getClassTypeId()))) { + if ( + prop->isDerivedFrom(App::PropertyQuantity::getClassTypeId()) || + prop->isDerivedFrom(App::PropertyFloat::getClassTypeId()) || + prop->isDerivedFrom(App::PropertyInteger::getClassTypeId()) + ) { field << cell->getFormattedQuantity(); - } else if (prop->isDerivedFrom((App::PropertyFloat::getClassTypeId()))) { - field << cell->getFormattedQuantity(); - } else if (prop->isDerivedFrom((App::PropertyInteger::getClassTypeId()))) { - field << cell->getFormattedQuantity(); - } else if (prop->isDerivedFrom((App::PropertyString::getClassTypeId()))) { + } else if (prop->isDerivedFrom(App::PropertyString::getClassTypeId())) { field << static_cast(prop)->getValue(); } else { Base::Console().Error("DVSS: Unknown property type\n"); - celltext = "???"; -// assert(0); } celltext = field.str(); } // get colors, style, alignment and span int alignment = 0; std::string bcolor = "none"; - std::string fcolor = c.asCSSString(); - std::string textstyle = ""; + std::string fcolor = c.asHexString(); + std::string textstyle; if (cell) { App::Color f,b; std::set st; int colspan, rowspan; if (cell->getBackground(b)) { - bcolor = b.asCSSString(); + bcolor = b.asHexString(); } if (cell->getForeground(f)) { - fcolor = f.asCSSString(); + fcolor = f.asHexString(); } if (cell->getStyle(st)) { for (std::set::const_iterator i = st.begin(); i != st.end(); ++i) { @@ -342,7 +339,7 @@ std::string DrawViewSpreadsheet::getSheetImage(void) if (std::find(skiplist.begin(), skiplist.end(), address.toString()) == skiplist.end()) { result << " " << endl; + << LineWidth.getValue()/getScale() << ";stroke:" << c.asHexString() << ";\" />" << endl; if (alignment & Spreadsheet::Cell::ALIGNMENT_LEFT) result << " & list, const std::string& toFind) { - int result = -1; auto match = std::find(std::begin(list), std::end(list), toFind); - if (match != std::end(list)) { - result = match - std::begin(list); + if (match == std::end(list)) { + return -1; // Error value } - return result; + + return match - std::begin(list); } // Python Drawing feature --------------------------------------------------------- @@ -389,7 +386,7 @@ int DrawViewSpreadsheet::colInList(const std::vector& list, namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewSpreadsheetPython, TechDraw::DrawViewSpreadsheet) -template<> const char* TechDraw::DrawViewSpreadsheetPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewSpreadsheetPython::getViewProviderName() const { return "TechDrawGui::ViewProviderSpreadsheet"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewSpreadsheet.h b/src/Mod/TechDraw/App/DrawViewSpreadsheet.h index 5558905f11..68ddadc35e 100644 --- a/src/Mod/TechDraw/App/DrawViewSpreadsheet.h +++ b/src/Mod/TechDraw/App/DrawViewSpreadsheet.h @@ -23,6 +23,8 @@ #ifndef _DrawViewSpreadsheet_h_ #define _DrawViewSpreadsheet_h_ +#include + #include #include #include @@ -35,11 +37,11 @@ namespace TechDraw class TechDrawExport DrawViewSpreadsheet : public TechDraw::DrawViewSymbol { - PROPERTY_HEADER(TechDraw::DrawViewSpreadsheet); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawViewSpreadsheet); public: - DrawViewSpreadsheet(void); - virtual ~DrawViewSpreadsheet(); + DrawViewSpreadsheet(); + ~DrawViewSpreadsheet() override; App::PropertyLink Source; App::PropertyString CellStart; App::PropertyString CellEnd; @@ -49,19 +51,19 @@ public: App::PropertyFloat TextSize; - virtual App::DocumentObjectExecReturn *execute(void); - virtual short mustExecute() const; - std::string getSheetImage(void); + App::DocumentObjectExecReturn *execute() override; + short mustExecute() const override; + std::string getSheetImage(); - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderSpreadsheet"; } protected: - virtual void onChanged(const App::Property* prop); - std::vector getAvailColumns(void); - std::string getSVGHead(void); - std::string getSVGTail(void); + void onChanged(const App::Property* prop) override; + std::vector getAvailColumns(); + std::string getSVGHead(); + std::string getSVGTail(); int colInList(const std::vector& list, const std::string& toFind); diff --git a/src/Mod/TechDraw/App/DrawViewSymbol.cpp b/src/Mod/TechDraw/App/DrawViewSymbol.cpp index d31f763720..4d6718fb6f 100644 --- a/src/Mod/TechDraw/App/DrawViewSymbol.cpp +++ b/src/Mod/TechDraw/App/DrawViewSymbol.cpp @@ -25,23 +25,17 @@ #ifndef _PreComp_ # include -#include #endif -#include -#include - -#include - +#include #include -#include +#include "QDomNodeModel.h" #include #include #include #include -#include "QDomNodeModel.h" #include "DrawUtil.h" #include "DrawPage.h" #include "DrawViewSymbol.h" @@ -51,7 +45,6 @@ using namespace TechDraw; using namespace std; - //=========================================================================== // DrawViewSymbol //=========================================================================== @@ -59,7 +52,7 @@ using namespace std; PROPERTY_SOURCE(TechDraw::DrawViewSymbol, TechDraw::DrawView) -DrawViewSymbol::DrawViewSymbol(void) +DrawViewSymbol::DrawViewSymbol() { static const char *vgroup = "Drawing view"; @@ -75,135 +68,25 @@ DrawViewSymbol::~DrawViewSymbol() void DrawViewSymbol::onChanged(const App::Property* prop) { -// Base::Console().Message("DVS::onChanged(%s) \n",prop->getName()); if (prop == &Symbol) { - if (!isRestoring() && Symbol.getValue()[0]) { - //this pulls the initial values from svg into editabletexts - // should only happen first time?? extra loop onChanged->execute->onChanged - - std::vector editables; - QDomDocument symbolDocument; - - const char* symbol = Symbol.getValue(); - QByteArray qba(symbol); - QString errorMsg; - int errorLine; - int errorCol; - bool nsProcess = false; - bool rc = symbolDocument.setContent(qba, nsProcess, &errorMsg, &errorLine, &errorCol); - if (rc) { - QDomElement symbolDocElem = symbolDocument.documentElement(); - - QXmlQuery query(QXmlQuery::XQuery10); - QDomNodeModel model(query.namePool(), symbolDocument); - query.setFocus(QXmlItem(model.fromDomNode(symbolDocElem))); - - // XPath query to select all nodes whose parent - // has "freecad:editable" attribute - query.setQuery(QString::fromUtf8( - "declare default element namespace \"" SVG_NS_URI "\"; " - "declare namespace freecad=\"" FREECAD_SVG_NS_URI "\"; " - "//text[@freecad:editable]/tspan")); - - QXmlResultItems queryResult; - query.evaluateTo(&queryResult); - - while (!queryResult.next().isNull()) - { - QDomElement tspanElement = model.toDomNode(queryResult.current().toNodeModelIndex()).toElement(); - editables.push_back(tspanElement.text().toStdString()); - } - } - else { - Base::Console().Warning("DVS::onChanged - %s - SVG for Symbol is not valid. See log.\n"); - Base::Console().Log( - "Warning: DVS::onChanged(Symbol) for %s - len: %d rc: %d error: %s line: %d col: %d\n", - getNameInDocument(), strlen(symbol), rc, - qPrintable(errorMsg), errorLine, errorCol); - - - } - + if (!isRestoring() && !Symbol.isEmpty()) { + std::vector editables = getEditableFields(); EditableTexts.setValues(editables); -// requestPaint(); } + } else if (prop == &EditableTexts) { + //this will change Symbol, which will call onChanged(Symbol), + //which will change EditableTexts, but the loop stops after + //1 cycle + updateFieldsInSymbol(); } TechDraw::DrawView::onChanged(prop); } -App::DocumentObjectExecReturn *DrawViewSymbol::execute(void) +App::DocumentObjectExecReturn *DrawViewSymbol::execute() { -// Base::Console().Message("DVS::execute() \n"); -// //dvs::execute is pretty fast. doesn't need to be blocked? -// if (!keepUpdated()) { -// return App::DocumentObject::StdReturn; -// } - - std::string svg = Symbol.getValue(); - if (svg.empty()) { - return App::DocumentObject::StdReturn; - } - - const std::vector& editText = EditableTexts.getValues(); - - if (!editText.empty()) { - QDomDocument symbolDocument; - const char* symbol = Symbol.getValue(); - QByteArray qba(symbol); - QString errorMsg; - int errorLine; - int errorCol; - bool nsProcess = false; - bool rc = symbolDocument.setContent(qba, nsProcess, &errorMsg, &errorLine, &errorCol); - if (rc) { - QDomElement symbolDocElem = symbolDocument.documentElement(); - - QXmlQuery query(QXmlQuery::XQuery10); - QDomNodeModel model(query.namePool(), symbolDocument); - query.setFocus(QXmlItem(model.fromDomNode(symbolDocElem))); - - // XPath query to select all nodes whose parent - // has "freecad:editable" attribute - query.setQuery(QString::fromUtf8( - "declare default element namespace \"" SVG_NS_URI "\"; " - "declare namespace freecad=\"" FREECAD_SVG_NS_URI "\"; " - "//text[@freecad:editable]/tspan")); - - QXmlResultItems queryResult; - query.evaluateTo(&queryResult); - - unsigned int count = 0; - while (!queryResult.next().isNull()) - { - QDomElement tspanElement = model.toDomNode(queryResult.current().toNodeModelIndex()).toElement(); - - // Keep all spaces in the text node - tspanElement.setAttribute(QString::fromUtf8("xml:space"), QString::fromUtf8("preserve")); - - // Remove all child nodes (if any) - while (!tspanElement.lastChild().isNull()) { - tspanElement.removeChild(tspanElement.lastChild()); - } - - // Finally append text node with editable replacement as the only descendant - tspanElement.appendChild(symbolDocument.createTextNode( - QString::fromUtf8(editText[count].c_str()))); - ++count; - } - - Symbol.setValue(symbolDocument.toString(1).toStdString()); - } - else { - Base::Console().Warning("DVS::execute - %s - SVG for Symbol is not valid. See log.\n"); - Base::Console().Log( - "Warning: DVS::execute() - %s - len: %d rc: %d error: %s line: %d col: %d\n", - getNameInDocument(), strlen(symbol), rc, - qPrintable(errorMsg), errorLine, errorCol); - } - } - -// requestPaint(); + //nothing to do. DVS is just a container for properties. + //the action takes place on the Gui side. return DrawView::execute(); } @@ -212,32 +95,9 @@ QRectF DrawViewSymbol::getRect() const double w = 64.0; //must default to something double h = 64.0; return (QRectF(0,0,w,h)); -// std::string svg = Symbol.getValue(); -// string::const_iterator begin, end; -// begin = svg.begin(); -// end = svg.end(); -// boost::match_results what; - -// boost::regex e1 ("width=\"([0-9.]*?)[a-zA-Z]*?\""); -// if (boost::regex_search(begin, end, what, e1)) { -// //std::string wText = what[0].str(); //this is the whole match 'width="100"' -// std::string wNum = what[1].str(); //this is just the number 100 -// w = std::stod(wNum); -// } -// -// boost::regex e2 ("height=\"([0-9.]*?)[a-zA-Z]*?\""); -// if (boost::regex_search(begin, end, what, e2)) { -// //std::string hText = what[0].str(); -// std::string hNum = what[1].str(); -// h = std::stod(hNum); -// } -// return (QRectF(0,0,getScale() * w,getScale() * h)); -//we now have a w x h, but we don't really know what it means - px,mm,in,... - } //!Assume all svg files fit the page and/or the user will scale manually -//see getRect() above bool DrawViewSymbol::checkFit(TechDraw::DrawPage* p) const { (void)p; @@ -245,21 +105,107 @@ bool DrawViewSymbol::checkFit(TechDraw::DrawPage* p) const return result; } -short DrawViewSymbol::mustExecute() const +//get editable fields from symbol +std::vector DrawViewSymbol::getEditableFields() { - short result = 0; - if (!isRestoring()) { - result = (Scale.isTouched() || - EditableTexts.isTouched()); + QDomDocument symbolDocument; + QXmlResultItems queryResult; + std::vector editables; + + bool rc = loadQDomDocument(symbolDocument); + if (rc) { + QDomElement symbolDocElem = symbolDocument.documentElement(); + QXmlQuery query(QXmlQuery::XQuery10); + QDomNodeModel model(query.namePool(), symbolDocument); + query.setFocus(QXmlItem(model.fromDomNode(symbolDocument.documentElement()))); + + // XPath query to select all nodes whose parent + // has "freecad:editable" attribute + query.setQuery(QString::fromUtf8( + "declare default element namespace \"" SVG_NS_URI "\"; " + "declare namespace freecad=\"" FREECAD_SVG_NS_URI "\"; " + "//text[@freecad:editable]/tspan")); + + query.evaluateTo(&queryResult); + + while (!queryResult.next().isNull()) { + QDomElement tspan = model.toDomNode(queryResult.current().toNodeModelIndex()).toElement(); + QString editableValue = tspan.firstChild().nodeValue(); + editables.emplace_back(editableValue.toUtf8().constData()); + } } - if ((bool) result) { - return result; - } - return DrawView::mustExecute(); + return editables; } +//replace editable field in symbol with values from property +void DrawViewSymbol::updateFieldsInSymbol() +{ + const std::vector& editText = EditableTexts.getValues(); + if (editText.empty()) { + return; + } -PyObject *DrawViewSymbol::getPyObject(void) + QDomDocument symbolDocument; + QXmlResultItems queryResult; + + bool rc = loadQDomDocument(symbolDocument); + if (rc) { + QDomElement symbolDocElem = symbolDocument.documentElement(); + QXmlQuery query(QXmlQuery::XQuery10); + QDomNodeModel model(query.namePool(), symbolDocument); + query.setFocus(QXmlItem(model.fromDomNode(symbolDocElem))); + + // XPath query to select all nodes whose parent + // has "freecad:editable" attribute + query.setQuery(QString::fromUtf8( + "declare default element namespace \"" SVG_NS_URI "\"; " + "declare namespace freecad=\"" FREECAD_SVG_NS_URI "\"; " + "//text[@freecad:editable]/tspan")); + query.evaluateTo(&queryResult); + + unsigned int count = 0; + while (!queryResult.next().isNull()) + { + QDomElement tspanElement = model.toDomNode(queryResult.current().toNodeModelIndex()).toElement(); + + // Keep all spaces in the text node + tspanElement.setAttribute(QString::fromUtf8("xml:space"), QString::fromUtf8("preserve")); + + // Remove all child nodes (if any) + while (!tspanElement.lastChild().isNull()) { + tspanElement.removeChild(tspanElement.lastChild()); + } + + // Finally append text node with editable replacement as the only descendant + tspanElement.appendChild(symbolDocument.createTextNode( + QString::fromUtf8(editText[count].c_str()))); + ++count; + } + Symbol.setValue(symbolDocument.toString(1).toStdString()); + } +} + +//load QDomDocument +bool DrawViewSymbol::loadQDomDocument(QDomDocument& symbolDocument) +{ + const char* symbol = Symbol.getValue(); + QByteArray qba(symbol); + QString errorMsg; + int errorLine; + int errorCol; + bool nsProcess = false; + 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().Log("DrawViewSymbol - %s - len: %d rc: %d error: %s line: %d col: %d\n", + getNameInDocument(), strlen(symbol), rc, + qPrintable(errorMsg), errorLine, errorCol); + } + return rc; +} + +PyObject *DrawViewSymbol::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -273,7 +219,7 @@ PyObject *DrawViewSymbol::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawViewSymbolPython, TechDraw::DrawViewSymbol) -template<> const char* TechDraw::DrawViewSymbolPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawViewSymbolPython::getViewProviderName() const { return "TechDrawGui::ViewProviderSymbol"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawViewSymbol.h b/src/Mod/TechDraw/App/DrawViewSymbol.h index e2fe910671..26887f37a5 100644 --- a/src/Mod/TechDraw/App/DrawViewSymbol.h +++ b/src/Mod/TechDraw/App/DrawViewSymbol.h @@ -23,26 +23,31 @@ #ifndef _DrawViewSymbol_h_ #define _DrawViewSymbol_h_ +#include + +#include + +#include +#include + #include #include #include #include "DrawView.h" - namespace TechDraw { class DrawPage; - class TechDrawExport DrawViewSymbol : public TechDraw::DrawView { PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawViewSymbol); public: /// Constructor - DrawViewSymbol(void); - virtual ~DrawViewSymbol(); + DrawViewSymbol(); + ~DrawViewSymbol() override; App::PropertyString Symbol; App::PropertyStringList EditableTexts; @@ -50,25 +55,26 @@ public: /** @name methods override Feature */ //@{ /// recalculate the Feature - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; //@} /// returns the type name of the ViewProvider - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderSymbol"; } - virtual QRectF getRect() const override; - virtual bool checkFit(TechDraw::DrawPage* p) const override; + QRectF getRect() const override; + bool checkFit(TechDraw::DrawPage* p) const override; //return PyObject as DrawViewSymbolPy - virtual PyObject *getPyObject(void) override; - - virtual short mustExecute() const override; - + PyObject *getPyObject() override; protected: - virtual void onChanged(const App::Property* prop) override; + void onChanged(const App::Property* prop) override; Base::BoundBox3d bbox; + + std::vector getEditableFields(); + void updateFieldsInSymbol(); + bool loadQDomDocument(QDomDocument& symbolDocument); }; typedef App::FeaturePythonT DrawViewSymbolPython; diff --git a/src/Mod/TechDraw/App/DrawViewSymbolPyImp.cpp b/src/Mod/TechDraw/App/DrawViewSymbolPyImp.cpp index 7d887a5cde..9e03f7dd7a 100644 --- a/src/Mod/TechDraw/App/DrawViewSymbolPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawViewSymbolPyImp.cpp @@ -37,7 +37,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawViewSymbolPy::representation(void) const +std::string DrawViewSymbolPy::representation() const { return std::string(""); } @@ -50,13 +50,13 @@ PyObject* DrawViewSymbolPy::dumpSymbol(PyObject *args) } auto dvs = getDrawViewSymbolPtr(); std::string symbolRepr; - if (dvs != nullptr) { + if (dvs) { symbolRepr = dvs->Symbol.getValue(); } Base::FileInfo fi(fileSpec); - std::ofstream outfile; - outfile.open(fi.filePath()); + Base::ofstream outfile; + outfile.open(fi); outfile.write (symbolRepr.c_str(),symbolRepr.size()); outfile.close(); if (outfile.good()) { diff --git a/src/Mod/TechDraw/App/DrawWeldSymbol.cpp b/src/Mod/TechDraw/App/DrawWeldSymbol.cpp index 89b64ea559..7c503b03b1 100644 --- a/src/Mod/TechDraw/App/DrawWeldSymbol.cpp +++ b/src/Mod/TechDraw/App/DrawWeldSymbol.cpp @@ -49,7 +49,7 @@ using namespace TechDraw; PROPERTY_SOURCE(TechDraw::DrawWeldSymbol, TechDraw::DrawView) -DrawWeldSymbol::DrawWeldSymbol(void) +DrawWeldSymbol::DrawWeldSymbol() { static const char *group = "Weld Symbol"; @@ -91,14 +91,14 @@ void DrawWeldSymbol::onSettingDocument() std::string tileName1 = doc->getUniqueObjectName("TileWeld"); auto tile1Obj( doc->addObject( "TechDraw::DrawTileWeld", tileName1.c_str() ) ); DrawTileWeld* tile1 = dynamic_cast(tile1Obj); - if (tile1 != nullptr) { + if (tile1) { tile1->TileParent.setValue(this); } std::string tileName2 = doc->getUniqueObjectName("TileWeld"); auto tile2Obj( doc->addObject( "TechDraw::DrawTileWeld", tileName2.c_str() ) ); DrawTileWeld* tile2 = dynamic_cast(tile2Obj); - if (tile2 != nullptr) { + if (tile2) { tile2->TileParent.setValue(this); tile2->TileRow.setValue(-1); //other side is row -1 } @@ -108,9 +108,6 @@ void DrawWeldSymbol::onSettingDocument() void DrawWeldSymbol::onChanged(const App::Property* prop) { - if (!isRestoring()) { - //nothing in particular - } DrawView::onChanged(prop); } @@ -119,29 +116,32 @@ short DrawWeldSymbol::mustExecute() const return DrawView::mustExecute(); } -App::DocumentObjectExecReturn *DrawWeldSymbol::execute(void) +App::DocumentObjectExecReturn *DrawWeldSymbol::execute() { // Base::Console().Message("DWS::execute()\n"); if (!keepUpdated()) { - return App::DocumentObject::StdReturn; + return DrawView::execute(); } - + + overrideKeepUpdated(false); return DrawView::execute(); } -std::vector DrawWeldSymbol::getTiles(void) const +std::vector DrawWeldSymbol::getTiles() const { // Base::Console().Message("DWS::getTiles()\n"); std::vector result; std::vector tiles = getInList(); - if (!tiles.empty()) { - for(std::vector::iterator it = tiles.begin(); it != tiles.end(); it++) { - if ((*it)->getTypeId().isDerivedFrom(TechDraw::DrawTileWeld::getClassTypeId())) { - App::DocumentObject* doTemp = (*it); - DrawTileWeld* temp = static_cast(doTemp); - result.push_back(temp); - } + if (tiles.empty()) { + return result; + } + + for(std::vector::iterator it = tiles.begin(); it != tiles.end(); it++) { + if ((*it)->getTypeId().isDerivedFrom(TechDraw::DrawTileWeld::getClassTypeId())) { + App::DocumentObject* doTemp = (*it); + DrawTileWeld* temp = static_cast(doTemp); + result.push_back(temp); } } return result; @@ -149,21 +149,20 @@ std::vector DrawWeldSymbol::getTiles(void) const bool DrawWeldSymbol::isTailRightSide() { - bool result = true; App::DocumentObject* obj = Leader.getValue(); TechDraw::DrawLeaderLine* realLeader = dynamic_cast(obj); - if (realLeader != nullptr) { + if (realLeader) { Base::Vector3d tail = realLeader->getTailPoint(); Base::Vector3d kink = realLeader->getKinkPoint(); if (tail.x < kink.x) { //tail is to left - result = false; + return false; } } - return result; + return true; } -PyObject *DrawWeldSymbol::getPyObject(void) +PyObject *DrawWeldSymbol::getPyObject() { if (PythonObject.is(Py::_None())) { // ref counter is set to 1 @@ -177,7 +176,7 @@ PyObject *DrawWeldSymbol::getPyObject(void) namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(TechDraw::DrawWeldSymbolPython, TechDraw::DrawWeldSymbol) -template<> const char* TechDraw::DrawWeldSymbolPython::getViewProviderName(void) const { +template<> const char* TechDraw::DrawWeldSymbolPython::getViewProviderName() const { return "TechDrawGui::ViewProviderWeld"; } /// @endcond diff --git a/src/Mod/TechDraw/App/DrawWeldSymbol.h b/src/Mod/TechDraw/App/DrawWeldSymbol.h index 122fe01872..7fb1dae33b 100644 --- a/src/Mod/TechDraw/App/DrawWeldSymbol.h +++ b/src/Mod/TechDraw/App/DrawWeldSymbol.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_DrawWeldSymbol_h_ #define _TechDraw_DrawWeldSymbol_h_ +#include + # include # include @@ -36,11 +38,11 @@ class DrawTileWeld; class TechDrawExport DrawWeldSymbol : public TechDraw::DrawView { - PROPERTY_HEADER(TechDraw::DrawWeldSymbol); + PROPERTY_HEADER_WITH_OVERRIDE(TechDraw::DrawWeldSymbol); public: DrawWeldSymbol(); - virtual ~DrawWeldSymbol(); + ~DrawWeldSymbol() override; App::PropertyLink Leader; App::PropertyBool AllAround; @@ -48,21 +50,21 @@ public: App::PropertyBool AlternatingWeld; App::PropertyString TailText; - virtual short mustExecute() const; - virtual App::DocumentObjectExecReturn *execute(void); - virtual void onSettingDocument(void); + short mustExecute() const override; + App::DocumentObjectExecReturn *execute() override; + void onSettingDocument() override; - virtual const char* getViewProviderName(void) const { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderWeld"; } - virtual PyObject *getPyObject(void); - virtual QRectF getRect() const { return QRectF(0,0,1,1);} + PyObject *getPyObject() override; + QRectF getRect() const override { return QRectF(0,0,1,1);} bool isTailRightSide(); - std::vector getTiles(void) const; + std::vector getTiles() const; protected: - virtual void onChanged(const App::Property* prop); + void onChanged(const App::Property* prop) override; private: }; diff --git a/src/Mod/TechDraw/App/DrawWeldSymbolPyImp.cpp b/src/Mod/TechDraw/App/DrawWeldSymbolPyImp.cpp index 4a4445d5f2..f5973f876c 100644 --- a/src/Mod/TechDraw/App/DrawWeldSymbolPyImp.cpp +++ b/src/Mod/TechDraw/App/DrawWeldSymbolPyImp.cpp @@ -38,7 +38,7 @@ using namespace TechDraw; // returns a string which represents the object e.g. when printed in python -std::string DrawWeldSymbolPy::representation(void) const +std::string DrawWeldSymbolPy::representation() const { return std::string(""); } diff --git a/src/Mod/TechDraw/App/EdgeWalker.cpp b/src/Mod/TechDraw/App/EdgeWalker.cpp index d549abed0a..a5fbf33fbc 100644 --- a/src/Mod/TechDraw/App/EdgeWalker.cpp +++ b/src/Mod/TechDraw/App/EdgeWalker.cpp @@ -85,7 +85,7 @@ void edgeVisitor::end_face() graphWires.push_back(wireEdges); } -TechDraw::ewWireList edgeVisitor::getResult(void) +TechDraw::ewWireList edgeVisitor::getResult() { return graphWires; } @@ -283,7 +283,7 @@ TopoDS_Wire EdgeWalker::makeCleanWire(std::vector edges, double tol ShapeFix_ShapeTolerance sTol; Handle(ShapeExtend_WireData) wireData = new ShapeExtend_WireData(); - for (auto e:edges) { + for (const auto& e:edges) { wireData->Add(e); } @@ -315,7 +315,7 @@ std::vector EdgeWalker:: makeUniqueVList(std::vector TopoDS_Vertex v2 = TopExp::LastVertex(e); bool addv1 = true; bool addv2 = true; - for (auto v:uniqueVert) { + for (const auto& v:uniqueVert) { if (DrawUtil::isSamePoint(v,v1,EWTOLERANCE)) addv1 = false; if (DrawUtil::isSamePoint(v,v2,EWTOLERANCE)) @@ -336,7 +336,7 @@ std::vector EdgeWalker::makeWalkerEdges(std::vector edg // Base::Console().Message("TRACE - EW::makeWalkerEdges()\n"); m_saveInEdges = edges; std::vector walkerEdges; - for (auto e:edges) { + for (const auto& e:edges) { TopoDS_Vertex ev1 = TopExp::FirstVertex(e); TopoDS_Vertex ev2 = TopExp::LastVertex(e); int v1dx = findUniqueVert(ev1, verts); @@ -376,7 +376,7 @@ std::vector EdgeWalker::sortStrip(std::vector fw, bool } } std::vector sortedWires = sortWiresBySize(closedWires,false); //biggest 1st - if (!sortedWires.size()) { + if (sortedWires.empty()) { Base::Console().Log("INFO - EW::sortStrip - no sorted Wires!\n"); return sortedWires; // might happen in the middle of changes? } @@ -488,7 +488,7 @@ bool WalkerEdge::isEqual(WalkerEdge w) return (i.idx < j.idx); } -std::string WalkerEdge::dump(void) +std::string WalkerEdge::dump() { std::string result; std::stringstream builder; @@ -523,7 +523,7 @@ void ewWire::push_back(WalkerEdge w) wedges.push_back(w); } -int ewWire::size(void) +int ewWire::size() { return wedges.size(); } @@ -560,7 +560,7 @@ void ewWireList::push_back(ewWire w) wires.push_back(w); } -int ewWireList::size(void) +int ewWireList::size() { return wires.size(); } @@ -569,7 +569,7 @@ int ewWireList::size(void) //* embedItem Methods //************************************* -std::string embedItem::dump(void) +std::string embedItem::dump() { std::string result; std::stringstream builder; diff --git a/src/Mod/TechDraw/App/EdgeWalker.h b/src/Mod/TechDraw/App/EdgeWalker.h index 113abcd277..b7ac595a4d 100644 --- a/src/Mod/TechDraw/App/EdgeWalker.h +++ b/src/Mod/TechDraw/App/EdgeWalker.h @@ -28,6 +28,8 @@ #ifndef TECHDRAW_EDGEWALKER_H #define TECHDRAW_EDGEWALKER_H +#include + #include #include #include @@ -75,7 +77,7 @@ class TechDrawExport WalkerEdge public: static bool weCompare(WalkerEdge i, WalkerEdge j); bool isEqual(WalkerEdge w); - std::string dump(void); + std::string dump(); std::size_t v1; std::size_t v2; @@ -91,7 +93,7 @@ public: std::vector wedges; //[WE] representing 1 wire void push_back(WalkerEdge w); void clear() {wedges.clear();} - int size(void); + int size(); }; class TechDrawExport ewWireList @@ -101,7 +103,7 @@ public: std::vector wires; void push_back(ewWire e); - int size(void); + int size(); }; @@ -113,7 +115,7 @@ public: void next_edge(Edge e); void begin_face(); void end_face(); - ewWireList getResult(void); //a list of many wires + ewWireList getResult(); //a list of many wires void setGraph(graph& g); private: @@ -145,7 +147,7 @@ public: int iVertex; std::vector incidenceList; - std::string dump(void); + std::string dump(); static std::vector sortIncidenceList (std::vector &list, bool ascend); }; @@ -153,7 +155,7 @@ public: class TechDrawExport EdgeWalker { public: - EdgeWalker(void); + EdgeWalker(); virtual ~EdgeWalker(); bool loadEdges(std::vector& edges); diff --git a/src/Mod/TechDraw/App/FeatureProjection.cpp b/src/Mod/TechDraw/App/FeatureProjection.cpp index a1a19e55c3..8e2e8f19d0 100644 --- a/src/Mod/TechDraw/App/FeatureProjection.cpp +++ b/src/Mod/TechDraw/App/FeatureProjection.cpp @@ -19,7 +19,7 @@ * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ -//this file originally part of TechDraw workbench +//this file originally part of Drawing workbench //migrated to TechDraw workbench 2022-01-26 by Wandererfan @@ -68,7 +68,7 @@ FeatureProjection::~FeatureProjection() { } -App::DocumentObjectExecReturn *FeatureProjection::execute(void) +App::DocumentObjectExecReturn *FeatureProjection::execute() { App::DocumentObject* link = Source.getValue(); if (!link) diff --git a/src/Mod/TechDraw/App/FeatureProjection.h b/src/Mod/TechDraw/App/FeatureProjection.h index 20a013448f..be4928cf32 100644 --- a/src/Mod/TechDraw/App/FeatureProjection.h +++ b/src/Mod/TechDraw/App/FeatureProjection.h @@ -24,6 +24,8 @@ #ifndef TECHDRAW_FEATUREPROJECTION #define TECHDRAW_FEATUREPROJECTION + +#include #include #include diff --git a/src/Mod/TechDraw/App/Geometry.cpp b/src/Mod/TechDraw/App/Geometry.cpp index abc6cd2b72..1f98f3ffeb 100644 --- a/src/Mod/TechDraw/App/Geometry.cpp +++ b/src/Mod/TechDraw/App/Geometry.cpp @@ -109,7 +109,7 @@ Wire::Wire(const TopoDS_Wire &w) for (; edges.More(); edges.Next()) { const auto edge( TopoDS::Edge(edges.Current()) ); BaseGeomPtr bg = BaseGeom::baseFactory(edge); - if (bg != nullptr) { + if (bg) { geoms.push_back(bg); } else { Base::Console().Log("G::Wire - baseFactory returned null geom ptr\n"); @@ -123,7 +123,7 @@ Wire::~Wire() geoms.clear(); } -TopoDS_Wire Wire::toOccWire(void) const +TopoDS_Wire Wire::toOccWire() const { TopoDS_Wire result; BRepBuilderAPI_MakeWire mkWire; @@ -143,7 +143,7 @@ void Wire::dump(std::string s) BRepTools::Write(toOccWire(), s.c_str()); //debug } -TopoDS_Face Face::toOccFace(void) const +TopoDS_Face Face::toOccFace() const { TopoDS_Face result; //if (!wires.empty) { @@ -192,7 +192,7 @@ BaseGeomPtr BaseGeom::copy() BaseGeomPtr result; if (!occEdge.IsNull()) { result = baseFactory(occEdge); - if (result != nullptr) { + if (result) { result->extractType = extractType; result->classOfEdge = classOfEdge; result->hlrVisible = hlrVisible; @@ -219,7 +219,7 @@ BaseGeomPtr BaseGeom::copy() return result; } -std::string BaseGeom::toString(void) const +std::string BaseGeom::toString() const { std::stringstream ss; ss << geomType << "," << @@ -239,7 +239,7 @@ boost::uuids::uuid BaseGeom::getTag() const return tag; } -std::string BaseGeom::getTagAsString(void) const +std::string BaseGeom::getTagAsString() const { std::string tmp = boost::uuids::to_string(getTag()); return tmp; @@ -433,7 +433,7 @@ std::string BaseGeom::dump() return ss.str(); } -bool BaseGeom::closed(void) +bool BaseGeom::closed() { bool result = false; Base::Vector3d start(getStartPoint().x, @@ -587,7 +587,7 @@ void BaseGeom::intersectionLL(TechDraw::BaseGeomPtr geom1, // Taken from: TechDraw::GenericPtr gen1 = std::static_pointer_cast(geom1); TechDraw::GenericPtr gen2 = std::static_pointer_cast(geom2); - // we calculate vectors to start points and direction verctors + // we calculate vectors to start points and direction vectors Base::Vector3d startPnt1 = gen1->points.at(0); Base::Vector3d endPnt1 = gen1->points.at(1); Base::Vector3d startPnt2 = gen2->points.at(0); @@ -785,7 +785,7 @@ AOE::AOE(const TopoDS_Edge &e) : Ellipse(e) } -Circle::Circle(void) +Circle::Circle() { geomType = CIRCLE; radius = 0.0; @@ -825,7 +825,7 @@ Circle::Circle(const TopoDS_Edge &e) radius = circ.Radius(); center = Base::Vector3d(p.X(), p.Y(), p.Z()); } -std::string Circle::toString(void) const +std::string Circle::toString() const { std::string baseCSV = BaseGeom::toString(); std::stringstream ss; @@ -934,7 +934,7 @@ AOC::AOC(Base::Vector3d c, double r, double sAng, double eAng) : Circle() } -AOC::AOC(void) : Circle() +AOC::AOC() : Circle() { geomType = ARCOFCIRCLE; @@ -998,7 +998,7 @@ bool AOC::intersectsArc(Base::Vector3d p1, Base::Vector3d p2) return result; } -std::string AOC::toString(void) const +std::string AOC::toString() const { std::string circleCSV = Circle::toString(); std::stringstream ss; @@ -1106,7 +1106,7 @@ Generic::Generic() geomType = GENERIC; } -std::string Generic::toString(void) const +std::string Generic::toString() const { std::string baseCSV = BaseGeom::toString(); std::stringstream ss; @@ -1157,13 +1157,13 @@ void Generic::Restore(Base::XMLReader &reader) reader.readEndElement("Points"); } -Base::Vector3d Generic::asVector(void) +Base::Vector3d Generic::asVector() { Base::Vector3d result = getEndPoint() - getStartPoint(); return result; } -double Generic::slope(void) +double Generic::slope() { double slope; Base::Vector3d v = asVector(); @@ -1704,7 +1704,7 @@ boost::uuids::uuid Vertex::getTag() const return tag; } -std::string Vertex::getTagAsString(void) const +std::string Vertex::getTagAsString() const { std::string tmp = boost::uuids::to_string(getTag()); return tmp; diff --git a/src/Mod/TechDraw/App/Geometry.h b/src/Mod/TechDraw/App/Geometry.h index a06d32f562..079cf2f807 100644 --- a/src/Mod/TechDraw/App/Geometry.h +++ b/src/Mod/TechDraw/App/Geometry.h @@ -106,14 +106,14 @@ class TechDrawExport BaseGeom : public std::enable_shared_from_this int ref3D; //obs? TopoDS_Edge occEdge; //projected Edge bool cosmetic; - int source(void) { return m_source; } + int source() { return m_source; } void source(int s) { m_source = s; } - int sourceIndex(void) { return m_sourceIndex; } + int sourceIndex() { return m_sourceIndex; } void sourceIndex(int si) { m_sourceIndex = si; } - std::string getCosmeticTag(void) { return cosmeticTag; } + std::string getCosmeticTag() { return cosmeticTag; } void setCosmeticTag(std::string t) { cosmeticTag = t; } - virtual std::string toString(void) const; + virtual std::string toString() const; virtual void Save(Base::Writer& w) const; virtual void Restore(Base::XMLReader& r); std::vector findEndPoints(); @@ -126,14 +126,14 @@ class TechDrawExport BaseGeom : public std::enable_shared_from_this Base::Vector3d nearPoint(const BaseGeomPtr p); static BaseGeomPtr baseFactory(TopoDS_Edge edge); static bool validateEdge(TopoDS_Edge edge); - bool closed(void); + bool closed(); BaseGeomPtr copy(); std::string dump(); std::vector intersection(TechDraw::BaseGeomPtr geom2); //Uniqueness boost::uuids::uuid getTag() const; - virtual std::string getTagAsString(void) const; + virtual std::string getTagAsString() const; private: void intersectionLL(TechDraw::BaseGeomPtr geom1, @@ -160,15 +160,15 @@ using BaseGeomPtrVector = std::vector; //new style class TechDrawExport Circle: public BaseGeom { public: - Circle(void); - Circle(const TopoDS_Edge &e); + Circle(); + explicit Circle(const TopoDS_Edge &e); Circle(Base::Vector3d center, double radius); - virtual ~Circle() = default; + ~Circle() override = default; public: - virtual std::string toString(void) const override; - virtual void Save(Base::Writer& w) const override; - virtual void Restore(Base::XMLReader& r) override; + std::string toString() const override; + void Save(Base::Writer& w) const override; + void Restore(Base::XMLReader& r) override; Base::Vector3d center; double radius; @@ -177,9 +177,9 @@ class TechDrawExport Circle: public BaseGeom class TechDrawExport Ellipse: public BaseGeom { public: - Ellipse(const TopoDS_Edge &e); + explicit Ellipse(const TopoDS_Edge &e); Ellipse(Base::Vector3d c, double mnr, double mjr); - virtual ~Ellipse() = default; + ~Ellipse() override = default; public: Base::Vector3d center; @@ -193,8 +193,8 @@ class TechDrawExport Ellipse: public BaseGeom class TechDrawExport AOE: public Ellipse { public: - AOE(const TopoDS_Edge &e); - ~AOE() = default; + explicit AOE(const TopoDS_Edge &e); + ~AOE() override = default; public: Base::Vector3d startPnt; //TODO: The points are used for drawing, the angles for bounding box calcs - seems redundant @@ -215,15 +215,15 @@ class TechDrawExport AOE: public Ellipse class TechDrawExport AOC: public Circle { public: - AOC(const TopoDS_Edge &e); + explicit AOC(const TopoDS_Edge &e); AOC(Base::Vector3d c, double r, double s, double e); - AOC(void); - ~AOC() = default; + AOC(); + ~AOC() override = default; public: - virtual std::string toString(void) const override; - virtual void Save(Base::Writer& w) const override; - virtual void Restore(Base::XMLReader& r) override; + std::string toString() const override; + void Save(Base::Writer& w) const override; + void Restore(Base::XMLReader& r) override; Base::Vector3d startPnt; Base::Vector3d endPnt; @@ -247,9 +247,9 @@ class TechDrawExport AOC: public Circle class TechDrawExport BezierSegment: public BaseGeom { public: - BezierSegment(const TopoDS_Edge &e); + explicit BezierSegment(const TopoDS_Edge &e); BezierSegment() { poles = degree = 0; } - ~BezierSegment() = default; + ~BezierSegment() override = default; int poles; int degree; @@ -260,8 +260,8 @@ public: class TechDrawExport BSpline: public BaseGeom { public: - BSpline(const TopoDS_Edge &e); - ~BSpline() = default; + explicit BSpline(const TopoDS_Edge &e); + ~BSpline() override = default; public: Base::Vector3d startPnt; @@ -273,8 +273,8 @@ class TechDrawExport BSpline: public BaseGeom bool cw; bool isArc; - bool isLine(void); - bool isCircle(void); + bool isLine(); + bool isCircle(); TopoDS_Edge asCircle(bool& isArc); void getCircleParms(bool& isCircle, double& radius, Base::Vector3d& center, bool& isArc); bool intersectsArc(Base::Vector3d p1,Base::Vector3d p2); @@ -284,15 +284,15 @@ class TechDrawExport BSpline: public BaseGeom class TechDrawExport Generic: public BaseGeom { public: - Generic(const TopoDS_Edge &e); + explicit Generic(const TopoDS_Edge &e); Generic(); - ~Generic() = default; + ~Generic() override = default; - virtual std::string toString(void) const override; - virtual void Save(Base::Writer& w) const override; - virtual void Restore(Base::XMLReader& r) override; - Base::Vector3d asVector(void); - double slope(void); + std::string toString() const override; + void Save(Base::Writer& w) const override; + void Restore(Base::XMLReader& r) override; + Base::Vector3d asVector(); + double slope(); Base::Vector3d apparentInter(GenericPtr g); std::vector points; }; @@ -303,10 +303,10 @@ class TechDrawExport Wire { public: Wire(); - Wire(const TopoDS_Wire &w); + explicit Wire(const TopoDS_Wire &w); ~Wire(); - TopoDS_Wire toOccWire(void) const; + TopoDS_Wire toOccWire() const; void dump(std::string s); BaseGeomPtrVector geoms; }; @@ -317,7 +317,7 @@ class TechDrawExport Face public: Face() = default; ~Face(); - TopoDS_Face toOccFace(void) const; + TopoDS_Face toOccFace() const; std::vector wires; }; using FacePtr = std::shared_ptr; @@ -326,9 +326,9 @@ class TechDrawExport Vertex { public: Vertex(); - Vertex(const Vertex* v); + explicit Vertex(const Vertex* v); Vertex(double x, double y); - Vertex(Base::Vector3d v); + explicit Vertex(Base::Vector3d v); virtual ~Vertex() {} virtual void Save(Base::Writer &/*writer*/) const; @@ -342,7 +342,7 @@ class TechDrawExport Vertex bool isCenter; TopoDS_Vertex occVertex; bool isEqual(const Vertex& v, double tol); - Base::Vector3d point(void) const { return Base::Vector3d(pnt.x,pnt.y,0.0); } + Base::Vector3d point() const { return Base::Vector3d(pnt.x,pnt.y,0.0); } void point(Base::Vector3d v){ pnt = Base::Vector3d(v.x, v.y); } bool cosmetic; int cosmeticLink; //deprec. use cosmeticTag @@ -353,7 +353,7 @@ class TechDrawExport Vertex double y() {return pnt.y;} boost::uuids::uuid getTag() const; - virtual std::string getTagAsString(void) const; + virtual std::string getTagAsString() const; protected: //Uniqueness diff --git a/src/Mod/TechDraw/App/GeometryObject.cpp b/src/Mod/TechDraw/App/GeometryObject.cpp index 94f3846366..7d2c247a06 100644 --- a/src/Mod/TechDraw/App/GeometryObject.cpp +++ b/src/Mod/TechDraw/App/GeometryObject.cpp @@ -158,29 +158,19 @@ void GeometryObject::clear() edgeGeom.clear(); } -//!set up a hidden line remover and project a shape with it -void GeometryObject::projectShape(const TopoDS_Shape& input, +void GeometryObject::projectShape(const TopoDS_Shape& inShape, const gp_Ax2& viewAxis) { -// Base::Console().Message("GO::projectShape() - %s\n", m_parentName.c_str()); - // Clear previous Geometry clear(); -// DrawUtil::dumpCS("GO::projectShape - VA in", viewAxis); //debug - auto start = chrono::high_resolution_clock::now(); Handle(HLRBRep_Algo) brep_hlr; try { brep_hlr = new HLRBRep_Algo(); - brep_hlr->Add(input, m_isoCount); - if (m_isPersp) { - double fLength = std::max(Precision::Confusion(),m_focus); - HLRAlgo_Projector projector( viewAxis, fLength ); - brep_hlr->Projector(projector); - } else { - HLRAlgo_Projector projector( viewAxis ); - brep_hlr->Projector(projector); - } +// brep_hlr->Debug(true); + brep_hlr->Add(inShape); + HLRAlgo_Projector projector( viewAxis ); + brep_hlr->Projector(projector); brep_hlr->Update(); brep_hlr->Hide(); @@ -188,77 +178,130 @@ void GeometryObject::projectShape(const TopoDS_Shape& input, catch (const Standard_Failure& e) { Base::Console().Error("GO::projectShape - OCC error - %s - while projecting shape\n", e.GetMessageString()); + throw Base::RuntimeError("GeometryObject::projectShape - OCC error"); } catch (...) { - Base::Console().Error("GeometryObject::projectShape - unknown error occurred while projecting shape\n"); -// throw Base::RuntimeError("GeometryObject::projectShape - unknown error occurred while projecting shape"); + throw Base::RuntimeError("GeometryObject::projectShape - unknown error"); } - auto end = chrono::high_resolution_clock::now(); - auto diff = end - start; - double diffOut = chrono::duration (diff).count(); - Base::Console().Log("TIMING - %s GO spent: %.3f millisecs in HLRBRep_Algo & co\n",m_parentName.c_str(),diffOut); - - start = chrono::high_resolution_clock::now(); - try { HLRBRep_HLRToShape hlrToShape(brep_hlr); - visHard = hlrToShape.VCompound(); - BRepLib::BuildCurves3d(visHard); - visHard = invertGeometry(visHard); -// BRepTools::Write(visHard, "GOvisHardi.brep"); //debug + if (!hlrToShape.VCompound().IsNull()) { + visHard = hlrToShape.VCompound(); + BRepLib::BuildCurves3d(visHard); + visHard = invertGeometry(visHard); + } - visSmooth = hlrToShape.Rg1LineVCompound(); - BRepLib::BuildCurves3d(visSmooth); - visSmooth = invertGeometry(visSmooth); + if (!hlrToShape.Rg1LineVCompound().IsNull()) { + visSmooth = hlrToShape.Rg1LineVCompound(); + BRepLib::BuildCurves3d(visSmooth); + visSmooth = invertGeometry(visSmooth); + } - visSeam = hlrToShape.RgNLineVCompound(); - BRepLib::BuildCurves3d(visSeam); - visSeam = invertGeometry(visSeam); + if (!hlrToShape.RgNLineVCompound().IsNull()) { + visSeam = hlrToShape.RgNLineVCompound(); + BRepLib::BuildCurves3d(visSeam); + visSeam = invertGeometry(visSeam); + } - visOutline = hlrToShape.OutLineVCompound(); - BRepLib::BuildCurves3d(visOutline); - visOutline = invertGeometry(visOutline); + if (!hlrToShape.OutLineVCompound().IsNull()) { +// BRepTools::Write(hlrToShape.OutLineVCompound(), "GOOutLineVCompound.brep"); //debug + visOutline = hlrToShape.OutLineVCompound(); + BRepLib::BuildCurves3d(visOutline); + visOutline = invertGeometry(visOutline); + } - visIso = hlrToShape.IsoLineVCompound(); - BRepLib::BuildCurves3d(visIso); - visIso = invertGeometry(visIso); + if (!hlrToShape.IsoLineVCompound().IsNull()) { + visIso = hlrToShape.IsoLineVCompound(); + BRepLib::BuildCurves3d(visIso); + visIso = invertGeometry(visIso); + } - hidHard = hlrToShape.HCompound(); - BRepLib::BuildCurves3d(hidHard); - hidHard = invertGeometry(hidHard); -// BRepTools::Write(hidHard, "GOhidHardi.brep"); //debug + if (!hlrToShape.HCompound().IsNull()) { + hidHard = hlrToShape.HCompound(); + BRepLib::BuildCurves3d(hidHard); + hidHard = invertGeometry(hidHard); + } - hidSmooth = hlrToShape.Rg1LineHCompound(); - BRepLib::BuildCurves3d(hidSmooth); - hidSmooth = invertGeometry(hidSmooth); + if (!hlrToShape.Rg1LineHCompound().IsNull()) { + hidSmooth = hlrToShape.Rg1LineHCompound(); + BRepLib::BuildCurves3d(hidSmooth); + hidSmooth = invertGeometry(hidSmooth); + } - hidSeam = hlrToShape.RgNLineHCompound(); - BRepLib::BuildCurves3d(hidSeam); - hidSeam = invertGeometry(hidSeam); + if (!hlrToShape.RgNLineHCompound().IsNull()) { + hidSeam = hlrToShape.RgNLineHCompound(); + BRepLib::BuildCurves3d(hidSeam); + hidSeam = invertGeometry(hidSeam); + } - hidOutline = hlrToShape.OutLineHCompound(); - BRepLib::BuildCurves3d(hidOutline); - hidOutline = invertGeometry(hidOutline); - - hidIso = hlrToShape.IsoLineHCompound(); - BRepLib::BuildCurves3d(hidIso); - hidIso = invertGeometry(hidIso); + if (!hlrToShape.OutLineHCompound().IsNull()) { + hidOutline = hlrToShape.OutLineHCompound(); + BRepLib::BuildCurves3d(hidOutline); + hidOutline = invertGeometry(hidOutline); + } + if (!hlrToShape.IsoLineHCompound().IsNull()) { + hidIso = hlrToShape.IsoLineHCompound(); + BRepLib::BuildCurves3d(hidIso); + hidIso = invertGeometry(hidIso); + } } catch (const Standard_Failure& e) { - Base::Console().Error("GO::projectShape - OCC error - %s - while extracting edges\n", - e.GetMessageString()); + throw Base::RuntimeError("GeometryObject::projectShape - OCC error occurred while extracting edges"); } catch (...) { - Base::Console().Error("GO::projectShape - unknown error while extracting edges\n"); -// throw Base::RuntimeError("GeometryObject::projectShape - error occurred while extracting edges"); + throw Base::RuntimeError("GeometryObject::projectShape - unknown error occurred while extracting edges"); } - end = chrono::high_resolution_clock::now(); - diff = end - start; - diffOut = chrono::duration (diff).count(); - Base::Console().Log("TIMING - %s GO spent: %.3f millisecs in hlrToShape and BuildCurves\n",m_parentName.c_str(),diffOut); + + makeTDGeometry(); +} + +//convert the hlr output into TD Geometry +void GeometryObject::makeTDGeometry() +{ + extractGeometry(TechDraw::ecHARD, //always show the hard&outline visible lines + true); + extractGeometry(TechDraw::ecOUTLINE, + true); + + const DrawViewPart* dvp = static_cast(m_parent); + if (!dvp) { + return; //some routines do not have a dvp (ex shape outline) + } + + if (dvp->SmoothVisible.getValue()) { + extractGeometry(TechDraw::ecSMOOTH, + true); + } + if (dvp->SeamVisible.getValue()) { + extractGeometry(TechDraw::ecSEAM, + true); + } + if ((dvp->IsoVisible.getValue()) && (dvp->IsoCount.getValue() > 0)) { + extractGeometry(TechDraw::ecUVISO, + true); + } + if (dvp->HardHidden.getValue()) { + extractGeometry(TechDraw::ecHARD, + false); + extractGeometry(TechDraw::ecOUTLINE, + false); + } + if (dvp->SmoothHidden.getValue()) { + extractGeometry(TechDraw::ecSMOOTH, + false); + } + if (dvp->SeamHidden.getValue()) { + extractGeometry(TechDraw::ecSEAM, + false); + } + if (dvp->IsoHidden.getValue() && (dvp->IsoCount.getValue() > 0)) { + extractGeometry(TechDraw::ecUVISO, + false); + } + } //mirror a shape thru XZ plane for Qt's inverted Y coordinate @@ -302,8 +345,6 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, inCopy = BuilderCopy.Shape(); } - auto start = chrono::high_resolution_clock::now(); - Handle(HLRBRep_PolyAlgo) brep_hlrPoly; try { @@ -331,11 +372,10 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, catch (const Standard_Failure& e) { Base::Console().Error("GO::projectShapeWithPolygonAlgo - OCC error - %s - while projecting shape\n", e.GetMessageString()); + throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error"); } catch (...) { - Base::Console().Error("GO::projectShapeWithPolygonAlgo - unknown error while projecting shape\n"); -// throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - error occurred while projecting shape"); -// Standard_Failure::Raise("GeometryObject::projectShapeWithPolygonAlgo - error occurred while projecting shape"); + throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - unknown error"); } try { @@ -379,16 +419,13 @@ void GeometryObject::projectShapeWithPolygonAlgo(const TopoDS_Shape& input, catch (const Standard_Failure& e) { Base::Console().Error("GO::projectShapeWithPolygonAlgo - OCC error - %s - while extracting edges\n", e.GetMessageString()); + throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - OCC error occurred while extracting edges"); } catch (...) { - Base::Console().Error("GO::projectShapeWithPolygonAlgo - - error occurred while extracting edges\n"); -// throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - error occurred while extracting edges"); -// Standard_Failure::Raise("GeometryObject::projectShapeWithPolygonAlgo - error occurred while extracting edges"); + throw Base::RuntimeError("GeometryObject::projectShapeWithPolygonAlgo - unknown error occurred while extracting edges"); } - auto end = chrono::high_resolution_clock::now(); - auto diff = end - start; - double diffOut = chrono::duration (diff).count(); - Base::Console().Log("TIMING - %s GO spent: %.3f millisecs in HLRBRep_PolyAlgo & co\n", m_parentName.c_str(), diffOut); + + makeTDGeometry(); } TopoDS_Shape GeometryObject::projectFace(const TopoDS_Shape &face, @@ -494,7 +531,7 @@ void GeometryObject::addGeomFromCompound(TopoDS_Shape edgeCompound, edgeClass ca } base = BaseGeom::baseFactory(edge); - if (base == nullptr) { + if (!base) { Base::Console().Log("Error - GO::addGeomFromCompound - baseFactory failed for edge: %d\n",i); continue; // throw Base::ValueError("GeometryObject::addGeomFromCompound - baseFactory failed"); @@ -716,9 +753,9 @@ void GeometryObject::addFaceGeom(FacePtr f) TechDraw::DrawViewDetail* GeometryObject::isParentDetail() { TechDraw::DrawViewDetail* result = nullptr; - if (m_parent != nullptr) { + if (m_parent) { TechDraw::DrawViewDetail* detail = dynamic_cast(m_parent); - if (detail != nullptr) { + if (detail) { result = detail; } } diff --git a/src/Mod/TechDraw/App/GeometryObject.h b/src/Mod/TechDraw/App/GeometryObject.h index 430d82315d..1f24baffe1 100644 --- a/src/Mod/TechDraw/App/GeometryObject.h +++ b/src/Mod/TechDraw/App/GeometryObject.h @@ -29,6 +29,7 @@ #include #include +#include #include #include @@ -121,32 +122,33 @@ public: TopoDS_Shape projectFace(const TopoDS_Shape &face, const gp_Ax2 &CS); + void makeTDGeometry(); void extractGeometry(edgeClass category, bool visible); void addFaceGeom(FacePtr f); void clearFaceGeom(); void setIsoCount(int i) { m_isoCount = i; } void setParentName(std::string n); //for debug messages void isPerspective(bool b) { m_isPersp = b; } - bool isPerspective(void) { return m_isPersp; } + bool isPerspective() { return m_isPersp; } void usePolygonHLR(bool b) { m_usePolygonHLR = b; } - bool usePolygonHLR(void) const { return m_usePolygonHLR; } + bool usePolygonHLR() const { return m_usePolygonHLR; } void setFocus(double f) { m_focus = f; } - double getFocus(void) { return m_focus; } + double getFocus() { return m_focus; } void pruneVertexGeom(Base::Vector3d center, double radius); //dupl mirrorShape??? static TopoDS_Shape invertGeometry(const TopoDS_Shape s); - TopoDS_Shape getVisHard(void) { return visHard; } - TopoDS_Shape getVisOutline(void) { return visOutline; } - TopoDS_Shape getVisSmooth(void) { return visSmooth; } - TopoDS_Shape getVisSeam(void) { return visSeam; } - TopoDS_Shape getVisIso(void) { return visIso; } - TopoDS_Shape getHidHard(void) { return hidHard; } - TopoDS_Shape getHidOutline(void) { return hidOutline; } - TopoDS_Shape getHidSmooth(void) { return hidSmooth; } - TopoDS_Shape getHidSeam(void) { return hidSeam; } - TopoDS_Shape getHidIso(void) { return hidIso; } + TopoDS_Shape getVisHard() { return visHard; } + TopoDS_Shape getVisOutline() { return visOutline; } + TopoDS_Shape getVisSmooth() { return visSmooth; } + TopoDS_Shape getVisSeam() { return visSeam; } + TopoDS_Shape getVisIso() { return visIso; } + TopoDS_Shape getHidHard() { return hidHard; } + TopoDS_Shape getHidOutline() { return hidOutline; } + TopoDS_Shape getHidSmooth() { return hidSmooth; } + TopoDS_Shape getHidSeam() { return hidSeam; } + TopoDS_Shape getHidIso() { return hidIso; } void addVertex(TechDraw::VertexPtr v); void addEdge(TechDraw::BaseGeomPtr bg); @@ -168,7 +170,6 @@ public: int addCenterLine(TechDraw::BaseGeomPtr bg, std::string tag); -/* int s = 0, int si = -1);*/ protected: //HLR output @@ -184,7 +185,7 @@ protected: TopoDS_Shape hidIso; void addGeomFromCompound(TopoDS_Shape edgeCompound, edgeClass category, bool visible); - TechDraw::DrawViewDetail* isParentDetail(void); + TechDraw::DrawViewDetail* isParentDetail(); //similar function in Geometry? /*! diff --git a/src/Mod/TechDraw/App/HatchLine.cpp b/src/Mod/TechDraw/App/HatchLine.cpp index 00b3ed5681..ddc4210da3 100644 --- a/src/Mod/TechDraw/App/HatchLine.cpp +++ b/src/Mod/TechDraw/App/HatchLine.cpp @@ -36,6 +36,7 @@ #include #include +#include #include #include "Geometry.h" @@ -45,35 +46,35 @@ using namespace TechDraw; -double LineSet::getMinX(void) +double LineSet::getMinX() { double xMin,yMin,zMin,xMax,yMax,zMax; m_box.Get(xMin,yMin,zMin,xMax,yMax,zMax); return xMin; } -double LineSet::getMinY(void) +double LineSet::getMinY() { double xMin,yMin,zMin,xMax,yMax,zMax; m_box.Get(xMin,yMin,zMin,xMax,yMax,zMax); return yMin; } -double LineSet::getMaxX(void) +double LineSet::getMaxX() { double xMin,yMin,zMin,xMax,yMax,zMax; m_box.Get(xMin,yMin,zMin,xMax,yMax,zMax); return xMax; } -double LineSet::getMaxY(void) +double LineSet::getMaxY() { double xMin,yMin,zMin,xMax,yMax,zMax; m_box.Get(xMin,yMin,zMin,xMax,yMax,zMax); return yMax; } -bool LineSet::isDashed(void) +bool LineSet::isDashed() { bool result = m_hatchLine.isDashed(); return result; @@ -99,7 +100,7 @@ Base::Vector3d LineSet::calcApparentStart(TechDraw::BaseGeomPtr g) return result; } -Base::Vector3d LineSet::getUnitDir(void) +Base::Vector3d LineSet::getUnitDir() { Base::Vector3d result; Base::Vector3d start(m_geoms.at(0)->getStartPoint().x, @@ -133,7 +134,7 @@ Base::Vector3d LineSet::getUnitOrtho() } -Base::Vector3d LineSet::findAtomStart(void) +Base::Vector3d LineSet::findAtomStart() { Base::Vector3d result; Base::Vector3d origin = getOrigin(); @@ -239,7 +240,7 @@ PATLineSpec::~PATLineSpec() { } -void PATLineSpec::init(void) +void PATLineSpec::init() { m_angle = 0.0; m_origin = Base::Vector3d(0.0,0.0,0.0); @@ -305,8 +306,9 @@ std::vector PATLineSpec::getSpecsForPattern(std::string& parmFile, { std::vector result; std::vector lineSpecs; - std::ifstream inFile; - inFile.open (parmFile, std::ifstream::in); + Base::FileInfo fi(parmFile); + Base::ifstream inFile; + inFile.open (fi, std::ifstream::in); if(!inFile.is_open()) { Base::Console().Message( "Cannot open input file.\n"); return result; @@ -385,8 +387,9 @@ std::vector PATLineSpec::loadPatternDef(std::ifstream& inFile) std::vector PATLineSpec::getPatternList(std::string& parmFile) { std::vector result; - std::ifstream inFile; - inFile.open (parmFile, std::ifstream::in); + Base::FileInfo fi(parmFile); + Base::ifstream inFile; + inFile.open (fi, std::ifstream::in); if(!inFile.is_open()) { Base::Console().Message( "Cannot open input file.\n"); return result; @@ -411,7 +414,7 @@ std::vector PATLineSpec::getPatternList(std::string& parmFile) return result; } -double PATLineSpec::getSlope(void) +double PATLineSpec::getSlope() { double angle = getAngle(); @@ -425,14 +428,14 @@ double PATLineSpec::getSlope(void) return slope; } -bool PATLineSpec::isDashed(void) +bool PATLineSpec::isDashed() { bool result = !m_dashParms.empty(); return result; } //! X component of distance between lines -double PATLineSpec::getIntervalX(void) +double PATLineSpec::getIntervalX() { if (getAngle() == 0.0) { return 0.0; @@ -445,7 +448,7 @@ double PATLineSpec::getIntervalX(void) } //! Y component of distance between lines -double PATLineSpec::getIntervalY(void) +double PATLineSpec::getIntervalY() { if (getAngle() == 0.0) { return getInterval(); @@ -460,7 +463,7 @@ double PATLineSpec::getIntervalY(void) //******************************************************** -double DashSpec::length(void) +double DashSpec::length() { double result = 0.0; for (auto& c: get()) { @@ -469,7 +472,7 @@ double DashSpec::length(void) return result; } -DashSpec DashSpec::reversed(void) +DashSpec DashSpec::reversed() { std::vector p = get(); std::reverse(p.begin(),p.end()); diff --git a/src/Mod/TechDraw/App/HatchLine.h b/src/Mod/TechDraw/App/HatchLine.h index 747b639498..b8fb3714bd 100644 --- a/src/Mod/TechDraw/App/HatchLine.h +++ b/src/Mod/TechDraw/App/HatchLine.h @@ -52,16 +52,16 @@ class TechDrawExport DashSpec { public: DashSpec() {} - DashSpec(std::vector p) { m_parms = p; } + explicit DashSpec(std::vector p) { m_parms = p; } ~DashSpec() {} double get(int i) {return m_parms.at(i); } - std::vector get(void) {return m_parms;} - bool empty(void) {return m_parms.empty();} - int size(void) {return m_parms.size();} - double length(void); + std::vector get() {return m_parms;} + bool empty() {return m_parms.empty();} + int size() {return m_parms.size();} + double length(); void dump(const char* title); - DashSpec reversed(void); + DashSpec reversed(); private: std::vector m_parms; @@ -72,32 +72,32 @@ class TechDrawExport PATLineSpec { public: PATLineSpec(); - PATLineSpec(std::string& lineSpec); + explicit PATLineSpec(std::string& lineSpec); ~PATLineSpec(); void load(std::string& lineSpec); - double getAngle(void) {return m_angle;} - Base::Vector3d getOrigin(void) {return m_origin;} - double getInterval(void) {return m_interval;} - double getIntervalX(void); - double getIntervalY(void); - double getOffset(void) {return m_offset;} - double getSlope(void); - double getLength(void) {return m_dashParms.length(); } - DashSpec getDashParms(void) {return m_dashParms;} + double getAngle() {return m_angle;} + Base::Vector3d getOrigin() {return m_origin;} + double getInterval() {return m_interval;} + double getIntervalX(); + double getIntervalY(); + double getOffset() {return m_offset;} + double getSlope(); + double getLength() {return m_dashParms.length(); } + DashSpec getDashParms() {return m_dashParms;} static std::vector getSpecsForPattern(std::string& parmFile, std::string& parmName); static bool findPatternStart(std::ifstream& inFile, std::string& parmName); static std::vector loadPatternDef(std::ifstream& inFile); static std::vector getPatternList(std::string& parmFile); - bool isDashed(void); + bool isDashed(); void dump(const char* title); private: - void init(void); + void init(); std::vector split(std::string line); //PAT line extracted tokens double m_angle; @@ -119,34 +119,34 @@ public: void setGeoms(std::vector g) {m_geoms = g;} void setBBox(const Bnd_Box& bb) {m_box = bb;} - std::vector getEdges(void) { return m_edges; } + std::vector getEdges() { return m_edges; } TopoDS_Edge getEdge(int i) {return m_edges.at(i);} - std::vector getGeoms(void) { return m_geoms; } + std::vector getGeoms() { return m_geoms; } - PATLineSpec getPATLineSpec(void) { return m_hatchLine; } - double getOffset(void) { return m_hatchLine.getOffset(); } //delta X offset - double getAngle(void) { return m_hatchLine.getAngle(); } - Base::Vector3d getOrigin(void) { return m_hatchLine.getOrigin(); } - double getInterval(void) {return m_hatchLine.getInterval(); } //space between lines - double getIntervalX(void) { return m_hatchLine.getIntervalX(); } //interval X-component - double getIntervalY(void) { return m_hatchLine.getIntervalY(); } //interval Y-component - double getSlope(void) { return m_hatchLine.getSlope(); } - double getPatternLength(void) { return m_hatchLine.getLength(); } - Base::Vector3d getUnitDir(void); - Base::Vector3d getUnitOrtho(void); - DashSpec getDashSpec(void) { return m_hatchLine.getDashParms();} + PATLineSpec getPATLineSpec() { return m_hatchLine; } + double getOffset() { return m_hatchLine.getOffset(); } //delta X offset + double getAngle() { return m_hatchLine.getAngle(); } + Base::Vector3d getOrigin() { return m_hatchLine.getOrigin(); } + double getInterval() {return m_hatchLine.getInterval(); } //space between lines + double getIntervalX() { return m_hatchLine.getIntervalX(); } //interval X-component + double getIntervalY() { return m_hatchLine.getIntervalY(); } //interval Y-component + double getSlope() { return m_hatchLine.getSlope(); } + double getPatternLength() { return m_hatchLine.getLength(); } + Base::Vector3d getUnitDir(); + Base::Vector3d getUnitOrtho(); + DashSpec getDashSpec() { return m_hatchLine.getDashParms();} Base::Vector3d calcApparentStart(TechDraw::BaseGeomPtr g); - Base::Vector3d findAtomStart(void); - Base::Vector3d getLineOrigin(void); //point corresponding to pattern origin for this line (O + n*intervalX) + Base::Vector3d findAtomStart(); + Base::Vector3d getLineOrigin(); //point corresponding to pattern origin for this line (O + n*intervalX) Base::Vector3d getPatternStartPoint(TechDraw::BaseGeomPtr g, double &offset, double scale = 1.0); - Bnd_Box getBBox(void) {return m_box;} - double getMinX(void); - double getMaxX(void); - double getMinY(void); - double getMaxY(void); + Bnd_Box getBBox() {return m_box;} + double getMinX(); + double getMaxX(); + double getMinY(); + double getMaxY(); - bool isDashed(void); + bool isDashed(); private: std::vector m_edges; diff --git a/src/Mod/TechDraw/App/LandmarkDimension.cpp b/src/Mod/TechDraw/App/LandmarkDimension.cpp index 811375e2b2..466a1d8150 100644 --- a/src/Mod/TechDraw/App/LandmarkDimension.cpp +++ b/src/Mod/TechDraw/App/LandmarkDimension.cpp @@ -68,7 +68,7 @@ using namespace TechDraw; PROPERTY_SOURCE(TechDraw::LandmarkDimension, TechDraw::DrawViewDimension) -LandmarkDimension::LandmarkDimension(void) +LandmarkDimension::LandmarkDimension() { static const char *group = "Landmark"; //this leaves a blank entry in position 1. @@ -100,7 +100,7 @@ short LandmarkDimension::mustExecute() const return DrawViewDimension::mustExecute(); } -App::DocumentObjectExecReturn *LandmarkDimension::execute(void) +App::DocumentObjectExecReturn *LandmarkDimension::execute() { // Base::Console().Message("LD::execute() - %s\n", getNameInDocument()); if (!keepUpdated()) { @@ -108,7 +108,7 @@ App::DocumentObjectExecReturn *LandmarkDimension::execute(void) } DrawViewPart* dvp = getViewPart(); - if (dvp == nullptr) { + if (!dvp) { return App::DocumentObject::StdReturn; } References2D.setValue(dvp); @@ -153,7 +153,9 @@ App::DocumentObjectExecReturn *LandmarkDimension::execute(void) // dvp->resetReferenceVerts(); dvp->addReferencesToGeom(); - dvp->requestPaint(); + dvp->requestPaint(); + + overrideKeepUpdated(false); return dvdResult; } @@ -172,7 +174,7 @@ Base::Vector3d LandmarkDimension::projectPoint(const Base::Vector3d& pt, DrawVie return result; } -std::vector LandmarkDimension::get2DPoints(void) const +std::vector LandmarkDimension::get2DPoints() const { // Base::Console().Message("LD::get2DPoints()\n"); std::vector result; @@ -187,7 +189,7 @@ std::vector LandmarkDimension::get2DPoints(void) const } //! References2D are only used to store ParentView -bool LandmarkDimension::has2DReferences(void) const +bool LandmarkDimension::has2DReferences() const { bool result = false; const std::vector &objects = References2D.getValues(); @@ -209,7 +211,7 @@ pointPair LandmarkDimension::getPointsTwoVerts() pointPair result; TechDraw::DrawViewPart* dvp = getViewPart(); - if (dvp != nullptr) { + if (dvp) { std::vector points = get2DPoints(); result.first = points.at(0) * dvp->getScale(); result.second = points.at(1) * dvp->getScale(); @@ -229,7 +231,7 @@ DrawViewPart* LandmarkDimension::getViewPart() const std::vector refs2d = References2D.getValues(); App::DocumentObject* obj = refs2d.front(); DrawViewPart* dvp = dynamic_cast(obj); - if (dvp != nullptr) { + if (dvp) { result = dvp; } return result; diff --git a/src/Mod/TechDraw/App/LandmarkDimension.h b/src/Mod/TechDraw/App/LandmarkDimension.h index b74a985208..36c5d3241a 100644 --- a/src/Mod/TechDraw/App/LandmarkDimension.h +++ b/src/Mod/TechDraw/App/LandmarkDimension.h @@ -23,6 +23,8 @@ #ifndef _TechDraw_LandmarkDimension_h_ #define _TechDraw_LandmarkDimension_h_ +#include + # include # include @@ -46,30 +48,30 @@ class TechDrawExport LandmarkDimension : public TechDraw::DrawViewDimension public: /// Constructor LandmarkDimension(); - virtual ~LandmarkDimension(); + ~LandmarkDimension() override; App::PropertyStringList ReferenceTags; //tags of 2d vertices in DVP - virtual App::DocumentObjectExecReturn *execute(void) override; + App::DocumentObjectExecReturn *execute() override; short mustExecute() const override; - virtual void unsetupObject() override; + void unsetupObject() override; - virtual const char* getViewProviderName(void) const override { + const char* getViewProviderName() const override { return "TechDrawGui::ViewProviderDimension"; } /* virtual PyObject *getPyObject(void) override;*/ - virtual bool checkReferences2D() const override; - virtual bool has2DReferences(void) const override; - virtual pointPair getPointsTwoVerts() override; - std::vector get2DPoints(void) const; - virtual DrawViewPart* getViewPart() const override; - virtual int getRefType() const override; + bool checkReferences2D() const override; + bool has2DReferences() const override; + pointPair getPointsTwoVerts() override; + std::vector get2DPoints() const; + DrawViewPart* getViewPart() const override; + int getRefType() const override; - gp_Ax2 getProjAxis(void) const; + gp_Ax2 getProjAxis() const; protected: - virtual void onChanged(const App::Property* prop) override; - virtual void onDocumentRestored() override; + void onChanged(const App::Property* prop) override; + void onDocumentRestored() override; Base::Vector3d projectPoint(const Base::Vector3d& pt, DrawViewPart* dvp) const; diff --git a/src/Mod/TechDraw/App/LineGroup.cpp b/src/Mod/TechDraw/App/LineGroup.cpp index 54a37f2278..80bf4c79b5 100644 --- a/src/Mod/TechDraw/App/LineGroup.cpp +++ b/src/Mod/TechDraw/App/LineGroup.cpp @@ -31,7 +31,9 @@ #include #include +#include #include +#include #include "Preferences.h" #include "LineGroup.h" @@ -54,7 +56,7 @@ LineGroup::~LineGroup() { } -void LineGroup::init(void) +void LineGroup::init() { m_name = "Default"; m_thin = 0.35; @@ -130,8 +132,8 @@ std::vector LineGroup::split(std::string line) std::string LineGroup::getRecordFromFile(std::string parmFile, int groupNumber) { std::string record; - std::ifstream inFile; - inFile.open (parmFile, std::ifstream::in); + 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()); return record; @@ -178,15 +180,19 @@ LineGroup* LineGroup::lineGroupFactory(int groupNumber) return lg; } -//valid weight names: Thick, Thin, Graphic, Extra -double LineGroup::getDefaultWidth(std::string weightName, int groupNumber) +/** + * @brief Returns the default line width given a weight name and group number. + * + * @param weightName can be "Thick", "Thin", "Graphic" or "Extra" + * @param lineGroupNumber if -1 will then use groupNumber in preferences. Default value is -1. + * @return the default line width. + */ +double LineGroup::getDefaultWidth(std::string weightName, int lineGroupNumber) { - //default line weights - int lgNumber = groupNumber; - if (lgNumber == -1) { - lgNumber = Preferences::lineGroup(); + if (lineGroupNumber == -1) { + lineGroupNumber = Preferences::lineGroup(); } - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); + auto lg = TechDraw::LineGroup::lineGroupFactory(lineGroupNumber); double weight = lg->getWeight(weightName); delete lg; @@ -197,8 +203,8 @@ double LineGroup::getDefaultWidth(std::string weightName, int groupNumber) std::string LineGroup::getGroupNamesFromFile(std::string FileName) { std::string record; - std::ifstream inFile; - inFile.open(FileName, std::ifstream::in); + 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()); return record; diff --git a/src/Mod/TechDraw/App/LineGroup.h b/src/Mod/TechDraw/App/LineGroup.h index 250a9d12cd..688f17488f 100644 --- a/src/Mod/TechDraw/App/LineGroup.h +++ b/src/Mod/TechDraw/App/LineGroup.h @@ -25,6 +25,8 @@ #ifndef _TechDraw_LINEGROUP_H_ #define _TechDraw_LINEGROUP_H_ +#include + #include namespace TechDraw diff --git a/src/Mod/TechDraw/App/PreCompiled.h b/src/Mod/TechDraw/App/PreCompiled.h index be238291a3..acd5ddec64 100644 --- a/src/Mod/TechDraw/App/PreCompiled.h +++ b/src/Mod/TechDraw/App/PreCompiled.h @@ -45,6 +45,10 @@ # define ImportExport #endif +#ifdef _MSC_VER +# pragma warning( disable : 4275 ) +#endif + #ifdef _PreComp_ // standard diff --git a/src/Mod/TechDraw/App/Preferences.cpp b/src/Mod/TechDraw/App/Preferences.cpp index 0ac0fef953..096f19a6f5 100644 --- a/src/Mod/TechDraw/App/Preferences.cpp +++ b/src/Mod/TechDraw/App/Preferences.cpp @@ -25,8 +25,6 @@ #ifndef _PreComp_ #include #include -//#include -//#include #endif #include @@ -277,13 +275,12 @@ std::string Preferences::svgFile() if (prefHatchFile.empty()) { prefHatchFile = defaultFileName; } - std::string result = prefHatchFile; - Base::FileInfo fi(result); + Base::FileInfo fi(prefHatchFile); if (!fi.isReadable()) { - result = defaultFileName; Base::Console().Warning("Svg Hatch File: %s is not readable\n", prefHatchFile.c_str()); + prefHatchFile = defaultFileName; } - return result; + return prefHatchFile; } std::string Preferences::patFile() @@ -294,16 +291,19 @@ std::string Preferences::patFile() std::string defaultDir = App::Application::getResourceDir() + "Mod/TechDraw/PAT/"; std::string defaultFileName = defaultDir + "FCPAT.pat"; std::string prefHatchFile = hGrp->GetASCII("FilePattern", defaultFileName.c_str()); - std::string result = prefHatchFile; - Base::FileInfo fi(result); - if (!fi.isReadable()) { - result = defaultFileName; - Base::Console().Warning("Pat Hatch File: %s is not readable\n", prefHatchFile.c_str()); + if (prefHatchFile.empty()) { + prefHatchFile = defaultFileName; } - return result; + Base::FileInfo fi(prefHatchFile); + if (!fi.isReadable()) { + Base::Console().Warning("Pat Hatch File: %s is not readable\n", prefHatchFile.c_str()); + prefHatchFile = defaultFileName; + } + + return prefHatchFile; } -std::string Preferences::bitmapFill(void) +std::string Preferences::bitmapFill() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Files"); @@ -311,13 +311,15 @@ std::string Preferences::bitmapFill(void) std::string defaultDir = App::Application::getResourceDir() + "Mod/TechDraw/Patterns/"; std::string defaultFileName = defaultDir + "default.png"; std::string prefBitmapFile = hGrp->GetASCII("BitmapFill", defaultFileName.c_str()); - std::string result = prefBitmapFile; - Base::FileInfo fi(result); - if (!fi.isReadable()) { - result = defaultFileName; - Base::Console().Warning("Bitmap Fill File: %s is not readable\n", prefBitmapFile.c_str()); + if (prefBitmapFile.empty()) { + prefBitmapFile = defaultFileName; } - return result; + Base::FileInfo fi(prefBitmapFile); + if (!fi.isReadable()) { + Base::Console().Warning("Bitmap Fill File: %s is not readable\n", prefBitmapFile.c_str()); + prefBitmapFile = defaultFileName; + } + return prefBitmapFile; } double Preferences::GapISO() @@ -337,3 +339,12 @@ double Preferences::GapASME() double factor = hGrp->GetFloat("GapASME", 6.0); return factor; } + +bool Preferences::reportProgress() +{ + Base::Reference hGrp = App::GetApplication().GetUserParameter(). + GetGroup("BaseApp")->GetGroup("Preferences")-> + GetGroup("Mod/TechDraw/General"); + bool report = hGrp->GetBool("ReportProgress", false); + return report; +} diff --git a/src/Mod/TechDraw/App/Preferences.h b/src/Mod/TechDraw/App/Preferences.h index 0e02796455..7eacaec1e9 100644 --- a/src/Mod/TechDraw/App/Preferences.h +++ b/src/Mod/TechDraw/App/Preferences.h @@ -23,6 +23,8 @@ #ifndef _Preferences_h_ #define _Preferences_h_ +#include + #include #include @@ -74,11 +76,12 @@ static int mattingStyle(); static std::string svgFile(); static std::string patFile(); -static std::string bitmapFill(void); +static std::string bitmapFill(); static double GapISO(); static double GapASME(); +static bool reportProgress(); }; } //end namespace TechDraw diff --git a/src/Mod/TechDraw/App/ProjectionAlgos.cpp b/src/Mod/TechDraw/App/ProjectionAlgos.cpp index a3f1e69f70..f69f7ceac0 100644 --- a/src/Mod/TechDraw/App/ProjectionAlgos.cpp +++ b/src/Mod/TechDraw/App/ProjectionAlgos.cpp @@ -108,7 +108,7 @@ static const TopoDS_Shape& build3dCurves(const TopoDS_Shape &shape) return shape; } -void ProjectionAlgos::execute(void) +void ProjectionAlgos::execute() { Handle( HLRBRep_Algo ) brep_hlr = new HLRBRep_Algo; brep_hlr->Add(Input); diff --git a/src/Mod/TechDraw/App/ProjectionAlgos.h b/src/Mod/TechDraw/App/ProjectionAlgos.h index a8b96fba75..effa99f2a4 100644 --- a/src/Mod/TechDraw/App/ProjectionAlgos.h +++ b/src/Mod/TechDraw/App/ProjectionAlgos.h @@ -19,7 +19,7 @@ * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ -//this file originally part of TechDraw workbench +//this file originally part of Drawing workbench //migrated to TechDraw workbench 2022-01-26 by Wandererfan @@ -46,7 +46,7 @@ public: ProjectionAlgos(const TopoDS_Shape &Input,const Base::Vector3d &Dir); virtual ~ProjectionAlgos(); - void execute(void); + void execute(); enum ExtractionType { Plain = 0, diff --git a/src/Mod/TechDraw/App/PropertyCenterLineList.cpp b/src/Mod/TechDraw/App/PropertyCenterLineList.cpp index adf48d8fa0..90faf9c731 100644 --- a/src/Mod/TechDraw/App/PropertyCenterLineList.cpp +++ b/src/Mod/TechDraw/App/PropertyCenterLineList.cpp @@ -72,7 +72,7 @@ void PropertyCenterLineList::setSize(int newSize) _lValueList.resize(newSize); } -int PropertyCenterLineList::getSize(void) const +int PropertyCenterLineList::getSize() const { return static_cast(_lValueList.size()); } @@ -96,7 +96,7 @@ void PropertyCenterLineList::setValues(const std::vector& lValue) hasSetValue(); } -PyObject *PropertyCenterLineList::getPyObject(void) +PyObject *PropertyCenterLineList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) @@ -190,7 +190,7 @@ void PropertyCenterLineList::Restore(Base::XMLReader &reader) setValues(values); } -App::Property *PropertyCenterLineList::Copy(void) const +App::Property *PropertyCenterLineList::Copy() const { PropertyCenterLineList *p = new PropertyCenterLineList(); p->setValues(_lValueList); @@ -203,7 +203,7 @@ void PropertyCenterLineList::Paste(const Property &from) setValues(FromList._lValueList); } -unsigned int PropertyCenterLineList::getMemSize(void) const +unsigned int PropertyCenterLineList::getMemSize() const { int size = sizeof(PropertyCenterLineList); for (int i = 0; i < getSize(); i++) diff --git a/src/Mod/TechDraw/App/PropertyCenterLineList.h b/src/Mod/TechDraw/App/PropertyCenterLineList.h index f397acb866..12085d6f98 100644 --- a/src/Mod/TechDraw/App/PropertyCenterLineList.h +++ b/src/Mod/TechDraw/App/PropertyCenterLineList.h @@ -22,6 +22,8 @@ #ifndef TECHDRAW_PropertyCenterLineList_H #define TECHDRAW_PropertyCenterLineList_H + +#include #include #include diff --git a/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp b/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp index 2356fbe2ff..121cd069b2 100644 --- a/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp +++ b/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.cpp @@ -72,7 +72,7 @@ void PropertyCosmeticEdgeList::setSize(int newSize) _lValueList.resize(newSize); } -int PropertyCosmeticEdgeList::getSize(void) const +int PropertyCosmeticEdgeList::getSize() const { return static_cast(_lValueList.size()); } @@ -98,7 +98,7 @@ void PropertyCosmeticEdgeList::setValues(const std::vector& lValu hasSetValue(); } -PyObject *PropertyCosmeticEdgeList::getPyObject(void) +PyObject *PropertyCosmeticEdgeList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) @@ -192,7 +192,7 @@ void PropertyCosmeticEdgeList::Restore(Base::XMLReader &reader) setValues(values); } -App::Property *PropertyCosmeticEdgeList::Copy(void) const +App::Property *PropertyCosmeticEdgeList::Copy() const { PropertyCosmeticEdgeList *p = new PropertyCosmeticEdgeList(); p->setValues(_lValueList); @@ -205,7 +205,7 @@ void PropertyCosmeticEdgeList::Paste(const Property &from) setValues(FromList._lValueList); } -unsigned int PropertyCosmeticEdgeList::getMemSize(void) const +unsigned int PropertyCosmeticEdgeList::getMemSize() const { int size = sizeof(PropertyCosmeticEdgeList); for (int i = 0; i < getSize(); i++) diff --git a/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.h b/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.h index 58d16fafd7..0f323da2bf 100644 --- a/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.h +++ b/src/Mod/TechDraw/App/PropertyCosmeticEdgeList.h @@ -22,6 +22,8 @@ #ifndef TECHDRAW_PropertyCosmeticEdgeList_H #define TECHDRAW_PropertyCosmeticEdgeList_H + +#include #include #include diff --git a/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp b/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp index 094dcecb71..296e52b037 100644 --- a/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp +++ b/src/Mod/TechDraw/App/PropertyCosmeticVertexList.cpp @@ -72,7 +72,7 @@ void PropertyCosmeticVertexList::setSize(int newSize) _lValueList.resize(newSize); } -int PropertyCosmeticVertexList::getSize(void) const +int PropertyCosmeticVertexList::getSize() const { return static_cast(_lValueList.size()); } @@ -96,7 +96,7 @@ void PropertyCosmeticVertexList::setValues(const std::vector& l hasSetValue(); } -PyObject *PropertyCosmeticVertexList::getPyObject(void) +PyObject *PropertyCosmeticVertexList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) @@ -192,7 +192,7 @@ void PropertyCosmeticVertexList::Restore(Base::XMLReader &reader) setValues(values); } -App::Property *PropertyCosmeticVertexList::Copy(void) const +App::Property *PropertyCosmeticVertexList::Copy() const { PropertyCosmeticVertexList *p = new PropertyCosmeticVertexList(); p->setValues(_lValueList); @@ -205,7 +205,7 @@ void PropertyCosmeticVertexList::Paste(const Property &from) setValues(FromList._lValueList); } -unsigned int PropertyCosmeticVertexList::getMemSize(void) const +unsigned int PropertyCosmeticVertexList::getMemSize() const { int size = sizeof(PropertyCosmeticVertexList); for (int i = 0; i < getSize(); i++) diff --git a/src/Mod/TechDraw/App/PropertyCosmeticVertexList.h b/src/Mod/TechDraw/App/PropertyCosmeticVertexList.h index b3f225c767..d54f2ddca4 100644 --- a/src/Mod/TechDraw/App/PropertyCosmeticVertexList.h +++ b/src/Mod/TechDraw/App/PropertyCosmeticVertexList.h @@ -22,6 +22,8 @@ #ifndef TECHDRAW_PropertyCosmeticVertexList_H #define TECHDRAW_PropertyCosmeticVertexList_H + +#include #include #include diff --git a/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp b/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp index 6bb4e7f18a..0688a20152 100644 --- a/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp +++ b/src/Mod/TechDraw/App/PropertyGeomFormatList.cpp @@ -74,7 +74,7 @@ void PropertyGeomFormatList::setSize(int newSize) _lValueList.resize(newSize); } -int PropertyGeomFormatList::getSize(void) const +int PropertyGeomFormatList::getSize() const { return static_cast(_lValueList.size()); } @@ -105,7 +105,7 @@ void PropertyGeomFormatList::setValues(const std::vector& lValue) hasSetValue(); } -PyObject *PropertyGeomFormatList::getPyObject(void) +PyObject *PropertyGeomFormatList::getPyObject() { PyObject* list = PyList_New(getSize()); for (int i = 0; i < getSize(); i++) @@ -204,7 +204,7 @@ void PropertyGeomFormatList::Restore(Base::XMLReader &reader) setValues(values); } -App::Property *PropertyGeomFormatList::Copy(void) const +App::Property *PropertyGeomFormatList::Copy() const { PropertyGeomFormatList *p = new PropertyGeomFormatList(); p->setValues(_lValueList); @@ -217,7 +217,7 @@ void PropertyGeomFormatList::Paste(const Property &from) setValues(FromList._lValueList); } -unsigned int PropertyGeomFormatList::getMemSize(void) const +unsigned int PropertyGeomFormatList::getMemSize() const { int size = sizeof(PropertyGeomFormatList); for (int i = 0; i < getSize(); i++) diff --git a/src/Mod/TechDraw/App/PropertyGeomFormatList.h b/src/Mod/TechDraw/App/PropertyGeomFormatList.h index 87348e5018..3e35a84a0c 100644 --- a/src/Mod/TechDraw/App/PropertyGeomFormatList.h +++ b/src/Mod/TechDraw/App/PropertyGeomFormatList.h @@ -22,6 +22,8 @@ #ifndef TECHDRAW_PropertyGeomFormatList_H #define TECHDRAW_PropertyGeomFormatList_H + +#include #include #include diff --git a/src/Mod/TechDraw/App/QDomNodeModel.h b/src/Mod/TechDraw/App/QDomNodeModel.h index 018a402ea7..c74bcd524c 100644 --- a/src/Mod/TechDraw/App/QDomNodeModel.h +++ b/src/Mod/TechDraw/App/QDomNodeModel.h @@ -26,6 +26,8 @@ #ifndef _QDOMNODEMODEL_H_ #define _QDOMNODEMODEL_H_ + +#include #include #include diff --git a/src/Mod/TechDraw/App/ShapeExtractor.cpp b/src/Mod/TechDraw/App/ShapeExtractor.cpp index 7c69ec00b9..03b5d97f86 100644 --- a/src/Mod/TechDraw/App/ShapeExtractor.cpp +++ b/src/Mod/TechDraw/App/ShapeExtractor.cpp @@ -70,7 +70,7 @@ std::vector ShapeExtractor::getShapes2d(const std::vector(l); - if (gex != nullptr) { + if (gex) { std::vector objs = gex->Group.getValues(); for (auto& d: objs) { if (is2dObject(d)) { @@ -161,7 +161,7 @@ std::vector ShapeExtractor::getXShapes(const App::Link* xLink) { // Base::Console().Message("SE::getXShapes(%X) - %s\n", xLink, xLink->getNameInDocument()); std::vector xSourceShapes; - if (xLink == nullptr) { + if (!xLink) { return xSourceShapes; } @@ -213,7 +213,7 @@ std::vector ShapeExtractor::getXShapes(const App::Link* xLink) } else { int depth = 1; //0 is default value, related to recursion of Links??? App::DocumentObject* link = xLink->getLink(depth); - if (link != nullptr) { + if (link) { auto shape = Part::Feature::getShape(link); if(!shape.IsNull()) { if (needsTransform) { @@ -259,7 +259,7 @@ std::vector ShapeExtractor::getShapesFromObject(const App::Documen return result; } - } else if (gex != nullptr) { //is a group extension + } else if (gex) { //is a group extension std::vector objs = gex->Group.getValues(); std::vector shapes; for (auto& d: objs) { @@ -269,9 +269,9 @@ std::vector ShapeExtractor::getShapesFromObject(const App::Documen } } //the next 2 bits are mostly for Arch module objects - } else if (gProp != nullptr) { //has a Group property + } else if (gProp) { //has a Group property App::PropertyLinkList* list = dynamic_cast(gProp); - if (list != nullptr) { + if (list) { std::vector objs = list->getValues(); std::vector shapes; for (auto& d: objs) { @@ -283,9 +283,9 @@ std::vector ShapeExtractor::getShapesFromObject(const App::Documen } else { Base::Console().Log("SE::getShapesFromObject - Group is not a PropertyLinkList!\n"); } - } else if (sProp != nullptr) { //has a Shape property + } else if (sProp) { //has a Shape property Part::PropertyPartShape* shape = dynamic_cast(sProp); - if (shape != nullptr) { + if (shape) { TopoDS_Shape occShape = shape->getValue(); result.push_back(occShape); } else { @@ -392,7 +392,7 @@ bool ShapeExtractor::isDraftPoint(App::DocumentObject* obj) bool result = false; //if the docObj doesn't have a Proxy property, it definitely isn't a Draft point App::PropertyPythonObject* proxy = dynamic_cast(obj->getPropertyByName("Proxy")); - if (proxy != nullptr) { + if (proxy) { std::string pp = proxy->toString(); // Base::Console().Message("SE::isDraftPoint - pp: %s\n", pp.c_str()); if (pp.find("Point") != std::string::npos) { @@ -414,7 +414,7 @@ Base::Vector3d ShapeExtractor::getLocation3dFromFeat(App::DocumentObject* obj) // //if Draft option "use part primitives" is not set are Draft points still PartFeature? Part::Feature* pf = dynamic_cast(obj); - if (pf != nullptr) { + if (pf) { Part::TopoShape pts = pf->Shape.getShape(); pts.setPlacement(pf->globalPlacement()); TopoDS_Shape ts = pts.getShape(); @@ -429,7 +429,7 @@ Base::Vector3d ShapeExtractor::getLocation3dFromFeat(App::DocumentObject* obj) return result; } -bool ShapeExtractor::prefAdd2d(void) +bool ShapeExtractor::prefAdd2d() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); diff --git a/src/Mod/TechDraw/App/ShapeExtractor.h b/src/Mod/TechDraw/App/ShapeExtractor.h index e2c9462ac7..7c8025bc4b 100644 --- a/src/Mod/TechDraw/App/ShapeExtractor.h +++ b/src/Mod/TechDraw/App/ShapeExtractor.h @@ -50,7 +50,7 @@ public: static bool isPointType(App::DocumentObject* obj); static bool isDraftPoint(App::DocumentObject* obj); static Base::Vector3d getLocation3dFromFeat(App::DocumentObject* obj); - static bool prefAdd2d(void); + static bool prefAdd2d(); static TopoDS_Shape stripInfiniteShapes(TopoDS_Shape inShape); diff --git a/src/Mod/TechDraw/App/TechDrawExport.h b/src/Mod/TechDraw/App/TechDrawExport.h index 286690d85f..87c28b2089 100644 --- a/src/Mod/TechDraw/App/TechDrawExport.h +++ b/src/Mod/TechDraw/App/TechDrawExport.h @@ -19,7 +19,7 @@ * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ -//this file originally part of TechDraw workbench +//this file originally part of Drawing workbench //migrated to TechDraw workbench 2022-01-26 by Wandererfan diff --git a/src/Mod/TechDraw/CMakeLists.txt b/src/Mod/TechDraw/CMakeLists.txt index 1f0e7e90cc..47238635fb 100644 --- a/src/Mod/TechDraw/CMakeLists.txt +++ b/src/Mod/TechDraw/CMakeLists.txt @@ -141,13 +141,16 @@ endif(BUILD_GUI) #unit test files SET(TDTest_SRCS TDTest/__init__.py - TDTest/DHatchTest.py - TDTest/DProjGroupTest.py - TDTest/DVAnnoSymImageTest.py - TDTest/DVDimensionTest.py - TDTest/DVPartTest.py - TDTest/DVSectionTest.py - TDTest/DVBalloonTest.py + TDTest/DrawHatchTest.py + TDTest/DrawProjectionGroupTest.py + TDTest/DrawViewAnnotationTest.py + TDTest/DrawViewImageTest.py + TDTest/DrawViewSymbolTest.py + TDTest/DrawViewDimensionTest.py + TDTest/DrawViewPartTest.py + TDTest/DrawViewSectionTest.py + TDTest/DrawViewBalloonTest.py + TDTest/TechDrawTestUtilities.py ) SET(TDTestFile_SRCS diff --git a/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp b/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp index b4e32a7904..69de80a612 100644 --- a/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp +++ b/src/Mod/TechDraw/Gui/AppTechDrawGui.cpp @@ -70,12 +70,12 @@ // use a different name to CreateCommand() -void CreateTechDrawCommands(void); -void CreateTechDrawCommandsDims(void); -void CreateTechDrawCommandsDecorate(void); -void CreateTechDrawCommandsAnnotate(void); -void CreateTechDrawCommandsExtensionDims(void); -void CreateTechDrawCommandsExtensions(void); +void CreateTechDrawCommands(); +void CreateTechDrawCommandsDims(); +void CreateTechDrawCommandsDecorate(); +void CreateTechDrawCommandsAnnotate(); +void CreateTechDrawCommandsExtensionDims(); +void CreateTechDrawCommandsExtensions(); void loadTechDrawResource() { diff --git a/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp b/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp index 3e4b4d59a1..d5796672cf 100644 --- a/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp +++ b/src/Mod/TechDraw/Gui/AppTechDrawGuiPy.cpp @@ -82,10 +82,10 @@ public: ); initialize("This is a module for displaying drawings"); // register with Python } - virtual ~Module() {} + ~Module() override {} private: - virtual Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) + Py::Object invoke_method_varargs(void *method_def, const Py::Tuple &args) override { try { return Py::ExtensionModule::invoke_method_varargs(method_def, args); @@ -299,8 +299,7 @@ private: try { if (PyObject_TypeCheck(docObj, &(App::DocumentPy::Type))) { appDoc = static_cast(docObj)->getDocumentPtr(); - if ( (colorObj != nullptr) && - PyTuple_Check(colorObj)) { + if (colorObj && PyTuple_Check(colorObj)) { App::Color c = TechDraw::DrawUtil::pyTupleToColor(colorObj); bgColor = c.asValue(); } @@ -341,13 +340,13 @@ private: dynamic_cast(vp); if (vpdv) { qgiv = vpdv->getQView(); - if (qgiv != nullptr) { + if (qgiv) { Gui::PythonWrapper wrap; if (!wrap.loadGuiModule()) { throw Py::RuntimeError("Failed to load Python wrapper for Qt::Gui"); } QGraphicsItem* item = wrap.toQGraphicsItem(qgiPy); - if (item != nullptr) { + if (item) { qgiv->addArbitraryItem(item); } } @@ -384,13 +383,13 @@ private: dynamic_cast(vp); if (vpdv) { qgiv = vpdv->getQView(); - if (qgiv != nullptr) { + if (qgiv) { Gui::PythonWrapper wrap; if (!wrap.loadGuiModule()) { throw Py::RuntimeError("Failed to load Python wrapper for Qt::Gui"); } QGraphicsObject* item = wrap.toQGraphicsObject(qgiPy); - if (item != nullptr) { + if (item) { qgiv->addArbitraryItem(item); } } diff --git a/src/Mod/TechDraw/Gui/CMakeLists.txt b/src/Mod/TechDraw/Gui/CMakeLists.txt index 306111ac2c..d16c01d9df 100644 --- a/src/Mod/TechDraw/Gui/CMakeLists.txt +++ b/src/Mod/TechDraw/Gui/CMakeLists.txt @@ -23,6 +23,7 @@ include_directories( ${PYTHON_INCLUDE_DIRS} ${OCC_INCLUDE_DIR} ${ZLIB_INCLUDE_DIR} + ${XercesC_INCLUDE_DIRS} ) if(BUILD_QT5) @@ -82,6 +83,7 @@ set(TechDrawGui_UIC_SRCS TaskRichAnno.ui TaskSectionView.ui TaskWeldingSymbol.ui + TaskSurfaceFinishSymbols.ui SymbolChooser.ui TaskMoveView.ui TaskProjection.ui @@ -93,7 +95,7 @@ else() qt4_wrap_ui(TechDrawGui_UIC_HDRS ${TechDrawGui_UIC_SRCS}) endif() -SET(MRTE_SRCS +SET(MRTE_SRCS mrichtextedit.ui mrichtextedit.cpp mrichtextedit.h @@ -186,6 +188,9 @@ SET(TechDrawGui_SRCS TaskWeldingSymbol.ui TaskWeldingSymbol.cpp TaskWeldingSymbol.h + TaskSurfaceFinishSymbols.ui + TaskSurfaceFinishSymbols.cpp + TaskSurfaceFinishSymbols.h TaskSelectLineAttributes.ui TaskSelectLineAttributes.cpp TaskSelectLineAttributes.h @@ -385,7 +390,7 @@ SET(TechDrawGuiViewProvider_SRCS ViewProviderWeld.cpp ViewProviderWeld.h ViewProviderCosmeticExtension.cpp - ViewProviderCosmeticExtension.h + ViewProviderCosmeticExtension.h ) SET(TechDrawGuiTaskDlgs_SRCS @@ -404,6 +409,7 @@ SET(TechDrawGuiTaskDlgs_SRCS TaskLineDecor.ui TaskRestoreLines.ui TaskWeldingSymbol.ui + TaskSurfaceFinishSymbols.ui SymbolChooser.ui TaskActiveView.ui TaskDetail.ui diff --git a/src/Mod/TechDraw/Gui/Command.cpp b/src/Mod/TechDraw/Gui/Command.cpp index 38d284171b..e4d0e156c9 100644 --- a/src/Mod/TechDraw/Gui/Command.cpp +++ b/src/Mod/TechDraw/Gui/Command.cpp @@ -22,23 +22,20 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -#endif - -#include - +#include +#include +#include +#include #include +#include #include -#include +#include +#include #include - +#include +#include #include +#endif #include #include @@ -166,7 +163,7 @@ void CmdTechDrawPageDefault::activated(int iMsg) } } -bool CmdTechDrawPageDefault::isActive(void) +bool CmdTechDrawPageDefault::isActive() { return hasActiveDocument(); } @@ -246,7 +243,7 @@ void CmdTechDrawPageTemplate::activated(int iMsg) } } -bool CmdTechDrawPageTemplate::isActive(void) +bool CmdTechDrawPageTemplate::isActive() { return hasActiveDocument(); } @@ -281,7 +278,7 @@ void CmdTechDrawRedrawPage::activated(int iMsg) page->redrawCommand(); } -bool CmdTechDrawRedrawPage::isActive(void) +bool CmdTechDrawRedrawPage::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); @@ -363,7 +360,7 @@ void CmdTechDrawView::activated(int iMsg) //not a Link and not null. assume to be drawable. Undrawables will be // skipped later. shapes.push_back(obj); - if (partObj != nullptr) { + if (partObj) { continue; } //don't know if this works for an XLink @@ -399,7 +396,7 @@ void CmdTechDrawView::activated(int iMsg) } dvp->Source.setValues(shapes); dvp->XSource.setValues(xShapes); - if (faceName.size()) { + if (!faceName.empty()) { std::pair dirs = DrawGuiUtil::getProjDirFromFace(partObj, faceName); projDir = dirs.first; getDocument()->setStatus(App::Document::Status::SkipRecompute, true); @@ -427,7 +424,7 @@ void CmdTechDrawView::activated(int iMsg) commitCommand(); } -bool CmdTechDrawView::isActive(void) +bool CmdTechDrawView::isActive() { return DrawGuiUtil::needPage(this); } @@ -461,7 +458,7 @@ void CmdTechDrawActiveView::activated(int iMsg) Gui::Control().showDialog(new TaskDlgActiveView(page)); } -bool CmdTechDrawActiveView::isActive(void) +bool CmdTechDrawActiveView::isActive() { return DrawGuiUtil::needPage(this); } @@ -505,7 +502,7 @@ void CmdTechDrawSectionView::activated(int iMsg) commitCommand(); } -bool CmdTechDrawSectionView::isActive(void) +bool CmdTechDrawSectionView::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -554,7 +551,7 @@ void CmdTechDrawDetailView::activated(int iMsg) Gui::Control().showDialog(new TaskDlgDetail(dvp)); } -bool CmdTechDrawDetailView::isActive(void) +bool CmdTechDrawDetailView::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -642,7 +639,7 @@ void CmdTechDrawProjectionGroup::activated(int iMsg) //not a Link and not null. assume to be drawable. Undrawables will be // skipped later. shapes.push_back(obj); - if (partObj != nullptr) { + if (partObj) { continue; } for (auto& sub : sel.getSubNames()) { @@ -677,7 +674,7 @@ void CmdTechDrawProjectionGroup::activated(int iMsg) multiView->XSource.setValues(xShapes); doCommand(Doc, "App.activeDocument().%s.addProjection('Front')", multiViewName.c_str()); - if (faceName.size()) { + if (!faceName.empty()) { std::pair dirs = DrawGuiUtil::getProjDirFromFace(partObj, faceName); getDocument()->setStatus(App::Document::Status::SkipRecompute, true); doCommand(Doc, "App.activeDocument().%s.Anchor.Direction = FreeCAD.Vector(%.3f,%.3f,%.3f)", @@ -708,7 +705,7 @@ void CmdTechDrawProjectionGroup::activated(int iMsg) Gui::Control().showDialog(new TaskDlgProjGroup(multiView, true)); } -bool CmdTechDrawProjectionGroup::isActive(void) +bool CmdTechDrawProjectionGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool taskInProgress = false; @@ -779,7 +776,7 @@ bool CmdTechDrawProjectionGroup::isActive(void) //non-empty selection, no more than maxObjs selected and at least 1 DrawingPage exists bool _checkSelectionBalloon(Gui::Command* cmd, unsigned maxObjs) { std::vector selection = cmd->getSelection().getSelectionEx(); - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Incorrect selection"), QObject::tr("Select an object first")); return false; @@ -876,7 +873,7 @@ void CmdTechDrawBalloon::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); auto objFeat(dynamic_cast(selection[0].getObject())); - if (objFeat == nullptr) { + if (!objFeat) { return; } @@ -890,8 +887,8 @@ void CmdTechDrawBalloon::activated(int iMsg) ViewProviderViewPart* partVP = dynamic_cast(guiDoc->getViewProvider(objFeat)); if (pageVP && partVP) { - QGVPage* viewPage = pageVP->getGraphicsView(); - QGSPage* scenePage = pageVP->getGraphicsScene(); + QGVPage* viewPage = pageVP->getQGVPage(); + QGSPage* scenePage = pageVP->getQGSPage(); if (viewPage) { viewPage->startBalloonPlacing(); @@ -904,7 +901,7 @@ void CmdTechDrawBalloon::activated(int iMsg) } } -bool CmdTechDrawBalloon::isActive(void) +bool CmdTechDrawBalloon::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -946,7 +943,7 @@ void CmdTechDrawClipGroup::activated(int iMsg) commitCommand(); } -bool CmdTechDrawClipGroup::isActive(void) +bool CmdTechDrawClipGroup::isActive() { return DrawGuiUtil::needPage(this); } @@ -1021,7 +1018,7 @@ void CmdTechDrawClipGroupAdd::activated(int iMsg) commitCommand(); } -bool CmdTechDrawClipGroupAdd::isActive(void) +bool CmdTechDrawClipGroupAdd::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveClip = false; @@ -1094,7 +1091,7 @@ void CmdTechDrawClipGroupRemove::activated(int iMsg) commitCommand(); } -bool CmdTechDrawClipGroupRemove::isActive(void) +bool CmdTechDrawClipGroupRemove::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveClip = false; @@ -1140,8 +1137,8 @@ void CmdTechDrawSymbol::activated(int iMsg) QString filename = Gui::FileDialog::getOpenFileName(Gui::getMainWindow(), QObject::tr("Choose an SVG file to open"), QString(), QString::fromLatin1("%1 (*.svg *.svgz);;%2 (*.*)"). - arg(QObject::tr("Scalable Vector Graphic")). - arg(QObject::tr("All Files"))); + arg(QObject::tr("Scalable Vector Graphic"), + QObject::tr("All Files"))); if (!filename.isEmpty()) { @@ -1159,7 +1156,7 @@ void CmdTechDrawSymbol::activated(int iMsg) } } -bool CmdTechDrawSymbol::isActive(void) +bool CmdTechDrawSymbol::isActive() { return DrawGuiUtil::needPage(this); } @@ -1217,7 +1214,7 @@ void CmdTechDrawDraftView::activated(int iMsg) } } -bool CmdTechDrawDraftView::isActive(void) +bool CmdTechDrawDraftView::isActive() { return DrawGuiUtil::needPage(this); } @@ -1266,7 +1263,7 @@ void CmdTechDrawArchView::activated(int iMsg) return; } - if (archObject == nullptr) { + if (!archObject) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("No Arch Sections in selection.")); return; @@ -1282,7 +1279,7 @@ void CmdTechDrawArchView::activated(int iMsg) commitCommand(); } -bool CmdTechDrawArchView::isActive(void) +bool CmdTechDrawArchView::isActive() { return DrawGuiUtil::needPage(this); } @@ -1331,7 +1328,7 @@ void CmdTechDrawSpreadsheetView::activated(int iMsg) commitCommand(); } -bool CmdTechDrawSpreadsheetView::isActive(void) +bool CmdTechDrawSpreadsheetView::isActive() { //need a Page and a SpreadSheet::Sheet bool havePage = DrawGuiUtil::needPage(this); @@ -1387,7 +1384,7 @@ void CmdTechDrawExportPageSVG::activated(int iMsg) } } -bool CmdTechDrawExportPageSVG::isActive(void) +bool CmdTechDrawExportPageSVG::isActive() { return DrawGuiUtil::needPage(this); } @@ -1453,7 +1450,7 @@ void CmdTechDrawExportPageDXF::activated(int iMsg) } -bool CmdTechDrawExportPageDXF::isActive(void) +bool CmdTechDrawExportPageDXF::isActive() { return DrawGuiUtil::needPage(this); } @@ -1485,12 +1482,12 @@ void CmdTechDrawProjectShape::activated(int iMsg) } } -bool CmdTechDrawProjectShape::isActive(void) +bool CmdTechDrawProjectShape::isActive() { return true; } -void CreateTechDrawCommands(void) +void CreateTechDrawCommands() { Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/TechDraw/Gui/CommandAnnotate.cpp b/src/Mod/TechDraw/Gui/CommandAnnotate.cpp index bef6ed17c3..6a0f42d588 100644 --- a/src/Mod/TechDraw/Gui/CommandAnnotate.cpp +++ b/src/Mod/TechDraw/Gui/CommandAnnotate.cpp @@ -72,6 +72,7 @@ #include "ViewProviderViewPart.h" #include "QGIView.h" #include "QGVPage.h" +#include "TaskSurfaceFinishSymbols.h" using namespace TechDrawGui; using namespace TechDraw; @@ -115,7 +116,7 @@ void CmdTechDrawLeaderLine::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -130,7 +131,7 @@ void CmdTechDrawLeaderLine::activated(int iMsg) TechDraw::DrawView* baseFeat = nullptr; if (!selection.empty()) { baseFeat = dynamic_cast(selection[0].getObject()); - if( baseFeat == nullptr ) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("Can not attach leader. No base View selected.")); return; @@ -147,7 +148,7 @@ void CmdTechDrawLeaderLine::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawLeaderLine::isActive(void) +bool CmdTechDrawLeaderLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); @@ -176,7 +177,7 @@ void CmdTechDrawRichTextAnnotation::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -199,7 +200,7 @@ void CmdTechDrawRichTextAnnotation::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawRichTextAnnotation::isActive(void) +bool CmdTechDrawRichTextAnnotation::isActive() { bool havePage = DrawGuiUtil::needPage(this); return havePage; @@ -228,7 +229,7 @@ void CmdTechDrawCosmeticVertexGroup::activated(int iMsg) { // Base::Console().Message("CMD::CosmeticVertexGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -253,7 +254,7 @@ void CmdTechDrawCosmeticVertexGroup::activated(int iMsg) Gui::Selection().clearSelection(); } -Gui::Action * CmdTechDrawCosmeticVertexGroup::createAction(void) +Gui::Action * CmdTechDrawCosmeticVertexGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -305,7 +306,7 @@ void CmdTechDrawCosmeticVertexGroup::languageChange() arc3->setStatusTip(arc3->toolTip()); } -bool CmdTechDrawCosmeticVertexGroup::isActive(void) +bool CmdTechDrawCosmeticVertexGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -347,10 +348,8 @@ void execMidpoints(Gui::Command* cmd) TechDraw::DrawViewPart * dvp = nullptr; std::vector selectedEdges = getSelectedSubElements(cmd, dvp, "Edge"); - if ( (dvp == nullptr) || - (selectedEdges.empty()) ) { + if (!dvp || selectedEdges.empty()) return; - } Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add Midpoint Vertices")); @@ -375,10 +374,8 @@ void execQuadrants(Gui::Command* cmd) TechDraw::DrawViewPart* dvp = nullptr; std::vector selectedEdges = getSelectedSubElements(cmd, dvp, "Edge"); - if ( (dvp == nullptr) || - (selectedEdges.empty()) ) { + if (!dvp || selectedEdges.empty()) return; - } Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Add Quadrant Vertices")); @@ -417,7 +414,7 @@ void CmdTechDrawCosmeticVertex::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -438,7 +435,7 @@ void CmdTechDrawCosmeticVertex::activated(int iMsg) TechDraw::DrawViewPart* baseFeat = nullptr; baseFeat = dynamic_cast((*shapes.begin())); - if (baseFeat == nullptr) { + if (!baseFeat) { Base::Console().Message("CMD::CosmeticVertex - 1st shape is not DVP. WTF?\n"); return; } @@ -449,7 +446,7 @@ void CmdTechDrawCosmeticVertex::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawCosmeticVertex::isActive(void) +bool CmdTechDrawCosmeticVertex::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -478,7 +475,7 @@ void CmdTechDrawMidpoints::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -488,7 +485,7 @@ void CmdTechDrawMidpoints::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawMidpoints::isActive(void) +bool CmdTechDrawMidpoints::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -517,7 +514,7 @@ void CmdTechDrawQuadrants::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -527,7 +524,7 @@ void CmdTechDrawQuadrants::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawQuadrants::isActive(void) +bool CmdTechDrawQuadrants::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -569,7 +566,7 @@ void CmdTechDrawAnnotation::activated(int iMsg) commitCommand(); } -bool CmdTechDrawAnnotation::isActive(void) +bool CmdTechDrawAnnotation::isActive() { return DrawGuiUtil::needPage(this); } @@ -596,7 +593,7 @@ void CmdTechDrawCenterLineGroup::activated(int iMsg) { // Base::Console().Message("CMD::CenterLineGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -619,7 +616,7 @@ void CmdTechDrawCenterLineGroup::activated(int iMsg) }; } -Gui::Action * CmdTechDrawCenterLineGroup::createAction(void) +Gui::Action * CmdTechDrawCenterLineGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -671,7 +668,7 @@ void CmdTechDrawCenterLineGroup::languageChange() arc3->setStatusTip(arc3->toolTip()); } -bool CmdTechDrawCenterLineGroup::isActive(void) +bool CmdTechDrawCenterLineGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -700,7 +697,7 @@ void CmdTechDrawFaceCenterLine::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -709,7 +706,7 @@ void CmdTechDrawFaceCenterLine::activated(int iMsg) execCenterLine(this); } -bool CmdTechDrawFaceCenterLine::isActive(void) +bool CmdTechDrawFaceCenterLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); @@ -724,18 +721,19 @@ void execCenterLine(Gui::Command* cmd) } std::vector selection = cmd->getSelection().getSelectionEx(); - TechDraw::DrawViewPart* baseFeat = nullptr; + TechDraw::DrawViewPart *baseFeat = nullptr; if (!selection.empty()) { - baseFeat = dynamic_cast(selection[0].getObject()); - if( baseFeat == nullptr ) { + baseFeat = dynamic_cast(selection[0].getObject()); + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("No base View in Selection.")); return; } - } else { - QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), - QObject::tr("You must select a base View for the line.")); - return; + } + else { + QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), + QObject::tr("You must select a base View for the line.")); + return; } std::vector subNames; @@ -775,7 +773,7 @@ void execCenterLine(Gui::Command* cmd) return; } else { TechDraw::CenterLine* cl = baseFeat->getCenterLineBySelection(edgeNames.front()); - if (cl == nullptr) { + if (!cl) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("Selection is not a CenterLine.")); return; @@ -810,7 +808,7 @@ void CmdTechDraw2LineCenterLine::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -819,7 +817,7 @@ void CmdTechDraw2LineCenterLine::activated(int iMsg) exec2LineCenterLine(this); } -bool CmdTechDraw2LineCenterLine::isActive(void) +bool CmdTechDraw2LineCenterLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -835,8 +833,7 @@ void exec2LineCenterLine(Gui::Command* cmd) TechDraw::DrawViewPart* dvp = nullptr; std::vector selectedEdges = getSelectedSubElements(cmd, dvp, "Edge"); - if ( (dvp == nullptr) || - (selectedEdges.empty()) ) { + if (!dvp || selectedEdges.empty()) { return; } @@ -847,7 +844,7 @@ void exec2LineCenterLine(Gui::Command* cmd) false)); } else if (selectedEdges.size() == 1) { TechDraw::CenterLine* cl = dvp->getCenterLineBySelection(selectedEdges.front()); - if (cl == nullptr) { + if (!cl) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("Selection is not a CenterLine.")); return; @@ -886,7 +883,7 @@ void CmdTechDraw2PointCenterLine::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -897,7 +894,7 @@ void CmdTechDraw2PointCenterLine::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDraw2PointCenterLine::isActive(void) +bool CmdTechDraw2PointCenterLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -920,7 +917,7 @@ void exec2PointCenterLine(Gui::Command* cmd) } baseFeat = dynamic_cast(selection[0].getObject()); - if( baseFeat == nullptr ) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("No base View in Selection.")); return; @@ -959,7 +956,7 @@ void exec2PointCenterLine(Gui::Command* cmd) false)); } else if (!edgeNames.empty() && (edgeNames.size() == 1)) { TechDraw::CenterLine* cl = baseFeat->getCenterLineBySelection(edgeNames.front()); - if (cl == nullptr) { + if (!cl) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("Selection is not a CenterLine.")); return; @@ -999,7 +996,7 @@ void CmdTechDraw2PointCosmeticLine::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1011,7 +1008,7 @@ void CmdTechDraw2PointCosmeticLine::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDraw2PointCosmeticLine::isActive(void) +bool CmdTechDraw2PointCosmeticLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1052,7 +1049,7 @@ void execLine2Points(Gui::Command* cmd) } } - if (baseFeat == nullptr) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("You must select a base View for the line.")); return; @@ -1080,7 +1077,7 @@ void execLine2Points(Gui::Command* cmd) //check if editing existing edge if (!edgeNames.empty() && (edgeNames.size() == 1)) { TechDraw::CosmeticEdge* ce = baseFeat->getCosmeticEdgeBySelection(edgeNames.front()); - if (ce == nullptr) { + if (!ce) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("Selection is not a Cosmetic Line.")); return; @@ -1154,7 +1151,7 @@ void CmdTechDrawCosmeticEraser::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1190,7 +1187,7 @@ void CmdTechDrawCosmeticEraser::activated(int iMsg) objFeat = static_cast ((*itSel).getObject()); subNames = (*itSel).getSubNames(); } - if (objFeat == nullptr) { + if (!objFeat) { break; } std::vector cv2Delete; @@ -1201,8 +1198,7 @@ void CmdTechDrawCosmeticEraser::activated(int iMsg) std::string geomType = TechDraw::DrawUtil::getGeomTypeFromName(s); if (geomType == "Edge") { TechDraw::BaseGeomPtr bg = objFeat->getGeomByIndex(idx); - if ((bg != nullptr) && - (bg->cosmetic) ) { + if (bg && bg->cosmetic) { int source = bg->source(); std::string tag = bg->getCosmeticTag(); if (source == COSMETICEDGE) { @@ -1216,14 +1212,12 @@ void CmdTechDrawCosmeticEraser::activated(int iMsg) } } else if (geomType == "Vertex") { TechDraw::VertexPtr tdv = objFeat->getProjVertexByIndex(idx); - if (tdv == nullptr) { + if (!tdv) Base::Console().Message("CMD::eraser - geom: %d not found!\n", idx); - } std::string delTag = tdv->cosmeticTag; - if (delTag.empty()) { + if (delTag.empty()) 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"), @@ -1246,7 +1240,7 @@ void CmdTechDrawCosmeticEraser::activated(int iMsg) } } -bool CmdTechDrawCosmeticEraser::isActive(void) +bool CmdTechDrawCosmeticEraser::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1276,7 +1270,7 @@ void CmdTechDrawDecorateLine::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1296,7 +1290,7 @@ void CmdTechDrawDecorateLine::activated(int iMsg) } baseFeat = dynamic_cast(selection[0].getObject()); - if( baseFeat == nullptr ) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("No View in Selection.")); return; @@ -1325,7 +1319,7 @@ void CmdTechDrawDecorateLine::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawDecorateLine::isActive(void) +bool CmdTechDrawDecorateLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1354,7 +1348,7 @@ void CmdTechDrawShowAll::activated(int iMsg) { Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1374,7 +1368,7 @@ void CmdTechDrawShowAll::activated(int iMsg) } baseFeat = dynamic_cast(selection[0].getObject()); - if (baseFeat == nullptr) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong selection"), QObject::tr("No Part Views in this selection")); return; @@ -1382,7 +1376,7 @@ void CmdTechDrawShowAll::activated(int iMsg) Gui::ViewProvider* vp = QGIView::getViewProvider(baseFeat); auto partVP = dynamic_cast(vp); - if ( partVP != nullptr ) { + if (partVP) { bool state = partVP->ShowAllEdges.getValue(); state = !state; partVP->ShowAllEdges.setValue(state); @@ -1390,7 +1384,7 @@ void CmdTechDrawShowAll::activated(int iMsg) } } -bool CmdTechDrawShowAll::isActive(void) +bool CmdTechDrawShowAll::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1420,7 +1414,7 @@ void CmdTechDrawWeldSymbol::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1454,15 +1448,59 @@ void CmdTechDrawWeldSymbol::activated(int iMsg) Gui::Selection().clearSelection(); } -bool CmdTechDrawWeldSymbol::isActive(void) +bool CmdTechDrawWeldSymbol::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); return (havePage && haveView); } +//=========================================================================== +// TechDraw_SurfaceFinishSymbols +//=========================================================================== -void CreateTechDrawCommandsAnnotate(void) +DEF_STD_CMD_A(CmdTechDrawSurfaceFinishSymbols) + +CmdTechDrawSurfaceFinishSymbols::CmdTechDrawSurfaceFinishSymbols() + : Command("TechDraw_SurfaceFinishSymbols") +{ + sAppModule = "TechDraw"; + sGroup = QT_TR_NOOP("TechDraw"); + sMenuText = QT_TR_NOOP("Create a Surface Finish Symbol"); + sToolTipText = QT_TR_NOOP("Select a view
\ + - click this button
\ + - select surface finish symbol attributes in opened panel"); + sWhatsThis = "TechDraw_SurfaceFinishSymbols"; + sStatusTip = sToolTipText; + sPixmap = "actions/TechDraw_SurfaceFinishSymbols"; +} + +void CmdTechDrawSurfaceFinishSymbols::activated(int iMsg) +{ + Q_UNUSED(iMsg); + std::vector selection = this->getSelection().getSelectionEx(); + if (selection.empty()) + { + QMessageBox::warning(Gui::getMainWindow(),QObject::tr("SurfaceFinishSymbols"),QObject::tr("Selection is empty")); + return; + } + TechDraw::DrawViewPart* objFeat = dynamic_cast (selection[0].getObject()); + if(!objFeat) + { + QMessageBox::warning(Gui::getMainWindow(),QObject::tr("SurfaceFinishSymbols"),QObject::tr("No object selected")); + return; + } + Gui::Control().showDialog(new TechDrawGui::TaskDlgSurfaceFinishSymbols(objFeat)); +} + +bool CmdTechDrawSurfaceFinishSymbols::isActive() +{ + bool havePage = DrawGuiUtil::needPage(this); + bool haveView = DrawGuiUtil::needView(this); + return havePage && haveView; +} + +void CreateTechDrawCommandsAnnotate() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); @@ -1482,6 +1520,7 @@ void CreateTechDrawCommandsAnnotate(void) rcCmdMgr.addCommand(new CmdTechDrawDecorateLine()); rcCmdMgr.addCommand(new CmdTechDrawShowAll()); rcCmdMgr.addCommand(new CmdTechDrawWeldSymbol()); + rcCmdMgr.addCommand(new CmdTechDrawSurfaceFinishSymbols()); } //=========================================================================== @@ -1505,7 +1544,7 @@ std::vector getSelectedSubElements(Gui::Command* cmd, break; } } - if (dvp == nullptr) { + if (!dvp) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Wrong Selection"), QObject::tr("No Part View in Selection")); return selectedSubs; diff --git a/src/Mod/TechDraw/Gui/CommandCreateDims.cpp b/src/Mod/TechDraw/Gui/CommandCreateDims.cpp index cb48e4e29f..b0b569948b 100644 --- a/src/Mod/TechDraw/Gui/CommandCreateDims.cpp +++ b/src/Mod/TechDraw/Gui/CommandCreateDims.cpp @@ -24,6 +24,7 @@ #ifndef _PreComp_ # include # include +# include # include # include # include @@ -31,7 +32,6 @@ # include #endif //#ifndef _PreComp_ -#include #include #include @@ -233,7 +233,7 @@ void CmdTechDrawDimension::activated(int iMsg) // objFeat->X.setValue(x); } -bool CmdTechDrawDimension::isActive(void) +bool CmdTechDrawDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -349,7 +349,7 @@ void CmdTechDrawRadiusDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDrawRadiusDimension::isActive(void) +bool CmdTechDrawRadiusDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -460,7 +460,7 @@ void CmdTechDrawDiameterDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDrawDiameterDimension::isActive(void) +bool CmdTechDrawDiameterDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -564,7 +564,7 @@ void CmdTechDrawLengthDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDrawLengthDimension::isActive(void) +bool CmdTechDrawLengthDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -669,7 +669,7 @@ void CmdTechDrawHorizontalDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDrawHorizontalDimension::isActive(void) +bool CmdTechDrawHorizontalDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -773,7 +773,7 @@ void CmdTechDrawVerticalDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDrawVerticalDimension::isActive(void) +bool CmdTechDrawVerticalDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -861,7 +861,7 @@ void CmdTechDrawAngleDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDrawAngleDimension::isActive(void) +bool CmdTechDrawAngleDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -950,7 +950,7 @@ void CmdTechDraw3PtAngleDimension::activated(int iMsg) objFeat->X.setValue(x); } -bool CmdTechDraw3PtAngleDimension::isActive(void) +bool CmdTechDraw3PtAngleDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1026,7 +1026,7 @@ void CmdTechDrawLinkDimension::activated(int iMsg) page->getDocument()->recompute(); //still need to recompute in Gui. why? } -bool CmdTechDrawLinkDimension::isActive(void) +bool CmdTechDrawLinkDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1059,7 +1059,7 @@ void CmdTechDrawExtentGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtentGrp - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1079,7 +1079,7 @@ void CmdTechDrawExtentGroup::activated(int iMsg) }; } -Gui::Action * CmdTechDrawExtentGroup::createAction(void) +Gui::Action * CmdTechDrawExtentGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1123,7 +1123,7 @@ void CmdTechDrawExtentGroup::languageChange() arc2->setStatusTip(arc2->toolTip()); } -bool CmdTechDrawExtentGroup::isActive(void) +bool CmdTechDrawExtentGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); @@ -1153,7 +1153,7 @@ void CmdTechDrawHorizontalExtentDimension::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1162,7 +1162,7 @@ void CmdTechDrawHorizontalExtentDimension::activated(int iMsg) execHExtent(this); } -bool CmdTechDrawHorizontalExtentDimension::isActive(void) +bool CmdTechDrawHorizontalExtentDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); @@ -1185,7 +1185,7 @@ void execHExtent(Gui::Command* cmd) } baseFeat = dynamic_cast(selection[0].getObject()); - if( baseFeat == nullptr ) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Selection Error"), QObject::tr("No base View in Selection.")); return; @@ -1240,7 +1240,7 @@ void CmdTechDrawVerticalExtentDimension::activated(int iMsg) Q_UNUSED(iMsg); Gui::TaskView::TaskDialog *dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1249,7 +1249,7 @@ void CmdTechDrawVerticalExtentDimension::activated(int iMsg) execVExtent(this); } -bool CmdTechDrawVerticalExtentDimension::isActive(void) +bool CmdTechDrawVerticalExtentDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, false); @@ -1273,7 +1273,7 @@ void execVExtent(Gui::Command* cmd) baseFeat = dynamic_cast(selection[0].getObject()); - if( baseFeat == nullptr ) { + if (!baseFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Selection Error"), QObject::tr("No base View in Selection.")); return; @@ -1347,8 +1347,8 @@ void CmdTechDrawLandmarkDimension::activated(int iMsg) std::vector refs2d; std::vector subs; - subs.push_back("Vertex1"); - subs.push_back("Vertex1"); + subs.emplace_back("Vertex1"); + subs.emplace_back("Vertex1"); TechDraw::DrawPage* page = dvp->findParentPage(); std::string parentName = dvp->getNameInDocument(); std::string PageName = page->getNameInDocument(); @@ -1390,7 +1390,7 @@ void CmdTechDrawLandmarkDimension::activated(int iMsg) dvp->X.setValue(x); } -bool CmdTechDrawLandmarkDimension::isActive(void) +bool CmdTechDrawLandmarkDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1399,7 +1399,7 @@ bool CmdTechDrawLandmarkDimension::isActive(void) //------------------------------------------------------------------------------ -void CreateTechDrawCommandsDims(void) +void CreateTechDrawCommandsDims() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); @@ -1426,7 +1426,7 @@ void CreateTechDrawCommandsDims(void) //non-empty selection, no more than maxObjs selected and at least 1 DrawingPage exists bool _checkSelection(Gui::Command* cmd, unsigned maxObjs) { std::vector selection = cmd->getSelection().getSelectionEx(); - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Incorrect selection"), QObject::tr("Select an object first")); return false; @@ -1481,9 +1481,8 @@ int _isValidSingleEdge(Gui::Command* cmd) { auto selection( cmd->getSelection().getSelectionEx() ); auto objFeat( dynamic_cast(selection[0].getObject()) ); - if( objFeat == nullptr ) { + if (!objFeat) return isInvalid; - } const std::vector SubNames = selection[0].getSubNames(); if (SubNames.size() != 1 || @@ -1579,7 +1578,7 @@ int _isValidEdgeToEdge(Gui::Command* cmd) { TechDraw::BaseGeomPtr geom0 = objFeat0->getGeomByIndex(GeoId0); TechDraw::BaseGeomPtr geom1 = objFeat0->getGeomByIndex(GeoId1); - if ((geom0 == nullptr) || (geom1 == nullptr)) { // missing gometry + if (!geom0 || !geom1) { // missing gometry Base::Console().Error("Logic Error: no geometry for GeoId: %d or GeoId: %d\n",GeoId0,GeoId1); return isInvalid; } @@ -1634,7 +1633,7 @@ bool _isValidVertexToEdge(Gui::Command* cmd) { } e = objFeat0->getGeomByIndex(eId); v = objFeat0->getProjVertexByIndex(vId); - if ((e == nullptr) || (v == nullptr)) { + if (!e || !v) { Base::Console().Error("Logic Error: no geometry for GeoId: %d or GeoId: %d\n",eId,vId); return false; } diff --git a/src/Mod/TechDraw/Gui/CommandDecorate.cpp b/src/Mod/TechDraw/Gui/CommandDecorate.cpp index 1672bb77f4..a650df65e8 100644 --- a/src/Mod/TechDraw/Gui/CommandDecorate.cpp +++ b/src/Mod/TechDraw/Gui/CommandDecorate.cpp @@ -23,6 +23,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ # include +# include # include # include # include @@ -30,7 +31,6 @@ # include #endif //#ifndef _PreComp_ -#include #include #include @@ -103,7 +103,7 @@ void CmdTechDrawHatch::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); auto partFeat( dynamic_cast(selection[0].getObject()) ); - if( partFeat == nullptr ) { + if (!partFeat) { return; } const std::vector &subNames = selection[0].getSubNames(); @@ -167,7 +167,7 @@ void CmdTechDrawHatch::activated(int iMsg) getDocument()->recompute(); } -bool CmdTechDrawHatch::isActive(void) +bool CmdTechDrawHatch::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -201,7 +201,7 @@ void CmdTechDrawGeometricHatch::activated(int iMsg) std::vector selection = getSelection().getSelectionEx(); auto objFeat( dynamic_cast(selection[0].getObject()) ); - if( objFeat == nullptr ) { + if (!objFeat) { return; } const std::vector &subNames = selection[0].getSubNames(); @@ -236,7 +236,7 @@ void CmdTechDrawGeometricHatch::activated(int iMsg) getDocument()->recompute(); } -bool CmdTechDrawGeometricHatch::isActive(void) +bool CmdTechDrawGeometricHatch::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -290,7 +290,7 @@ void CmdTechDrawImage::activated(int iMsg) commitCommand(); } -bool CmdTechDrawImage::isActive(void) +bool CmdTechDrawImage::isActive() { return DrawGuiUtil::needPage(this); } @@ -326,7 +326,7 @@ void CmdTechDrawToggleFrame::activated(int iMsg) Gui::ViewProvider* vp = activeGui->getViewProvider(page); ViewProviderPage* vpp = dynamic_cast(vp); - if (vpp == nullptr) { + if (!vpp) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("No TechDraw Page"), QObject::tr("Need a TechDraw Page for this command")); return; @@ -334,7 +334,7 @@ void CmdTechDrawToggleFrame::activated(int iMsg) vpp->toggleFrameState(); } -bool CmdTechDrawToggleFrame::isActive(void) +bool CmdTechDrawToggleFrame::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this,false); @@ -342,7 +342,7 @@ bool CmdTechDrawToggleFrame::isActive(void) } -void CreateTechDrawCommandsDecorate(void) +void CreateTechDrawCommandsDecorate() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); @@ -360,7 +360,7 @@ void CreateTechDrawCommandsDecorate(void) bool _checkSelectionHatch(Gui::Command* cmd) { std::vector selection = cmd->getSelection().getSelectionEx(); - if (selection.size() == 0) { + if (selection.empty()) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Incorrect selection"), QObject::tr("Select a Face first")); return false; diff --git a/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp b/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp index f31e97ab5c..f19479ed9f 100644 --- a/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp +++ b/src/Mod/TechDraw/Gui/CommandExtensionDims.cpp @@ -140,7 +140,7 @@ void CmdTechDrawExtensionInsertDiameter::activated(int iMsg) execInsertPrefixChar(this, "⌀"); } -bool CmdTechDrawExtensionInsertDiameter::isActive(void) +bool CmdTechDrawExtensionInsertDiameter::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -173,7 +173,7 @@ void CmdTechDrawExtensionInsertSquare::activated(int iMsg) execInsertPrefixChar(this, "□"); //□ white square U+25A1 } -bool CmdTechDrawExtensionInsertSquare::isActive(void) +bool CmdTechDrawExtensionInsertSquare::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -231,7 +231,7 @@ void CmdTechDrawExtensionRemovePrefixChar::activated(int iMsg) execRemovePrefixChar(this); } -bool CmdTechDrawExtensionRemovePrefixChar::isActive(void) +bool CmdTechDrawExtensionRemovePrefixChar::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -261,7 +261,7 @@ void CmdTechDrawExtensionInsertPrefixGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionLinePPGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -284,7 +284,7 @@ void CmdTechDrawExtensionInsertPrefixGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionInsertPrefixGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionInsertPrefixGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -345,7 +345,7 @@ void CmdTechDrawExtensionInsertPrefixGroup::languageChange() arc3->setStatusTip(arc3->text()); } -bool CmdTechDrawExtensionInsertPrefixGroup::isActive(void) +bool CmdTechDrawExtensionInsertPrefixGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -407,7 +407,7 @@ void CmdTechDrawExtensionIncreaseDecimal::activated(int iMsg) execIncreaseDecreaseDecimal(this, 1); } -bool CmdTechDrawExtensionIncreaseDecimal::isActive(void) +bool CmdTechDrawExtensionIncreaseDecimal::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -440,7 +440,7 @@ void CmdTechDrawExtensionDecreaseDecimal::activated(int iMsg) execIncreaseDecreaseDecimal(this, -1); } -bool CmdTechDrawExtensionDecreaseDecimal::isActive(void) +bool CmdTechDrawExtensionDecreaseDecimal::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -470,7 +470,7 @@ void CmdTechDrawExtensionIncreaseDecreaseGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionIncreaseDecreaseGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -490,7 +490,7 @@ void CmdTechDrawExtensionIncreaseDecreaseGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionIncreaseDecreaseGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionIncreaseDecreaseGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -540,7 +540,7 @@ void CmdTechDrawExtensionIncreaseDecreaseGroup::languageChange() arc2->setStatusTip(arc2->text()); } -bool CmdTechDrawExtensionIncreaseDecreaseGroup::isActive(void) +bool CmdTechDrawExtensionIncreaseDecreaseGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -601,7 +601,7 @@ void CmdTechDrawExtensionPosHorizChainDimension::activated(int iMsg) execPosHorizChainDimension(this); } -bool CmdTechDrawExtensionPosHorizChainDimension::isActive(void) +bool CmdTechDrawExtensionPosHorizChainDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -663,7 +663,7 @@ void CmdTechDrawExtensionPosVertChainDimension::activated(int iMsg) execPosVertChainDimension(this); } -bool CmdTechDrawExtensionPosVertChainDimension::isActive(void) +bool CmdTechDrawExtensionPosVertChainDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -731,7 +731,7 @@ void CmdTechDrawExtensionPosObliqueChainDimension::activated(int iMsg) ///Base::Console().Message("TechDraw_ExtensionPosObliqueChainDimension started\n"); } -bool CmdTechDrawExtensionPosObliqueChainDimension::isActive(void) +bool CmdTechDrawExtensionPosObliqueChainDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -762,7 +762,7 @@ void CmdTechDrawExtensionPosChainDimensionGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionPosChainDimensionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -785,7 +785,7 @@ void CmdTechDrawExtensionPosChainDimensionGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionPosChainDimensionGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionPosChainDimensionGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -849,7 +849,7 @@ void CmdTechDrawExtensionPosChainDimensionGroup::languageChange() arc3->setStatusTip(arc3->text()); } -bool CmdTechDrawExtensionPosChainDimensionGroup::isActive(void) +bool CmdTechDrawExtensionPosChainDimensionGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -915,7 +915,7 @@ void CmdTechDrawExtensionCascadeHorizDimension::activated(int iMsg) execCascadeHorizDimension(this); } -bool CmdTechDrawExtensionCascadeHorizDimension::isActive(void) +bool CmdTechDrawExtensionCascadeHorizDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -982,7 +982,7 @@ void CmdTechDrawExtensionCascadeVertDimension::activated(int iMsg) execCascadeVertDimension(this); } -bool CmdTechDrawExtensionCascadeVertDimension::isActive(void) +bool CmdTechDrawExtensionCascadeVertDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1058,7 +1058,7 @@ void CmdTechDrawExtensionCascadeObliqueDimension::activated(int iMsg) ///Base::Console().Message("TechDraw_ExtensionPosObliqueChainDimension started\n"); } -bool CmdTechDrawExtensionCascadeObliqueDimension::isActive(void) +bool CmdTechDrawExtensionCascadeObliqueDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1090,7 +1090,7 @@ void CmdTechDrawExtensionCascadeDimensionGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1113,7 +1113,7 @@ void CmdTechDrawExtensionCascadeDimensionGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionCascadeDimensionGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionCascadeDimensionGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1180,7 +1180,7 @@ void CmdTechDrawExtensionCascadeDimensionGroup::languageChange() arc3->setStatusTip(arc3->text()); } -bool CmdTechDrawExtensionCascadeDimensionGroup::isActive(void) +bool CmdTechDrawExtensionCascadeDimensionGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1244,7 +1244,7 @@ void CmdTechDrawExtensionCreateHorizChainDimension::activated(int iMsg) //execSortieren(this); } -bool CmdTechDrawExtensionCreateHorizChainDimension::isActive(void) +bool CmdTechDrawExtensionCreateHorizChainDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1308,7 +1308,7 @@ void CmdTechDrawExtensionCreateVertChainDimension::activated(int iMsg) execCreateVertChainDimension(this); } -bool CmdTechDrawExtensionCreateVertChainDimension::isActive(void) +bool CmdTechDrawExtensionCreateVertChainDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1399,7 +1399,7 @@ void CmdTechDrawExtensionCreateObliqueChainDimension::activated(int iMsg) execCreateObliqueChainDimension(this); } -bool CmdTechDrawExtensionCreateObliqueChainDimension::isActive(void) +bool CmdTechDrawExtensionCreateObliqueChainDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1429,7 +1429,7 @@ void CmdTechDrawExtensionCreateChainDimensionGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1452,7 +1452,7 @@ void CmdTechDrawExtensionCreateChainDimensionGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionCreateChainDimensionGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionCreateChainDimensionGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1514,7 +1514,7 @@ void CmdTechDrawExtensionCreateChainDimensionGroup::languageChange() arc3->setStatusTip(arc3->text()); } -bool CmdTechDrawExtensionCreateChainDimensionGroup::isActive(void) +bool CmdTechDrawExtensionCreateChainDimensionGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1585,7 +1585,7 @@ void CmdTechDrawExtensionCreateHorizCoordDimension::activated(int iMsg) execCreateHorizCoordDimension(this); } -bool CmdTechDrawExtensionCreateHorizCoordDimension::isActive(void) +bool CmdTechDrawExtensionCreateHorizCoordDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1657,7 +1657,7 @@ void CmdTechDrawExtensionCreateVertCoordDimension::activated(int iMsg) execCreateVertCoordDimension(this); } -bool CmdTechDrawExtensionCreateVertCoordDimension::isActive(void) +bool CmdTechDrawExtensionCreateVertCoordDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1755,7 +1755,7 @@ void CmdTechDrawExtensionCreateObliqueCoordDimension::activated(int iMsg) execCreateObliqueCoordDimension(this); } -bool CmdTechDrawExtensionCreateObliqueCoordDimension::isActive(void) +bool CmdTechDrawExtensionCreateObliqueCoordDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1787,7 +1787,7 @@ void CmdTechDrawExtensionCreateCoordDimensionGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionCascadeDimansionGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1810,7 +1810,7 @@ void CmdTechDrawExtensionCreateCoordDimensionGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionCreateCoordDimensionGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionCreateCoordDimensionGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1878,7 +1878,7 @@ void CmdTechDrawExtensionCreateCoordDimensionGroup::languageChange() arc3->setStatusTip(arc3->text()); } -bool CmdTechDrawExtensionCreateCoordDimensionGroup::isActive(void) +bool CmdTechDrawExtensionCreateCoordDimensionGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1945,7 +1945,7 @@ void CmdTechDrawExtensionCreateHorizChamferDimension::activated(int iMsg) execCreateHorizChamferDimension(this); } -bool CmdTechDrawExtensionCreateHorizChamferDimension::isActive(void) +bool CmdTechDrawExtensionCreateHorizChamferDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -2012,7 +2012,7 @@ void CmdTechDrawExtensionCreateVertChamferDimension::activated(int iMsg) execCreateVertChamferDimension(this); } -bool CmdTechDrawExtensionCreateVertChamferDimension::isActive(void) +bool CmdTechDrawExtensionCreateVertChamferDimension::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -2042,7 +2042,7 @@ void CmdTechDrawExtensionChamferDimensionGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionIncreaseDecreaseGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -2062,7 +2062,7 @@ void CmdTechDrawExtensionChamferDimensionGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionChamferDimensionGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionChamferDimensionGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -2112,7 +2112,7 @@ void CmdTechDrawExtensionChamferDimensionGroup::languageChange() arc2->setStatusTip(arc2->text()); } -bool CmdTechDrawExtensionChamferDimensionGroup::isActive(void) +bool CmdTechDrawExtensionChamferDimensionGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -2188,7 +2188,7 @@ void CmdTechDrawExtensionCreateLengthArc::activated(int iMsg) { Gui::Command::commitCommand(); } -bool CmdTechDrawExtensionCreateLengthArc::isActive(void) +bool CmdTechDrawExtensionCreateLengthArc::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -2227,7 +2227,7 @@ void CmdTechDrawExtensionCustomizeFormat::activated(int iMsg) Gui::Control().showDialog(new TaskDlgCustomizeFormat(object)); } -bool CmdTechDrawExtensionCustomizeFormat::isActive(void) +bool CmdTechDrawExtensionCustomizeFormat::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -2260,7 +2260,7 @@ namespace TechDrawGui { // check selection of getSelectionEx() and selection[0].getObject() if (_checkSelection(cmd, selection, message)) { objFeat = dynamic_cast(selection[0].getObject()); - if (objFeat == nullptr) { + if (!objFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr(message.c_str()), QObject::tr("No object selected")); @@ -2306,7 +2306,7 @@ namespace TechDrawGui { // get subNames and coordinates of all selected vertexes std::vector vertexes; dimVertex nextVertex; - for (std::string name : subNames) { + for (const std::string& name : subNames) { std::string geoType = TechDraw::DrawUtil::getGeomTypeFromName(name); if (geoType == "Vertex") { int geoId = TechDraw::DrawUtil::getIndexFromName(name); @@ -2352,7 +2352,7 @@ namespace TechDrawGui { } //------------------------------------------------------------------------------ -void CreateTechDrawCommandsExtensionDims(void) +void CreateTechDrawCommandsExtensionDims() { Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp b/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp index 1a77370f18..8828407c3d 100644 --- a/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp +++ b/src/Mod/TechDraw/Gui/CommandExtensionPack.cpp @@ -110,7 +110,7 @@ namespace TechDrawGui { return; const std::vector SubNames = selection[0].getSubNames(); std::vector Circles; - for (std::string Name : SubNames) { + for (const std::string& Name : SubNames) { int GeoId = TechDraw::DrawUtil::getIndexFromName(Name); std::string GeoType = TechDraw::DrawUtil::getGeomTypeFromName(Name); TechDraw::BaseGeomPtr geom = objFeat->getGeomByIndex(GeoId); @@ -138,7 +138,7 @@ namespace TechDrawGui { std::string bigCircleTag = objFeat->addCosmeticEdge(bigCircle); TechDraw::CosmeticEdge* ceCircle = objFeat->getCosmeticEdge(bigCircleTag); _setLineAttributes(ceCircle); - for (TechDraw::CirclePtr oneCircle : Circles) { + for (const TechDraw::CirclePtr& oneCircle : Circles) { Base::Vector3d oneCircleCenter = oneCircle->center; float oneRadius = oneCircle->radius; Base::Vector3d delta = (oneCircle->center - bigCenter).Normalize() * (oneRadius + 2); @@ -181,7 +181,7 @@ void CmdTechDrawExtensionHoleCircle::activated(int iMsg) //Base::Console().Message("HoleCircle started\n"); } -bool CmdTechDrawExtensionHoleCircle::isActive(void) +bool CmdTechDrawExtensionHoleCircle::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -201,7 +201,7 @@ void execCircleCenterLines(Gui::Command* cmd) { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Circle Centerlines")); double scale = objFeat->getScale(); const std::vector SubNames = selection[0].getSubNames(); - for (std::string Name : SubNames) { + for (const std::string& Name : SubNames) { int GeoId = TechDraw::DrawUtil::getIndexFromName(Name); TechDraw::BaseGeomPtr geom = objFeat->getGeomByIndex(GeoId); std::string GeoType = TechDraw::DrawUtil::getGeomTypeFromName(Name); @@ -254,7 +254,7 @@ void CmdTechDrawExtensionCircleCenterLines::activated(int iMsg) execCircleCenterLines(this); } -bool CmdTechDrawExtensionCircleCenterLines::isActive(void) +bool CmdTechDrawExtensionCircleCenterLines::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -283,7 +283,7 @@ CmdTechDrawExtensionCircleCenterLinesGroup::CmdTechDrawExtensionCircleCenterLine void CmdTechDrawExtensionCircleCenterLinesGroup::activated(int iMsg) { Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -303,7 +303,7 @@ void CmdTechDrawExtensionCircleCenterLinesGroup::activated(int iMsg) { }; } -Gui::Action* CmdTechDrawExtensionCircleCenterLinesGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionCircleCenterLinesGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -355,7 +355,7 @@ void CmdTechDrawExtensionCircleCenterLinesGroup::languageChange() arc2->setStatusTip(arc2->text()); } -bool CmdTechDrawExtensionCircleCenterLinesGroup::isActive(void) +bool CmdTechDrawExtensionCircleCenterLinesGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -406,7 +406,7 @@ void CmdTechDrawExtensionThreadHoleSide::activated(int iMsg) execThreadHoleSide(this); } -bool CmdTechDrawExtensionThreadHoleSide::isActive(void) +bool CmdTechDrawExtensionThreadHoleSide::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -457,7 +457,7 @@ void CmdTechDrawExtensionThreadBoltSide::activated(int iMsg) execThreadBoltSide(this); } -bool CmdTechDrawExtensionThreadBoltSide::isActive(void) +bool CmdTechDrawExtensionThreadBoltSide::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -476,7 +476,7 @@ void execThreadHoleBottom(Gui::Command* cmd) { return; Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Cosmetic Thread Hole Bottom")); const std::vector SubNames = selection[0].getSubNames(); - for (std::string Name : SubNames) { + for (const std::string& Name : SubNames) { _createThreadCircle(Name, objFeat, 1.177f); } cmd->getSelection().clearSelection(); @@ -508,7 +508,7 @@ void CmdTechDrawExtensionThreadHoleBottom::activated(int iMsg) execThreadHoleBottom(this); } -bool CmdTechDrawExtensionThreadHoleBottom::isActive(void) +bool CmdTechDrawExtensionThreadHoleBottom::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -527,7 +527,7 @@ void execThreadBoltBottom(Gui::Command* cmd) { return; Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Cosmetic Thread Bolt Bottom")); const std::vector SubNames = selection[0].getSubNames(); - for (std::string Name : SubNames) { + for (const std::string& Name : SubNames) { _createThreadCircle(Name, objFeat, 0.85f); } cmd->getSelection().clearSelection(); @@ -559,7 +559,7 @@ void CmdTechDrawExtensionThreadBoltBottom::activated(int iMsg) execThreadBoltBottom(this); } -bool CmdTechDrawExtensionThreadBoltBottom::isActive(void) +bool CmdTechDrawExtensionThreadBoltBottom::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -590,7 +590,7 @@ void CmdTechDrawExtensionThreadsGroup::activated(int iMsg) { // Base::Console().Message("CMD::TechDrawExtensionThreadsGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -616,7 +616,7 @@ void CmdTechDrawExtensionThreadsGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionThreadsGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionThreadsGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -692,7 +692,7 @@ void CmdTechDrawExtensionThreadsGroup::languageChange() arc4->setStatusTip(arc4->text()); } -bool CmdTechDrawExtensionThreadsGroup::isActive(void) +bool CmdTechDrawExtensionThreadsGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -726,7 +726,7 @@ void CmdTechDrawExtensionSelectLineAttributes::activated(int iMsg) Gui::Control().showDialog(new TaskDlgSelectLineAttributes(&_getActiveLineAttributes())); } -bool CmdTechDrawExtensionSelectLineAttributes::isActive(void) +bool CmdTechDrawExtensionSelectLineAttributes::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -763,10 +763,10 @@ void CmdTechDrawExtensionChangeLineAttributes::activated(int iMsg) { return; Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Change Line Attributes")); const std::vector subNames = selection[0].getSubNames(); - for (std::string name : subNames) { + for (const std::string& name : subNames) { int num = DrawUtil::getIndexFromName(name); BaseGeomPtr baseGeo = objFeat->getGeomByIndex(num); - if (baseGeo != nullptr) { + if (baseGeo) { if (baseGeo->cosmetic) { if (baseGeo->source() == 1) { TechDraw::CosmeticEdge* cosEdgeTag = objFeat->getCosmeticEdgeBySelection(name); @@ -785,7 +785,7 @@ void CmdTechDrawExtensionChangeLineAttributes::activated(int iMsg) { Gui::Command::commitCommand(); } -bool CmdTechDrawExtensionChangeLineAttributes::isActive(void) +bool CmdTechDrawExtensionChangeLineAttributes::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -849,7 +849,7 @@ void CmdTechDrawExtensionVertexAtIntersection::activated(int iMsg) Gui::Command::commitCommand(); } -bool CmdTechDrawExtensionVertexAtIntersection::isActive(void) +bool CmdTechDrawExtensionVertexAtIntersection::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -912,7 +912,7 @@ void CmdTechDrawExtensionDrawCosmArc::activated(int iMsg) execDrawCosmArc(this); } -bool CmdTechDrawExtensionDrawCosmArc::isActive(void) +bool CmdTechDrawExtensionDrawCosmArc::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -972,7 +972,7 @@ void CmdTechDrawExtensionDrawCosmCircle::activated(int iMsg) execDrawCosmCircle(this); } -bool CmdTechDrawExtensionDrawCosmCircle::isActive(void) +bool CmdTechDrawExtensionDrawCosmCircle::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1036,7 +1036,7 @@ void CmdTechDrawExtensionDrawCosmCircle3Points::activated(int iMsg) execDrawCosmCircle3Points(this); } -bool CmdTechDrawExtensionDrawCosmCircle3Points::isActive(void) +bool CmdTechDrawExtensionDrawCosmCircle3Points::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1068,7 +1068,7 @@ void CmdTechDrawExtensionDrawCirclesGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionDrawCirclesGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1091,7 +1091,7 @@ void CmdTechDrawExtensionDrawCirclesGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionDrawCirclesGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionDrawCirclesGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1158,7 +1158,7 @@ void CmdTechDrawExtensionDrawCirclesGroup::languageChange() arc3->setStatusTip(arc3->text()); } -bool CmdTechDrawExtensionDrawCirclesGroup::isActive(void) +bool CmdTechDrawExtensionDrawCirclesGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1234,7 +1234,7 @@ void CmdTechDrawExtensionLineParallel::activated(int iMsg) execLineParallelPerpendicular(this, true); } -bool CmdTechDrawExtensionLineParallel::isActive(void) +bool CmdTechDrawExtensionLineParallel::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1268,7 +1268,7 @@ void CmdTechDrawExtensionLinePerpendicular::activated(int iMsg) execLineParallelPerpendicular(this, false); } -bool CmdTechDrawExtensionLinePerpendicular::isActive(void) +bool CmdTechDrawExtensionLinePerpendicular::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1299,7 +1299,7 @@ void CmdTechDrawExtensionLinePPGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtensionLinePPGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1319,7 +1319,7 @@ void CmdTechDrawExtensionLinePPGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtensionLinePPGroup::createAction(void) +Gui::Action* CmdTechDrawExtensionLinePPGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1371,7 +1371,7 @@ void CmdTechDrawExtensionLinePPGroup::languageChange() arc2->setStatusTip(arc2->text()); } -bool CmdTechDrawExtensionLinePPGroup::isActive(void) +bool CmdTechDrawExtensionLinePPGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1414,7 +1414,7 @@ void CmdTechDrawExtensionLockUnlockView::activated(int iMsg) { Gui::Command::commitCommand(); } -bool CmdTechDrawExtensionLockUnlockView::isActive(void) +bool CmdTechDrawExtensionLockUnlockView::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1481,7 +1481,7 @@ void CmdTechDrawExtensionPositionSectionView::activated(int iMsg) { } } -bool CmdTechDrawExtensionPositionSectionView::isActive(void) +bool CmdTechDrawExtensionPositionSectionView::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1506,7 +1506,7 @@ void execExtendShortenLine(Gui::Command* cmd, bool extend) { std::string geoType = TechDraw::DrawUtil::getGeomTypeFromName(name); if (geoType == "Edge") { TechDraw::BaseGeomPtr baseGeo = objFeat->getGeomByIndex(num); - if (baseGeo != nullptr) { + if (baseGeo) { if (baseGeo->geomType == TechDraw::GENERIC) { TechDraw::GenericPtr genLine = std::static_pointer_cast(baseGeo); Base::Vector3d P0 = genLine->points.at(0); @@ -1587,7 +1587,7 @@ void CmdTechDrawExtensionExtendLine::activated(int iMsg) ///Base::Console().Message("ExtendLine started\n"); } -bool CmdTechDrawExtensionExtendLine::isActive(void) +bool CmdTechDrawExtensionExtendLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1622,7 +1622,7 @@ void CmdTechDrawExtensionShortenLine::activated(int iMsg) ///Base::Console().Message("ShortenLine started\n"); } -bool CmdTechDrawExtensionShortenLine::isActive(void) +bool CmdTechDrawExtensionShortenLine::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1653,7 +1653,7 @@ void CmdTechDrawExtendShortenLineGroup::activated(int iMsg) { // Base::Console().Message("CMD::ExtendShortenLineGroup - activated(%d)\n", iMsg); Gui::TaskView::TaskDialog* dlg = Gui::Control().activeDialog(); - if (dlg != nullptr) { + if (dlg) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr("Task In Progress"), QObject::tr("Close active task dialog and try again.")); return; @@ -1673,7 +1673,7 @@ void CmdTechDrawExtendShortenLineGroup::activated(int iMsg) }; } -Gui::Action* CmdTechDrawExtendShortenLineGroup::createAction(void) +Gui::Action* CmdTechDrawExtendShortenLineGroup::createAction() { Gui::ActionGroup* pcAction = new Gui::ActionGroup(this, Gui::getMainWindow()); pcAction->setDropDownMenu(true); @@ -1725,7 +1725,7 @@ void CmdTechDrawExtendShortenLineGroup::languageChange() arc2->setStatusTip(arc2->text()); } -bool CmdTechDrawExtendShortenLineGroup::isActive(void) +bool CmdTechDrawExtendShortenLineGroup::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this, true); @@ -1767,7 +1767,7 @@ void CmdTechDrawExtensionAreaAnnotation::activated(int iMsg) int idx = TechDraw::DrawUtil::getIndexFromName(name); std::vector faceEdges = objFeat->getFaceEdgesByIndex(idx); // We filter arcs, circles etc. which are not allowed. - for (TechDraw::BaseGeomPtr geoPtr : faceEdges) + for (const TechDraw::BaseGeomPtr& geoPtr : faceEdges) if (geoPtr->geomType != TechDraw::GENERIC) throw Base::TypeError("CmdTechDrawAreaAnnotation - forbidden border element found\n"); // We create a list of all points along the boundary of the face. @@ -1858,7 +1858,7 @@ void CmdTechDrawExtensionAreaAnnotation::activated(int iMsg) Gui::Command::updateActive(); } -bool CmdTechDrawExtensionAreaAnnotation::isActive(void) +bool CmdTechDrawExtensionAreaAnnotation::isActive() { bool havePage = DrawGuiUtil::needPage(this); bool haveView = DrawGuiUtil::needView(this); @@ -1885,7 +1885,7 @@ namespace TechDrawGui { Gui::Document* guiDoc = Gui::Application::Instance->getDocument(page->getDocument()); ViewProviderPage* pageVP = dynamic_cast(guiDoc->getViewProvider(page)); if (pageVP) { - QGSPage* scenePage = pageVP->getGraphicsScene(); + QGSPage* scenePage = pageVP->getQGSPage(); featName = scenePage->getDrawPage()->getDocument()->getUniqueObjectName("Balloon"); std::string pageName = scenePage->getDrawPage()->getNameInDocument(); cmd->doCommand(cmd->Doc, "App.activeDocument().addObject('TechDraw::DrawViewBalloon','%s')", @@ -1910,7 +1910,7 @@ namespace TechDrawGui { } objFeat = dynamic_cast(selection[0].getObject()); - if (objFeat == nullptr) { + if (!objFeat) { QMessageBox::warning(Gui::getMainWindow(), QObject::tr(message.c_str()), QObject::tr("No object selected")); @@ -1923,7 +1923,7 @@ namespace TechDrawGui { std::vector _getVertexPoints(std::vector SubNames, TechDraw::DrawViewPart* objFeat) { // get vertex points as Vector3d std::vector vertexPoints; - for (std::string Name : SubNames) { + for (const std::string& Name : SubNames) { std::string GeoType = TechDraw::DrawUtil::getGeomTypeFromName(Name); if (GeoType == "Vertex") { int GeoId = TechDraw::DrawUtil::getIndexFromName(Name); @@ -2051,7 +2051,7 @@ namespace TechDrawGui { } //------------------------------------------------------------------------------ -void CreateTechDrawCommandsExtensions(void) +void CreateTechDrawCommandsExtensions() { Gui::CommandManager& rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/TechDraw/Gui/DlgPageChooser.cpp b/src/Mod/TechDraw/Gui/DlgPageChooser.cpp index f54780d1ae..47318b9638 100644 --- a/src/Mod/TechDraw/Gui/DlgPageChooser.cpp +++ b/src/Mod/TechDraw/Gui/DlgPageChooser.cpp @@ -74,7 +74,7 @@ void DlgPageChooser::fillList(std::vector labels, std::vectorlwPages); item->setData(Qt::UserRole, qName); } diff --git a/src/Mod/TechDraw/Gui/DlgPageChooser.h b/src/Mod/TechDraw/Gui/DlgPageChooser.h index 5e9675445c..f3db38a431 100644 --- a/src/Mod/TechDraw/Gui/DlgPageChooser.h +++ b/src/Mod/TechDraw/Gui/DlgPageChooser.h @@ -22,6 +22,8 @@ #ifndef GUI_DLGPAGECHOOSER_H #define GUI_DLGPAGECHOOSER_H +#include + #include namespace TechDrawGui { diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvanced.ui b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvanced.ui index 96f55db62e..02ef961dcb 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvanced.ui +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvanced.ui @@ -242,7 +242,7 @@ can be a performance penalty in complex models.
- + @@ -499,7 +499,23 @@ when hatching a face with a PAT pattern - + + + + Issue progress messages while building View geometry + + + Report Progress + + + ReportProgress + + + /Mod/TechDraw/General + + + + @@ -513,7 +529,7 @@ when hatching a face with a PAT pattern - <html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html> + <html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html> Qt::RichText diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.cpp b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.cpp index 746678620d..ccb567efb0 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.cpp +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.cpp @@ -57,6 +57,7 @@ void DlgPrefsTechDrawAdvancedImp::saveSettings() ui->cbEndCap->onSave(); ui->sbMaxTiles->onSave(); ui->sbMaxPat->onSave(); + ui->cbReportProgress->onSave(); } void DlgPrefsTechDrawAdvancedImp::loadSettings() @@ -73,6 +74,7 @@ void DlgPrefsTechDrawAdvancedImp::loadSettings() ui->cbEndCap->onRestore(); ui->sbMaxTiles->onRestore(); ui->sbMaxPat->onRestore(); + ui->cbReportProgress->onRestore(); } /** diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.h index 118ad9cd3c..8a62ddfa08 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAdvancedImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPADVANCED_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPADVANCED_H +#include + #include #include @@ -36,13 +38,13 @@ class DlgPrefsTechDrawAdvancedImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawAdvancedImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawAdvancedImp(); + explicit DlgPrefsTechDrawAdvancedImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawAdvancedImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.cpp b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.cpp index 6f9a5e6265..aeb2a9c7e0 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.cpp +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.cpp @@ -48,7 +48,7 @@ DlgPrefsTechDrawAnnotationImp::DlgPrefsTechDrawAnnotationImp( QWidget* parent ) ui->setupUi(this); ui->pdsbBalloonKink->setUnit(Base::Unit::Length); ui->pdsbBalloonKink->setMinimum(0); - + // connect the LineGroup the update the tooltip if index changed connect(ui->pcbLineGroup, SIGNAL(currentIndexChanged(int)), this, SLOT(onLineGroupChanged(int))); @@ -98,7 +98,7 @@ void DlgPrefsTechDrawAnnotationImp::loadSettings() for (auto it = lgNames.begin(); it < lgNames.end(); ++it) { ui->pcbLineGroup->addItem(tr((*it).c_str())); } - + ui->cbAutoHoriz->onRestore(); ui->cbPrintCenterMarks->onRestore(); ui->cbPyramidOrtho->onRestore(); @@ -133,7 +133,7 @@ void DlgPrefsTechDrawAnnotationImp::changeEvent(QEvent *e) } } -int DlgPrefsTechDrawAnnotationImp::prefBalloonArrow(void) const +int DlgPrefsTechDrawAnnotationImp::prefBalloonArrow() const { return Preferences::balloonArrow(); } @@ -147,7 +147,7 @@ void DlgPrefsTechDrawAnnotationImp::onLineGroupChanged(int index) ui->pcbLineGroup->setToolTip(QObject::tr("Please select a Line Group")); return; } - // get the definition the the selected LineGroup (includes the name) + // get the definition of the selected LineGroup (includes the name) std::string lgRecord = LineGroup::getRecordFromFile(Preferences::lineGroupFile(), index); std::stringstream ss(lgRecord); std::vector lgNames; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.h index c27b1c64eb..77ebd9d422 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawAnnotationImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPANNOTATION_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPANNOTATION_H +#include + #include #include @@ -36,18 +38,18 @@ class DlgPrefsTechDrawAnnotationImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawAnnotationImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawAnnotationImp(); + explicit DlgPrefsTechDrawAnnotationImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawAnnotationImp() override; public Q_SLOTS: void onLineGroupChanged(int); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; - int prefBalloonArrow(void) const; + int prefBalloonArrow() const; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawColorsImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawColorsImp.h index 5ca8fafd10..bad5a33fe2 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawColorsImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawColorsImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPCOLORS_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPCOLORS_H +#include + #include #include @@ -36,13 +38,13 @@ class DlgPrefsTechDrawColorsImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawColorsImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawColorsImp(); + explicit DlgPrefsTechDrawColorsImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawColorsImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.cpp b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.cpp index 6c2ea69ca2..afe5ad09d2 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.cpp +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.cpp @@ -119,7 +119,7 @@ void DlgPrefsTechDrawDimensionsImp::changeEvent(QEvent *e) } } -int DlgPrefsTechDrawDimensionsImp::prefArrowStyle(void) const +int DlgPrefsTechDrawDimensionsImp::prefArrowStyle() const { return PreferencesGui::dimArrowStyle(); } diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.h index 1f72827feb..f7da5e0627 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawDimensionsImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPDIMENSIONS_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPDIMENSIONS_H +#include + #include #include @@ -36,15 +38,15 @@ class DlgPrefsTechDrawDimensionsImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawDimensionsImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawDimensionsImp(); + explicit DlgPrefsTechDrawDimensionsImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawDimensionsImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; - int prefArrowStyle(void) const; + int prefArrowStyle() const; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawGeneralImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawGeneralImp.h index 480edf86af..bcb4b95b91 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawGeneralImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawGeneralImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPGENERAL_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPGENERAL_H +#include + #include #include @@ -36,13 +38,13 @@ class DlgPrefsTechDrawGeneralImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawGeneralImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawGeneralImp(); + explicit DlgPrefsTechDrawGeneralImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawGeneralImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawHLRImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawHLRImp.h index aa471e307b..2ae48cdb3b 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawHLRImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawHLRImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPHLR_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPHLR_H +#include + #include #include @@ -36,13 +38,13 @@ class DlgPrefsTechDrawHLRImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawHLRImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawHLRImp(); + explicit DlgPrefsTechDrawHLRImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawHLRImp() override; protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawScaleImp.h b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawScaleImp.h index d3747547eb..bae0d1b3d3 100644 --- a/src/Mod/TechDraw/Gui/DlgPrefsTechDrawScaleImp.h +++ b/src/Mod/TechDraw/Gui/DlgPrefsTechDrawScaleImp.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_DLGPREFSTECHDRAWIMPSCALE_H #define DRAWINGGUI_DLGPREFSTECHDRAWIMPSCALE_H +#include + #include #include @@ -36,16 +38,16 @@ class DlgPrefsTechDrawScaleImp : public Gui::Dialog::PreferencePage Q_OBJECT public: - DlgPrefsTechDrawScaleImp( QWidget* parent = nullptr ); - ~DlgPrefsTechDrawScaleImp(); + explicit DlgPrefsTechDrawScaleImp( QWidget* parent = nullptr ); + ~DlgPrefsTechDrawScaleImp() override; protected Q_SLOTS: void onScaleTypeChanged(int index); protected: - void saveSettings(); - void loadSettings(); - void changeEvent(QEvent *e); + void saveSettings() override; + void loadSettings() override; + void changeEvent(QEvent *e) override; private: std::unique_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DlgTemplateField.h b/src/Mod/TechDraw/Gui/DlgTemplateField.h index 729e5265f7..b5ba4e3191 100644 --- a/src/Mod/TechDraw/Gui/DlgTemplateField.h +++ b/src/Mod/TechDraw/Gui/DlgTemplateField.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_DLGTEMPLATEFIELD_H #define DRAWINGGUI_DLGTEMPLATEFIELD_H +#include + #include #include #include @@ -36,19 +38,19 @@ class DlgTemplateField : public QDialog Q_OBJECT public: - DlgTemplateField( QWidget *parent = nullptr ); - virtual ~DlgTemplateField() = default; + explicit DlgTemplateField( QWidget *parent = nullptr ); + ~DlgTemplateField() override = default; void setFieldName(std::string name); void setFieldContent(std::string content); QString getFieldContent(); public Q_SLOTS: - void accept(); - void reject(); + void accept() override; + void reject() override; protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; private: std::shared_ptr ui; diff --git a/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp b/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp index 4d3be0aa33..a7bda9d681 100644 --- a/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp +++ b/src/Mod/TechDraw/Gui/DrawGuiUtil.cpp @@ -128,8 +128,7 @@ TechDraw::DrawPage* DrawGuiUtil::findPage(Gui::Command* cmd) Gui::MDIView* mv = w->activeWindow(); MDIViewPage* mvp = dynamic_cast(mv); if (mvp) { - QString windowTitle = mvp->windowTitle(); - QGSPage* qp = mvp->getQGSPage(); + QGSPage* qp = mvp->getViewProviderPage()->getQGSPage(); page = qp->getDrawPage(); } else { @@ -181,7 +180,7 @@ bool DrawGuiUtil::isDraftObject(App::DocumentObject* obj) bool result = false; App::PropertyPythonObject* proxy = dynamic_cast(obj->getPropertyByName("Proxy")); - if (proxy != nullptr) { + if (proxy) { //if no proxy, can not be Draft obj //if has proxy, might be Draft obj std::stringstream ss; @@ -213,7 +212,7 @@ bool DrawGuiUtil::isArchObject(App::DocumentObject* obj) bool result = false; App::PropertyPythonObject* proxy = dynamic_cast(obj->getPropertyByName("Proxy")); - if (proxy != nullptr) { + if (proxy) { //if no proxy, can not be Arch obj //if has proxy, might be Arch obj Py::Object proxyObj = proxy->getValue(); @@ -243,7 +242,7 @@ bool DrawGuiUtil::isArchSection(App::DocumentObject* obj) bool result = false; App::PropertyPythonObject* proxy = dynamic_cast(obj->getPropertyByName("Proxy")); - if (proxy != nullptr) { + if (proxy) { //if no proxy, can not be Arch obj //if has proxy, might be Arch obj Py::Object proxyObj = proxy->getValue(); diff --git a/src/Mod/TechDraw/Gui/DrawGuiUtil.h b/src/Mod/TechDraw/Gui/DrawGuiUtil.h index e47f0f6e1a..6704d56473 100644 --- a/src/Mod/TechDraw/Gui/DrawGuiUtil.h +++ b/src/Mod/TechDraw/Gui/DrawGuiUtil.h @@ -23,6 +23,8 @@ #ifndef _DrawGuiUtil_h_ #define _DrawGuiUtil_h_ +#include + #include #include diff --git a/src/Mod/TechDraw/Gui/Grabber3d.cpp b/src/Mod/TechDraw/Gui/Grabber3d.cpp index 8f3660b483..f6a0139496 100644 --- a/src/Mod/TechDraw/Gui/Grabber3d.cpp +++ b/src/Mod/TechDraw/Gui/Grabber3d.cpp @@ -79,19 +79,19 @@ double Grabber3d::copyActiveViewToSvgFile(App::Document* appDoc, //get the active view Gui::Document* guiDoc = Gui::Application::Instance->getDocument(appDoc); Gui::MDIView* mdiView = guiDoc->getActiveView(); - if (mdiView == nullptr) { + if (!mdiView) { Base::Console().Warning("G3d::copyActiveViewToSvgFile - no ActiveView - returning\n"); return result; } View3DInventor* view3d = qobject_cast(mdiView); - if (view3d == nullptr) { + if (!view3d) { Base::Console().Warning("G3d::copyActiveViewToSvgFile - no viewer for ActiveView - returning\n"); return result; } View3DInventorViewer* viewer = view3d->getViewer(); - if (viewer == nullptr) { + if (!viewer) { Base::Console().Warning("G3d::copyActiveViewToSvgFile - could not create viewer - returning\n"); return result; } @@ -179,7 +179,6 @@ double Grabber3d::copyActiveViewToSvgFile(App::Document* appDoc, Base::Console().Error("G3D::copyActiveViewToSvgFile - can not open file - %s/n", fileSpec.c_str()); return result; } - QColor dbColor(Qt::blue); execVectorizeAction(viewerSvg, va.get(), outWidth, outHeight, diff --git a/src/Mod/TechDraw/Gui/Grabber3d.h b/src/Mod/TechDraw/Gui/Grabber3d.h index a2a4e2d560..c181edd4ea 100644 --- a/src/Mod/TechDraw/Gui/Grabber3d.h +++ b/src/Mod/TechDraw/Gui/Grabber3d.h @@ -23,6 +23,7 @@ #ifndef _Grabber3d_h_ #define _Grabber3d_h_ +#include class SoSeparator; class SoCamera; diff --git a/src/Mod/TechDraw/Gui/MDIViewPage.cpp b/src/Mod/TechDraw/Gui/MDIViewPage.cpp index 4e0ddf4050..62bb29d214 100644 --- a/src/Mod/TechDraw/Gui/MDIViewPage.cpp +++ b/src/Mod/TechDraw/Gui/MDIViewPage.cpp @@ -24,6 +24,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ + #include #include #include #include @@ -43,7 +44,6 @@ #include #endif // #ifndef _PreComp_ -#include #include "MDIViewPage.h" @@ -68,27 +68,9 @@ #include #include -#include #include #include -#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include "Rez.h" #include "QGIDrawingTemplate.h" @@ -119,20 +101,13 @@ TYPESYSTEM_SOURCE_ABSTRACT(TechDrawGui::MDIViewPage, Gui::MDIView) MDIViewPage::MDIViewPage(ViewProviderPage *pageVp, Gui::Document* doc, QWidget* parent) : Gui::MDIView(doc, parent), + m_vpPage(pageVp), m_orientation(QPageLayout::Landscape), m_paperSize(QPageSize::A4), - pagewidth(0.0), - pageheight(0.0), - m_vpPage(pageVp) + m_pagewidth(0.0), + m_pageheight(0.0) { - setMouseTracking(true); - m_scene = new QGSPage(pageVp, this); - m_scene->setItemIndexMethod(QGraphicsScene::NoIndex); //this prevents crash when deleting dims. - //scene(view?) indices of dirty regions gets - //out of sync. missing prepareGeometryChange - //somewhere???? QTBUG-18021??? - m_view = new QGVPage(pageVp,m_scene,this); m_toggleKeepUpdatedAction = new QAction(tr("Toggle &Keep Updated"), this); connect(m_toggleKeepUpdatedAction, SIGNAL(triggered()), this, SLOT(toggleKeepUpdated())); @@ -154,134 +129,30 @@ MDIViewPage::MDIViewPage(ViewProviderPage *pageVp, Gui::Document* doc, QWidget* QString tabText = QString::fromUtf8(pageVp->getDrawPage()->getNameInDocument()); tabText += QString::fromUtf8("[*]"); setWindowTitle(tabText); - setCentralWidget(m_view); //this makes m_view a Qt child of MDIViewPage - - m_timer = new QTimer(this); - m_timer->setSingleShot(true); - QObject::connect(m_timer,SIGNAL(timeout()),this,SLOT(onTimer())); - - // Connect Signals and Slots - QObject::connect( - m_scene, SIGNAL(selectionChanged()), - this , SLOT (sceneSelectionChanged()) - ); //get informed by App side about deleted DocumentObjects App::Document* appDoc = m_vpPage->getDocument()->getDocument(); auto bnd = boost::bind(&MDIViewPage::onDeleteObject, this, bp::_1); connectDeletedObject = appDoc->signalDeletedObject.connect(bnd); - -// setContextMenuPolicy(Qt::NoContextMenu); } - MDIViewPage::~MDIViewPage() { connectDeletedObject.disconnect(); } -void MDIViewPage::addChildrenToPage(void) +void MDIViewPage::setScene(QGSPage* scene, QGVPage* viewWidget) { - // A fresh page is added and we iterate through its collected children and add these to Canvas View -MLP - // if docobj is a featureviewcollection (ex orthogroup), add its child views. if there are ever children that have children, - // we'll have to make this recursive. -WF - const std::vector &grp = m_vpPage->getDrawPage()->Views.getValues(); - std::vector childViews; - for (std::vector::const_iterator it = grp.begin();it != grp.end(); ++it) { - attachView(*it); - TechDraw::DrawViewCollection* collect = dynamic_cast(*it); - if (collect) { - childViews = collect->Views.getValues(); - for (std::vector::iterator itChild = childViews.begin();itChild != childViews.end(); ++itChild) { - attachView(*itChild); - } - } - } - //when restoring, it is possible for a Dimension to be loaded before the ViewPart it applies to - //therefore we need to make sure parentage of the graphics representation is set properly. bit of a kludge. - setDimensionGroups(); - setBalloonGroups(); - setLeaderGroups(); - - App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); - auto pageTemplate( dynamic_cast(obj) ); - if( pageTemplate ) { - attachTemplate(pageTemplate); - matchSceneRectToTemplate(); - } - - viewAll(); -} - -void MDIViewPage::matchSceneRectToTemplate(void) -{ - App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); - auto pageTemplate( dynamic_cast(obj) ); - if( pageTemplate ) { - //make sceneRect 1 pagesize bigger in every direction - double width = Rez::guiX(pageTemplate->Width.getValue()); - double height = Rez::guiX(pageTemplate->Height.getValue()); - m_scene->setSceneRect(QRectF(-width,-2.0 * height,3.0*width,3.0*height)); - } -} - -void MDIViewPage::setDimensionGroups(void) -{ - const std::vector &allItems = m_scene->getViews(); - std::vector::const_iterator itInspect; - int dimItemType = QGraphicsItem::UserType + 106; - - for (itInspect = allItems.begin(); itInspect != allItems.end(); itInspect++) { - if (((*itInspect)->type() == dimItemType) && (!(*itInspect)->group())) { - QGIView* parent = m_scene->findParent((*itInspect)); - if (parent) { - QGIViewDimension* dim = dynamic_cast((*itInspect)); - m_scene->addDimToParent(dim,parent); - } - } - } -} - -void MDIViewPage::setBalloonGroups(void) -{ - const std::vector &allItems = m_scene->getViews(); - std::vector::const_iterator itInspect; - int balloonItemType = QGraphicsItem::UserType + 140; - - for (itInspect = allItems.begin(); itInspect != allItems.end(); itInspect++) { - if (((*itInspect)->type() == balloonItemType) && (!(*itInspect)->group())) { - QGIView* parent = m_scene->findParent((*itInspect)); - if (parent) { - QGIViewBalloon* balloon = dynamic_cast((*itInspect)); - m_scene->addBalloonToParent(balloon,parent); - } - } - } -} - -void MDIViewPage::setLeaderGroups(void) -{ -// Base::Console().Message("MDIVP::setLeaderGroups()\n"); - const std::vector &allItems = m_scene->getViews(); - std::vector::const_iterator itInspect; - int leadItemType = QGraphicsItem::UserType + 232; - - //make sure that qgileader belongs to correct parent. - //quite possibly redundant - for (itInspect = allItems.begin(); itInspect != allItems.end(); itInspect++) { - if (((*itInspect)->type() == leadItemType) && (!(*itInspect)->group())) { - QGIView* parent = m_scene->findParent((*itInspect)); - if (parent) { - QGILeaderLine* lead = dynamic_cast((*itInspect)); - m_scene->addLeaderToParent(lead,parent); - } - } - } + m_scene = scene; + setCentralWidget(viewWidget); //this makes viewWidget a Qt child of MDIViewPage + QObject::connect(m_scene, SIGNAL(selectionChanged()), + this, SLOT (sceneSelectionChanged())); } void MDIViewPage::setDocumentObject(const std::string& name) { m_objectName = name; + setObjectName(Base::Tools::fromStdString(name)); } void MDIViewPage::setDocumentName(const std::string& name) @@ -291,6 +162,7 @@ void MDIViewPage::setDocumentName(const std::string& name) void MDIViewPage::closeEvent(QCloseEvent* ev) { +// Base::Console().Message("MDIVP::closeEvent()\n"); MDIView::closeEvent(ev); if (!ev->isAccepted()) return; @@ -310,102 +182,6 @@ void MDIViewPage::closeEvent(QCloseEvent* ev) blockSceneSelection(false); } -void MDIViewPage::attachTemplate(TechDraw::DrawTemplate *obj) -{ - m_scene->setPageTemplate(obj); - pagewidth = obj->Width.getValue(); - pageheight = obj->Height.getValue(); - m_paperSize = QPageSize::id(QSizeF(pagewidth, pageheight), QPageSize::Millimeter, QPageSize::FuzzyOrientationMatch); - if (pagewidth > pageheight) { - m_orientation = QPageLayout::Landscape; - } else { - m_orientation = QPageLayout::Portrait; - } -} - -QPointF MDIViewPage::getTemplateCenter(TechDraw::DrawTemplate *obj) -{ - double cx = Rez::guiX(obj->Width.getValue())/2.0; - double cy = -Rez::guiX(obj->Height.getValue())/2.0; - QPointF result(cx,cy); - return result; -} - -void MDIViewPage::centerOnPage(void) -{ - App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); - auto pageTemplate( dynamic_cast(obj) ); - if( pageTemplate ) { - QPointF viewCenter = getTemplateCenter(pageTemplate); - m_view->centerOn(viewCenter); - } -} - -bool MDIViewPage::addView(const App::DocumentObject *obj) -{ - return attachView(const_cast(obj)); -} - -bool MDIViewPage::attachView(App::DocumentObject *obj) -{ - auto typeId(obj->getTypeId()); - - QGIView *qview(nullptr); - - if (typeId.isDerivedFrom(TechDraw::DrawViewSection::getClassTypeId()) ) { - qview = m_scene->addViewSection( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId()) ) { - qview = m_scene->addViewPart( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawProjGroup::getClassTypeId()) ) { - qview = m_scene->addProjectionGroup( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId()) ) { - qview = m_scene->addDrawView( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) ) { - qview = m_scene->addViewDimension( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewBalloon::getClassTypeId()) ) { - qview = m_scene->addViewBalloon( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewAnnotation::getClassTypeId()) ) { - qview = m_scene->addDrawViewAnnotation( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewSymbol::getClassTypeId()) ) { - qview = m_scene->addDrawViewSymbol( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewClip::getClassTypeId()) ) { - qview = m_scene->addDrawViewClip( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewSpreadsheet::getClassTypeId()) ) { - qview = m_scene->addDrawViewSpreadsheet( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawViewImage::getClassTypeId()) ) { - qview = m_scene->addDrawViewImage( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawLeaderLine::getClassTypeId()) ) { - qview = m_scene->addViewLeader( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawRichAnno::getClassTypeId()) ) { - qview = m_scene->addRichAnno( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawWeldSymbol::getClassTypeId()) ) { - qview = m_scene->addWeldSymbol( static_cast(obj) ); - - } else if (typeId.isDerivedFrom(TechDraw::DrawHatch::getClassTypeId()) ) { - //Hatch is not attached like other Views (since it isn't really a View) - return true; - //DrawGeomHatch?? - - } else { - Base::Console().Log("Logic Error - Unknown view type in MDIViewPage::attachView\n"); - } - - return (qview != nullptr); -} - void MDIViewPage::onDeleteObject(const App::DocumentObject& obj) { //if this page has a QView for this obj, delete it. @@ -416,201 +192,6 @@ void MDIViewPage::onDeleteObject(const App::DocumentObject& obj) blockSceneSelection(false); } -void MDIViewPage::onTimer() { - fixOrphans(true); -} - -void MDIViewPage::updateTemplate(bool forceUpdate) -{ - App::DocumentObject *templObj = m_vpPage->getDrawPage()->Template.getValue(); - // TODO: what if template has been deleted? templObj will be NULL. segfault? - if (!templObj) { - Base::Console().Log("INFO - MDIViewPage::updateTemplate - Page: %s has NO template!!\n",m_vpPage->getDrawPage()->getNameInDocument()); - return; - } - - if(m_vpPage->getDrawPage()->Template.isTouched() || templObj->isTouched()) { - // Template is touched so update - - if(forceUpdate || - (templObj && templObj->isTouched() && templObj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) ) { - - QGITemplate *qItemTemplate = m_scene->getTemplate(); - - if(qItemTemplate) { - TechDraw::DrawTemplate *pageTemplate = dynamic_cast(templObj); - qItemTemplate->setTemplate(pageTemplate); - qItemTemplate->updateView(); - } - } - } -} - -//this is time consuming. should only be used when there is a problem. -//Solve the situation where a DrawView belonging to this DrawPage has no QGraphicsItem in -//the QGScene for the DrawPage -or- -//a QGraphics item exists in the DrawPage's QGScene, but there is no corresponding DrawView -//in the DrawPage. -void MDIViewPage::fixOrphans(bool force) -{ - if(!force) { - m_timer->start(100); - return; - } - m_timer->stop(); - - // get all the DrawViews for this page, including the second level ones - // if we ever have collections of collections, we'll need to revisit this - TechDraw::DrawPage* thisPage = m_vpPage->getDrawPage(); - - if(!thisPage->getNameInDocument()) - return; - - std::vector pChildren = thisPage->getAllViews(); - - // if dv doesn't have a graphic, make one - for (auto& dv: pChildren) { - if (dv->isRemoving()) { - continue; - } - QGIView* qv = m_scene->findQViewForDocObj(dv); - if (qv == nullptr) { - attachView(dv); - } - } - // if qView doesn't have a Feature on this Page, delete it - std::vector qvss = m_scene->getViews(); - // qvss may contain an item and its child item(s) and to avoid to access a deleted item a QPointer is needed - std::vector> qvs; - std::for_each(qvss.begin(), qvss.end(), [&qvs](QGIView* v) { - qvs.emplace_back(v); - }); - App::Document* doc = getAppDocument(); - for (auto& qv: qvs) { - if (!qv) - continue; // already deleted? - App::DocumentObject* obj = doc->getObject(qv->getViewName()); - if (obj == nullptr) { - //no DrawView anywhere in Document - m_scene->removeQView(qv); - } else { - //DrawView exists in Document. Does it belong to this DrawPage? - int numParentPages = qv->getViewObject()->countParentPages(); - if (numParentPages == 0) { - //DrawView does not belong to any DrawPage - //remove QGItem from QGScene - m_scene->removeQView(qv); - } else if (numParentPages == 1) { - //Does DrawView belong to this DrawPage? - TechDraw::DrawPage* pp = qv->getViewObject()->findParentPage(); - if (thisPage != pp) { - //DrawView does not belong to this DrawPage - //remove QGItem from QGScene - m_scene->removeQView(qv); - } - } else if (numParentPages > 1) { - //DrawView belongs to multiple DrawPages - //check if this MDIViewPage corresponds to any parent DrawPage - //if not, delete the QGItem - std::vector pPages = qv->getViewObject()->findAllParentPages(); - bool found = false; - for (auto p: pPages) { - if (thisPage == p) { - found = true; - break; - } - } - if (!found) { - //none of the parent Pages for View correspond to this Page - m_scene->removeQView(qv); - } - } - } - } -} - -//NOTE: this doesn't add missing views. see fixOrphans() -void MDIViewPage::redrawAllViews() -{ - const std::vector &upviews = m_scene->getViews(); - for(std::vector::const_iterator it = upviews.begin(); it != upviews.end(); ++it) { - (*it)->updateView(true); - } -} - -//NOTE: this doesn't add missing views. see fixOrphans() -void MDIViewPage::redraw1View(TechDraw::DrawView* dv) -{ - std::string dvName = dv->getNameInDocument(); - const std::vector &upviews = m_scene->getViews(); - for(std::vector::const_iterator it = upviews.begin(); it != upviews.end(); ++it) { - std::string qgivName = (*it)->getViewName(); - if(dvName == qgivName) { - (*it)->updateView(true); - } - } -} - -void MDIViewPage::findMissingViews(const std::vector &list, std::vector &missing) -{ - for(std::vector::const_iterator it = list.begin(); it != list.end(); ++it) { - - if(!hasQView(*it)) - missing.push_back(*it); - - if((*it)->getTypeId().isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId())) { - std::vector missingChildViews; - TechDraw::DrawViewCollection *collection = dynamic_cast(*it); - // Find Child Views recursively - findMissingViews(collection->Views.getValues(), missingChildViews); - - // Append the views to current missing list - for(std::vector::const_iterator it = missingChildViews.begin(); it != missingChildViews.end(); ++it) { - missing.push_back(*it); - } - } - } -} - -/// Helper function -bool MDIViewPage::hasQView(App::DocumentObject *obj) -{ - const std::vector &views = m_scene->getViews(); - std::vector::const_iterator qview = views.begin(); - - while(qview != views.end()) { - // Unsure if we can compare pointers so rely on name - if(strcmp((*qview)->getViewName(), obj->getNameInDocument()) == 0) { - return true; - } - qview++; - } - - return false; -} - - -/// Helper function -bool MDIViewPage::orphanExists(const char *viewName, const std::vector &list) -{ - for(std::vector::const_iterator it = list.begin(); it != list.end(); ++it) { - - //Check child objects too recursively - if((*it)->isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId())) { - TechDraw::DrawViewCollection *collection = dynamic_cast(*it); - if(orphanExists(viewName, collection->Views.getValues())) - return true; - } - - // Unsure if we can compare pointers so rely on name - if(strcmp(viewName, (*it)->getNameInDocument()) == 0) { - return true; - } - } - return false; -} - - bool MDIViewPage::onMsg(const char *pMsg, const char **) { Gui::Document *doc(getGuiDocument()); @@ -639,7 +220,6 @@ bool MDIViewPage::onMsg(const char *pMsg, const char **) return false; } - bool MDIViewPage::onHasMsg(const char* pMsg) const { if (strcmp("ViewFit",pMsg) == 0) @@ -671,6 +251,24 @@ void MDIViewPage::setTabText(std::string t) } } +//**** printing routines + +void MDIViewPage::getPaperAttributes(void) +{ + App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); + auto pageTemplate( dynamic_cast(obj) ); + if( pageTemplate ) { + m_pagewidth = Rez::guiX(pageTemplate->Width.getValue()); + m_pageheight = Rez::guiX(pageTemplate->Height.getValue()); + } + m_paperSize = QPageSize::id(QSizeF(m_pagewidth, m_pageheight), QPageSize::Millimeter, QPageSize::FuzzyOrientationMatch); + if (m_pagewidth > m_pageheight) { + m_orientation = QPageLayout::Landscape; + } else { + m_orientation = QPageLayout::Portrait; + } +} + void MDIViewPage::printPdf() { QStringList filter; @@ -693,6 +291,8 @@ void MDIViewPage::printPdf(std::string file) Base::Console().Warning("MDIViewPage - no file specified\n"); return; } + getPaperAttributes(); + QString filename = QString::fromUtf8(file.data(),file.size()); QPrinter printer(QPrinter::HighResolution); printer.setFullPage(true); @@ -704,7 +304,7 @@ void MDIViewPage::printPdf(std::string file) printer.setPageOrientation(m_orientation); } if (m_paperSize == QPageSize::Custom) { - printer.setPageSize(QPageSize(QSizeF(pagewidth, pageheight), QPageSize::Millimeter)); + printer.setPageSize(QPageSize(QSizeF(m_pagewidth, m_pageheight), QPageSize::Millimeter)); } else { printer.setPageSize(QPageSize(m_paperSize)); } @@ -713,10 +313,12 @@ void MDIViewPage::printPdf(std::string file) void MDIViewPage::print() { + getPaperAttributes(); + QPrinter printer(QPrinter::HighResolution); printer.setFullPage(true); if (m_paperSize == QPageSize::Custom) { - printer.setPageSize(QPageSize(QSizeF(pagewidth, pageheight), QPageSize::Millimeter)); + printer.setPageSize(QPageSize(QSizeF(m_pagewidth, m_pageheight), QPageSize::Millimeter)); } else { printer.setPageSize(QPageSize(m_paperSize)); } @@ -730,10 +332,12 @@ void MDIViewPage::print() void MDIViewPage::printPreview() { + getPaperAttributes(); + QPrinter printer(QPrinter::HighResolution); printer.setFullPage(true); if (m_paperSize == QPageSize::Custom) { - printer.setPageSize(QPageSize(QSizeF(pagewidth, pageheight), QPageSize::Millimeter)); + printer.setPageSize(QPageSize(QSizeF(m_pagewidth, m_pageheight), QPageSize::Millimeter)); } else { printer.setPageSize(QPageSize(m_paperSize)); } @@ -748,6 +352,8 @@ void MDIViewPage::printPreview() void MDIViewPage::print(QPrinter* printer) { + getPaperAttributes(); + // As size of the render area paperRect() should be used. When performing a real // print pageRect() may also work but the output is cropped at the bottom part. // So, independent whether pageRect() or paperRect() is used there is no scaling effect. @@ -855,12 +461,12 @@ void MDIViewPage::contextMenuEvent(QContextMenuEvent *event) menu.exec(event->globalPos()); } -void MDIViewPage::toggleFrame(void) +void MDIViewPage::toggleFrame() { m_vpPage->toggleFrameState(); } -void MDIViewPage::toggleKeepUpdated(void) +void MDIViewPage::toggleKeepUpdated() { bool state = m_vpPage->getDrawPage()->KeepUpdated.getValue(); m_vpPage->getDrawPage()->KeepUpdated.setValue(!state); @@ -868,7 +474,7 @@ void MDIViewPage::toggleKeepUpdated(void) void MDIViewPage::viewAll() { - m_view->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); + m_vpPage->getQGVPage()->fitInView(m_scene->itemsBoundingRect(), Qt::KeepAspectRatio); } void MDIViewPage::saveSVG() @@ -1019,11 +625,11 @@ void MDIViewPage::clearSceneSelection() //handle oddballs QGIViewDimension* dim = dynamic_cast(*it); - if (dim != nullptr) { + if (dim) { state = dim->getDatumLabel()->isSelected(); } else { QGIViewBalloon* bal = dynamic_cast(*it); - if (bal != nullptr) { + if (bal) { state = bal->getBalloonLabel()->isSelected(); } } @@ -1101,7 +707,7 @@ void MDIViewPage::sceneSelectionManager() //add to m_qgSceneSelected anything that is in q_sceneSel for (auto qts: sceneSel) { bool found = false; - for (auto ms: m_qgSceneSelected) { + for (auto ms: qAsConst(m_qgSceneSelected)) { if ( qts == ms ) { found = true; break; @@ -1115,7 +721,7 @@ void MDIViewPage::sceneSelectionManager() //remove items from m_qgSceneSelected that are not in q_sceneSel QList m_new; - for (auto m: m_qgSceneSelected) { + for (auto m: qAsConst(m_qgSceneSelected)) { for (auto q: sceneSel) { if (m == q) { m_new.push_back(m); @@ -1149,7 +755,7 @@ void MDIViewPage::sceneSelectionChanged() } //Note: Qt says: "no guarantee of selection order"!!! -void MDIViewPage::setTreeToSceneSelect(void) +void MDIViewPage::setTreeToSceneSelect() { bool saveBlock = blockSelection(true); // block selectionChanged signal from Tree/Observer blockSceneSelection(true); @@ -1157,7 +763,7 @@ void MDIViewPage::setTreeToSceneSelect(void) QList sceneSel = m_qgSceneSelected; for (QList::iterator it = sceneSel.begin(); it != sceneSel.end(); ++it) { QGIView *itemView = dynamic_cast(*it); - if(itemView == nullptr) { + if (!itemView) { QGIEdge *edge = dynamic_cast(*it); if(edge) { QGraphicsItem*parent = edge->parentItem(); @@ -1330,25 +936,27 @@ bool MDIViewPage::compareSelections(std::vector treeSel, Q std::sort(treeNames.begin(),treeNames.end()); treeCount = treeNames.size(); - for (auto sn:sceneSel){ + for (auto sn : sceneSel) { QGIView *itemView = dynamic_cast(sn); - if(itemView == nullptr) { - QGIDatumLabel* dl = dynamic_cast(sn); - QGIPrimPath* pp = dynamic_cast(sn); //count Vertex/Edge/Face - if (pp != nullptr) { + if (!itemView) { + QGIDatumLabel *dl = dynamic_cast(sn); + QGIPrimPath *pp = dynamic_cast(sn);//count Vertex/Edge/Face + if (pp) { ppCount++; - } else if (dl != nullptr) { + } + else if (dl) { //get dim associated with this label - QGraphicsItem* qgi = dl->parentItem(); - if (qgi != nullptr) { - QGIViewDimension* vd = dynamic_cast(qgi); - if (vd != nullptr) { + QGraphicsItem *qgi = dl->parentItem(); + if (qgi) { + QGIViewDimension *vd = dynamic_cast(qgi); + if (vd) { std::string s = vd->getViewNameAsString(); sceneNames.push_back(s); } } } - } else { + } + else { std::string s = itemView->getViewNameAsString(); sceneNames.push_back(s); } @@ -1397,7 +1005,7 @@ void MDIViewPage::showStatusMsg(const char* s1, const char* s2, const char* s3) //return the MDIViewPage that owns the scene MDIViewPage *MDIViewPage::getFromScene(const QGSPage *scene) { - if (scene != nullptr && scene->parent() != nullptr) { + if (scene && scene->parent()) { return dynamic_cast(scene->parent()); } @@ -1453,7 +1061,7 @@ Py::Object MDIViewPagePy::getattr(const char * attr) if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); - for (auto it : dict_base) { + for (const auto& it : dict_base) { dict_self.setItem(it.first, it.second); } return dict_self; diff --git a/src/Mod/TechDraw/Gui/MDIViewPage.h b/src/Mod/TechDraw/Gui/MDIViewPage.h index 3c5910b622..0c74b3b4e8 100644 --- a/src/Mod/TechDraw/Gui/MDIViewPage.h +++ b/src/Mod/TechDraw/Gui/MDIViewPage.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_MDIVIEWPAGE_H #define TECHDRAWGUI_MDIVIEWPAGE_H +#include + #include #include @@ -37,7 +39,6 @@ QT_BEGIN_NAMESPACE class QAction; class QGraphicsItem; class QGraphicsScene; -class QTimer; QT_END_NAMESPACE namespace TechDraw { @@ -57,17 +58,17 @@ class QGIView; class TechDrawGuiExport MDIViewPage : public Gui::MDIView, public Gui::SelectionObserver { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: MDIViewPage(ViewProviderPage *page, Gui::Document* doc, QWidget* parent = nullptr); - virtual ~MDIViewPage(); + ~MDIViewPage() override; - void addChildrenToPage(void); + void addChildrenToPage(); /// Observer message from the Tree Selection mechanism - void onSelectionChanged(const Gui::SelectionChanges& msg); + void onSelectionChanged(const Gui::SelectionChanges& msg) override; void preSelectionChanged(const QPoint &pos); /// QGraphicsScene selection routines @@ -75,19 +76,14 @@ public: void clearSceneSelection(); void blockSceneSelection(bool isBlocked); - void attachTemplate(TechDraw::DrawTemplate *obj); - void updateTemplate(bool force = false); - void fixOrphans(bool force = false); - void matchSceneRectToTemplate(void); - - bool onMsg(const char* pMsg,const char** ppReturn); - bool onHasMsg(const char* pMsg) const; + bool onMsg(const char* pMsg,const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; - void print(); - void print(QPrinter* printer); - void printPdf(); + void print() override; + void print(QPrinter* printer) override; + void printPdf() override; void printPdf(std::string file); - void printPreview(); + void printPreview() override; void saveSVG(std::string file); void saveDXF(std::string file); @@ -95,50 +91,32 @@ public: void setDocumentObject(const std::string&); void setDocumentName(const std::string&); - PyObject* getPyObject(); + + PyObject* getPyObject() override; TechDraw::DrawPage * getPage() { return m_vpPage->getDrawPage(); } - QGVPage* getQGVPage(void) {return m_view;} - QGSPage* getQGSPage(void) {return m_scene;} ViewProviderPage* getViewProviderPage() {return m_vpPage;} - QPointF getTemplateCenter(TechDraw::DrawTemplate *obj); - void centerOnPage(void); - - void redrawAllViews(void); - void redraw1View(TechDraw::DrawView* dv); - void setTabText(std::string t); - bool addView(const App::DocumentObject *obj); - static MDIViewPage *getFromScene(const QGSPage *scene); - void contextMenuEvent(QContextMenuEvent *event); + void contextMenuEvent(QContextMenuEvent *event) override; + + void setScene(QGSPage* scene, QGVPage* view); public Q_SLOTS: - void viewAll(); - void saveSVG(void); - void saveDXF(void); - void savePDF(void); - void toggleFrame(void); - void toggleKeepUpdated(void); + void viewAll() override; + void saveSVG(); + void saveDXF(); + void savePDF(); + void toggleFrame(); + void toggleKeepUpdated(); // void testAction(void); void sceneSelectionChanged(); - void onTimer(); protected: - void findMissingViews( const std::vector &list, std::vector &missing); - bool hasQView(App::DocumentObject *obj); - bool orphanExists(const char *viewName, const std::vector &list); + void closeEvent(QCloseEvent*) override; - /// Attaches view of obj to m_scene. Returns true on success, false otherwise - bool attachView(App::DocumentObject *obj); - - void closeEvent(QCloseEvent*); - - void setDimensionGroups(void); - void setBalloonGroups(void); - void setLeaderGroups(void); void showStatusMsg(const char* s1, const char* s2, const char* s3) const; void onDeleteObject(const App::DocumentObject& obj); @@ -147,9 +125,8 @@ protected: Connection connectDeletedObject; bool compareSelections(std::vector treeSel,QList sceneSel); - void setTreeToSceneSelect(void); - void sceneSelectionManager(void); - + void setTreeToSceneSelect(); + void sceneSelectionManager(); private: QAction *m_toggleFrameAction; @@ -162,18 +139,18 @@ private: std::string m_objectName; std::string m_documentName; bool isSelectionBlocked; - QGSPage* m_scene; - QGVPage *m_view; - QTimer *m_timer; + QPointer m_scene; QString m_currentPath; - QPageLayout::Orientation m_orientation; - QPageSize::PageSizeId m_paperSize; - qreal pagewidth, pageheight; - ViewProviderPage *m_vpPage; + ViewProviderPage* m_vpPage; QList m_qgSceneSelected; //items in selection order -// QList deleteItems; + + void getPaperAttributes(void); + QPageLayout::Orientation m_orientation; + QPageSize::PageSizeId m_paperSize; + double m_pagewidth, m_pageheight; + }; class MDIViewPagePy : public Py::PythonExtension @@ -182,11 +159,11 @@ public: using BaseType = Py::PythonExtension; static void init_type(); - MDIViewPagePy(MDIViewPage *mdi); - ~MDIViewPagePy(); + explicit MDIViewPagePy(MDIViewPage *mdi); + ~MDIViewPagePy() override; - Py::Object repr(); - Py::Object getattr(const char *); + Py::Object repr() override; + Py::Object getattr(const char *) override; Py::Object getPage(const Py::Tuple&); Py::Object cast_to_base(const Py::Tuple&); diff --git a/src/Mod/TechDraw/Gui/PreCompiled.h b/src/Mod/TechDraw/Gui/PreCompiled.h index 1035911529..321afaec6d 100644 --- a/src/Mod/TechDraw/Gui/PreCompiled.h +++ b/src/Mod/TechDraw/Gui/PreCompiled.h @@ -79,9 +79,12 @@ #ifndef __QtAll__ # include #endif +#include #include #include -#include +#include +#include +#include #include #include diff --git a/src/Mod/TechDraw/Gui/PreferencesGui.cpp b/src/Mod/TechDraw/Gui/PreferencesGui.cpp index dfcbe76d0e..48b281653a 100644 --- a/src/Mod/TechDraw/Gui/PreferencesGui.cpp +++ b/src/Mod/TechDraw/Gui/PreferencesGui.cpp @@ -37,6 +37,8 @@ #include #include +#include + #include "Rez.h" #include "PreferencesGui.h" diff --git a/src/Mod/TechDraw/Gui/PreferencesGui.h b/src/Mod/TechDraw/Gui/PreferencesGui.h index 3f66c0340a..3da59ca9e7 100644 --- a/src/Mod/TechDraw/Gui/PreferencesGui.h +++ b/src/Mod/TechDraw/Gui/PreferencesGui.h @@ -25,12 +25,12 @@ #include +#include + class QFont; class QString; -class QColor; #include -#include namespace TechDrawGui { diff --git a/src/Mod/TechDraw/Gui/QGCustomBorder.cpp b/src/Mod/TechDraw/Gui/QGCustomBorder.cpp index ac61f1b24e..c9fabd025b 100644 --- a/src/Mod/TechDraw/Gui/QGCustomBorder.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomBorder.cpp @@ -25,8 +25,10 @@ #include #include #include +#include #include #include +#include #include #endif @@ -35,8 +37,6 @@ #include #include -#include -#include #include "QGCustomBorder.h" using namespace TechDrawGui; diff --git a/src/Mod/TechDraw/Gui/QGCustomBorder.h b/src/Mod/TechDraw/Gui/QGCustomBorder.h index 256fcbe501..103bcb1a8a 100644 --- a/src/Mod/TechDraw/Gui/QGCustomBorder.h +++ b/src/Mod/TechDraw/Gui/QGCustomBorder.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGCUSTOMBORDER_H #define DRAWINGGUI_QGCUSTOMBORDER_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGCustomClip.h b/src/Mod/TechDraw/Gui/QGCustomClip.h index ba64ee74db..230540132f 100644 --- a/src/Mod/TechDraw/Gui/QGCustomClip.h +++ b/src/Mod/TechDraw/Gui/QGCustomClip.h @@ -42,14 +42,14 @@ namespace TechDrawGui class TechDrawGuiExport QGCustomClip : public QGraphicsItemGroup { public: - explicit QGCustomClip(void); - ~QGCustomClip() {} + explicit QGCustomClip(); + ~QGCustomClip() override {} enum {Type = QGraphicsItem::UserType + 132}; - int type() const { return Type;} - virtual QRectF boundingRect() const; + int type() const override { return Type;} + QRectF boundingRect() const override; - void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ); + void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; virtual void centerAt(QPointF centerPos); virtual void centerAt(double cX, double cY); virtual void setRect(QRectF r); diff --git a/src/Mod/TechDraw/Gui/QGCustomImage.cpp b/src/Mod/TechDraw/Gui/QGCustomImage.cpp index 663ec24abe..ccdb10a01a 100644 --- a/src/Mod/TechDraw/Gui/QGCustomImage.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomImage.cpp @@ -23,15 +23,14 @@ #include "PreCompiled.h" #ifndef _PreComp_ #include +#include +#include #include #include #endif #include -#include -#include - #include "QGCustomImage.h" using namespace TechDrawGui; @@ -83,7 +82,7 @@ bool QGCustomImage::load(QPixmap map) return(success); } -QSize QGCustomImage::imageSize(void) +QSize QGCustomImage::imageSize() { QSize result = m_px.size() * scale(); return result; diff --git a/src/Mod/TechDraw/Gui/QGCustomImage.h b/src/Mod/TechDraw/Gui/QGCustomImage.h index d1616858e1..737a444477 100644 --- a/src/Mod/TechDraw/Gui/QGCustomImage.h +++ b/src/Mod/TechDraw/Gui/QGCustomImage.h @@ -44,20 +44,20 @@ namespace TechDrawGui class TechDrawGuiExport QGCustomImage : public QGraphicsPixmapItem { public: - explicit QGCustomImage(void); - ~QGCustomImage(); + explicit QGCustomImage(); + ~QGCustomImage() override; enum {Type = QGraphicsItem::UserType + 201}; int type() const override { return Type;} - virtual void paint( QPainter *painter, + void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr ) override; virtual void centerAt(QPointF centerPos); virtual void centerAt(double cX, double cY); virtual bool load(QString fileSpec); virtual bool load(QPixmap map); - virtual QSize imageSize(void); + virtual QSize imageSize(); protected: QPixmap m_px; diff --git a/src/Mod/TechDraw/Gui/QGCustomLabel.cpp b/src/Mod/TechDraw/Gui/QGCustomLabel.cpp index 778312bfae..a720213023 100644 --- a/src/Mod/TechDraw/Gui/QGCustomLabel.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomLabel.cpp @@ -25,10 +25,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #endif @@ -38,8 +40,6 @@ #include #include -#include -#include #include "Rez.h" #include "QGCustomLabel.h" diff --git a/src/Mod/TechDraw/Gui/QGCustomLabel.h b/src/Mod/TechDraw/Gui/QGCustomLabel.h index ef39694282..fb8a2e0512 100644 --- a/src/Mod/TechDraw/Gui/QGCustomLabel.h +++ b/src/Mod/TechDraw/Gui/QGCustomLabel.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGCUSTOMLABEL_H #define DRAWINGGUI_QGCUSTOMLABEL_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGCustomRect.cpp b/src/Mod/TechDraw/Gui/QGCustomRect.cpp index feb4c1cd38..0de4c724cd 100644 --- a/src/Mod/TechDraw/Gui/QGCustomRect.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomRect.cpp @@ -25,8 +25,10 @@ #include #include #include +#include #include #include +#include #include #endif @@ -35,8 +37,6 @@ #include #include -#include -#include #include "QGCustomRect.h" using namespace TechDrawGui; diff --git a/src/Mod/TechDraw/Gui/QGCustomRect.h b/src/Mod/TechDraw/Gui/QGCustomRect.h index c554c000f6..866cf509e3 100644 --- a/src/Mod/TechDraw/Gui/QGCustomRect.h +++ b/src/Mod/TechDraw/Gui/QGCustomRect.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGCUSTOMRECT_H #define DRAWINGGUI_QGCUSTOMRECT_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGCustomSvg.cpp b/src/Mod/TechDraw/Gui/QGCustomSvg.cpp index 82471600c4..09b3d6b533 100644 --- a/src/Mod/TechDraw/Gui/QGCustomSvg.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomSvg.cpp @@ -23,12 +23,12 @@ #include "PreCompiled.h" #ifndef _PreComp_ #include +#include #include #endif #include -#include #include "QGCustomSvg.h" using namespace TechDrawGui; diff --git a/src/Mod/TechDraw/Gui/QGCustomSvg.h b/src/Mod/TechDraw/Gui/QGCustomSvg.h index 602a4b9884..bdeb34e23e 100644 --- a/src/Mod/TechDraw/Gui/QGCustomSvg.h +++ b/src/Mod/TechDraw/Gui/QGCustomSvg.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGCUSTOMSVG_H #define DRAWINGGUI_QGCUSTOMSVG_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGCustomText.cpp b/src/Mod/TechDraw/Gui/QGCustomText.cpp index 44de673dd3..5831a12cb6 100644 --- a/src/Mod/TechDraw/Gui/QGCustomText.cpp +++ b/src/Mod/TechDraw/Gui/QGCustomText.cpp @@ -25,10 +25,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #endif @@ -38,14 +40,13 @@ #include #include -#include -#include -#include "Rez.h" -#include "ZVALUE.h" #include "DrawGuiUtil.h" +#include "PreferencesGui.h" #include "QGICMark.h" #include "QGIView.h" -#include "PreferencesGui.h" +#include "Rez.h" +#include "ZVALUE.h" + #include "QGCustomText.h" using namespace TechDrawGui; @@ -112,12 +113,12 @@ void QGCustomText::justifyRightAt(double cX, double cY, bool vCenter) setPos(newX,newY); } -double QGCustomText::getHeight(void) +double QGCustomText::getHeight() { return boundingRect().height(); } -double QGCustomText::getWidth(void) +double QGCustomText::getWidth() { return boundingRect().width(); } diff --git a/src/Mod/TechDraw/Gui/QGCustomText.h b/src/Mod/TechDraw/Gui/QGCustomText.h index 30d93fd9e3..804d6ead43 100644 --- a/src/Mod/TechDraw/Gui/QGCustomText.h +++ b/src/Mod/TechDraw/Gui/QGCustomText.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGCUSTOMTEXT_H #define DRAWINGGUI_QGCUSTOMTEXT_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGDisplayArea.cpp b/src/Mod/TechDraw/Gui/QGDisplayArea.cpp index 00f2e51bad..1882342709 100644 --- a/src/Mod/TechDraw/Gui/QGDisplayArea.cpp +++ b/src/Mod/TechDraw/Gui/QGDisplayArea.cpp @@ -39,7 +39,7 @@ using namespace TechDrawGui; -QGDisplayArea::QGDisplayArea(void) +QGDisplayArea::QGDisplayArea() { setHandlesChildEvents(false); setCacheMode(QGraphicsItem::NoCache); diff --git a/src/Mod/TechDraw/Gui/QGDisplayArea.h b/src/Mod/TechDraw/Gui/QGDisplayArea.h index 4b606c4de7..3acd564d71 100644 --- a/src/Mod/TechDraw/Gui/QGDisplayArea.h +++ b/src/Mod/TechDraw/Gui/QGDisplayArea.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGDISPLAYAREA_H #define DRAWINGGUI_QGDISPLAYAREA_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGEPath.cpp b/src/Mod/TechDraw/Gui/QGEPath.cpp index ae509f0735..0f01188377 100644 --- a/src/Mod/TechDraw/Gui/QGEPath.cpp +++ b/src/Mod/TechDraw/Gui/QGEPath.cpp @@ -59,24 +59,6 @@ QGMarker::QGMarker(int idx) : QGIVertex(idx), setFlag(QGraphicsItem::ItemIsMovable, true); } -QVariant QGMarker::itemChange(GraphicsItemChange change, const QVariant &value) -{ -// Base::Console().Message("QGMarker::itemChange(%d)\n",change); - return QGIVertex::itemChange(change, value); -} - -void QGMarker::hoverEnterEvent(QGraphicsSceneHoverEvent *event) -{ -// Base::Console().Message("QGMarker::hoverEnterEvent(%d)\n",getProjIndex()); - QGIVertex::hoverEnterEvent(event); -} - -void QGMarker::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) -{ -// Base::Console().Message("QGMarker::hoverLeaveEvent(%d)\n",getProjIndex()); - QGIVertex::hoverLeaveEvent(event); -} - void QGMarker::mousePressEvent(QGraphicsSceneMouseEvent * event) { // Base::Console().Message("QGMarker::mousePressEvent() - focustype: %d\n", @@ -94,12 +76,6 @@ void QGMarker::mousePressEvent(QGraphicsSceneMouseEvent * event) QGIVertex::mousePressEvent(event); } -void QGMarker::mouseMoveEvent(QGraphicsSceneMouseEvent * event) -{ -// Base::Console().Message("QGMarker::mouseMoveEvent(%d)\n", getProjIndex()); - QGIVertex::mouseMoveEvent(event); -} - void QGMarker::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if (event->button() == Qt::RightButton) { //we're done @@ -148,16 +124,6 @@ void QGMarker::setRadius(float r) setPath(p); } -void QGMarker::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) -{ - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - - //~ painter->drawRect(boundingRect()); //good for debugging - - QGIVertex::paint (painter, &myOption, widget); -} - //****************************************************************************** QGEPath::QGEPath(QGILeaderLine* leader) : @@ -210,13 +176,13 @@ void QGEPath::hoverEnterEvent(QGraphicsSceneHoverEvent *event) void QGEPath::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGIView *view = dynamic_cast (parentItem()); - assert(view != nullptr); + assert(view); Q_UNUSED(view); Q_EMIT hover(false); QGraphicsItem* parent = parentItem(); bool parentSel(false); - if (parent != nullptr) { + if (parent) { parentSel = parent->isSelected(); } if (!parentSel && !isSelected()) { @@ -291,10 +257,10 @@ void QGEPath::clearMarkers() return; } for (auto& m: m_markers) { - if (m != nullptr) { + if (m) { m->hide(); QGraphicsScene* s = m->scene(); - if (s != nullptr) { + if (s) { s->removeItem(m); //should this be setParentItem(nullptr) instead?? } delete m; @@ -332,10 +298,10 @@ void QGEPath::onDoubleClick(QPointF pos, int markerIndex) onEndEdit(); } -void QGEPath::onEndEdit(void) +void QGEPath::onEndEdit() { // Base::Console().Message("QGEPath::onEndEdit()\n"); - if (m_ghost != nullptr) { + if (m_ghost) { scene()->removeItem(m_ghost); //stop ghost from messing up brect } inEdit(false); @@ -344,16 +310,16 @@ void QGEPath::onEndEdit(void) clearMarkers(); } -std::vector QGEPath::getDeltasFromLeader(void) +std::vector QGEPath::getDeltasFromLeader() { std::vector qDeltas; - if (m_parentLeader == nullptr) { + if (!m_parentLeader) { Base::Console().Message("QGEP::getDeltasFromLeader - m_parentLeader is nullptr\n"); return qDeltas; } DrawLeaderLine* featLeader = m_parentLeader->getFeature(); - if (featLeader == nullptr) { + if (!featLeader) { Base::Console().Message("QGEP::getDeltasFromLeader - featLeader is nullptr\n"); return qDeltas; } @@ -371,7 +337,7 @@ std::vector QGEPath::getDeltasFromLeader(void) } //announce points editing is finished -void QGEPath::updateParent(void) +void QGEPath::updateParent() { // Base::Console().Message("QGEPath::updateParent() - inEdit: %d pts: %d\n",inEdit(), m_ghostPoints.size()); // dumpGhostPoints("QGEP::updateParent"); @@ -382,10 +348,10 @@ void QGEPath::updateParent(void) } //the ghost is the red line drawn when creating or editing the Leader points -void QGEPath::drawGhost(void) +void QGEPath::drawGhost() { // Base::Console().Message("QGEPath::drawGhost()\n"); - if (m_ghost->scene() == nullptr) { + if (!m_ghost->scene()) { m_ghost->setParentItem(this); } QPainterPath qpp; @@ -421,20 +387,11 @@ QPainterPath QGEPath::shape() const return outline; } - double QGEPath::getEdgeFuzz(void) const + double QGEPath::getEdgeFuzz() const { return PreferencesGui::edgeFuzz(); } -void QGEPath::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - -// painter->drawRect(boundingRect()); //good for debugging - - QGIPrimPath::paint (painter, &myOption, widget); -} - void QGEPath::dumpGhostPoints(const char* text) { int idb = 0; diff --git a/src/Mod/TechDraw/Gui/QGEPath.h b/src/Mod/TechDraw/Gui/QGEPath.h index 1916947b9b..f30c6af384 100644 --- a/src/Mod/TechDraw/Gui/QGEPath.h +++ b/src/Mod/TechDraw/Gui/QGEPath.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_EDITABLEPATH_H #define TECHDRAWGUI_EDITABLEPATH_H +#include + #include #include #include @@ -30,7 +32,6 @@ #include "QGIPrimPath.h" #include "QGIVertex.h" - namespace TechDrawGui { @@ -47,7 +48,6 @@ public: enum {Type = QGraphicsItem::UserType + 302}; int type() const override { return Type;} - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; @@ -62,11 +62,7 @@ Q_SIGNALS: void endEdit(void); protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; private: bool m_dragging; @@ -86,7 +82,6 @@ public: int type() const override { return Type;} virtual QRectF boundingRect() const override; virtual QPainterPath shape() const override; - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; void inEdit(bool b) { m_inEdit = b; } bool inEdit(void) { return m_inEdit; } diff --git a/src/Mod/TechDraw/Gui/QGIArrow.cpp b/src/Mod/TechDraw/Gui/QGIArrow.cpp index 0ff68991cc..d97a3fa39c 100644 --- a/src/Mod/TechDraw/Gui/QGIArrow.cpp +++ b/src/Mod/TechDraw/Gui/QGIArrow.cpp @@ -359,11 +359,3 @@ double QGIArrow::getOverlapAdjust(int style, double size) } return result; } - -void QGIArrow::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - - QGIPrimPath::paint (painter, &myOption, widget); -} diff --git a/src/Mod/TechDraw/Gui/QGIArrow.h b/src/Mod/TechDraw/Gui/QGIArrow.h index fa513f1166..5417469d03 100644 --- a/src/Mod/TechDraw/Gui/QGIArrow.h +++ b/src/Mod/TechDraw/Gui/QGIArrow.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMARROW_H #define DRAWINGGUI_QGRAPHICSITEMARROW_H +#include + #include # include "QGIPrimPath.h" @@ -73,8 +75,6 @@ public: static double getPrefArrowSize(); static double getOverlapAdjust(int style, double size); - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ); - protected: QPainterPath makeFilledTriangle(double length, double width, bool flipped); QPainterPath makeFilledTriangle(Base::Vector3d dir, double length, double width); diff --git a/src/Mod/TechDraw/Gui/QGICMark.cpp b/src/Mod/TechDraw/Gui/QGICMark.cpp index f061791920..bf560fb50b 100644 --- a/src/Mod/TechDraw/Gui/QGICMark.cpp +++ b/src/Mod/TechDraw/Gui/QGICMark.cpp @@ -46,7 +46,7 @@ QGICMark::QGICMark(int index) : QGIVertex(index) m_width = 0.75; draw(); } -void QGICMark::draw(void) +void QGICMark::draw() { QPainterPath cmPath; cmPath.moveTo(0.0,m_size); @@ -103,7 +103,7 @@ QPainterPath QGICMark::shape() const return outline; } - double QGICMark::getMarkFuzz(void) const + double QGICMark::getMarkFuzz() const { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/General"); diff --git a/src/Mod/TechDraw/Gui/QGICMark.h b/src/Mod/TechDraw/Gui/QGICMark.h index 93b601a498..bee5b8201d 100644 --- a/src/Mod/TechDraw/Gui/QGICMark.h +++ b/src/Mod/TechDraw/Gui/QGICMark.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMCMARK_H #define DRAWINGGUI_QGRAPHICSITEMCMARK_H +#include + # include "QGIVertex.h" namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/QGICaption.cpp b/src/Mod/TechDraw/Gui/QGICaption.cpp index c4dbbe40eb..e6451e1bfe 100644 --- a/src/Mod/TechDraw/Gui/QGICaption.cpp +++ b/src/Mod/TechDraw/Gui/QGICaption.cpp @@ -25,10 +25,12 @@ #include #include #include +#include #include #include #include #include +#include #include #include #endif @@ -38,8 +40,6 @@ #include #include -#include -#include #include "QGICaption.h" using namespace TechDrawGui; diff --git a/src/Mod/TechDraw/Gui/QGICaption.h b/src/Mod/TechDraw/Gui/QGICaption.h index 902dea6072..5683891895 100644 --- a/src/Mod/TechDraw/Gui/QGICaption.h +++ b/src/Mod/TechDraw/Gui/QGICaption.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGICAPTION_H #define DRAWINGGUI_QGICAPTION_H +#include + #include "QGCustomText.h" namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/QGICenterLine.cpp b/src/Mod/TechDraw/Gui/QGICenterLine.cpp index c8123263d5..e19986a26d 100644 --- a/src/Mod/TechDraw/Gui/QGICenterLine.cpp +++ b/src/Mod/TechDraw/Gui/QGICenterLine.cpp @@ -22,19 +22,19 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #include #endif -#include - #include #include #include #include #include "PreferencesGui.h" + #include "QGICenterLine.h" using namespace TechDrawGui; diff --git a/src/Mod/TechDraw/Gui/QGICenterLine.h b/src/Mod/TechDraw/Gui/QGICenterLine.h index 56bd7f69ac..052cef956a 100644 --- a/src/Mod/TechDraw/Gui/QGICenterLine.h +++ b/src/Mod/TechDraw/Gui/QGICenterLine.h @@ -23,12 +23,13 @@ #ifndef TECHDRAWGUI_QGICENTERLINE_H #define TECHDRAWGUI_QGICENTERLINE_H +#include + #include #include #include "QGIDecoration.h" - namespace TechDrawGui { diff --git a/src/Mod/TechDraw/Gui/QGIDecoration.h b/src/Mod/TechDraw/Gui/QGIDecoration.h index 53e3bad899..a32228b494 100644 --- a/src/Mod/TechDraw/Gui/QGIDecoration.h +++ b/src/Mod/TechDraw/Gui/QGIDecoration.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGIDECORATION_H #define DRAWINGGUI_QGIDECORATION_H +#include + #include #include #include @@ -36,6 +38,7 @@ QT_END_NAMESPACE #include #include #include +#include namespace TechDrawGui { diff --git a/src/Mod/TechDraw/Gui/QGIDimLines.cpp b/src/Mod/TechDraw/Gui/QGIDimLines.cpp index 6d8a09a8bb..3cc7045375 100644 --- a/src/Mod/TechDraw/Gui/QGIDimLines.cpp +++ b/src/Mod/TechDraw/Gui/QGIDimLines.cpp @@ -66,7 +66,7 @@ QPainterPath QGIDimLines::shape() const return outline; } -double QGIDimLines::getEdgeFuzz(void) const +double QGIDimLines::getEdgeFuzz() const { return PreferencesGui::edgeFuzz(); } @@ -76,16 +76,3 @@ QRectF QGIDimLines::boundingRect() const { return shape().controlPointRect().adjusted(-3, -3, 3, 3); } - -void QGIDimLines::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) -{ - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - -// painter->drawRect(boundingRect()); //good for debugging -// painter->drawPath(shape()); //good for debugging - - QGIPrimPath::paint (painter, &myOption, widget); -} - - diff --git a/src/Mod/TechDraw/Gui/QGIDimLines.h b/src/Mod/TechDraw/Gui/QGIDimLines.h index 898be3843e..281a6acc5b 100644 --- a/src/Mod/TechDraw/Gui/QGIDimLines.h +++ b/src/Mod/TechDraw/Gui/QGIDimLines.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMDIMLINES_H #define DRAWINGGUI_QGRAPHICSITEMDIMLINES_H +#include + # include "QGIPrimPath.h" QT_BEGIN_NAMESPACE @@ -50,7 +52,6 @@ public: //double getLineWidth() { return m_lineWidth; } //void setLineWidth(double w); //QPainterPath shape() const; - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr) override; protected: //QVariant itemChange(GraphicsItemChange change, const QVariant &value); diff --git a/src/Mod/TechDraw/Gui/QGIDrawingTemplate.cpp b/src/Mod/TechDraw/Gui/QGIDrawingTemplate.cpp index aeb1da358d..58926f3289 100644 --- a/src/Mod/TechDraw/Gui/QGIDrawingTemplate.cpp +++ b/src/Mod/TechDraw/Gui/QGIDrawingTemplate.cpp @@ -66,12 +66,6 @@ QGIDrawingTemplate::~QGIDrawingTemplate() pathItem = nullptr; } -QVariant QGIDrawingTemplate::itemChange(GraphicsItemChange change, const QVariant &value) -{ - return QGraphicsItemGroup::itemChange(change, value); -} - - void QGIDrawingTemplate::clearContents() { diff --git a/src/Mod/TechDraw/Gui/QGIDrawingTemplate.h b/src/Mod/TechDraw/Gui/QGIDrawingTemplate.h index 98846c783b..e1667dfaf7 100644 --- a/src/Mod/TechDraw/Gui/QGIDrawingTemplate.h +++ b/src/Mod/TechDraw/Gui/QGIDrawingTemplate.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMDRAWINGTEMPLATE_H #define DRAWINGGUI_QGRAPHICSITEMDRAWINGTEMPLATE_H +#include + #include "QGITemplate.h" QT_BEGIN_NAMESPACE @@ -43,7 +45,7 @@ class TechDrawGuiExport QGIDrawingTemplate : public QGITemplate Q_OBJECT public: - QGIDrawingTemplate(QGSPage *); + explicit QGIDrawingTemplate(QGSPage *); ~QGIDrawingTemplate(); enum {Type = QGraphicsItem::UserType + 151}; @@ -57,7 +59,6 @@ protected: TechDraw::DrawParametricTemplate * getParametricTemplate(); protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); QGraphicsPathItem *pathItem; }; diff --git a/src/Mod/TechDraw/Gui/QGIEdge.cpp b/src/Mod/TechDraw/Gui/QGIEdge.cpp index 380e4b762a..009b9f9672 100644 --- a/src/Mod/TechDraw/Gui/QGIEdge.cpp +++ b/src/Mod/TechDraw/Gui/QGIEdge.cpp @@ -100,7 +100,7 @@ Qt::PenStyle QGIEdge::getHiddenStyle() return hidStyle; } - double QGIEdge::getEdgeFuzz(void) const + double QGIEdge::getEdgeFuzz() const { return PreferencesGui::edgeFuzz(); } @@ -119,12 +119,3 @@ QPainterPath QGIEdge::shape() const outline = stroker.createStroke(path()); return outline; } - -void QGIEdge::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - - //~ painter->drawRect(boundingRect()); //good for debugging - - QGIPrimPath::paint (painter, &myOption, widget); -} diff --git a/src/Mod/TechDraw/Gui/QGIEdge.h b/src/Mod/TechDraw/Gui/QGIEdge.h index 5ee7da3963..476c2f962a 100644 --- a/src/Mod/TechDraw/Gui/QGIEdge.h +++ b/src/Mod/TechDraw/Gui/QGIEdge.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMEDGE_H #define DRAWINGGUI_QGRAPHICSITEMEDGE_H +#include + #include "QGIPrimPath.h" namespace TechDrawGui @@ -39,7 +41,6 @@ public: int type() const override { return Type;} virtual QRectF boundingRect() const override; virtual QPainterPath shape() const override; - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; int getProjIndex() const { return projIndex; } diff --git a/src/Mod/TechDraw/Gui/QGIFace.cpp b/src/Mod/TechDraw/Gui/QGIFace.cpp index fb85e72780..af73319adc 100644 --- a/src/Mod/TechDraw/Gui/QGIFace.cpp +++ b/src/Mod/TechDraw/Gui/QGIFace.cpp @@ -22,10 +22,13 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #include #include +#include +#include #include #include #include @@ -34,18 +37,10 @@ #include #include #include -#endif - -#include #include #include #include - -#include -#include -#include - -#include +#endif #include #include @@ -247,7 +242,7 @@ void QGIFace::setOutline(const QPainterPath & path) m_outline = path; } -void QGIFace::clearLineSets(void) +void QGIFace::clearLineSets() { m_dashSpecs.clear(); clearFillItems(); @@ -356,7 +351,7 @@ QGraphicsPathItem* QGIFace::geomToStubbyLine(TechDraw::BaseGeomPtr base, double return fillItem; } -QPen QGIFace::setGeomPen(void) +QPen QGIFace::setGeomPen() { QPen result; result.setWidthF(Rez::guiX(m_geomWeight)); @@ -488,7 +483,7 @@ double QGIFace::dashRemain(const std::vector dv, const double offset) //! get zoom level (scale) from QGraphicsView // not used currently -double QGIFace::getXForm(void) +double QGIFace::getXForm() { //try to keep the pattern the same when View scales double result = 1.0; @@ -504,7 +499,7 @@ double QGIFace::getXForm(void) return result; } -void QGIFace::clearFillItems(void) +void QGIFace::clearFillItems() { for (auto& f: m_fillItems) { f->setParentItem(nullptr); @@ -670,7 +665,7 @@ QPixmap QGIFace::textureFromSvg(std::string fileSpec) void QGIFace::setHatchColor(App::Color c) { - m_svgCol = c.asCSSString(); + m_svgCol = c.asHexString(); m_geomColor = c.asValue(); } @@ -704,7 +699,7 @@ void QGIFace::setLineWeight(double w) { m_geomWeight = w; } -void QGIFace::getParameters(void) +void QGIFace::getParameters() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/PAT"); @@ -717,7 +712,7 @@ void QGIFace::getParameters(void) hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Colors"); - App::Color temp = hGrp->GetUnsigned("FaceColor",0xffffffff); + App::Color temp {static_cast(hGrp->GetUnsigned("FaceColor",0xffffffff))}; setFillColor(temp.asValue()); hGrp = App::GetApplication().GetUserParameter() @@ -734,12 +729,3 @@ QPainterPath QGIFace::shape() const { return path(); } - -void QGIFace::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; -// painter->drawRect(boundingRect()); //good for debugging - - QGIPrimPath::paint (painter, &myOption, widget); -} - diff --git a/src/Mod/TechDraw/Gui/QGIFace.h b/src/Mod/TechDraw/Gui/QGIFace.h index e5da739e35..fac417db27 100644 --- a/src/Mod/TechDraw/Gui/QGIFace.h +++ b/src/Mod/TechDraw/Gui/QGIFace.h @@ -23,14 +23,12 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMFACE_H #define DRAWINGGUI_QGRAPHICSITEMFACE_H -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include + +#include #include #include @@ -51,13 +49,12 @@ class QGIFace : public QGIPrimPath { public: explicit QGIFace(int index = -1); - ~QGIFace(); + ~QGIFace() override; enum {Type = QGraphicsItem::UserType + 104}; int type() const override { return Type;} QRectF boundingRect() const override; QPainterPath shape() const override; - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; public: enum fillMode { @@ -73,15 +70,15 @@ public: int getProjIndex() const { return projIndex; } void draw(); - virtual void setPrettyNormal() override; - virtual void setPrettyPre() override; - virtual void setPrettySel() override; + void setPrettyNormal() override; + void setPrettyPre() override; + void setPrettySel() override; void setDrawEdges(bool b); virtual void setOutline(const QPainterPath& path); //shared fill parms void isHatched(bool s) {m_isHatched = s; } - bool isHatched(void) {return m_isHatched;} + bool isHatched() {return m_isHatched;} void setFillMode(fillMode m); //general hatch parms & methods @@ -91,9 +88,9 @@ public: //svg fill parms & methods void setHatchFile(std::string fileSpec); void loadSvgHatch(std::string fileSpec); - void buildSvgHatch(void); + void buildSvgHatch(); void hideSvg(bool b); - void clearSvg(void); + void clearSvg(); //tiled pixmap fill from svg void buildPixHatch(); @@ -102,9 +99,9 @@ public: void setGeomHatchWeight(double w) { m_geomWeight = w; } void setLineWeight(double w); - void clearLineSets(void); + void clearLineSets(); void addLineSet(TechDraw::LineSet& ls); - void clearFillItems(void); + void clearFillItems(); void lineSetToFillItems(TechDraw::LineSet& ls); QGraphicsPathItem* geomToLine(TechDraw::BaseGeomPtr base, TechDraw::LineSet& ls); @@ -118,8 +115,8 @@ public: protected: void makeMark(double x, double y); - double getXForm(void); - void getParameters(void); + double getXForm(); + void getParameters(); std::vector offsetDash(const std::vector dv, const double offset); QPainterPath dashedPPath(const std::vector dv, const Base::Vector3d start, const Base::Vector3d end); @@ -138,7 +135,7 @@ protected: bool m_isHatched; QGIFace::fillMode m_mode; - QPen setGeomPen(void); + QPen setGeomPen(); std::vector decodeDashSpec(TechDraw::DashSpec d); std::vector m_fillItems; std::vector m_lineSets; diff --git a/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp b/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp index 1c28ff6996..dadd2e6880 100644 --- a/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp +++ b/src/Mod/TechDraw/Gui/QGIGhostHighlight.cpp @@ -69,14 +69,6 @@ QGIGhostHighlight::~QGIGhostHighlight() } -QVariant QGIGhostHighlight::itemChange(GraphicsItemChange change, const QVariant &value) -{ - if (change == ItemPositionHasChanged && scene()) { - // nothing to do here? - } - return QGIHighlight::itemChange(change, value); -} - void QGIGhostHighlight::mousePressEvent(QGraphicsSceneMouseEvent * event) { // Base::Console().Message("QGIGhostHighlight::mousePress() - %X\n", this); diff --git a/src/Mod/TechDraw/Gui/QGIGhostHighlight.h b/src/Mod/TechDraw/Gui/QGIGhostHighlight.h index 21bde21e74..9c37a6a388 100644 --- a/src/Mod/TechDraw/Gui/QGIGhostHighlight.h +++ b/src/Mod/TechDraw/Gui/QGIGhostHighlight.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_QGIGHOSTHIGHLIGHT_H #define TECHDRAWGUI_QGIGHOSTHIGHLIGHT_H +#include + #include #include #include @@ -52,7 +54,6 @@ Q_SIGNALS: void positionChange(QPointF p); protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) override; virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; diff --git a/src/Mod/TechDraw/Gui/QGIHighlight.h b/src/Mod/TechDraw/Gui/QGIHighlight.h index 6cf0d4c2b5..750093c220 100644 --- a/src/Mod/TechDraw/Gui/QGIHighlight.h +++ b/src/Mod/TechDraw/Gui/QGIHighlight.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_QGIHIGHLIGHT_H #define TECHDRAWGUI_QGIHIGHLIGHT_H +#include + #include #include #include diff --git a/src/Mod/TechDraw/Gui/QGILeaderLine.cpp b/src/Mod/TechDraw/Gui/QGILeaderLine.cpp index 58adadc082..3c87f34c02 100644 --- a/src/Mod/TechDraw/Gui/QGILeaderLine.cpp +++ b/src/Mod/TechDraw/Gui/QGILeaderLine.cpp @@ -164,11 +164,6 @@ void QGILeaderLine::mousePressEvent(QGraphicsSceneMouseEvent * event) QGraphicsItem::mousePressEvent(event); } -//void QGILeaderLine::mouseMoveEvent(QGraphicsSceneMouseEvent * event) -//{ -// QGraphicsItem::mouseMoveEvent(event); -//} - //QGILL isn't draggable so skip QGIV::mouseRelease void QGILeaderLine::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { @@ -201,7 +196,7 @@ void QGILeaderLine::onSourceChange(TechDraw::DrawView* newParent) // Base::Console().Message("QGILL::onSoureChange(%s)\n",newParent->getNameInDocument()); std::string parentName = newParent->getNameInDocument(); QGIView* qgiParent = getQGIVByName(parentName); - if (qgiParent != nullptr) { + if (qgiParent) { m_parentItem = qgiParent; setParentItem(m_parentItem); draw(); @@ -243,10 +238,10 @@ void QGILeaderLine::setPrettySel() { } -void QGILeaderLine::closeEdit(void) +void QGILeaderLine::closeEdit() { // Base::Console().Message("QGIL::closeEdit()\n"); - if (m_editPath != nullptr) { + if (m_editPath) { m_editPath->onEndEdit(); //tell QEPath that edit session ended } } @@ -259,10 +254,8 @@ void QGILeaderLine::onLineEditFinished(QPointF tipDisplace, std::vector // points.size()); m_blockDraw = true; auto featLeader = getFeature(); - if (featLeader == nullptr) { - //tarfu + if (!featLeader) return; - } double baseScale = featLeader->getBaseScale(); if ( !(TechDraw::DrawUtil::fpCompare(tipDisplace.x(),0.0) && @@ -295,13 +288,12 @@ void QGILeaderLine::onLineEditFinished(QPointF tipDisplace, std::vector draw(); } -void QGILeaderLine::startPathEdit(void) +void QGILeaderLine::startPathEdit() { saveState(); auto featLeader( dynamic_cast(getViewObject()) ); - if (featLeader == nullptr) { + if (!featLeader) return; - } double scale = featLeader->getScale(); m_editPath->setScale(scale); @@ -310,22 +302,22 @@ void QGILeaderLine::startPathEdit(void) m_editPath->startPathEdit(getWayPointsFromFeature()); } -void QGILeaderLine::saveState(void) +void QGILeaderLine::saveState() { // Base::Console().Message("QGILL::saveState()\n"); auto featLeader = getFeature(); - if (featLeader != nullptr) { + if (featLeader) { m_savePoints = featLeader->WayPoints.getValues(); m_saveX = featLeader->X.getValue(); m_saveY = featLeader->Y.getValue(); } } -void QGILeaderLine::restoreState(void) +void QGILeaderLine::restoreState() { // Base::Console().Message("QGILL::restoreState()\n"); auto featLeader = getFeature(); - if (featLeader != nullptr) { + if (featLeader) { featLeader->WayPoints.setValues(m_savePoints); featLeader->X.setValue(m_saveX); featLeader->Y.setValue(m_saveY); @@ -340,52 +332,44 @@ void QGILeaderLine::updateView(bool update) // Base::Console().Message("QGIL::updateView() %s\n",getViewObject()->getNameInDocument()); Q_UNUSED(update); auto featLeader( dynamic_cast(getViewObject()) ); - if ( featLeader == nullptr ) { + if (!featLeader) { Base::Console().Warning("QGILL::updateView - no feature!\n"); return; } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } draw(); } void QGILeaderLine::draw() { // Base::Console().Message("QGILL::draw()- %s\n", getViewObject()->getNameInDocument()); - if (m_blockDraw) { + if (m_blockDraw) return; - } - if (!isVisible()) { + if (!isVisible()) return; - } TechDraw::DrawLeaderLine* featLeader = getFeature(); - if((!featLeader) ) { + if (!featLeader) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } double scale = 1.0; TechDraw::DrawView* parent = featLeader->getBaseView(); - if (parent != nullptr) { + if (parent) scale = parent->getScale(); - } - if (m_editPath->inEdit()) { + if (m_editPath->inEdit()) return; - } //******** - if (featLeader->isLocked()) { + if (featLeader->isLocked()) setFlag(QGraphicsItem::ItemIsMovable, false); - } else { + else setFlag(QGraphicsItem::ItemIsMovable, true); - } m_lineStyle = (Qt::PenStyle) vp->LineStyle.getValue(); double baseScale = featLeader->getBaseScale(); @@ -427,7 +411,7 @@ QPainterPath QGILeaderLine::makeLeaderPath(std::vector qPoints) // Base::Console().Message("QGILeaderLine::makeLeaderPath()\n"); QPainterPath result; DrawLeaderLine* featLeader = getFeature(); - if (featLeader == nullptr) { + if (!featLeader) { Base::Console().Message("QGILL::makeLeaderPath - featLeader is nullptr\n"); return result; } @@ -469,7 +453,7 @@ QPainterPath QGILeaderLine::makeLeaderPath(std::vector qPoints) return result; } -QPointF QGILeaderLine::getAttachFromFeature(void) +QPointF QGILeaderLine::getAttachFromFeature() { // Base::Console().Message("QGILL::getAttachFromFeature()\n"); QPointF result; @@ -484,12 +468,12 @@ QPointF QGILeaderLine::getAttachFromFeature(void) return result; } -std::vector QGILeaderLine::getWayPointsFromFeature(void) +std::vector QGILeaderLine::getWayPointsFromFeature() { std::vector qPoints; DrawLeaderLine* featLeader = getFeature(); - if (featLeader == nullptr) { + if (!featLeader) { Base::Console().Message("QGILL::getWayPointsFromFeature - featLeader is nullptr\n"); return qPoints; } @@ -565,7 +549,7 @@ void QGILeaderLine::drawBorder() //****************************************************************************** -void QGILeaderLine::abandonEdit(void) +void QGILeaderLine::abandonEdit() { // Base::Console().Message("QGIL::abandonEdit()\n"); m_editPath->clearMarkers(); @@ -573,23 +557,22 @@ void QGILeaderLine::abandonEdit(void) restoreState(); } -double QGILeaderLine::getLineWidth(void) +double QGILeaderLine::getLineWidth() { auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return Rez::guiX(LineGroup::getDefaultWidth("Graphic")); - } return Rez::guiX(vp->LineWidth.getValue()); } -TechDraw::DrawLeaderLine* QGILeaderLine::getFeature(void) +TechDraw::DrawLeaderLine* QGILeaderLine::getFeature() { TechDraw::DrawLeaderLine* result = static_cast(getViewObject()); return result; } -double QGILeaderLine::getEdgeFuzz(void) const +double QGILeaderLine::getEdgeFuzz() const { return PreferencesGui::edgeFuzz(); } @@ -600,16 +583,14 @@ QColor QGILeaderLine::getNormalColor() m_colNormal = PreferencesGui::leaderQColor(); auto lead( dynamic_cast(getViewObject()) ); - if( lead == nullptr ) { + if (!lead) // Base::Console().Message("QGILL::getNormalColor - no feature\n"); return m_colNormal; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) // Base::Console().Message("QGILL::getNormalColor - no viewProvider\n"); return m_colNormal; - } m_colNormal = vp->Color.getValue().asValue(); return m_colNormal; @@ -620,11 +601,6 @@ QRectF QGILeaderLine::boundingRect() const return childrenBoundingRect(); } -QPainterPath QGILeaderLine::shape() const -{ - return QGraphicsItemGroup::shape(); -} - void QGILeaderLine::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { QStyleOptionGraphicsItem myOption(*option); myOption.state &= ~QStyle::State_Selected; diff --git a/src/Mod/TechDraw/Gui/QGILeaderLine.h b/src/Mod/TechDraw/Gui/QGILeaderLine.h index 38145307ca..ac45b19140 100644 --- a/src/Mod/TechDraw/Gui/QGILeaderLine.h +++ b/src/Mod/TechDraw/Gui/QGILeaderLine.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMLEADERLINE_H #define DRAWINGGUI_QGRAPHICSITEMLEADERLINE_H +#include + #include #include #include @@ -57,34 +59,32 @@ public: enum {Type = QGraphicsItem::UserType + 232}; explicit QGILeaderLine(); - ~QGILeaderLine() = default; + ~QGILeaderLine() override = default; int type() const override { return Type;} - virtual void paint( QPainter * painter, + void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; - virtual QRectF boundingRect() const override; - virtual QPainterPath shape(void) const override; + QRectF boundingRect() const override; - virtual void drawBorder() override; - virtual void updateView(bool update = false) override; + void drawBorder() override; + void updateView(bool update = false) override; - virtual TechDraw::DrawLeaderLine* getFeature(void); + virtual TechDraw::DrawLeaderLine* getFeature(); - void startPathEdit(void); + void startPathEdit(); void setArrows(std::vector pathPoints); - void abandonEdit(void); - void closeEdit(void); + void abandonEdit(); + void closeEdit(); - double getLineWidth(void); - double getEdgeFuzz(void) const; + double getLineWidth(); + double getEdgeFuzz() const; - virtual void mousePressEvent(QGraphicsSceneMouseEvent * event) override; - //void mouseMoveEvent(QGraphicsSceneMouseEvent * event) override; - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent * event) override; - virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void mousePressEvent(QGraphicsSceneMouseEvent * event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent * event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; void setPrettyNormal(); void setPrettyPre(); @@ -94,23 +94,23 @@ public: public Q_SLOTS: void onLineEditFinished(QPointF attach, std::vector deltas); //QGEPath is finished editing points - virtual void onSourceChange(TechDraw::DrawView* newParent) override; + void onSourceChange(TechDraw::DrawView* newParent) override; Q_SIGNALS: - void editComplete(void); //tell caller that edit session is finished + void editComplete(); //tell caller that edit session is finished protected: - virtual void draw() override; + void draw() override; QPainterPath makeLeaderPath(std::vector qPoints); - std::vector getWayPointsFromFeature(void); - QPointF getAttachFromFeature(void); + std::vector getWayPointsFromFeature(); + QPointF getAttachFromFeature(); - virtual QVariant itemChange( GraphicsItemChange change, + QVariant itemChange( GraphicsItemChange change, const QVariant &value ) override; std::vector m_pathPoints; - void saveState(void); - void restoreState(void); + void saveState(); + void restoreState(); protected: QColor getNormalColor() override; diff --git a/src/Mod/TechDraw/Gui/QGIMatting.cpp b/src/Mod/TechDraw/Gui/QGIMatting.cpp index 72bcdc164a..c462168838 100644 --- a/src/Mod/TechDraw/Gui/QGIMatting.cpp +++ b/src/Mod/TechDraw/Gui/QGIMatting.cpp @@ -23,8 +23,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ #include +#include #include #include +#include #include #endif @@ -33,8 +35,6 @@ #include #include -#include -#include #include "PreferencesGui.h" #include "QGCustomRect.h" #include "ZVALUE.h" diff --git a/src/Mod/TechDraw/Gui/QGIMatting.h b/src/Mod/TechDraw/Gui/QGIMatting.h index aa15599f16..ab031a7a15 100644 --- a/src/Mod/TechDraw/Gui/QGIMatting.h +++ b/src/Mod/TechDraw/Gui/QGIMatting.h @@ -29,7 +29,6 @@ #include #include - QT_BEGIN_NAMESPACE class QPainter; class QStyleOptionGraphicsItem; @@ -42,26 +41,26 @@ class QGCustomRect; class TechDrawGuiExport QGIMatting : public QGraphicsItemGroup { public: - explicit QGIMatting(void); - ~QGIMatting() {} + explicit QGIMatting(); + ~QGIMatting() override {} enum {Type = QGraphicsItem::UserType + 205}; - int type() const { return Type;} + int type() const override { return Type;} - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ); - virtual QRectF boundingRect() const; + void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; + QRectF boundingRect() const override; virtual void setSize(double w, double h) {m_height = h; m_width = w;} //virtual void setHoleStyle(int hs) {m_holeStyle = hs;} virtual void setRadius(double r) {m_radius = r;} - virtual void draw(void); + virtual void draw(); protected: double m_height; double m_width; //int m_holeStyle; //round or rect double m_radius; - int getHoleStyle(void); + int getHoleStyle(); QGraphicsPathItem* m_mat; QGraphicsPathItem* m_border; diff --git a/src/Mod/TechDraw/Gui/QGIPrimPath.cpp b/src/Mod/TechDraw/Gui/QGIPrimPath.cpp index 93e7b91300..474ab003c0 100644 --- a/src/Mod/TechDraw/Gui/QGIPrimPath.cpp +++ b/src/Mod/TechDraw/Gui/QGIPrimPath.cpp @@ -157,13 +157,13 @@ QColor QGIPrimPath::getNormalColor() } QGraphicsItem* qparent = parentItem(); - if (qparent == nullptr) { + if (!qparent) { parent = nullptr; } else { parent = dynamic_cast (qparent); } - if (parent != nullptr) { + if (parent) { result = parent->getNormalColor(); } else { result = PreferencesGui::normalQColor(); @@ -177,13 +177,13 @@ QColor QGIPrimPath::getPreColor() QColor result; QGIView *parent; QGraphicsItem* qparent = parentItem(); - if (qparent == nullptr) { + if (!qparent) { parent = nullptr; } else { parent = dynamic_cast (qparent); } - if (parent != nullptr) { + if (parent) { result = parent->getPreColor(); } else { result = PreferencesGui::preselectQColor(); @@ -196,13 +196,13 @@ QColor QGIPrimPath::getSelectColor() QColor result; QGIView *parent; QGraphicsItem* qparent = parentItem(); - if (qparent == nullptr) { + if (!qparent) { parent = nullptr; } else { parent = dynamic_cast (qparent); } - if (parent != nullptr) { + if (parent) { result = parent->getSelectColor(); } else { result = PreferencesGui::selectQColor(); @@ -279,9 +279,9 @@ void QGIPrimPath::mousePressEvent(QGraphicsSceneMouseEvent * event) //wf: this seems a bit of a hack. does it mess up selection of QGIPP?? QGIView *parent; QGraphicsItem* qparent = parentItem(); - if (qparent != nullptr) { + if (qparent) { parent = dynamic_cast (qparent); - if (parent != nullptr) { + if (parent) { // Base::Console().Message("QGIPP::mousePressEvent - passing event to QGIV parent\n"); parent->mousePressEvent(event); } else { diff --git a/src/Mod/TechDraw/Gui/QGIPrimPath.h b/src/Mod/TechDraw/Gui/QGIPrimPath.h index 746cb708b7..bdcb4adacf 100644 --- a/src/Mod/TechDraw/Gui/QGIPrimPath.h +++ b/src/Mod/TechDraw/Gui/QGIPrimPath.h @@ -23,7 +23,12 @@ #ifndef DRAWINGGUI_QGIPRIMPATH_H #define DRAWINGGUI_QGIPRIMPATH_H +#include + +#include #include +#include + #include QT_BEGIN_NAMESPACE diff --git a/src/Mod/TechDraw/Gui/QGIProjGroup.cpp b/src/Mod/TechDraw/Gui/QGIProjGroup.cpp index 8589ba93bd..406b86dd3f 100644 --- a/src/Mod/TechDraw/Gui/QGIProjGroup.cpp +++ b/src/Mod/TechDraw/Gui/QGIProjGroup.cpp @@ -58,7 +58,7 @@ QGIProjGroup::QGIProjGroup() // setFrameState(false); } -TechDraw::DrawProjGroup * QGIProjGroup::getDrawView(void) const +TechDraw::DrawProjGroup * QGIProjGroup::getDrawView() const { App::DocumentObject *obj = getViewObject(); return dynamic_cast(obj); @@ -180,7 +180,7 @@ QGIView * QGIProjGroup::getAnchorQItem() const // Get the currently assigned anchor view App::DocumentObject *anchorObj = getDrawView()->Anchor.getValue(); auto anchorView( dynamic_cast(anchorObj) ); - if( anchorView == nullptr ) { + if (!anchorView) { return nullptr; } @@ -196,13 +196,8 @@ QGIView * QGIProjGroup::getAnchorQItem() const return nullptr; } -void QGIProjGroup::updateView(bool update) -{ - return QGIViewCollection::updateView(update); -} - //QGIPG does not rotate. Only individual views rotate -void QGIProjGroup::rotateView(void) +void QGIProjGroup::rotateView() { Base::Console().Warning("QGIPG: Projection Groups do not rotate. Change ignored\n"); } diff --git a/src/Mod/TechDraw/Gui/QGIProjGroup.h b/src/Mod/TechDraw/Gui/QGIProjGroup.h index 262845b4a7..afb345bc2c 100644 --- a/src/Mod/TechDraw/Gui/QGIProjGroup.h +++ b/src/Mod/TechDraw/Gui/QGIProjGroup.h @@ -23,9 +23,11 @@ #ifndef DRAWINGGUI_QGIProjGroup_H #define DRAWINGGUI_QGIProjGroup_H -#include "QGIViewCollection.h" +#include + #include +#include "QGIViewCollection.h" QT_BEGIN_NAMESPACE class QGraphicsScene; @@ -33,6 +35,10 @@ class QGraphicsSceneMouseEvent; class QEvent; QT_END_NAMESPACE +namespace TechDraw { + class DrawProjGroup; +} + namespace TechDrawGui { @@ -42,30 +48,29 @@ public: QGIProjGroup(); // TODO: if the QGIVO is deleted, should we clean up any remaining QGIVParts?? - ~QGIProjGroup() = default; + ~QGIProjGroup() override = default; enum {Type = QGraphicsItem::UserType + 113}; int type() const override { return Type;} void alignTo(QGIProjGroup *, const QString &alignment); - virtual void updateView(bool update = false) override; - virtual void rotateView(void) override; + void rotateView() override; - virtual void drawBorder(void) override; + void drawBorder() override; protected: - virtual bool sceneEventFilter(QGraphicsItem* watched, QEvent *event) override; - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + bool sceneEventFilter(QGraphicsItem* watched, QEvent *event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; // Mouse handling - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent * event ) override; - virtual void mousePressEvent(QGraphicsSceneMouseEvent * event) override; - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent * event) override; + void mouseMoveEvent(QGraphicsSceneMouseEvent * event ) override; + void mousePressEvent(QGraphicsSceneMouseEvent * event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent * event) override; QGIView * getAnchorQItem() const; private: /// Convenience function - TechDraw::DrawProjGroup * getDrawView(void) const; + TechDraw::DrawProjGroup* getDrawView() const; QGraphicsItem* m_origin; QPoint mousePos; diff --git a/src/Mod/TechDraw/Gui/QGIRichAnno.cpp b/src/Mod/TechDraw/Gui/QGIRichAnno.cpp index 9d9b9a9dde..b6f06e2fa8 100644 --- a/src/Mod/TechDraw/Gui/QGIRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/QGIRichAnno.cpp @@ -76,7 +76,6 @@ #include "QGIPrimPath.h" #include "QGEPath.h" #include "QGMText.h" -#include "QGIView.h" #include "QGCustomText.h" #include "QGCustomRect.h" @@ -88,8 +87,7 @@ using namespace TechDrawGui; //************************************************************** -QGIRichAnno::QGIRichAnno(QGraphicsItem* myParent, - TechDraw::DrawRichAnno* anno) : +QGIRichAnno::QGIRichAnno() : m_isExporting(false), m_hasHover(false) { setHandlesChildEvents(false); @@ -99,12 +97,6 @@ QGIRichAnno::QGIRichAnno(QGraphicsItem* myParent, setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true); setFlag(QGraphicsItem::ItemSendsGeometryChanges,true); - if (myParent != nullptr) { - setParentItem(myParent); - } - - setViewFeature(anno); - m_text = new QGCustomText(); m_text->setTextInteractionFlags(Qt::NoTextInteraction); addToGroup(m_text); @@ -120,16 +112,6 @@ QGIRichAnno::QGIRichAnno(QGraphicsItem* myParent, } -QVariant QGIRichAnno::itemChange(GraphicsItemChange change, const QVariant &value) -{ - if (change == ItemSelectedHasChanged && scene()) { - //There's nothing special for QGIRA to do when selection changes! - } else if(change == ItemSceneChange && scene()) { - // nothing special! - } - return QGIView::itemChange(change, value); -} - //void QGIRichAnno::select(bool state) //{ // setSelected(state); @@ -147,15 +129,14 @@ void QGIRichAnno::updateView(bool update) // Base::Console().Message("QGIRA::updateView() - %s\n", getViewName()); Q_UNUSED(update); auto annoFeat( dynamic_cast(getViewObject()) ); - if ( annoFeat == nullptr ) { + if (!annoFeat) { Base::Console().Log("QGIRA::updateView - no feature!\n"); return; } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } if (annoFeat->X.isTouched() || annoFeat->Y.isTouched()) { float x = Rez::guiX(annoFeat->X.getValue()); @@ -177,28 +158,24 @@ void QGIRichAnno::drawBorder() void QGIRichAnno::draw() { // Base::Console().Log("QGIRA::draw() - %s - parent: %X\n",getFeature()->getNameInDocument(), parentItem()); - if (!isVisible()) { + if (!isVisible()) // Base::Console().Message("QGIRA::draw - not visible\n"); return; - } TechDraw::DrawRichAnno* annoFeat = getFeature(); - if((!annoFeat) ) { + if (!annoFeat) // Base::Console().Message("QGIRA::draw - no feature\n"); return; - } auto vp = static_cast(getViewProvider(getFeature())); - if ( vp == nullptr ) { + if (!vp) { // Base::Console().Message("QGIRA::draw - no viewprovider\n"); return; } -// double appX = Rez::guiX(annoFeat->X.getValue()); -// double appY = Rez::guiX(annoFeat->Y.getValue()); - - QGIView::draw(); setTextItem(); + + QGIView::draw(); } void QGIRichAnno::setTextItem() @@ -212,7 +189,6 @@ void QGIRichAnno::setTextItem() if (!getExporting()) { //convert point font sizes to (Rez,mm) font sizes QRegExp rxFontSize(QString::fromUtf8("font-size:([0-9]*)pt;")); - QString match; double mmPerPoint = 0.353; double sizeConvert = Rez::getRezFactor() * mmPerPoint; int pos = 0; @@ -295,7 +271,7 @@ void QGIRichAnno::setLineSpacing(int lineSpacing) //} -TechDraw::DrawRichAnno* QGIRichAnno::getFeature(void) +TechDraw::DrawRichAnno* QGIRichAnno::getFeature() { TechDraw::DrawRichAnno* result = static_cast(getViewObject()); @@ -308,11 +284,6 @@ QRectF QGIRichAnno::boundingRect() const return rect.adjusted(-10.,-10.,10.,10.); } -QPainterPath QGIRichAnno::shape() const -{ - return QGraphicsItemGroup::shape(); -} - void QGIRichAnno::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { QStyleOptionGraphicsItem myOption(*option); myOption.state &= ~QStyle::State_Selected; @@ -326,13 +297,11 @@ QPen QGIRichAnno::rectPen() const { QPen pen; const auto sym( dynamic_cast(getViewObject()) ); - if( sym == nullptr ) { + if (!sym) return pen; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return pen; - } double rectWeight = Rez::guiX(vp->LineWidth.getValue()); Qt::PenStyle rectStyle = (Qt::PenStyle) vp->LineStyle.getValue(); @@ -345,12 +314,12 @@ QPen QGIRichAnno::rectPen() const return pen; } -QFont QGIRichAnno::prefFont(void) +QFont QGIRichAnno::prefFont() { return PreferencesGui::labelFontQFont(); } -double QGIRichAnno::prefPointSize(void) +double QGIRichAnno::prefPointSize() { // Base::Console().Message("QGIRA::prefPointSize()\n"); double fontSize = Preferences::dimFontSizeMM(); @@ -366,9 +335,8 @@ void QGIRichAnno::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { Q_UNUSED(event); TechDraw::DrawRichAnno *annotation = dynamic_cast(getViewObject()); - if (annotation == nullptr) { + if (!annotation) return; - } QString text = QString::fromUtf8(annotation->AnnoText.getValue()); diff --git a/src/Mod/TechDraw/Gui/QGIRichAnno.h b/src/Mod/TechDraw/Gui/QGIRichAnno.h index 4e23e311c1..ddc9491dd4 100644 --- a/src/Mod/TechDraw/Gui/QGIRichAnno.h +++ b/src/Mod/TechDraw/Gui/QGIRichAnno.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_QGIRICHANNO_H #define TECHDRAWGUI_QGIRICHANNO_H +#include + #include #include #include @@ -30,6 +32,7 @@ #include #include +#include "QGIView.h" namespace TechDraw { class DrawRichAnno; @@ -55,8 +58,7 @@ class TechDrawGuiExport QGIRichAnno : public QGIView public: enum {Type = QGraphicsItem::UserType + 233}; - explicit QGIRichAnno(QGraphicsItem* myParent = nullptr, - TechDraw::DrawRichAnno* lead = nullptr); + explicit QGIRichAnno(); ~QGIRichAnno() = default; int type() const override { return Type;} @@ -64,7 +66,6 @@ public: const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; virtual QRectF boundingRect() const override; - virtual QPainterPath shape(void) const override; virtual void drawBorder() override; virtual void updateView(bool update = false) override; @@ -86,8 +87,6 @@ public Q_SLOTS: protected: virtual void draw() override; - virtual QVariant itemChange( GraphicsItemChange change, - const QVariant &value ) override; void setLineSpacing(int lineSpacing); double prefPointSize(void); QFont prefFont(void); diff --git a/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp b/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp index c06906dd83..3df35c26a1 100644 --- a/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp +++ b/src/Mod/TechDraw/Gui/QGISVGTemplate.cpp @@ -29,11 +29,11 @@ #include #include #include -#endif // #ifndef _PreComp_ - #include #include #include +#endif // #ifndef _PreComp_ + #include #include @@ -79,13 +79,6 @@ QGISVGTemplate::~QGISVGTemplate() delete m_svgRender; } -QVariant QGISVGTemplate::itemChange(GraphicsItemChange change, - const QVariant &value) -{ - return QGraphicsItemGroup::itemChange(change, value); -} - - void QGISVGTemplate::openFile(const QFile &file) { Q_UNUSED(file); @@ -145,7 +138,7 @@ void QGISVGTemplate::updateView(bool update) draw(); } -void QGISVGTemplate::createClickHandles(void) +void QGISVGTemplate::createClickHandles() { TechDraw::DrawSVGTemplate *svgTemplate = getSVGTemplate(); QString templateFilename(QString::fromUtf8(svgTemplate->PageResult.getValue())); diff --git a/src/Mod/TechDraw/Gui/QGISVGTemplate.h b/src/Mod/TechDraw/Gui/QGISVGTemplate.h index 06a11b637c..f0a3999fe3 100644 --- a/src/Mod/TechDraw/Gui/QGISVGTemplate.h +++ b/src/Mod/TechDraw/Gui/QGISVGTemplate.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMSVGTEMPLATE_H #define DRAWINGGUI_QGRAPHICSITEMSVGTEMPLATE_H +#include + QT_BEGIN_NAMESPACE class QGraphicsScene; class QGraphicsSvgItem; @@ -46,7 +48,7 @@ class TechDrawGuiExport QGISVGTemplate : public QGITemplate Q_OBJECT public: - QGISVGTemplate(QGSPage* scene); + explicit QGISVGTemplate(QGSPage* scene); virtual ~QGISVGTemplate(); enum {Type = QGraphicsItem::UserType + 153}; @@ -66,7 +68,6 @@ protected: bool firstTime; QGraphicsSvgItem *m_svgItem; QSvgRenderer *m_svgRender; - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); }; // class QGISVGTemplate } diff --git a/src/Mod/TechDraw/Gui/QGISectionLine.cpp b/src/Mod/TechDraw/Gui/QGISectionLine.cpp index 205bed5824..04d62ee0e3 100644 --- a/src/Mod/TechDraw/Gui/QGISectionLine.cpp +++ b/src/Mod/TechDraw/Gui/QGISectionLine.cpp @@ -22,6 +22,7 @@ #include "PreCompiled.h" #ifndef _PreComp_ +#include #include #include #include @@ -36,11 +37,11 @@ //#include #include -#include -#include "Rez.h" -#include "PreferencesGui.h" -#include "QGIView.h" +#include "QGIArrow.h" #include "QGISectionLine.h" +#include "QGIView.h" +#include "PreferencesGui.h" +#include "Rez.h" #define ANSISTANDARD 0 #define ISOSTANDARD 1 diff --git a/src/Mod/TechDraw/Gui/QGISectionLine.h b/src/Mod/TechDraw/Gui/QGISectionLine.h index ea336298da..31eaed6337 100644 --- a/src/Mod/TechDraw/Gui/QGISectionLine.h +++ b/src/Mod/TechDraw/Gui/QGISectionLine.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_QGISECTIONLINE_H #define TECHDRAWGUI_QGISECTIONLINE_H +#include + #include #include #include @@ -30,13 +32,14 @@ #include #include "QGCustomText.h" -#include "QGIArrow.h" #include "QGIDecoration.h" - namespace TechDrawGui { +class QGIArrow; +class QGCustomText; + class TechDrawGuiExport QGISectionLine : public QGIDecoration { public: diff --git a/src/Mod/TechDraw/Gui/QGITemplate.cpp b/src/Mod/TechDraw/Gui/QGITemplate.cpp index 52e08b57f9..90095c305e 100644 --- a/src/Mod/TechDraw/Gui/QGITemplate.cpp +++ b/src/Mod/TechDraw/Gui/QGITemplate.cpp @@ -52,14 +52,9 @@ QGITemplate::~QGITemplate() pageTemplate = nullptr; } -QVariant QGITemplate::itemChange(GraphicsItemChange change, const QVariant &value) -{ - return QGraphicsItemGroup::itemChange(change, value); -} - void QGITemplate::setTemplate(TechDraw::DrawTemplate *obj) { - if(obj == nullptr) + if (!obj) return; pageTemplate = obj; diff --git a/src/Mod/TechDraw/Gui/QGITemplate.h b/src/Mod/TechDraw/Gui/QGITemplate.h index 2e33931ef5..38cc3a073e 100644 --- a/src/Mod/TechDraw/Gui/QGITemplate.h +++ b/src/Mod/TechDraw/Gui/QGITemplate.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMTEMPLATE_H #define DRAWINGGUI_QGRAPHICSITEMTEMPLATE_H +#include + #include #include @@ -63,12 +65,11 @@ public: virtual void draw() = 0; protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); TechDraw::DrawTemplate *pageTemplate; std::vector textFields; }; -} // namespace MDIViewPageGui +} // namespace #endif // DRAWINGGUI_QGRAPHICSITEMTEMPLATE_H diff --git a/src/Mod/TechDraw/Gui/QGITile.cpp b/src/Mod/TechDraw/Gui/QGITile.cpp index 717d71ee96..fe3096fe08 100644 --- a/src/Mod/TechDraw/Gui/QGITile.cpp +++ b/src/Mod/TechDraw/Gui/QGITile.cpp @@ -29,24 +29,29 @@ #include #endif +#include + #include #include #include +#include #include +#include #include #include -//#include #include #include #include -#include #include "Rez.h" #include "PreferencesGui.h" #include "DrawGuiUtil.h" #include "QGIView.h" #include "QGIWeldSymbol.h" +#include "QGCustomSvg.h" +#include "QGCustomText.h" + #include "QGITile.h" using namespace TechDrawGui; @@ -98,18 +103,12 @@ QGITile::QGITile(TechDraw::DrawTileWeld* dtw) : m_colCurrent = m_colNormal; } -QGITile::~QGITile(void) +QGITile::~QGITile() { } -QVariant QGITile::itemChange(GraphicsItemChange change, const QVariant &value) -{ -// Base::Console().Message("QGIT::itemChange(%d)\n", change); - return QGIDecoration::itemChange(change, value); -} - -void QGITile::draw(void) +void QGITile::draw() { // Base::Console().Message("QGIT::draw()\n"); @@ -150,7 +149,7 @@ void QGITile::draw(void) } } -void QGITile::makeSymbol(void) +void QGITile::makeSymbol() { // Base::Console().Message("QGIT::makeSymbol()\n"); // m_effect->setColor(m_colCurrent); @@ -169,7 +168,7 @@ void QGITile::makeSymbol(void) m_qgSvg->centerAt(0.0, 0.0); //(0,0) is based on symbol size } -void QGITile::makeText(void) +void QGITile::makeText() { // Base::Console().Message("QGIT::makeText()\n"); prepareGeometryChange(); @@ -234,7 +233,8 @@ void QGITile::makeText(void) //read whole text file into std::string std::string QGITile::getStringFromFile(std::string inSpec) { - std::ifstream f(inSpec); + Base::FileInfo fi(inSpec); + Base::ifstream f(fi); std::stringstream ss; ss << f.rdbuf(); return ss.str(); @@ -323,18 +323,18 @@ void QGITile::setPrettySel() { draw(); } -bool QGITile::isTailRight(void) +bool QGITile::isTailRight() { return m_tailRight; } -bool QGITile::getAltWeld(void) +bool QGITile::getAltWeld() { return m_altWeld; } //TODO: this is Pen, not Brush. sb Brush to colour background -QColor QGITile::getTileColor(void) const +QColor QGITile::getTileColor() const { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Colors"); @@ -342,7 +342,7 @@ QColor QGITile::getTileColor(void) const return fcColor.asValue(); } -double QGITile::getSymbolWidth(void) const +double QGITile::getSymbolWidth() const { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Dimensions"); @@ -356,7 +356,7 @@ double QGITile::getSymbolWidth(void) const return w; } -double QGITile::getSymbolHeight(void) const +double QGITile::getSymbolHeight() const { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Dimensions"); @@ -369,7 +369,7 @@ double QGITile::getSymbolHeight(void) const } //make symbols larger or smaller than standard -double QGITile::getSymbolFactor(void) const +double QGITile::getSymbolFactor() const { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); @@ -378,28 +378,18 @@ double QGITile::getSymbolFactor(void) const return s; } -double QGITile::prefFontSize(void) const +double QGITile::prefFontSize() const { // Base::Reference hGrp = App::GetApplication().GetUserParameter(). // GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Dimensions"); return Preferences::dimFontSizeMM(); } -QString QGITile::prefTextFont(void) const +QString QGITile::prefTextFont() const { return Preferences::labelFontQString(); } -void QGITile::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { - QStyleOptionGraphicsItem myOption(*option); - myOption.state &= ~QStyle::State_Selected; - -// painter->setPen(Qt::magenta); -// painter->drawRect(boundingRect()); //good for debugging - - QGIDecoration::paint (painter, &myOption, widget); -} - QRectF QGITile::boundingRect() const { return childrenBoundingRect(); diff --git a/src/Mod/TechDraw/Gui/QGITile.h b/src/Mod/TechDraw/Gui/QGITile.h index 990ca6649d..d307f2b3c5 100644 --- a/src/Mod/TechDraw/Gui/QGITile.h +++ b/src/Mod/TechDraw/Gui/QGITile.h @@ -23,16 +23,15 @@ #ifndef TECHDRAWGUI_QGITILE_H #define TECHDRAWGUI_QGITILE_H +#include + #include #include #include #include -#include "QGCustomText.h" -#include "QGCustomSvg.h" #include "QGIDecoration.h" - namespace TechDraw { class DrawTile; class DrawTileWeld; @@ -40,6 +39,8 @@ class DrawTileWeld; namespace TechDrawGui { +class QGCustomSvg; +class QGCustomText; class QGIWeldSymbol; class TechDrawGuiExport QGITile : public QGIDecoration @@ -51,7 +52,6 @@ public: enum {Type = QGraphicsItem::UserType + 325}; int type(void) const { return Type;} - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ); virtual QRectF boundingRect() const; void setTileTextLeft(std::string s); @@ -68,8 +68,6 @@ public: virtual void draw(void); protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); - QColor getTileColor(void) const; void setPrettyNormal(); void setPrettyPre(); diff --git a/src/Mod/TechDraw/Gui/QGIVertex.h b/src/Mod/TechDraw/Gui/QGIVertex.h index 59410ef083..3f846a8682 100644 --- a/src/Mod/TechDraw/Gui/QGIVertex.h +++ b/src/Mod/TechDraw/Gui/QGIVertex.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVERTEX_H #define DRAWINGGUI_QGRAPHICSITEMVERTEX_H +#include + # include "QGIPrimPath.h" namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/QGIView.cpp b/src/Mod/TechDraw/Gui/QGIView.cpp index e18dce5fc7..316977d36e 100644 --- a/src/Mod/TechDraw/Gui/QGIView.cpp +++ b/src/Mod/TechDraw/Gui/QGIView.cpp @@ -141,26 +141,26 @@ void QGIView::onSourceChange(TechDraw::DrawView* newParent) void QGIView::isVisible(bool state) { auto feat = getViewObject(); - if (feat != nullptr) { + if (feat) { auto vp = QGIView::getViewProvider(feat); - if (vp != nullptr) { + if (vp) { Gui::ViewProviderDocumentObject* vpdo = dynamic_cast(vp); - if (vpdo != nullptr) { + if (vpdo) { vpdo->Visibility.setValue(state); } } } } -bool QGIView::isVisible(void) +bool QGIView::isVisible() { bool result = false; auto feat = getViewObject(); - if (feat != nullptr) { + if (feat) { auto vp = QGIView::getViewProvider(feat); - if (vp != nullptr) { + if (vp) { Gui::ViewProviderDocumentObject* vpdo = dynamic_cast(vp); - if (vpdo != nullptr) { + if (vpdo) { result = vpdo->Visibility.getValue(); } } @@ -198,7 +198,7 @@ QVariant QGIView::itemChange(GraphicsItemChange change, const QVariant &value) if (getViewObject()->isDerivedFrom(TechDraw::DrawProjGroupItem::getClassTypeId())) { TechDraw::DrawProjGroupItem* dpgi = static_cast(getViewObject()); TechDraw::DrawProjGroup* dpg = dpgi->getPGroup(); - if (dpg != nullptr) { + if (dpg) { if(alignHash.size() == 1) { //if aligned. QGraphicsItem* item = alignHash.begin().value(); QString alignMode = alignHash.begin().key(); @@ -321,7 +321,7 @@ double QGIView::getYInClip(double y) return -y; } -QGIViewClip* QGIView::getClipGroup(void) +QGIViewClip* QGIView::getClipGroup() { if (!getViewObject()->isInClip()) { Base::Console().Log( "Logic Error - getClipGroup called for child " @@ -340,10 +340,9 @@ QGIViewClip* QGIView::getClipGroup(void) return result; } -void QGIView::updateView(bool update) +void QGIView::updateView(bool forceUpdate) { // Base::Console().Message("QGIV::updateView() - %s\n",getViewObject()->getNameInDocument()); - (void) update; //allow/prevent dragging if (getViewObject()->isLocked()) { @@ -352,6 +351,11 @@ void QGIView::updateView(bool update) setFlag(QGraphicsItem::ItemIsMovable, true); } + if (getViewObject() && forceUpdate) { + setPosition(Rez::guiX(getViewObject()->X.getValue()), + Rez::guiX(getViewObject()->Y.getValue())); + } + double appRotation = getViewObject()->Rotation.getValue(); double guiRotation = rotation(); if (!TechDraw::DrawUtil::fpCompare(appRotation,guiRotation)) { @@ -362,7 +366,7 @@ void QGIView::updateView(bool update) } //QGIVP derived classes do not need a rotate view method as rotation is handled on App side. -void QGIView::rotateView(void) +void QGIView::rotateView() { //NOTE: QPainterPaths have to be rotated individually. This transform handles Rotation for everything else. //Scale is handled in GeometryObject for DVP & descendents @@ -377,7 +381,7 @@ double QGIView::getScale() { double result = 1.0; TechDraw::DrawView* feat = getViewObject(); - if (feat != nullptr) { + if (feat) { result = feat->getScale(); } return result; @@ -399,7 +403,7 @@ TechDraw::DrawView * QGIView::getViewObject() const void QGIView::setViewFeature(TechDraw::DrawView *obj) { - if(obj == nullptr) + if (!obj) return; viewObj = obj; @@ -422,7 +426,7 @@ void QGIView::draw() { // Base::Console().Message("QGIV::draw()\n"); double xFeat, yFeat; - if (getViewObject() != nullptr) { + if (getViewObject()) { xFeat = Rez::guiX(getViewObject()->X.getValue()); yFeat = Rez::guiX(getViewObject()->Y.getValue()); if (!getViewObject()->LockPosition.getValue()) { @@ -465,9 +469,8 @@ void QGIView::drawBorder() { // Base::Console().Message("QGIV::drawBorder() - %s\n",getViewName()); auto feat = getViewObject(); - if (feat == nullptr) { + if (!feat) return; - } drawCaption(); //always draw caption @@ -607,70 +610,82 @@ QGIView* QGIView::getQGIVByName(std::string name) /* static */ Gui::ViewProvider* QGIView::getViewProvider(App::DocumentObject* obj) { - Gui::ViewProvider* result = nullptr; - if (obj != nullptr) { + if (obj) { Gui::Document* guiDoc = Gui::Application::Instance->getDocument(obj->getDocument()); - result = guiDoc->getViewProvider(obj); + return guiDoc->getViewProvider(obj); } - return result; + return nullptr; } -QGVPage* QGIView::getGraphicsView(TechDraw::DrawView* dv) +QGVPage* QGIView::getQGVPage(TechDraw::DrawView* dv) { - QGVPage* graphicsView = nullptr; - Gui::ViewProvider* vp = getViewProvider(dv); - ViewProviderDrawingView* vpdv = dynamic_cast(vp); - if (vpdv != nullptr) { - MDIViewPage* mdi = vpdv->getMDIViewPage(); - if (mdi != nullptr) { - graphicsView = mdi->getQGVPage(); - } + ViewProviderPage* vpp = getViewProviderPage(dv); + if (!vpp) { + return vpp->getQGVPage(); } - return graphicsView; + return nullptr; } -QGSPage* QGIView::getGraphicsScene(TechDraw::DrawView* dv) +QGSPage* QGIView::getQGSPage(TechDraw::DrawView* dv) { - QGSPage* graphicsScene = nullptr; - Gui::ViewProvider* vp = getViewProvider(dv); - ViewProviderDrawingView* vpdv = dynamic_cast(vp); - if (vpdv != nullptr) { - MDIViewPage* mdi = vpdv->getMDIViewPage(); - if (mdi != nullptr) { - graphicsScene = mdi->getQGSPage(); - } + ViewProviderPage* vpp = getViewProviderPage(dv); + if (vpp) { + return vpp->getQGSPage(); } - return graphicsScene; + return nullptr; } -MDIViewPage* QGIView::getMDIViewPage(void) const +MDIViewPage* QGIView::getMDIViewPage() const { - QGSPage* qgsp = static_cast(scene()); - return MDIViewPage::getFromScene(qgsp); + if (!getViewObject()) { + return nullptr; + } + ViewProviderPage* vpp = getViewProviderPage(getViewObject()); + if (vpp) { + return vpp->getMDIViewPage(); + } + return nullptr; +} + +ViewProviderPage* QGIView::getViewProviderPage(TechDraw::DrawView* dv) +{ + if (!dv) { + return nullptr; + } + TechDraw::DrawPage* page = dv->findParentPage(); + if (!page) { + return nullptr; + } + + Gui::Document* activeGui = Gui::Application::Instance->getDocument(page->getDocument()); + if (!activeGui) { + return nullptr; + } + + return dynamic_cast(activeGui->getViewProvider(page)); } //remove a child of this from scene while keeping scene indexes valid void QGIView::removeChild(QGIView* child) { - if ( (child != nullptr) && - (child->parentItem() == this) ) { + if (child && (child->parentItem() == this) ) { prepareGeometryChange(); scene()->removeItem(child); } } -bool QGIView::getFrameState(void) +bool QGIView::getFrameState() { // Base::Console().Message("QGIV::getFrameState() - %s\n",getViewName()); bool result = true; TechDraw::DrawView* dv = getViewObject(); - if (dv != nullptr) { + if (dv) { TechDraw::DrawPage* page = dv->findParentPage(); - if (page != nullptr) { + if (page) { Gui::Document* activeGui = Gui::Application::Instance->getDocument(page->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(page); ViewProviderPage* vpp = dynamic_cast(vp); - if (vpp != nullptr) { + if (vpp) { result = vpp->getFrameState(); } } @@ -680,7 +695,7 @@ bool QGIView::getFrameState(void) void QGIView::addArbitraryItem(QGraphicsItem* qgi) { - if (qgi != nullptr) { + if (qgi) { // m_randomItems.push_back(qgi); addToGroup(qgi); qgi->show(); diff --git a/src/Mod/TechDraw/Gui/QGIView.h b/src/Mod/TechDraw/Gui/QGIView.h index cf52f19cde..49d68f59ab 100644 --- a/src/Mod/TechDraw/Gui/QGIView.h +++ b/src/Mod/TechDraw/Gui/QGIView.h @@ -25,6 +25,8 @@ #include +#include + #include #include #include @@ -35,7 +37,6 @@ #include #include - QT_BEGIN_NAMESPACE class QGraphicsScene; class QGraphicsSceneMouseEvent; @@ -60,6 +61,7 @@ namespace TechDrawGui { class QGSPage; class QGVPage; +class ViewProviderPage; class QGCustomBorder; class QGCustomLabel; class QGCustomText; @@ -75,12 +77,12 @@ class TechDrawGuiExport QGIView : public QObject, public QGraphicsItemGroup Q_OBJECT public: QGIView(); - virtual ~QGIView(); + ~QGIView() override; enum {Type = QGraphicsItem::UserType + 101}; int type() const override { return Type;} - virtual QRectF boundingRect() const override; - virtual void paint( QPainter *painter, + QRectF boundingRect() const override; + void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr ) override; @@ -88,20 +90,22 @@ public: const std::string getViewNameAsString() const; void setViewFeature(TechDraw::DrawView *obj); TechDraw::DrawView * getViewObject() const; - double getScale(void); + MDIViewPage* getMDIViewPage() const; - virtual bool getFrameState(void); + double getScale(); + + virtual bool getFrameState(); virtual void toggleCache(bool state); virtual void updateView(bool update = false); - virtual void drawBorder(void); + virtual void drawBorder(); virtual void isVisible(bool state); - virtual bool isVisible(void); + virtual bool isVisible(); virtual void setGroupSelection(bool b); - virtual void draw(void); - virtual void drawCaption(void); - virtual void rotateView(void); + virtual void draw(); + virtual void drawCaption(); + virtual void rotateView(); void makeMark(double x, double y, QColor c = Qt::red); void makeMark(Base::Vector3d v, QColor c = Qt::red); void makeMark(QPointF p, QColor c = Qt::red); @@ -115,32 +119,31 @@ public: void isInnerView(bool state) { m_innerView = state; } double getYInClip(double y); /** @} */ - QGIViewClip* getClipGroup(void); + QGIViewClip* getClipGroup(); void alignTo(QGraphicsItem*, const QString &alignment); void setLocked(bool b) { m_locked = b; } - virtual QColor getNormalColor(void); //preference - virtual QColor getPreColor(void); //preference - virtual QColor getSelectColor(void); //preference - virtual QColor getCurrentColor(void) { return m_colCurrent; } - virtual QColor getSettingColor(void) { return m_colSetting; } + virtual QColor getNormalColor(); //preference + virtual QColor getPreColor(); //preference + virtual QColor getSelectColor(); //preference + virtual QColor getCurrentColor() { return m_colCurrent; } + virtual QColor getSettingColor() { return m_colSetting; } virtual void setSettingColor(QColor c) { m_colSetting = c; } static Gui::ViewProvider* getViewProvider(App::DocumentObject* obj); - static QGVPage* getGraphicsView(TechDraw::DrawView* dv); - static QGSPage* getGraphicsScene(TechDraw::DrawView* dv); + static ViewProviderPage* getViewProviderPage(TechDraw::DrawView* dv); + static QGVPage* getQGVPage(TechDraw::DrawView* dv); + static QGSPage* getQGSPage(TechDraw::DrawView* dv); static int calculateFontPixelSize(double sizeInMillimetres); static int calculateFontPixelWidth(const QFont &font); static const double DefaultFontSizeInMM; - static QString getPrefFont(void); - static double getPrefFontSize(void); - static double getDimFontSize(void); + static QString getPrefFont(); + static double getPrefFontSize(); + static double getDimFontSize(); - - MDIViewPage* getMDIViewPage(void) const; virtual void removeChild(QGIView* child); virtual void addArbitraryItem(QGraphicsItem* qgi); @@ -162,14 +165,14 @@ protected: // Preselection events: void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - virtual QRectF customChildrenBoundingRect(void) const; + virtual QRectF customChildrenBoundingRect() const; void dumpRect(const char* text, QRectF r); /* QString getPrefFont(void);*/ /* double getPrefFontSize(void);*/ /* double getDimFontSize(void);*/ - Base::Reference getParmGroupCol(void); + Base::Reference getParmGroupCol(); TechDraw::DrawView *viewObj; std::string viewName; diff --git a/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp b/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp index c1ad8cfa0a..471b1826c6 100644 --- a/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewAnnotation.cpp @@ -24,8 +24,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ #include +#include +#include #include #include +#include #include #include #include @@ -36,18 +39,14 @@ #include #include #include -#include -#endif - -#include -#include - -#include #include #include #include #include #include +#endif + +#include #include #include @@ -81,12 +80,6 @@ QGIViewAnnotation::QGIViewAnnotation() } - -QVariant QGIViewAnnotation::itemChange(GraphicsItemChange change, const QVariant &value) -{ - return QGIView::itemChange(change, value); -} - void QGIViewAnnotation::setViewAnnoFeature(TechDraw::DrawViewAnnotation *obj) { // called from QGVPage. (once) @@ -96,7 +89,7 @@ void QGIViewAnnotation::setViewAnnoFeature(TechDraw::DrawViewAnnotation *obj) void QGIViewAnnotation::updateView(bool update) { auto viewAnno( dynamic_cast(getViewObject()) ); - if( viewAnno == nullptr) + if (!viewAnno) return; if (update || @@ -129,7 +122,7 @@ void QGIViewAnnotation::draw() void QGIViewAnnotation::drawAnnotation() { auto viewAnno( dynamic_cast(getViewObject()) ); - if( viewAnno == nullptr ) { + if (!viewAnno) { return; } @@ -156,7 +149,7 @@ void QGIViewAnnotation::drawAnnotation() } ss << "line-height:" << viewAnno->LineSpace.getValue() << "%; "; App::Color c = viewAnno->TextColor.getValue(); - ss << "color:" << c.asCSSString() << "; "; + ss << "color:" << c.asHexString() << "; "; ss << "}\n\n\n\n

"; for(std::vector::const_iterator it = annoText.begin(); it != annoText.end(); it++) { if (it != annoText.begin()) { @@ -176,7 +169,7 @@ void QGIViewAnnotation::drawAnnotation() m_textItem->centerAt(0.,0.); } -void QGIViewAnnotation::rotateView(void) +void QGIViewAnnotation::rotateView() { QRectF r = m_textItem->boundingRect(); m_textItem->setTransformOriginPoint(r.center()); @@ -189,13 +182,13 @@ void QGIViewAnnotation::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) Q_UNUSED(event); TechDraw::DrawViewAnnotation *annotation = dynamic_cast(getViewObject()); - if (annotation == nullptr) { + if (!annotation) { return; } const std::vector &values = annotation->Text.getValues(); QString text; - if (values.size() > 0) { + if (!values.empty()) { text = QString::fromUtf8(values[0].c_str()); for (unsigned int i = 1; i < values.size(); ++i) { diff --git a/src/Mod/TechDraw/Gui/QGIViewAnnotation.h b/src/Mod/TechDraw/Gui/QGIViewAnnotation.h index 0552d99125..0034df9536 100644 --- a/src/Mod/TechDraw/Gui/QGIViewAnnotation.h +++ b/src/Mod/TechDraw/Gui/QGIViewAnnotation.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWANNOTATION_H #define DRAWINGGUI_QGRAPHICSITEMVIEWANNOTATION_H +#include + #include "QGIView.h" namespace TechDraw { @@ -41,22 +43,21 @@ public: explicit QGIViewAnnotation(); /// m_textItem belongs to this group and will be deleted by Qt - ~QGIViewAnnotation() = default; + ~QGIViewAnnotation() override = default; enum {Type = QGraphicsItem::UserType + 120}; int type() const override { return Type;} - virtual void updateView(bool update = false) override; + void updateView(bool update = false) override; void setViewAnnoFeature(TechDraw::DrawViewAnnotation *obj); - virtual void draw() override; - virtual void rotateView(void) override; + void draw() override; + void rotateView() override; protected: void drawAnnotation(); - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; QGCustomText *m_textItem; QColor m_colNormal; diff --git a/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp b/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp index 1788d172e2..aefaeda13e 100644 --- a/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewBalloon.cpp @@ -132,11 +132,6 @@ void QGIBalloonLabel::mousePressEvent(QGraphicsSceneMouseEvent * event) QGraphicsItem::mousePressEvent(event); } -void QGIBalloonLabel::mouseMoveEvent(QGraphicsSceneMouseEvent * event) -{ - QGraphicsItem::mouseMoveEvent(event); -} - void QGIBalloonLabel::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)) @@ -183,7 +178,7 @@ void QGIBalloonLabel::hoverEnterEvent(QGraphicsSceneHoverEvent *event) void QGIBalloonLabel::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { QGIView *view = dynamic_cast (parentItem()); - assert(view != nullptr); + assert(view); Q_UNUSED(view); Q_EMIT hover(false); @@ -348,25 +343,6 @@ QVariant QGIViewBalloon::itemChange(GraphicsItemChange change, const QVariant &v return QGIView::itemChange(change, value); } -//QGIViewBalloon does not behave the same as other QGIView derived classes -//and so mouse events need to be ignored. Only the QGIBalloonLabel mouse events are relevant. -void QGIViewBalloon::mousePressEvent(QGraphicsSceneMouseEvent * event) -{ -// Base::Console().Message("QGIVB::mousePressEvent() - %s\n",getViewName()); - QGraphicsItem::mousePressEvent(event); -} - -void QGIViewBalloon::mouseMoveEvent(QGraphicsSceneMouseEvent * event) -{ - QGraphicsItem::mouseMoveEvent(event); -} - -void QGIViewBalloon::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) -{ -// Base::Console().Message("QGIVB::mouseReleaseEvent() - %s\n",getViewName()); - QGraphicsItem::mouseReleaseEvent(event); -} - //Set selection state for this and it's children void QGIViewBalloon::setGroupSelection(bool b) { @@ -393,7 +369,7 @@ void QGIViewBalloon::hover(bool state) void QGIViewBalloon::setViewPartFeature(TechDraw::DrawViewBalloon *balloon) { // Base::Console().Message("QGIVB::setViewPartFeature()\n"); - if(balloon == nullptr) + if (!balloon) return; setViewFeature(static_cast(balloon)); diff --git a/src/Mod/TechDraw/Gui/QGIViewBalloon.h b/src/Mod/TechDraw/Gui/QGIViewBalloon.h index ca378e492e..36c16fd69f 100644 --- a/src/Mod/TechDraw/Gui/QGIViewBalloon.h +++ b/src/Mod/TechDraw/Gui/QGIViewBalloon.h @@ -24,6 +24,8 @@ #ifndef TECHDRAWGUI_QGIVBALLOON_H #define TECHDRAWGUI_QGIVBALLOON_H +#include + #include #include #include @@ -59,14 +61,14 @@ Q_OBJECT public: QGIBalloonLabel(); - virtual ~QGIBalloonLabel() = default; + ~QGIBalloonLabel() override = default; enum {Type = QGraphicsItem::UserType + 141}; int type() const override { return Type;} - virtual QRectF boundingRect() const override; - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - virtual void paint( QPainter *painter, + QRectF boundingRect() const override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr ) override; void setLabelCenter(); @@ -75,18 +77,18 @@ public: double Y() const { return posY; } //minus posY? void setFont(QFont f); - QFont getFont(void) { return m_labelText->font(); } + QFont getFont() { return m_labelText->font(); } void setDimString(QString t); void setDimString(QString t, qreal maxWidth); - void setPrettySel(void); - void setPrettyPre(void); - void setPrettyNormal(void); + void setPrettySel(); + void setPrettyPre(); + void setPrettyNormal(); void setColor(QColor c); bool verticalSep; std::vector seps; - QGCustomText* getDimText(void) { return m_labelText; } + QGCustomText* getDimText() { return m_labelText; } void setDimText(QGCustomText* newText) { m_labelText = newText; } bool hasHover; @@ -100,13 +102,11 @@ Q_SIGNALS: void dragFinished(); protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; -// virtual void mouseReleaseEvent( QGraphicsSceneMouseEvent * event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; QGCustomText* m_labelText; QColor m_colNormal; @@ -129,51 +129,47 @@ public: enum {Type = QGraphicsItem::UserType + 140}; explicit QGIViewBalloon(); - virtual ~QGIViewBalloon() = default; + ~QGIViewBalloon() override = default; void setViewPartFeature(TechDraw::DrawViewBalloon *obj); int type() const override { return Type;} - virtual void drawBorder() override; - virtual void updateView(bool update = false) override; - virtual void paint( QPainter * painter, + void drawBorder() override; + void updateView(bool update = false) override; + void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; - QString getLabelText(void); + QString getLabelText(); void placeBalloon(QPointF pos); TechDraw::DrawViewBalloon *dvBalloon; - void setPrettyPre(void); - void setPrettySel(void); - void setPrettyNormal(void); + void setPrettyPre(); + void setPrettySel(); + void setPrettyNormal(); - virtual void setGroupSelection(bool b) override; - virtual QGIBalloonLabel* getBalloonLabel(void) { return balloonLabel; } + void setGroupSelection(bool b) override; + virtual QGIBalloonLabel* getBalloonLabel() { return balloonLabel; } - virtual QColor getNormalColor(void) override; + QColor getNormalColor() override; int prefDefaultArrow() const; bool prefOrthoPyramid() const; public Q_SLOTS: void balloonLabelDragged(bool ctrl); - void balloonLabelDragFinished(void); + void balloonLabelDragFinished(); void select(bool state); void hover(bool state); void updateBalloon(bool obtuse = false); protected: - virtual void mousePressEvent( QGraphicsSceneMouseEvent * event) override; - virtual void mouseMoveEvent( QGraphicsSceneMouseEvent * event) override; - virtual void mouseReleaseEvent( QGraphicsSceneMouseEvent * event) override; - void draw() override; void drawBalloon(bool dragged = false); - virtual QVariant itemChange( GraphicsItemChange change, + QVariant itemChange( GraphicsItemChange change, const QVariant &value ) override; - virtual void setSvgPens(void); - virtual void setPens(void); - QString getPrecision(void); + virtual void setSvgPens(); + virtual void setPens(); + QString getPrecision(); protected: bool hasHover; diff --git a/src/Mod/TechDraw/Gui/QGIViewClip.cpp b/src/Mod/TechDraw/Gui/QGIViewClip.cpp index e5b118b4b6..7f96c5f01d 100644 --- a/src/Mod/TechDraw/Gui/QGIViewClip.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewClip.cpp @@ -61,18 +61,11 @@ QGIViewClip::QGIViewClip() m_frame->setRect(0.,0.,Rez::guiX(5.),Rez::guiX(5.)); } - -QVariant QGIViewClip::itemChange(GraphicsItemChange change, const QVariant &value) -{ - return QGIView::itemChange(change, value); -} - void QGIViewClip::updateView(bool update) { auto viewClip( dynamic_cast(getViewObject()) ); - if( viewClip == nullptr ) { + if (!viewClip) return; - } if (update || viewClip->isTouched() || @@ -103,9 +96,8 @@ void QGIViewClip::drawClip() { auto viewClip( dynamic_cast(getViewObject()) ); - if( viewClip == nullptr ) { + if (!viewClip) return; - } prepareGeometryChange(); double h = viewClip->Height.getValue(); diff --git a/src/Mod/TechDraw/Gui/QGIViewClip.h b/src/Mod/TechDraw/Gui/QGIViewClip.h index 0f7a85f8c1..ec8d18094e 100644 --- a/src/Mod/TechDraw/Gui/QGIViewClip.h +++ b/src/Mod/TechDraw/Gui/QGIViewClip.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMCLIP_H #define DRAWINGGUI_QGRAPHICSITEMCLIP_H +#include + #include "QGIView.h" namespace TechDrawGui @@ -35,20 +37,19 @@ class TechDrawGuiExport QGIViewClip : public QGIView public: QGIViewClip(); - ~QGIViewClip() = default; + ~QGIViewClip() override = default; enum {Type = QGraphicsItem::UserType + 123}; int type() const override { return Type;} - virtual void updateView(bool update = false) override; + void updateView(bool update = false) override; - virtual void draw() override; - QGCustomRect* getFrame(void) {return m_frame;} - QGCustomClip* getClipArea(void) {return m_cliparea;} + void draw() override; + QGCustomRect* getFrame() {return m_frame;} + QGCustomClip* getClipArea() {return m_cliparea;} protected: void drawClip(); - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; private: QGCustomRect* m_frame; diff --git a/src/Mod/TechDraw/Gui/QGIViewCollection.cpp b/src/Mod/TechDraw/Gui/QGIViewCollection.cpp index 94566a64f4..ddbdb1c365 100644 --- a/src/Mod/TechDraw/Gui/QGIViewCollection.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewCollection.cpp @@ -52,21 +52,3 @@ QGIViewCollection::QGIViewCollection() setAcceptHoverEvents(true); setFlag(QGraphicsItem::ItemIsMovable, true); } - - -QVariant QGIViewCollection::itemChange(GraphicsItemChange change, const QVariant &value) -{ - - return QGIView::itemChange(change, value); -} - -void QGIViewCollection::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) -{ - //TODO: should MouseMove logic go here instead of QGIView? - QGIView::mouseReleaseEvent(event); -} - -void QGIViewCollection::updateView(bool update) -{ - return QGIView::updateView(update); -} diff --git a/src/Mod/TechDraw/Gui/QGIViewCollection.h b/src/Mod/TechDraw/Gui/QGIViewCollection.h index 2a5ca7f153..32e54becd6 100644 --- a/src/Mod/TechDraw/Gui/QGIViewCollection.h +++ b/src/Mod/TechDraw/Gui/QGIViewCollection.h @@ -23,6 +23,8 @@ #ifndef _DRAWINGGUI_QGRAPHICSITEMVIEWCOLLECTION_H #define _DRAWINGGUI_QGRAPHICSITEMVIEWCOLLECTION_H +#include + #include "QGIView.h" QT_BEGIN_NAMESPACE @@ -37,17 +39,10 @@ class TechDrawGuiExport QGIViewCollection : public QGIView { public: QGIViewCollection(); - ~QGIViewCollection() = default; + ~QGIViewCollection() override = default; enum {Type = QGraphicsItem::UserType + 110}; int type() const override { return Type;} - - virtual void updateView(bool update = false) override; - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent * event) override; - -protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - }; } // namespace MDIViewPageGui diff --git a/src/Mod/TechDraw/Gui/QGIViewDimension.cpp b/src/Mod/TechDraw/Gui/QGIViewDimension.cpp index 1e056db734..d2d307982c 100644 --- a/src/Mod/TechDraw/Gui/QGIViewDimension.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewDimension.cpp @@ -95,7 +95,14 @@ enum SnapMode{ HorizontalSnap }; -QGIDatumLabel::QGIDatumLabel() +enum DragState { + NoDrag, + DragStarted, + Dragging }; + + +QGIDatumLabel::QGIDatumLabel() : + m_dragState(NoDrag) { verticalSep = false; posX = 0; @@ -136,10 +143,16 @@ QVariant QGIDatumLabel::itemChange(GraphicsItemChange change, const QVariant &va setPrettySel(); } else { setPrettyNormal(); + if (m_dragState == Dragging) { + //stop the drag if we are no longer selected. + m_dragState = NoDrag; + Q_EMIT dragFinished(); + } } - update(); + } else if(change == ItemPositionHasChanged && scene()) { setLabelCenter(); + m_dragState = Dragging; Q_EMIT dragging(m_ctrl); } @@ -155,20 +168,13 @@ void QGIDatumLabel::mousePressEvent(QGraphicsSceneMouseEvent * event) QGraphicsItem::mousePressEvent(event); } -void QGIDatumLabel::mouseMoveEvent(QGraphicsSceneMouseEvent * event) -{ - QGraphicsItem::mouseMoveEvent(event); -} - void QGIDatumLabel::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { // Base::Console().Message("QGIDL::mouseReleaseEvent()\n"); m_ctrl = false; - if (QLineF(event->screenPos(), event->buttonDownScreenPos(Qt::LeftButton)) - .length() > 0) { - if (scene() && this == scene()->mouseGrabberItem()) { - Q_EMIT dragFinished(); - } + if (m_dragState == Dragging) { + m_dragState = NoDrag; + Q_EMIT dragFinished(); } QGraphicsItem::mouseReleaseEvent(event); @@ -177,13 +183,13 @@ void QGIDatumLabel::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) void QGIDatumLabel::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { QGIViewDimension* qgivDimension = dynamic_cast(parentItem()); - if (qgivDimension == nullptr) { + if (!qgivDimension) { qWarning() << "QGIDatumLabel::mouseDoubleClickEvent: No parent item"; return; } auto ViewProvider = dynamic_cast(qgivDimension->getViewProvider(qgivDimension->getViewObject())); - if (ViewProvider == nullptr) { + if (!ViewProvider) { qWarning() << "QGIDatumLabel::mouseDoubleClickEvent: No valid view provider"; return; } @@ -249,13 +255,11 @@ void QGIDatumLabel::setPosFromCenter(const double &xCenter, const double &yCente { prepareGeometryChange(); QGIViewDimension* qgivd = dynamic_cast(parentItem()); - if( qgivd == nullptr ) { + if (!qgivd) return; - } const auto dim( dynamic_cast(qgivd->getViewObject()) ); - if( dim == nullptr ) { + if (!dim) return; - } //set label's Qt position(top,left) given boundingRect center point setPos(xCenter - m_dimText->boundingRect().width() / 2., yCenter - m_dimText->boundingRect().height() / 2.); @@ -337,11 +341,10 @@ void QGIDatumLabel::setToleranceString() { prepareGeometryChange(); QGIViewDimension* qgivd = dynamic_cast(parentItem()); - if( qgivd == nullptr ) { + if (!qgivd) return; - } const auto dim( dynamic_cast(qgivd->getViewObject()) ); - if( dim == nullptr ) { + if (!dim) { return; // don't show if both are zero or if EqualTolerance is true } else if (!dim->hasOverUnderTolerance() || dim->EqualTolerance.getValue() || dim->TheoreticalExact.getValue()) { @@ -399,7 +402,7 @@ void QGIDatumLabel::setUnitString(QString t) } -int QGIDatumLabel::getPrecision(void) +int QGIDatumLabel::getPrecision() { int precision; bool global = false; @@ -415,7 +418,7 @@ int QGIDatumLabel::getPrecision(void) return precision; } -double QGIDatumLabel::getTolAdjust(void) +double QGIDatumLabel::getTolAdjust() { double adjust; Base::Reference hGrp = App::GetApplication().GetUserParameter() @@ -425,7 +428,7 @@ double QGIDatumLabel::getTolAdjust(void) } -void QGIDatumLabel::setPrettySel(void) +void QGIDatumLabel::setPrettySel() { // Base::Console().Message("QGIDL::setPrettySel()\n"); m_dimText->setPrettySel(); @@ -435,7 +438,7 @@ void QGIDatumLabel::setPrettySel(void) Q_EMIT setPretty(SEL); } -void QGIDatumLabel::setPrettyPre(void) +void QGIDatumLabel::setPrettyPre() { // Base::Console().Message("QGIDL::setPrettyPre()\n"); m_dimText->setPrettyPre(); @@ -445,7 +448,7 @@ void QGIDatumLabel::setPrettyPre(void) Q_EMIT setPretty(PRE); } -void QGIDatumLabel::setPrettyNormal(void) +void QGIDatumLabel::setPrettyNormal() { // Base::Console().Message("QGIDL::setPrettyNormal()\n"); m_dimText->setPrettyNormal(); @@ -566,7 +569,7 @@ void QGIViewDimension::hover(bool state) void QGIViewDimension::setViewPartFeature(TechDraw::DrawViewDimension *obj) { // Base::Console().Message("QGIVD::setViewPartFeature()\n"); - if(obj == nullptr) + if (!obj) return; setViewFeature(static_cast(obj)); @@ -617,14 +620,13 @@ void QGIViewDimension::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) void QGIViewDimension::updateView(bool update) { Q_UNUSED(update); - auto dim( dynamic_cast(getViewObject()) ); - if( dim == nullptr ) + auto dim(dynamic_cast(getViewObject())); + if (!dim) return; auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } if (update|| dim->X.isTouched() || @@ -649,18 +651,15 @@ void QGIViewDimension::updateView(bool update) void QGIViewDimension::updateDim() { const auto dim( dynamic_cast(getViewObject()) ); - if( dim == nullptr ) { + if (!dim) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } QString labelText= QString::fromUtf8(dim->getFormattedDimensionValue(1).c_str()); // pre value [unit] post - if (dim->isMultiValueSchema()) { + if (dim->isMultiValueSchema()) labelText = QString::fromUtf8(dim->getFormattedDimensionValue(0).c_str()); //don't format multis - } QFont font = datumLabel->getFont(); font.setFamily(QString::fromUtf8(vp->Font.getValue())); @@ -686,9 +685,8 @@ void QGIViewDimension::datumLabelDragFinished() { auto dim( dynamic_cast(getViewObject()) ); - if( dim == nullptr ) { + if (!dim) return; - } double x = Rez::appX(datumLabel->X()), y = Rez::appX(datumLabel->Y()); @@ -699,7 +697,7 @@ void QGIViewDimension::datumLabelDragFinished() } //this is for formatting and finding centers, not display -QString QGIViewDimension::getLabelText(void) +QString QGIViewDimension::getLabelText() { QString result; QString first = datumLabel->getDimText()->toPlainText(); @@ -722,26 +720,25 @@ void QGIViewDimension::draw() } TechDraw::DrawViewDimension *dim = dynamic_cast(getViewObject()); - if((!dim) || //nothing to draw, don't try - (!dim->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId())) || - (!dim->has2DReferences()) ) { + if (!dim ||//nothing to draw, don't try + !dim->isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) || + !dim->has2DReferences()) { datumLabel->hide(); hide(); return; } const TechDraw::DrawViewPart *refObj = dim->getViewPart(); - if (refObj == nullptr) { + if (!refObj) return; - } - if(!refObj->hasGeometry()) { //nothing to draw yet (restoring) + if (!refObj->hasGeometry()) { //nothing to draw yet (restoring) datumLabel->hide(); hide(); return; } auto vp = static_cast(getViewProvider(getViewObject())); - if (vp == nullptr) { + if (!vp) { datumLabel->show(); show(); return; @@ -983,7 +980,7 @@ double QGIViewDimension::computeArcStrikeFactor(const Base::BoundBox2d &labelRec const Base::Vector2d &arcCenter, double arcRadius, const std::vector> &drawMarking) { - if (drawMarking.size() < 1) { + if (drawMarking.empty()) { return 0.0; } @@ -1210,7 +1207,7 @@ bool QGIViewDimension::constructDimensionArc(const Base::Vector2d &arcCenter, do return flipArrows; } -void QGIViewDimension::resetArrows(void) const +void QGIViewDimension::resetArrows() const { aHead1->setDirMode(true); aHead1->setRotation(0.0); @@ -1257,7 +1254,7 @@ void QGIViewDimension::drawArrows(int count, const Base::Vector2d positions[], d void QGIViewDimension::arrowPositionsToFeature(const Base::Vector2d positions[]) const { auto dim( dynamic_cast(getViewObject()) ); - if( dim == nullptr ) + if (!dim) return; dim->saveArrowPositions(positions); @@ -1321,7 +1318,7 @@ void QGIViewDimension::drawSingleArc(QPainterPath &painterPath, const Base::Vect void QGIViewDimension::drawMultiArc(QPainterPath &painterPath, const Base::Vector2d &arcCenter, double arcRadius, const std::vector> &drawMarking) const { - if (drawMarking.size() < 1) { + if (drawMarking.empty()) { return; } @@ -2373,22 +2370,20 @@ QColor QGIViewDimension::prefNormalColor() // auto dim( dynamic_cast(getViewObject()) ); TechDraw::DrawViewDimension* dim = nullptr; TechDraw::DrawView* dv = getViewObject(); - if (dv != nullptr) { + if (dv) { dim = dynamic_cast(dv); - if( dim == nullptr ) { + if (!dim) return m_colNormal; - } } else { return m_colNormal; } ViewProviderDimension* vpDim = nullptr; Gui::ViewProvider* vp = getViewProvider(dim); - if ( vp != nullptr ) { + if (vp) { vpDim = dynamic_cast(vp); - if (vpDim == nullptr) { + if (!vpDim) return m_colNormal; - } } else { return m_colNormal; } @@ -2463,28 +2458,28 @@ void QGIViewDimension::onPrettyChanged(int state) } } -void QGIViewDimension::setPrettyPre(void) +void QGIViewDimension::setPrettyPre() { aHead1->setPrettyPre(); aHead2->setPrettyPre(); dimLines->setPrettyPre(); } -void QGIViewDimension::setPrettySel(void) +void QGIViewDimension::setPrettySel() { aHead1->setPrettySel(); aHead2->setPrettySel(); dimLines->setPrettySel(); } -void QGIViewDimension::setPrettyNormal(void) +void QGIViewDimension::setPrettyNormal() { aHead1->setPrettyNormal(); aHead2->setPrettyNormal(); dimLines->setPrettyNormal(); } -void QGIViewDimension::drawBorder(void) +void QGIViewDimension::drawBorder() { //Dimensions have no border! // Base::Console().Message("TRACE - QGIViewDimension::drawBorder - doing nothing!\n"); @@ -2557,7 +2552,7 @@ void QGIViewDimension::paint ( QPainter * painter, const QStyleOptionGraphicsIte setPens(); } -void QGIViewDimension::setSvgPens(void) +void QGIViewDimension::setSvgPens() { double svgLineFactor = 3.0; //magic number. should be a setting somewhere. dimLines->setWidth(m_lineWidth/svgLineFactor); @@ -2565,7 +2560,7 @@ void QGIViewDimension::setSvgPens(void) aHead2->setWidth(aHead2->getWidth()/svgLineFactor); } -void QGIViewDimension::setPens(void) +void QGIViewDimension::setPens() { dimLines->setWidth(m_lineWidth); aHead1->setWidth(m_lineWidth); diff --git a/src/Mod/TechDraw/Gui/QGIViewDimension.h b/src/Mod/TechDraw/Gui/QGIViewDimension.h index b7eae9b80e..396052f4e8 100644 --- a/src/Mod/TechDraw/Gui/QGIViewDimension.h +++ b/src/Mod/TechDraw/Gui/QGIViewDimension.h @@ -61,14 +61,14 @@ Q_OBJECT public: QGIDatumLabel(); - virtual ~QGIDatumLabel() = default; + ~QGIDatumLabel() override = default; enum {Type = QGraphicsItem::UserType + 107}; int type() const override { return Type;} - virtual QRectF boundingRect() const override; - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - virtual void paint( QPainter *painter, + QRectF boundingRect() const override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr ) override; void setLabelCenter(); @@ -77,34 +77,34 @@ public: double Y() const { return posY; } //minus posY? void setFont(QFont f); - QFont getFont(void) { return m_dimText->font(); } + QFont getFont() { return m_dimText->font(); } void setDimString(QString t); void setDimString(QString t, qreal maxWidth); void setUnitString(QString t); void setToleranceString(); - void setPrettySel(void); - void setPrettyPre(void); - void setPrettyNormal(void); + void setPrettySel(); + void setPrettyPre(); + void setPrettyNormal(); void setColor(QColor c); bool verticalSep; std::vector seps; - QGCustomText* getDimText(void) { return m_dimText; } + QGCustomText* getDimText() { return m_dimText; } void setDimText(QGCustomText* newText) { m_dimText = newText; } - QGCustomText* getTolTextOver(void) { return m_tolTextOver; } + QGCustomText* getTolTextOver() { return m_tolTextOver; } void setTolTextOver(QGCustomText* newTol) { m_tolTextOver = newTol; } - QGCustomText* getTolTextUnder(void) { return m_tolTextUnder; } + QGCustomText* getTolTextUnder() { return m_tolTextUnder; } void setTolTextUnder(QGCustomText* newTol) { m_tolTextOver = newTol; } - double getTolAdjust(void); + double getTolAdjust(); /* bool hasHover;*/ QGIViewDimension* parent; - bool isFramed(void) { return m_isFramed; } + bool isFramed() { return m_isFramed; } void setFramed(bool framed) { m_isFramed = framed; } - double getLineWidth(void) { return m_lineWidth; } + double getLineWidth() { return m_lineWidth; } void setLineWidth(double lineWidth) { m_lineWidth = lineWidth; } Q_SIGNALS: @@ -115,19 +115,17 @@ Q_SIGNALS: void dragFinished(); protected: - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; -// virtual void mouseReleaseEvent( QGraphicsSceneMouseEvent * event) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) override; QGCustomText* m_dimText; QGCustomText* m_tolTextOver; QGCustomText* m_tolTextUnder; QGCustomText* m_unitText; - int getPrecision(void); + int getPrecision(); QColor m_colNormal; bool m_ctrl; @@ -136,6 +134,8 @@ protected: bool m_isFramed; double m_lineWidth; + + int m_dragState; private: }; @@ -150,42 +150,42 @@ public: enum {Type = QGraphicsItem::UserType + 106}; explicit QGIViewDimension(); - ~QGIViewDimension() = default; + ~QGIViewDimension() override = default; void setViewPartFeature(TechDraw::DrawViewDimension *obj); int type() const override { return Type;} - virtual QRectF boundingRect() const override; - virtual void paint( QPainter * painter, + QRectF boundingRect() const override; + void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; TechDraw::DrawViewDimension *dvDimension; - virtual void drawBorder() override; - virtual void updateView(bool update = false) override; - virtual QColor prefNormalColor(void); - QString getLabelText(void); - void setPrettyPre(void); - void setPrettySel(void); - void setPrettyNormal(void); + void drawBorder() override; + void updateView(bool update = false) override; + virtual QColor prefNormalColor(); + QString getLabelText(); + void setPrettyPre(); + void setPrettySel(); + void setPrettyNormal(); - virtual void setGroupSelection(bool b) override; - virtual QGIDatumLabel* getDatumLabel(void) { return datumLabel; } + void setGroupSelection(bool b) override; + virtual QGIDatumLabel* getDatumLabel() { return datumLabel; } - void setNormalColorAll(void); + void setNormalColorAll(); public Q_SLOTS: void onPrettyChanged(int state); void datumLabelDragged(bool ctrl); - void datumLabelDragFinished(void); + void datumLabelDragFinished(); void select(bool state); void hover(bool state); void updateDim(); protected: - virtual void mousePressEvent( QGraphicsSceneMouseEvent * event) override; - virtual void mouseMoveEvent( QGraphicsSceneMouseEvent * event) override; - virtual void mouseReleaseEvent( QGraphicsSceneMouseEvent * event) override; + void mousePressEvent( QGraphicsSceneMouseEvent * event) override; + void mouseMoveEvent( QGraphicsSceneMouseEvent * event) override; + void mouseReleaseEvent( QGraphicsSceneMouseEvent * event) override; static double getAnglePlacementFactor(double testAngle, double endAngle, double startRotation); static int compareAngleStraightness(double straightAngle, double leftAngle, double rightAngle, @@ -222,7 +222,7 @@ protected: void draw() override; - void resetArrows(void) const; + void resetArrows() const; void drawArrows(int count, const Base::Vector2d positions[], double angles[], bool flipped) const; void drawSingleLine(QPainterPath &painterPath, const Base::Vector2d &lineOrigin, double lineAngle, @@ -257,13 +257,13 @@ protected: void drawDiameter(TechDraw::DrawViewDimension *dimension, ViewProviderDimension *viewProvider) const; void drawAngle(TechDraw::DrawViewDimension *dimension, ViewProviderDimension *viewProvider) const; - virtual QVariant itemChange( GraphicsItemChange change, + QVariant itemChange( GraphicsItemChange change, const QVariant &value ) override; - virtual void setSvgPens(void); - virtual void setPens(void); + virtual void setSvgPens(); + virtual void setPens(); Base::Vector3d findIsoDir(Base::Vector3d ortho) const; Base::Vector3d findIsoExt(Base::Vector3d isoDir) const; - QString getPrecision(void); + QString getPrecision(); bool hasHover; QGIDatumLabel* datumLabel; //dimension text diff --git a/src/Mod/TechDraw/Gui/QGIViewImage.cpp b/src/Mod/TechDraw/Gui/QGIViewImage.cpp index 93b9957953..9774ce2f55 100644 --- a/src/Mod/TechDraw/Gui/QGIViewImage.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewImage.cpp @@ -76,12 +76,6 @@ QGIViewImage::~QGIViewImage() // m_imageItem belongs to this group and will be deleted by Qt } -QVariant QGIViewImage::itemChange(GraphicsItemChange change, const QVariant &value) -{ - - return QGIView::itemChange(change, value); -} - void QGIViewImage::setViewImageFeature(TechDraw::DrawViewImage *obj) { setViewFeature(static_cast(obj)); @@ -90,9 +84,8 @@ void QGIViewImage::setViewImageFeature(TechDraw::DrawViewImage *obj) void QGIViewImage::updateView(bool update) { auto viewImage( dynamic_cast(getViewObject()) ); - if( viewImage == nullptr ) { + if (!viewImage) return; - } if (update || viewImage->isTouched() || @@ -120,9 +113,8 @@ void QGIViewImage::draw() return; auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } bool crop = vp->Crop.getValue(); drawImage(); @@ -141,9 +133,8 @@ void QGIViewImage::draw() void QGIViewImage::drawImage() { auto viewImage( dynamic_cast(getViewObject()) ); - if( viewImage == nullptr ) { + if (!viewImage) return; - } if (!viewImage->ImageIncluded.isEmpty()) { QString fileSpec = QString::fromUtf8(viewImage->ImageIncluded.getValue(),strlen(viewImage->ImageIncluded.getValue())); @@ -157,7 +148,7 @@ void QGIViewImage::drawImage() } } -void QGIViewImage::rotateView(void) +void QGIViewImage::rotateView() { QRectF r = m_cliparea->boundingRect(); m_cliparea->setTransformOriginPoint(r.center()); diff --git a/src/Mod/TechDraw/Gui/QGIViewImage.h b/src/Mod/TechDraw/Gui/QGIViewImage.h index 6899d84b69..1707be26d4 100644 --- a/src/Mod/TechDraw/Gui/QGIViewImage.h +++ b/src/Mod/TechDraw/Gui/QGIViewImage.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWIMAGE_H #define DRAWINGGUI_QGRAPHICSITEMVIEWIMAGE_H +#include + #include "QGIView.h" namespace TechDraw { @@ -38,20 +40,19 @@ class TechDrawGuiExport QGIViewImage : public QGIView { public: QGIViewImage(); - ~QGIViewImage(); + ~QGIViewImage() override; enum {Type = QGraphicsItem::UserType + 200}; int type() const override { return Type;} - virtual void updateView(bool update = false) override; + void updateView(bool update = false) override; void setViewImageFeature(TechDraw::DrawViewImage *obj); - virtual void draw() override; - virtual void rotateView(void) override; + void draw() override; + void rotateView() override; protected: virtual void drawImage(); - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; QGCustomImage* m_imageItem; QGCustomClip* m_cliparea; diff --git a/src/Mod/TechDraw/Gui/QGIViewPart.cpp b/src/Mod/TechDraw/Gui/QGIViewPart.cpp index 0e68eaabb2..d3d85ecc49 100644 --- a/src/Mod/TechDraw/Gui/QGIViewPart.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewPart.cpp @@ -154,9 +154,8 @@ QPainterPath QGIViewPart::geomToPainterPath(BaseGeomPtr baseGeom, double rot) Q_UNUSED(rot); QPainterPath path; - if (baseGeom == nullptr) { + if (!baseGeom) return path; - } switch(baseGeom->geomType) { case CIRCLE: { @@ -411,24 +410,20 @@ void QGIViewPart::updateView(bool update) { // Base::Console().Message("QGIVP::updateView() - %s\n", getViewObject()->getNameInDocument()); auto viewPart( dynamic_cast(getViewObject()) ); - if( viewPart == nullptr ) { + if (!viewPart) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } - if (update ) { + if (update) draw(); - } QGIView::updateView(update); } void QGIViewPart::draw() { - if (!isVisible()) { + if (!isVisible()) return; - } drawViewPart(); drawMatting(); @@ -440,9 +435,8 @@ void QGIViewPart::draw() { void QGIViewPart::drawViewPart() { auto viewPart( dynamic_cast(getViewObject()) ); - if ( viewPart == nullptr ) { + if (!viewPart) return; - } // Base::Console().Message("QGIVP::DVP() - %s / %s\n", viewPart->getNameInDocument(), viewPart->Label.getValue()); if (!viewPart->hasGeometry()) { removePrimitives(); //clean the slate @@ -451,9 +445,8 @@ void QGIViewPart::drawViewPart() } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } float lineWidth = vp->LineWidth.getValue() * lineScaleFactor; float lineWidthHid = vp->HiddenWidth.getValue() * lineScaleFactor; @@ -465,8 +458,7 @@ void QGIViewPart::drawViewPart() removePrimitives(); //clean the slate removeDecorations(); -#if MOD_TECHDRAW_HANDLE_FACES - if (viewPart->handleFaces()) { + if (viewPart->handleFaces() && !viewPart->CoarseView.getValue()) { // Draw Faces std::vector hatchObjs = viewPart->getHatches(); std::vector geomObjs = viewPart->getGeomHatches(); @@ -496,7 +488,7 @@ void QGIViewPart::drawViewPart() newFace->setHatchFile(fGeom->PatIncluded.getValue()); Gui::ViewProvider* gvp = QGIView::getViewProvider(fGeom); ViewProviderGeomHatch* geomVp = dynamic_cast(gvp); - if (geomVp != nullptr) { + if (geomVp) { newFace->setHatchColor(geomVp->ColorPattern.getValue()); newFace->setLineWeight(geomVp->WeightPattern.getValue()); } @@ -515,7 +507,7 @@ void QGIViewPart::drawViewPart() newFace->setHatchFile(fHatch->SvgIncluded.getValue()); Gui::ViewProvider* gvp = QGIView::getViewProvider(fHatch); ViewProviderHatch* hatchVp = dynamic_cast(gvp); - if (hatchVp != nullptr) { + if (hatchVp) { double hatchScale = hatchVp->HatchScale.getValue(); if (hatchScale > 0.0) { newFace->setHatchScale(hatchVp->HatchScale.getValue()); @@ -536,7 +528,6 @@ void QGIViewPart::drawViewPart() newFace->draw(); } } -#endif //#if MOD_TECHDRAW_HANDLE_FACES // Draw Edges QColor edgeColor = PreferencesGui::normalQColor(); @@ -582,7 +573,7 @@ void QGIViewPart::drawViewPart() } } else { TechDraw::GeomFormat* gf = viewPart->getGeomFormatBySelection(i); - if (gf != nullptr) { + if (gf) { item->setNormalColor(gf->m_format.m_color.asValue()); item->setWidth(gf->m_format.m_weight * lineScaleFactor); item->setStyle(gf->m_format.m_style); @@ -662,7 +653,7 @@ void QGIViewPart::drawViewPart() QGIVertex *item = new QGIVertex(i); TechDraw::CosmeticVertex* cv = viewPart->getCosmeticVertexBySelection(i); // TechDraw::CosmeticVertex* cv = viewPart->getCosmeticVertexByGeom(i); - if (cv != nullptr) { + if (cv) { item->setNormalColor(cv->color.asValue()); item->setRadius(Rez::guiX(cv->size)); } else { @@ -691,7 +682,7 @@ bool QGIViewPart::formatGeomFromCosmetic(std::string cTag, QGIEdge* item) bool result = true; auto partFeat( dynamic_cast(getViewObject()) ); TechDraw::CosmeticEdge* ce = partFeat ? partFeat->getCosmeticEdge(cTag) : nullptr; - if (ce != nullptr) { + if (ce) { item->setNormalColor(ce->m_format.m_color.asValue()); item->setWidth(ce->m_format.m_weight * lineScaleFactor); item->setStyle(ce->m_format.m_style); @@ -707,7 +698,7 @@ bool QGIViewPart::formatGeomFromCenterLine(std::string cTag, QGIEdge* item) bool result = true; auto partFeat( dynamic_cast(getViewObject()) ); TechDraw::CenterLine* cl = partFeat ? partFeat->getCenterLine(cTag) : nullptr; - if (cl != nullptr) { + if (cl) { item->setNormalColor(cl->m_format.m_color.asValue()); item->setWidth(cl->m_format.m_weight * lineScaleFactor); item->setStyle(cl->m_format.m_style); @@ -773,7 +764,7 @@ void QGIViewPart::removePrimitives() { QList children = childItems(); MDIViewPage* mdi = getMDIViewPage(); - if (mdi != nullptr) { + if (mdi) { getMDIViewPage()->blockSceneSelection(true); } for (auto& c:children) { @@ -784,7 +775,7 @@ void QGIViewPart::removePrimitives() delete prim; } } - if (mdi != nullptr) { + if (mdi) { getMDIViewPage()->blockSceneSelection(false); } } @@ -809,17 +800,15 @@ void QGIViewPart::removeDecorations() } } -void QGIViewPart::drawAllSectionLines(void) +void QGIViewPart::drawAllSectionLines() { TechDraw::DrawViewPart *viewPart = static_cast(getViewObject()); - if (!viewPart) { + if (!viewPart) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } if (vp->ShowSectionLine.getValue()) { auto refs = viewPart->getSectionRefs(); for (auto& r:refs) { @@ -831,21 +820,17 @@ void QGIViewPart::drawAllSectionLines(void) void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b) { TechDraw::DrawViewPart *viewPart = static_cast(getViewObject()); - if (!viewPart) { + if (!viewPart) return; - } - if (viewSection == nullptr) { + if (!viewSection) return; - } - if (!viewSection->hasGeometry()) { + if (!viewSection->hasGeometry()) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } if (b) { QGISectionLine* sectionLine = new QGISectionLine(); @@ -890,14 +875,12 @@ void QGIViewPart::drawSectionLine(TechDraw::DrawViewSection* viewSection, bool b void QGIViewPart::drawCenterLines(bool b) { TechDraw::DrawViewPart *viewPart = dynamic_cast(getViewObject()); - if (!viewPart) { + if (!viewPart) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } if (b) { bool horiz = vp->HorizCenterLine.getValue(); @@ -954,9 +937,8 @@ void QGIViewPart::drawHighlight(TechDraw::DrawViewDetail* viewDetail, bool b) } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } if (b) { // double fontSize = getPrefFontSize(); @@ -1229,11 +1211,11 @@ void QGIViewPart::paint ( QPainter * painter, const QStyleOptionGraphicsItem * o } //QGIViewPart derived classes do not need a rotate view method as rotation is handled on App side. -void QGIViewPart::rotateView(void) +void QGIViewPart::rotateView() { } -bool QGIViewPart::prefFaceEdges(void) +bool QGIViewPart::prefFaceEdges() { bool result = false; Base::Reference hGrp = App::GetApplication().GetUserParameter() @@ -1242,7 +1224,7 @@ bool QGIViewPart::prefFaceEdges(void) return result; } -bool QGIViewPart::prefPrintCenters(void) +bool QGIViewPart::prefPrintCenters() { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); diff --git a/src/Mod/TechDraw/Gui/QGIViewPart.h b/src/Mod/TechDraw/Gui/QGIViewPart.h index a2f4e00eca..fb944d0337 100644 --- a/src/Mod/TechDraw/Gui/QGIViewPart.h +++ b/src/Mod/TechDraw/Gui/QGIViewPart.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWPART_H #define DRAWINGGUI_QGRAPHICSITEMVIEWPART_H +#include + #include #include #include @@ -49,11 +51,11 @@ class TechDrawGuiExport QGIViewPart : public QGIView public: explicit QGIViewPart(); - ~QGIViewPart(); + ~QGIViewPart() override; enum {Type = QGraphicsItem::UserType + 102}; int type() const override { return Type;} - virtual void paint( QPainter * painter, + void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; @@ -61,18 +63,18 @@ public: void toggleCache(bool state) override; void toggleCosmeticLines(bool state); void setViewPartFeature(TechDraw::DrawViewPart *obj); - virtual void updateView(bool update = false) override; + void updateView(bool update = false) override; void tidy(); - virtual QRectF boundingRect() const override; - virtual void drawAllSectionLines(void); + QRectF boundingRect() const override; + virtual void drawAllSectionLines(); virtual void drawSectionLine(TechDraw::DrawViewSection* s, bool b); virtual void drawCenterLines(bool b); virtual void drawHighlight(TechDraw::DrawViewDetail* viewDetail, bool b); - virtual void drawMatting(void); + virtual void drawMatting(); bool showSection; - virtual void draw() override; - virtual void rotateView(void) override; + void draw() override; + void rotateView() override; static QPainterPath geomToPainterPath(TechDraw::BaseGeomPtr baseGeom, double rotation = 0.0); @@ -92,22 +94,22 @@ public: double x, double y, double curx, double cury); void setExporting(bool b) { m_isExporting = b; } - bool getExporting(void) { return m_isExporting; } + bool getExporting() { return m_isExporting; } protected: QPainterPath drawPainterPath(TechDraw::BaseGeomPtr baseGeom) const; void drawViewPart(); QGIFace* drawFace(TechDraw::FacePtr f, int idx); - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; + QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; TechDraw::DrawHatch* faceIsHatched(int i,std::vector hatchObjs) const; TechDraw::DrawGeomHatch* faceIsGeomHatched(int i,std::vector geomObjs) const; void dumpPath(const char* text,QPainterPath path); - void removePrimitives(void); - void removeDecorations(void); - bool prefFaceEdges(void); - bool prefPrintCenters(void); + void removePrimitives(); + void removeDecorations(); + bool prefFaceEdges(); + bool prefPrintCenters(); bool formatGeomFromCosmetic(std::string cTag, QGIEdge* item); bool formatGeomFromCenterLine(std::string cTag, QGIEdge* item); diff --git a/src/Mod/TechDraw/Gui/QGIViewSection.cpp b/src/Mod/TechDraw/Gui/QGIViewSection.cpp index d1323edfa3..44d98de155 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSection.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewSection.cpp @@ -67,29 +67,26 @@ void QGIViewSection::draw() void QGIViewSection::drawSectionFace() { auto section( dynamic_cast(getViewObject()) ); - if( section == nullptr ) { + if (!section) { return; } - if ( !section->hasGeometry()) { + if (!section->hasGeometry()) { return; } + Gui::ViewProvider* gvp = QGIView::getViewProvider(section); ViewProviderViewSection* sectionVp = dynamic_cast(gvp); - if ((sectionVp == nullptr) || - (!sectionVp->ShowCutSurface.getValue())) { + if (!sectionVp || !sectionVp->ShowCutSurface.getValue()) + return; + + auto sectionFaces( section->getTDFaceGeometry() ); + if (sectionFaces.empty()) { return; } float lineWidth = sectionVp->LineWidth.getValue(); - auto sectionFaces( section->getTDFaceGeometry() ); - if (sectionFaces.empty()) { - Base::Console(). - Log("INFO - QGIViewSection::drawSectionFace - No sectionFaces available. Check Section plane.\n"); - return; - } - std::vector::iterator fit = sectionFaces.begin(); int i = 0; for(; fit != sectionFaces.end(); fit++, i++) { @@ -152,9 +149,8 @@ void QGIViewSection::updateView(bool update) { Q_UNUSED(update); auto viewPart( dynamic_cast(getViewObject()) ); - if( viewPart == nullptr ) { + if (!viewPart) return; - } draw(); QGIView::updateView(update); } diff --git a/src/Mod/TechDraw/Gui/QGIViewSection.h b/src/Mod/TechDraw/Gui/QGIViewSection.h index c18d1b54dc..e01bb0b4f7 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSection.h +++ b/src/Mod/TechDraw/Gui/QGIViewSection.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWSECTION_H #define DRAWINGGUI_QGRAPHICSITEMVIEWSECTION_H +#include + #include "QGIViewPart.h" namespace TechDrawGui @@ -33,10 +35,10 @@ class TechDrawGuiExport QGIViewSection : public QGIViewPart public: QGIViewSection() = default; - ~QGIViewSection() = default; + ~QGIViewSection() override = default; - virtual void draw() override; - virtual void updateView(bool update = false) override; + void draw() override; + void updateView(bool update = false) override; enum {Type = QGraphicsItem::UserType + 108}; int type() const override { return Type;} void drawSectionLine(TechDraw::DrawViewSection* s, bool b) override; diff --git a/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.cpp b/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.cpp index d7667be4d8..1696e4d6e8 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.cpp @@ -21,8 +21,6 @@ ***************************************************************************/ #include "PreCompiled.h" -#ifndef _PreComp_ -#endif #include #include "QGIViewSpreadsheet.h" diff --git a/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.h b/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.h index 8d5cb1a624..6d2effe014 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.h +++ b/src/Mod/TechDraw/Gui/QGIViewSpreadsheet.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWSPREADSHEET_H #define DRAWINGGUI_QGRAPHICSITEMVIEWSPREADSHEET_H +#include + #include "QGIViewSymbol.h" namespace TechDraw { @@ -36,7 +38,7 @@ class TechDrawGuiExport QGIViewSpreadsheet : public QGIViewSymbol { public: QGIViewSpreadsheet(); - ~QGIViewSpreadsheet() = default; + ~QGIViewSpreadsheet() override = default; enum {Type = QGraphicsItem::UserType + 124}; int type() const override { return Type;} diff --git a/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp b/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp index e752bc9052..1f909f7e0d 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp +++ b/src/Mod/TechDraw/Gui/QGIViewSymbol.cpp @@ -76,12 +76,6 @@ QGIViewSymbol::~QGIViewSymbol() // m_svgItem belongs to this group and will be deleted by Qt } -QVariant QGIViewSymbol::itemChange(GraphicsItemChange change, const QVariant &value) -{ - - return QGIView::itemChange(change, value); -} - void QGIViewSymbol::setViewSymbolFeature(TechDraw::DrawViewSymbol *obj) { // called from QGVPage. (once) @@ -91,9 +85,8 @@ void QGIViewSymbol::setViewSymbolFeature(TechDraw::DrawViewSymbol *obj) void QGIViewSymbol::updateView(bool update) { auto viewSymbol( dynamic_cast(getViewObject()) ); - if( viewSymbol == nullptr ) { + if (!viewSymbol) return; - } if (update || viewSymbol->isTouched() || @@ -121,9 +114,8 @@ void QGIViewSymbol::draw() void QGIViewSymbol::drawSvg() { auto viewSymbol( dynamic_cast(getViewObject()) ); - if( viewSymbol == nullptr ) { + if (!viewSymbol) return; - } double rezfactor = Rez::getRezFactor(); double scaling = viewSymbol->getScale(); @@ -157,7 +149,7 @@ void QGIViewSymbol::symbolToSvg(QByteArray qba) m_svgItem->centerAt(0.,0.); } -void QGIViewSymbol::rotateView(void) +void QGIViewSymbol::rotateView() { QRectF r = m_displayArea->boundingRect(); m_displayArea->setTransformOriginPoint(r.center()); diff --git a/src/Mod/TechDraw/Gui/QGIViewSymbol.h b/src/Mod/TechDraw/Gui/QGIViewSymbol.h index 98b4455631..5283868220 100644 --- a/src/Mod/TechDraw/Gui/QGIViewSymbol.h +++ b/src/Mod/TechDraw/Gui/QGIViewSymbol.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMVIEWSYMBOL_H #define DRAWINGGUI_QGRAPHICSITEMVIEWSYMBOL_H +#include + #include #include "QGIView.h" @@ -42,22 +44,21 @@ class TechDrawGuiExport QGIViewSymbol : public QGIView { public: QGIViewSymbol(); - ~QGIViewSymbol(); + ~QGIViewSymbol() override; enum {Type = QGraphicsItem::UserType + 121}; int type() const override { return Type;} - virtual void updateView(bool update = false) override; + void updateView(bool update = false) override; void setViewSymbolFeature(TechDraw::DrawViewSymbol *obj); - virtual void draw() override; - virtual void rotateView(void) override; + void draw() override; + void rotateView() override; protected: virtual void drawSvg(); void symbolToSvg(QByteArray qba); - QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; QGDisplayArea* m_displayArea; QGCustomSvg *m_svgItem; diff --git a/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp b/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp index f1a3ec0cee..ce1d059123 100644 --- a/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp +++ b/src/Mod/TechDraw/Gui/QGIWeldSymbol.cpp @@ -149,11 +149,10 @@ void QGIWeldSymbol::updateView(bool update) // Base::Console().Message("QGIWS::updateView()\n"); Q_UNUSED(update); auto viewWeld( dynamic_cast(getViewObject()) ); - if( viewWeld == nullptr ) { + if (!viewWeld) return; - } - if ( getFeature() == nullptr ) { + if (!getFeature()) { Base::Console().Warning("QGIWS::updateView - no feature!\n"); return; } @@ -171,11 +170,11 @@ void QGIWeldSymbol::draw() removeQGITiles(); - if (m_arrowFeat != nullptr) { + if (m_arrowFeat) { drawTile(m_arrowFeat); } - if (m_otherFeat != nullptr) { + if (m_otherFeat) { drawTile(m_otherFeat); } @@ -189,19 +188,17 @@ void QGIWeldSymbol::draw() void QGIWeldSymbol::drawTile(TechDraw::DrawTileWeld* tileFeat) { // Base::Console().Message("QGIWS::drawTile() - tileFeat: %X\n", tileFeat); - if (tileFeat == nullptr) { + if (!tileFeat) { Base::Console().Message("QGIWS::drawTile - tile is null\n"); return; } const auto sym( dynamic_cast(getViewObject()) ); - if( sym == nullptr ) { + if (!sym) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } std::string fontName = vp->Font.getValue(); double sizeMM = vp->TileFontSize.getValue(); double fontSize = QGIView::calculateFontPixelSize(sizeMM); @@ -234,7 +231,7 @@ void QGIWeldSymbol::drawTile(TechDraw::DrawTileWeld* tileFeat) tile->draw(); } -void QGIWeldSymbol::drawAllAround(void) +void QGIWeldSymbol::drawAllAround() { // Base::Console().Message("QGIWS::drawAllAround()\n"); QPointF allAroundPos = getKinkPoint(); @@ -258,7 +255,7 @@ void QGIWeldSymbol::drawAllAround(void) m_allAround->setZValue(ZVALUE::DIMENSION); } -void QGIWeldSymbol::drawTailText(void) +void QGIWeldSymbol::drawTailText() { // Base::Console().Message("QGIWS::drawTailText()\n"); QPointF textPos = getTailPoint(); @@ -271,13 +268,11 @@ void QGIWeldSymbol::drawTailText(void) m_tailText->show(); } const auto sym( dynamic_cast(getViewObject()) ); - if( sym == nullptr ) { + if (!sym) return; - } auto vp = static_cast(getViewProvider(getViewObject())); - if ( vp == nullptr ) { + if (!vp) return; - } std::string fontName = vp->Font.getValue(); QString qFontName = Base::Tools::fromStdString(fontName); double sizeMM = vp->FontSize.getValue(); @@ -340,7 +335,7 @@ void QGIWeldSymbol::drawFieldFlag() m_fieldFlag->setPath(path); } -void QGIWeldSymbol::getTileFeats(void) +void QGIWeldSymbol::getTileFeats() { std::vector tiles = getFeature()->getTiles(); m_arrowFeat = nullptr; @@ -364,7 +359,7 @@ void QGIWeldSymbol::getTileFeats(void) } } -void QGIWeldSymbol::removeQGITiles(void) +void QGIWeldSymbol::removeQGITiles() { std::vector tiles = getQGITiles(); for (auto t: tiles) { @@ -380,7 +375,7 @@ void QGIWeldSymbol::removeQGITiles(void) } } -std::vector QGIWeldSymbol::getQGITiles(void) const +std::vector QGIWeldSymbol::getQGITiles() const { std::vector result; QList children = childItems(); @@ -475,21 +470,21 @@ void QGIWeldSymbol::setPrettySel() m_tailText->setPrettySel(); } -QPointF QGIWeldSymbol::getTileOrigin(void) +QPointF QGIWeldSymbol::getTileOrigin() { Base::Vector3d org = m_leadFeat->getTileOrigin(); QPointF result(org.x, org.y); return result; } -QPointF QGIWeldSymbol::getKinkPoint(void) +QPointF QGIWeldSymbol::getKinkPoint() { Base::Vector3d org = m_leadFeat->getKinkPoint(); QPointF result(org.x, org.y); return result; } -QPointF QGIWeldSymbol::getTailPoint(void) +QPointF QGIWeldSymbol::getTailPoint() { Base::Vector3d org = m_leadFeat->getTailPoint(); QPointF result(org.x, org.y); @@ -503,7 +498,7 @@ void QGIWeldSymbol::setFeature(TechDraw::DrawWeldSymbol* feat) m_weldFeatName = feat->getNameInDocument(); } -TechDraw::DrawWeldSymbol* QGIWeldSymbol::getFeature(void) +TechDraw::DrawWeldSymbol* QGIWeldSymbol::getFeature() { return m_weldFeat; } @@ -520,7 +515,7 @@ double QGIWeldSymbol::prefArrowSize() return PreferencesGui::dimArrowSize(); } -double QGIWeldSymbol::prefFontSize(void) const +double QGIWeldSymbol::prefFontSize() const { return Preferences::labelFontSizeMM(); } diff --git a/src/Mod/TechDraw/Gui/QGIWeldSymbol.h b/src/Mod/TechDraw/Gui/QGIWeldSymbol.h index 30d43db873..b2fdb2df9f 100644 --- a/src/Mod/TechDraw/Gui/QGIWeldSymbol.h +++ b/src/Mod/TechDraw/Gui/QGIWeldSymbol.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_QGRAPHICSITEMWELDSYMBOL_H #define DRAWINGGUI_QGRAPHICSITEMWELDSYMBOL_H +#include + #include #include #include @@ -61,51 +63,51 @@ public: enum {Type = QGraphicsItem::UserType + 340}; explicit QGIWeldSymbol(QGILeaderLine* myParent = nullptr); - ~QGIWeldSymbol() = default; + ~QGIWeldSymbol() override = default; int type() const override { return Type;} - virtual void paint( QPainter * painter, + void paint( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; - virtual QRectF boundingRect() const override; - virtual QPainterPath shape(void) const override; - double getEdgeFuzz(void) const; + QRectF boundingRect() const override; + QPainterPath shape() const override; + double getEdgeFuzz() const; - virtual void drawBorder() override; - virtual void updateView(bool update = false) override; + void drawBorder() override; + void updateView(bool update = false) override; - virtual TechDraw::DrawWeldSymbol* getFeature(void); + virtual TechDraw::DrawWeldSymbol* getFeature(); virtual void setFeature(TechDraw::DrawWeldSymbol* feat); - QPointF getTileOrigin(void); - QPointF getKinkPoint(void); - QPointF getTailPoint(void); + QPointF getTileOrigin(); + QPointF getKinkPoint(); + QPointF getTailPoint(); virtual void setPrettyNormal(); virtual void setPrettySel(); virtual void setPrettyPre(); - void getTileFeats(void); + void getTileFeats(); protected: - virtual QVariant itemChange( GraphicsItemChange change, + QVariant itemChange( GraphicsItemChange change, const QVariant &value ) override; - virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; + void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; + void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - virtual void draw() override; + void draw() override; void drawTile(TechDraw::DrawTileWeld* tileFeat); - void drawAllAround(void); - void drawTailText(void); + void drawAllAround(); + void drawTailText(); void drawFieldFlag(); protected: - void removeQGITiles(void); - std::vector getQGITiles(void) const; + void removeQGITiles(); + std::vector getQGITiles() const; virtual QColor prefNormalColor(); double prefArrowSize(); - double prefFontSize(void) const; + double prefFontSize() const; TechDraw::DrawWeldSymbol* m_weldFeat; TechDraw::DrawLeaderLine* m_leadFeat; diff --git a/src/Mod/TechDraw/Gui/QGMText.cpp b/src/Mod/TechDraw/Gui/QGMText.cpp index 54ed8536ff..7197bdd413 100644 --- a/src/Mod/TechDraw/Gui/QGMText.cpp +++ b/src/Mod/TechDraw/Gui/QGMText.cpp @@ -54,19 +54,6 @@ QVariant QGMText::itemChange(GraphicsItemChange change, const QVariant &value) return QGCustomText::itemChange(change, value); } -void QGMText::mousePressEvent(QGraphicsSceneMouseEvent * event) -{ -// if(scene() && this == scene()->mouseGrabberItem()) { //why would we get even if not mousegrabber? -// Q_EMIT dragging(); -// } - QGCustomText::mousePressEvent(event); -} - -void QGMText::mouseMoveEvent(QGraphicsSceneMouseEvent * event) -{ - QGCustomText::mouseMoveEvent(event); -} - void QGMText::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) { if(scene() && this == scene()->mouseGrabberItem()) { @@ -78,34 +65,28 @@ void QGMText::mouseReleaseEvent(QGraphicsSceneMouseEvent * event) void QGMText::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { Q_EMIT hover(true); - if (!isSelected()) { - setPrettyPre(); - } QGCustomText::hoverEnterEvent(event); } void QGMText::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { Q_EMIT hover(false); - if (!isSelected()) { - setPrettyNormal(); - } QGCustomText::hoverLeaveEvent(event); } -void QGMText::setPrettySel(void) +void QGMText::setPrettySel() { m_prettyState = "Sel"; QGCustomText::setPrettySel(); } -void QGMText::setPrettyPre(void) +void QGMText::setPrettyPre() { m_prettyState = "Pre"; QGCustomText::setPrettyPre(); } -void QGMText::setPrettyNormal(void) +void QGMText::setPrettyNormal() { m_prettyState = "Normal"; QGCustomText::setPrettyNormal(); diff --git a/src/Mod/TechDraw/Gui/QGMText.h b/src/Mod/TechDraw/Gui/QGMText.h index 9c04658823..86fd62fb54 100644 --- a/src/Mod/TechDraw/Gui/QGMText.h +++ b/src/Mod/TechDraw/Gui/QGMText.h @@ -26,9 +26,11 @@ #ifndef TECHDRAWGUI_MOVABLETEXT_H #define TECHDRAWGUI_MOVABLETEXT_H -#include "QGCustomText.h" +#include + #include +#include "QGCustomText.h" QT_BEGIN_NAMESPACE class QPainter; @@ -69,8 +71,6 @@ Q_SIGNALS: protected: virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; - virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override; - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) override; virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; diff --git a/src/Mod/TechDraw/Gui/QGSPage.cpp b/src/Mod/TechDraw/Gui/QGSPage.cpp index 1c9a1e8aac..1778433a12 100644 --- a/src/Mod/TechDraw/Gui/QGSPage.cpp +++ b/src/Mod/TechDraw/Gui/QGSPage.cpp @@ -61,29 +61,31 @@ #include #include -#include -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include #include -#include -#include #include +#include +#include +#include #include -#include +#include +#include #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + #include "Rez.h" #include "PreferencesGui.h" @@ -109,6 +111,7 @@ #include "QGITile.h" #include "ZVALUE.h" +#include "DrawGuiUtil.h" #include "ViewProviderPage.h" #include "QGSPage.h" #include "MDIViewPage.h" @@ -131,9 +134,8 @@ QGSPage::QGSPage(ViewProviderPage *vp, QWidget *parent) { assert(vp); m_vpPage = vp; - const char* name = vp->getDrawPage()->getNameInDocument(); - setObjectName(QString::fromLocal8Bit(name)); - m_vpPage->setGraphicsScene(this); + setItemIndexMethod(QGraphicsScene::BspTreeIndex); //the default +// setItemIndexMethod(QGraphicsScene::NoIndex); //sometimes faster } QGSPage::~QGSPage() @@ -141,6 +143,131 @@ QGSPage::~QGSPage() } +void QGSPage::addChildrenToPage(void) +{ +// Base::Console().Message("QGSP::addChildrenToPage()\n"); + // A fresh page is added and we iterate through its collected children and add these to Canvas View -MLP + // if docobj is a featureviewcollection (ex orthogroup), add its child views. if there are ever children that have children, + // we'll have to make this recursive. -WF + const std::vector &grp = m_vpPage->getDrawPage()->Views.getValues(); + std::vector childViews; + for (std::vector::const_iterator it = grp.begin();it != grp.end(); ++it) { + attachView(*it); + TechDraw::DrawViewCollection* collect = dynamic_cast(*it); + if (collect) { + childViews = collect->Views.getValues(); + for (std::vector::iterator itChild = childViews.begin();itChild != childViews.end(); ++itChild) { + attachView(*itChild); + } + } + } + //when restoring, it is possible for a Dimension to be loaded before the ViewPart it applies to + //therefore we need to make sure parentage of the graphics representation is set properly. bit of a kludge. + setDimensionGroups(); + setBalloonGroups(); + setLeaderGroups(); + setRichAnnoGroups(); + + App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); + auto pageTemplate( dynamic_cast(obj) ); + if( pageTemplate ) { + attachTemplate(pageTemplate); + matchSceneRectToTemplate(); + } + +// viewAll(); +} + +//********** template related routines ********* + +void QGSPage::attachTemplate(TechDraw::DrawTemplate *obj) +{ +// Base::Console().Message("QGSP::attachTemplate()\n"); + setPageTemplate(obj); +} + +void QGSPage::updateTemplate(bool forceUpdate) +{ +// Base::Console().Message("QGSP::updateTemplate()\n"); + App::DocumentObject *templObj = m_vpPage->getDrawPage()->Template.getValue(); + // TODO: what if template has been deleted? templObj will be NULL. segfault? + if (!templObj) { + Base::Console().Log("INFO - QGSPage::updateTemplate - Page: %s has NO template!!\n",m_vpPage->getDrawPage()->getNameInDocument()); + return; + } + + if(m_vpPage->getDrawPage()->Template.isTouched() || templObj->isTouched()) { + // Template is touched so update + + if(forceUpdate || + (templObj && templObj->isTouched() && templObj->isDerivedFrom(TechDraw::DrawTemplate::getClassTypeId())) ) { + + QGITemplate *qItemTemplate = getTemplate(); + + if(qItemTemplate) { + TechDraw::DrawTemplate *pageTemplate = dynamic_cast(templObj); + qItemTemplate->setTemplate(pageTemplate); + qItemTemplate->updateView(); + } + } + } +} + +QPointF QGSPage::getTemplateCenter() +{ + App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); + auto pageTemplate( dynamic_cast(obj) ); + if( pageTemplate != nullptr ) { + double cx = Rez::guiX(pageTemplate->Width.getValue())/2.0; + double cy = -Rez::guiX(pageTemplate->Height.getValue())/2.0; + return QPointF(cx,cy); + } + return QPointF(0.0, 0.0); +} + +void QGSPage::matchSceneRectToTemplate(void) +{ +// Base::Console().Message("QGSP::matchSceneRectToTemplate()\n"); + App::DocumentObject *obj = m_vpPage->getDrawPage()->Template.getValue(); + auto pageTemplate( dynamic_cast(obj) ); + if( pageTemplate ) { + //make sceneRect 1 pagesize bigger in every direction + double width = Rez::guiX(pageTemplate->Width.getValue()); + double height = Rez::guiX(pageTemplate->Height.getValue()); + setSceneRect(QRectF(-width,-2.0 * height,3.0*width,3.0*height)); + } +} + +void QGSPage::setPageTemplate(TechDraw::DrawTemplate *obj) +{ +// Base::Console().Message("QGSP::setPageTemplate()\n"); + removeTemplate(); + + if(obj->isDerivedFrom(TechDraw::DrawParametricTemplate::getClassTypeId())) { + pageTemplate = new QGIDrawingTemplate(this); + } else if(obj->isDerivedFrom(TechDraw::DrawSVGTemplate::getClassTypeId())) { + pageTemplate = new QGISVGTemplate(this); + } + pageTemplate->setTemplate(obj); + pageTemplate->updateView(); +} + +QGITemplate* QGSPage::getTemplate() const +{ + return pageTemplate; +} + +void QGSPage::removeTemplate() +{ + if(pageTemplate) { + removeItem(pageTemplate); + pageTemplate->deleteLater(); + pageTemplate = nullptr; + } +} + +//******* QGIView related routines + //! retrieve the QGIView objects currently in the scene std::vector QGSPage::getViews() const { @@ -148,7 +275,7 @@ std::vector QGSPage::getViews() const QList items = this->items(); for (auto& v:items) { QGIView* qv = dynamic_cast(v); - if (qv != nullptr) { + if (qv) { result.push_back(qv); } } @@ -159,7 +286,7 @@ int QGSPage::addQView(QGIView *view) { //don't add twice! QGIView* existing = getQGIVByName(view->getViewName()); - if (existing == nullptr) { + if (!existing) { addItem(view); // Find if it belongs to a parent @@ -186,7 +313,7 @@ int QGSPage::addQView(QGIView *view) int QGSPage::removeQView(QGIView *view) { - if (view != nullptr) { + if (view) { removeQViewFromScene(view); delete view; } @@ -224,22 +351,86 @@ int QGSPage::removeQViewByName(const char* name) void QGSPage::removeQViewFromScene(QGIView *view) { QGIView* qgParent = dynamic_cast(view->parentItem()); - if (qgParent != nullptr) { + if (qgParent) { qgParent->removeChild(view); } else { removeItem(view); } } +bool QGSPage::addView(const App::DocumentObject *obj) +{ + return attachView(const_cast(obj)); +} + +bool QGSPage::attachView(App::DocumentObject *obj) +{ +// Base::Console().Message("QGSP::attachView(%s)\n", obj->getNameInDocument()); + QGIView* existing = findQViewForDocObj(obj); + if (existing != nullptr) { + return true; + } + + auto typeId(obj->getTypeId()); + + QGIView *qview(nullptr); + + if (typeId.isDerivedFrom(TechDraw::DrawViewSection::getClassTypeId()) ) { + qview = addViewSection( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewPart::getClassTypeId()) ) { + qview = addViewPart( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawProjGroup::getClassTypeId()) ) { + qview = addProjectionGroup( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId()) ) { + qview = addDrawView( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewDimension::getClassTypeId()) ) { + qview = addViewDimension( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewBalloon::getClassTypeId()) ) { + qview = addViewBalloon( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewAnnotation::getClassTypeId()) ) { + qview = addDrawViewAnnotation( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewSymbol::getClassTypeId()) ) { + qview = addDrawViewSymbol( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewClip::getClassTypeId()) ) { + qview = addDrawViewClip( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewSpreadsheet::getClassTypeId()) ) { + qview = addDrawViewSpreadsheet( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawViewImage::getClassTypeId()) ) { + qview = addDrawViewImage( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawLeaderLine::getClassTypeId()) ) { + qview = addViewLeader( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawRichAnno::getClassTypeId()) ) { + qview = addRichAnno( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawWeldSymbol::getClassTypeId()) ) { + qview = addWeldSymbol( static_cast(obj) ); + + } else if (typeId.isDerivedFrom(TechDraw::DrawHatch::getClassTypeId()) ) { + //Hatch is not attached like other Views (since it isn't really a View) + return true; + + } else { + Base::Console().Log("Logic Error - Unknown view type in QGSPage::attachView\n"); + } + + return (qview != nullptr); +} QGIView * QGSPage::addViewPart(TechDraw::DrawViewPart *part) { // Base::Console().Message("QGSP::addViewPart(%s)\n", part->getNameInDocument()); - QGIView* existing = findQViewForDocObj(part); - if (existing != nullptr) { - return existing; - } - auto viewPart( new QGIViewPart ); viewPart->setViewPartFeature(part); @@ -258,7 +449,8 @@ QGIView * QGSPage::addViewSection(TechDraw::DrawViewPart *part) return viewSection; } -QGIView * QGSPage::addProjectionGroup(TechDraw::DrawProjGroup *view) { +QGIView * QGSPage::addProjectionGroup(TechDraw::DrawProjGroup *view) +{ auto qview( new QGIProjGroup ); qview->setViewFeature(view); @@ -397,7 +589,6 @@ void QGSPage::createBalloon(QPointF origin, DrawViewPart *parent) balloon->Y.setValue(appOrigin.y() + textOffset); int idx = getDrawPage()->getNextBalloonIndex(); - QString labelText = QString::number(idx); balloon->Text.setValue(std::to_string(idx).c_str()); Command::doCommand(Command::Doc, "App.activeDocument().%s.addView(App.activeDocument().%s)", pageName.c_str(), featName.c_str()); @@ -427,7 +618,7 @@ QGIView * QGSPage::addViewDimension(TechDraw::DrawViewDimension *dim) void QGSPage::addDimToParent(QGIViewDimension* dim, QGIView* parent) { -// Base::Console().Message("QGVP::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.); @@ -439,7 +630,7 @@ void QGSPage::addDimToParent(QGIViewDimension* dim, QGIView* parent) QGIView * QGSPage::addViewLeader(TechDraw::DrawLeaderLine *leader) { -// Base::Console().Message("QGVP::addViewLeader(%s)\n",leader->getNameInDocument()); +// Base::Console().Message("QGSP::addViewLeader(%s)\n",leader->getNameInDocument()); QGILeaderLine* leaderGroup = new QGILeaderLine(); addItem(leaderGroup); @@ -459,72 +650,140 @@ QGIView * QGSPage::addViewLeader(TechDraw::DrawLeaderLine *leader) void QGSPage::addLeaderToParent(QGILeaderLine* lead, QGIView* parent) { -// Base::Console().Message("QGVP::addLeaderToParent()\n"); +// Base::Console().Message("QGSP::addLeaderToParent()\n"); parent->addToGroup(lead); lead->setZValue(ZVALUE::DIMENSION); } QGIView * QGSPage::addRichAnno(TechDraw::DrawRichAnno* anno) { - QGIRichAnno* annoGroup = nullptr; - TechDraw::DrawView* parentDV = nullptr; - - App::DocumentObject* parentObj = anno->AnnoParent.getValue(); - if (parentObj != nullptr) { - parentDV = dynamic_cast(parentObj); - } - if (parentDV != nullptr) { - QGIView* parentQV = findQViewForDocObj(parentObj); - annoGroup = new QGIRichAnno(parentQV, anno); - annoGroup->updateView(true); - } else { - annoGroup = new QGIRichAnno(nullptr, anno); - addItem(annoGroup); - annoGroup->updateView(true); + QGIRichAnno* annoGroup = new QGIRichAnno(); + addItem(annoGroup); + annoGroup->setViewFeature(anno); + + QGIView *parent = findParent(annoGroup); + if (parent != nullptr) { + addAnnoToParent(annoGroup, parent); } + + annoGroup->updateView(true); + return annoGroup; } +void QGSPage::addAnnoToParent(QGIRichAnno* anno, QGIView* parent) +{ +// Base::Console().Message("QGSP::addAnnoToParent()\n"); + parent->addToGroup(anno); + anno->setZValue(ZVALUE::DIMENSION); +} + + QGIView * QGSPage::addWeldSymbol(TechDraw::DrawWeldSymbol* weld) { -// Base::Console().Message("QGVP::addWeldSymbol()\n"); +// Base::Console().Message("QGSP::addWeldSymbol()\n"); QGIWeldSymbol* weldGroup = nullptr; TechDraw::DrawView* parentDV = nullptr; App::DocumentObject* parentObj = weld->Leader.getValue(); - if (parentObj != nullptr) { + if (parentObj) { parentDV = dynamic_cast(parentObj); } else { -// Base::Console().Message("QGVP::addWeldSymbol - no parent doc obj\n"); +// Base::Console().Message("QGSP::addWeldSymbol - no parent doc obj\n"); } - if (parentDV != nullptr) { + if (parentDV) { QGIView* parentQV = findQViewForDocObj(parentObj); QGILeaderLine* leadParent = dynamic_cast(parentQV); - if (leadParent != nullptr) { + if (leadParent) { weldGroup = new QGIWeldSymbol(leadParent); weldGroup->setFeature(weld); //for QGIWS weldGroup->setViewFeature(weld); //for QGIV weldGroup->updateView(true); - } else { - Base::Console().Error("QGVP::addWeldSymbol - no parent QGILL\n"); } - } else { - Base::Console().Error("QGVP::addWeldSymbol - parent is not DV!\n"); } return weldGroup; } +void QGSPage::setDimensionGroups(void) +{ + const std::vector &allItems = getViews(); + int dimItemType = QGraphicsItem::UserType + 106; + + for (auto& item : allItems) { + if (item->type() == dimItemType && !item->group()) { + QGIView* parent = findParent(item); + if (parent) { + QGIViewDimension* dim = dynamic_cast(item); + addDimToParent(dim,parent); + } + } + } +} + +void QGSPage::setBalloonGroups(void) +{ + const std::vector &allItems = getViews(); + int balloonItemType = QGraphicsItem::UserType + 140; + + for (auto& item : allItems) { + if (item->type() == balloonItemType && !item->group()) { + QGIView* parent = findParent(item); + if (parent) { + QGIViewBalloon* balloon = dynamic_cast(item); + addBalloonToParent(balloon,parent); + } + } + } +} + +void QGSPage::setLeaderGroups(void) +{ +// Base::Console().Message("QGSP::setLeaderGroups()\n"); + const std::vector &allItems = getViews(); + int leadItemType = QGraphicsItem::UserType + 232; + + //make sure that qgileader belongs to correct parent. + //quite possibly redundant + for (auto& item : allItems) { + if (item->type() == leadItemType && !item->group()) { + QGIView* parent = findParent(item); + if (parent) { + QGILeaderLine* lead = dynamic_cast(item); + addLeaderToParent(lead,parent); + } + } + } +} + +void QGSPage::setRichAnnoGroups(void) +{ +// Base::Console().Message("QGSP::setRichAnnoGroups()\n"); + const std::vector &allItems = getViews(); + int annoItemType = QGraphicsItem::UserType + 233; + + //make sure that qgirichanno belongs to correct parent. + for (auto& item : allItems) { + if (item->type() == annoItemType && !item->group()) { + QGIView* parent = findParent(item); + if (parent) { + QGIRichAnno* anno = dynamic_cast(item); + addAnnoToParent(anno,parent); + } + } + } +} //! find the graphic for a DocumentObject QGIView * QGSPage::findQViewForDocObj(App::DocumentObject *obj) const { - if(obj) { - const std::vector qviews = getViews(); - for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { - if(strcmp(obj->getNameInDocument(), (*it)->getViewName()) == 0) - return *it; - } - } +// Base::Console().Message("QGSP::findQViewForDocObj(%s)\n", obj->getNameInDocument()); + if(obj) { + const std::vector qviews = getViews(); + for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { + if(strcmp(obj->getNameInDocument(), (*it)->getViewName()) == 0) + return *it; + } + } return nullptr; } @@ -546,22 +805,23 @@ QGIView* QGSPage::getQGIVByName(std::string name) } //find the parent of a QGIV based on the corresponding feature's parentage -QGIView * QGSPage::findParent(QGIView *view) const +QGIView *QGSPage::findParent(QGIView *view) const { +// Base::Console().Message("QGSP::findParent(%s)\n", view->getViewName()); const std::vector qviews = getViews(); TechDraw::DrawView *myFeat = view->getViewObject(); //If type is dimension we check references first TechDraw::DrawViewDimension *dim = nullptr; dim = dynamic_cast(myFeat); - if(dim) { + if (dim) { std::vector objs = dim->References2D.getValues(); - if(objs.size() > 0) { + if (!objs.empty()) { std::vector objs = dim->References2D.getValues(); // Attach the dimension to the first object's group - for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { - if(strcmp((*it)->getViewName(), objs.at(0)->getNameInDocument()) == 0) { + for (std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { + if (strcmp((*it)->getViewName(), objs.at(0)->getNameInDocument()) == 0) { return *it; } } @@ -572,86 +832,89 @@ QGIView * QGSPage::findParent(QGIView *view) const TechDraw::DrawViewBalloon *balloon = nullptr; balloon = dynamic_cast(myFeat); - if(balloon) { - App::DocumentObject* obj = balloon->SourceView.getValue(); + if (balloon) { + App::DocumentObject *obj = balloon->SourceView.getValue(); - if(obj) { + if (obj) { // Attach the dimension to the first object's group - for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { - if(strcmp((*it)->getViewName(), obj->getNameInDocument()) == 0) { + for (std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { + if (strcmp((*it)->getViewName(), obj->getNameInDocument()) == 0) { return *it; } } } } + //If type is LeaderLine we check LeaderParent + TechDraw::DrawLeaderLine *lead = nullptr; + lead = dynamic_cast(myFeat); + + if(lead != nullptr) { + App::DocumentObject* obj = lead->LeaderParent.getValue(); + if(obj != nullptr) { + std::string parentName = obj->getNameInDocument(); + for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { + if(strcmp((*it)->getViewName(), parentName.c_str()) == 0) { + return *it; + } + } + } + } + + //if type is a RichTextAnno we check AnnoParent + TechDraw::DrawRichAnno* anno = dynamic_cast(myFeat); + if (anno != nullptr) { + App::DocumentObject* obj = anno->AnnoParent.getValue(); + if (obj != nullptr) { + std::string parentName = obj->getNameInDocument(); + for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { + if(strcmp((*it)->getViewName(), parentName.c_str()) == 0) { + return *it; + } + } + } + } + // Check if part of view collection - for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { + for (std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { QGIViewCollection *grp = nullptr; grp = dynamic_cast(*it); - if(grp) { + if (grp) { TechDraw::DrawViewCollection *collection = nullptr; collection = dynamic_cast(grp->getViewObject()); - if(collection) { + if (collection) { std::vector objs = collection->Views.getValues(); - for( std::vector::iterator it = objs.begin(); it != objs.end(); ++it) { - if(strcmp(myFeat->getNameInDocument(), (*it)->getNameInDocument()) == 0) + for (std::vector::iterator it = objs.begin(); it != objs.end(); ++it) { + if (strcmp(myFeat->getNameInDocument(), (*it)->getNameInDocument()) == 0) return grp; } } } } - - //If type is LeaderLine we check LeaderParent - TechDraw::DrawLeaderLine *lead = nullptr; - lead = dynamic_cast(myFeat); - - if(lead) { - App::DocumentObject* obj = lead->LeaderParent.getValue(); - if(obj != nullptr) { - std::string parentName = obj->getNameInDocument(); - for(std::vector::const_iterator it = qviews.begin(); it != qviews.end(); ++it) { - if(strcmp((*it)->getViewName(), parentName.c_str()) == 0) { - return *it; - } - } - } - } // Not found a parent return nullptr; } -void QGSPage::setPageTemplate(TechDraw::DrawTemplate *obj) +bool QGSPage::hasQView(App::DocumentObject *obj) { - removeTemplate(); + const std::vector &views = getViews(); + std::vector::const_iterator qview = views.begin(); - if(obj->isDerivedFrom(TechDraw::DrawParametricTemplate::getClassTypeId())) { - pageTemplate = new QGIDrawingTemplate(this); - } else if(obj->isDerivedFrom(TechDraw::DrawSVGTemplate::getClassTypeId())) { - pageTemplate = new QGISVGTemplate(this); + while(qview != views.end()) { + // Unsure if we can compare pointers so rely on name + if(strcmp((*qview)->getViewName(), obj->getNameInDocument()) == 0) { + return true; + } + qview++; } - pageTemplate->setTemplate(obj); - pageTemplate->updateView(); + + return false; } -QGITemplate* QGSPage::getTemplate() const +void QGSPage::refreshViews() { - return pageTemplate; -} - -void QGSPage::removeTemplate() -{ - if(pageTemplate) { - removeItem(pageTemplate); - pageTemplate->deleteLater(); - pageTemplate = nullptr; - } -} - -void QGSPage::refreshViews(void) -{ -// Base::Console().Message("QGVP::refreshViews()\n"); +// Base::Console().Message("QGSP::refreshViews()\n"); QList list = items(); QList qgiv; //find only QGIV's @@ -669,6 +932,151 @@ void QGSPage::refreshViews(void) } } +void QGSPage::findMissingViews(const std::vector &list, std::vector &missing) +{ + for(std::vector::const_iterator it = list.begin(); it != list.end(); ++it) { + + if(!hasQView(*it)) + missing.push_back(*it); + + if((*it)->getTypeId().isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId())) { + std::vector missingChildViews; + TechDraw::DrawViewCollection *collection = dynamic_cast(*it); + // Find Child Views recursively + findMissingViews(collection->Views.getValues(), missingChildViews); + + // Append the views to current missing list + for(std::vector::const_iterator it = missingChildViews.begin(); it != missingChildViews.end(); ++it) { + missing.push_back(*it); + } + } + } +} + +//this is time consuming. should only be used when there is a problem. +//Solve the situation where a DrawView belonging to this DrawPage has no QGraphicsItem in +//the QGScene for the DrawPage -or- +//a QGraphics item exists in the DrawPage's QGScene, but there is no corresponding DrawView +//in the DrawPage. +void QGSPage::fixOrphans(bool force) +{ + Q_UNUSED(force) + + // get all the DrawViews for this page, including the second level ones + // if we ever have collections of collections, we'll need to revisit this + TechDraw::DrawPage* thisPage = m_vpPage->getDrawPage(); + + if(!thisPage->getNameInDocument()) + return; + + std::vector pChildren = thisPage->getAllViews(); + + // if dv doesn't have a graphic, make one + for (auto& dv: pChildren) { + if (dv->isRemoving()) { + continue; + } + QGIView* qv = findQViewForDocObj(dv); + if (qv == nullptr) { + attachView(dv); + } + } + // if qView doesn't have a Feature on this Page, delete it + std::vector qvss = getViews(); + // qvss may contain an item and its child item(s) and to avoid to access a deleted item a QPointer is needed + std::vector> qvs; + std::for_each(qvss.begin(), qvss.end(), [&qvs](QGIView* v) { + qvs.emplace_back(v); + }); + App::Document* doc = m_vpPage->getDrawPage()->getDocument(); + for (auto& qv: qvs) { + if (!qv) + continue; // already deleted? + + App::DocumentObject* obj = doc->getObject(qv->getViewName()); + if (!obj) { + //no DrawView anywhere in Document + removeQView(qv); + } else { + //DrawView exists in Document. Does it belong to this DrawPage? + int numParentPages = qv->getViewObject()->countParentPages(); + if (numParentPages == 0) { + //DrawView does not belong to any DrawPage + //remove QGItem from QGScene + removeQView(qv); + } else if (numParentPages == 1) { + //Does DrawView belong to this DrawPage? + TechDraw::DrawPage* parentPage = qv->getViewObject()->findParentPage(); + if (thisPage != parentPage) { + //DrawView does not belong to this DrawPage + //remove QGItem from QGScene + removeQView(qv); + } + } else if (numParentPages > 1) { + //DrawView belongs to multiple DrawPages + //check if this MDIViewPage corresponds to any parent DrawPage + //if not, delete the QGItem + std::vector potentialParentPages = qv->getViewObject()->findAllParentPages(); + bool found = false; + for (auto p: potentialParentPages) { + if (thisPage == p) { + found = true; + break; + } + } + if (!found) { + //none of the parent Pages for View correspond to this Page + removeQView(qv); + } + } + } + } + + setRichAnnoGroups(); //hack to fix QGIRA parentage; +} + +bool QGSPage::orphanExists(const char *viewName, const std::vector &list) +{ + for(std::vector::const_iterator it = list.begin(); it != list.end(); ++it) { + + //Check child objects too recursively + if((*it)->isDerivedFrom(TechDraw::DrawViewCollection::getClassTypeId())) { + TechDraw::DrawViewCollection *collection = dynamic_cast(*it); + if(orphanExists(viewName, collection->Views.getValues())) + return true; + } + + // Unsure if we can compare pointers so rely on name + if(strcmp(viewName, (*it)->getNameInDocument()) == 0) { + return true; + } + } + return false; +} + +//NOTE: this doesn't add missing views. see fixOrphans() +void QGSPage::redrawAllViews() +{ +// Base::Console().Message("QGSP::redrawAllViews() - views: %d\n", getViews().size()); + const std::vector &upviews = getViews(); + for(std::vector::const_iterator it = upviews.begin(); it != upviews.end(); ++it) { + (*it)->updateView(true); + } +} + +//NOTE: this doesn't add missing views. see fixOrphans() +void QGSPage::redraw1View(TechDraw::DrawView* dv) +{ + std::string dvName = dv->getNameInDocument(); + const std::vector &upviews = getViews(); + for(std::vector::const_iterator it = upviews.begin(); it != upviews.end(); ++it) { + std::string qgivName = (*it)->getViewName(); + if(dvName == qgivName) { + (*it)->updateView(true); + } + } +} + void QGSPage::setExporting(bool enable) { QList sceneItems = items(); @@ -785,11 +1193,11 @@ void QGSPage::postProcessXml(QTemporaryFile& temporaryFile, QString fileName, QS QDomDocument exportDoc(QString::fromUtf8("SvgDoc")); QFile file(temporaryFile.fileName()); if (!file.open(QIODevice::ReadOnly)) { - Base::Console().Message("QGSPage::ppsvg - tempfile open error\n"); + Base::Console().Error("QGSPage::ppsvg - tempfile open error\n"); return; } if (!exportDoc.setContent(&file)) { - Base::Console().Message("QGSPage::ppsvg - xml error\n"); + Base::Console().Error("QGSPage::ppsvg - xml error\n"); file.close(); return; } @@ -875,7 +1283,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().Message("QGVP::ppxml - failed to open file for writing: %s\n",qPrintable(fileName) ); + Base::Console().Error("QGSP::ppxml - failed to open file for writing: %s\n",qPrintable(fileName) ); } QTextStream stream( &outFile ); diff --git a/src/Mod/TechDraw/Gui/QGSPage.h b/src/Mod/TechDraw/Gui/QGSPage.h index d0174996b0..a2788bb881 100644 --- a/src/Mod/TechDraw/Gui/QGSPage.h +++ b/src/Mod/TechDraw/Gui/QGSPage.h @@ -26,6 +26,7 @@ #include #include +#include class QTemporaryFile; class QLabel; @@ -69,9 +70,11 @@ class TechDrawGuiExport QGSPage : public QGraphicsScene Q_OBJECT public: - QGSPage(ViewProviderPage *vp, QWidget *parent = nullptr); - virtual ~QGSPage(); + explicit QGSPage(ViewProviderPage *vp, QWidget *parent = nullptr); + ~QGSPage() override; + bool addView(const App::DocumentObject *obj); + bool attachView(App::DocumentObject *obj); QGIView * addViewDimension(TechDraw::DrawViewDimension *dim); QGIView * addViewBalloon(TechDraw::DrawViewBalloon *balloon); QGIView * addProjectionGroup(TechDraw::DrawProjGroup *view); @@ -88,15 +91,24 @@ public: QGIView * addRichAnno(TechDraw::DrawRichAnno* anno); QGIView * addWeldSymbol(TechDraw::DrawWeldSymbol* weld); + void addChildrenToPage(void); + void fixOrphans(bool force = false); + + void redrawAllViews(void); + void redraw1View(TechDraw::DrawView* dv); + QGIView* findQViewForDocObj(App::DocumentObject *obj) const; QGIView* getQGIVByName(std::string name); QGIView* findParent(QGIView *) const; + void findMissingViews( const std::vector &list, std::vector &missing); + bool hasQView(App::DocumentObject *obj); void addBalloonToParent(QGIViewBalloon* balloon, QGIView* parent); void createBalloon(QPointF origin, TechDraw::DrawViewPart *parent); void addDimToParent(QGIViewDimension* dim, QGIView* parent); void addLeaderToParent(QGILeaderLine* lead, QGIView* parent); + void addAnnoToParent(QGIRichAnno* anno, QGIView* parent); std::vector getViews() const; @@ -106,19 +118,27 @@ public: void removeQViewFromScene(QGIView *view); void setPageTemplate(TechDraw::DrawTemplate *pageTemplate); - QGITemplate * getTemplate() const; void removeTemplate(); + void matchSceneRectToTemplate(void); + void attachTemplate(TechDraw::DrawTemplate *obj); + void updateTemplate(bool force = false); + QPointF getTemplateCenter(); TechDraw::DrawPage * getDrawPage(); void setExporting(bool enable); - virtual void refreshViews(void); + virtual void refreshViews(); /// Renders the page to SVG with filename. void saveSvg(QString filename); void postProcessXml(QTemporaryFile& tempFile, QString filename, QString pagename); + void setDimensionGroups(void); + void setBalloonGroups(void); + void setLeaderGroups(void); + void setRichAnnoGroups(void); + public Q_SLOTS: protected: @@ -129,9 +149,15 @@ protected: QGITemplate *pageTemplate; + bool orphanExists(const char *viewName, const std::vector &list); + private: ViewProviderPage *m_vpPage; + QPageLayout::Orientation m_orientation; + QPageSize::PageSizeId m_paperSize; + qreal pagewidth, pageheight; + }; } // namespace diff --git a/src/Mod/TechDraw/Gui/QGTracker.cpp b/src/Mod/TechDraw/Gui/QGTracker.cpp index 78fd8cde61..74cc50a918 100644 --- a/src/Mod/TechDraw/Gui/QGTracker.cpp +++ b/src/Mod/TechDraw/Gui/QGTracker.cpp @@ -59,7 +59,7 @@ QGTracker::QGTracker(QGSPage* inScene, TrackerMode m): m_lastClick(QPointF(FLT_MAX,FLT_MAX)) { setTrackerMode(m); - if (inScene != nullptr) { + if (inScene) { inScene->addItem(this); } else { throw Base::ValueError("QGT::QGT() - passed scene is NULL\n"); @@ -106,11 +106,6 @@ QGTracker::~QGTracker() { } -QVariant QGTracker::itemChange(GraphicsItemChange change, const QVariant &value) -{ - return QGIPrimPath::itemChange(change, value); -} - void QGTracker::mousePressEvent(QGraphicsSceneMouseEvent *event) { QPointF myScenePos = event->scenePos(); @@ -157,16 +152,6 @@ void QGTracker::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event) QGIPrimPath::mouseDoubleClickEvent(event); } -void QGTracker::hoverEnterEvent(QGraphicsSceneHoverEvent *event) -{ - QGIPrimPath::hoverEnterEvent(event); -} - -void QGTracker::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) -{ - QGIPrimPath::hoverLeaveEvent(event); -} - void QGTracker::hoverMoveEvent(QGraphicsSceneHoverEvent* event) { if (!m_sleep) { @@ -201,7 +186,7 @@ void QGTracker::sleep(bool b) QPointF QGTracker::snapToAngle(QPointF dumbPt) { // If no point selected yet, snapping has no sense - if (m_points.size() < 1) + if (m_points.empty()) return dumbPt; QPointF result(dumbPt); @@ -321,13 +306,13 @@ void QGTracker::getPickedQGIV(QPointF pos) QGraphicsView* ourView = views.front(); //only 1 view / 1 scene / 1 mdipage QTransform viewXForm = ourView->transform(); QGraphicsItem* pickedItem = scene()->itemAt(pos,viewXForm); - if (pickedItem != nullptr) { + if (pickedItem) { QGraphicsItem* topItem = pickedItem->topLevelItem(); if (topItem != pickedItem) { pickedItem = topItem; } //pickedItem sb a QGIV QGIView* qgParent = dynamic_cast(pickedItem); - if (qgParent != nullptr) { + if (qgParent) { m_qgParent = qgParent; } } @@ -340,7 +325,7 @@ QRectF QGTracker::boundingRect() const return scene()->sceneRect(); } -QPainterPath QGTracker::shape(void) const +QPainterPath QGTracker::shape() const { QPainterPath result; result.addRect(boundingRect()); @@ -465,7 +450,7 @@ void QGTracker::setPoint(std::vector pts) setPrettyNormal(); } -std::vector QGTracker::convertPoints(void) +std::vector QGTracker::convertPoints() { std::vector result; for (auto& p: m_points) { @@ -475,7 +460,7 @@ std::vector QGTracker::convertPoints(void) return result; } -void QGTracker::terminateDrawing(void) +void QGTracker::terminateDrawing() { // Base::Console().Message("QGTracker::terminateDrawing()\n"); m_track->hide(); diff --git a/src/Mod/TechDraw/Gui/QGTracker.h b/src/Mod/TechDraw/Gui/QGTracker.h index 3a7652e2f6..f5bc2115ad 100644 --- a/src/Mod/TechDraw/Gui/QGTracker.h +++ b/src/Mod/TechDraw/Gui/QGTracker.h @@ -26,6 +26,7 @@ #include #include +#include QT_BEGIN_NAMESPACE class QPainter; @@ -33,6 +34,7 @@ class QStyleOptionGraphicsItem; QT_END_NAMESPACE #include +#include #include "QGIPrimPath.h" @@ -49,15 +51,15 @@ public: enum TrackerMode { None, Line, Circle, Rectangle, Point }; explicit QGTracker(QGSPage* scene = nullptr, QGTracker::TrackerMode m = QGTracker::TrackerMode::None); - ~QGTracker(); + ~QGTracker() override; enum {Type = QGraphicsItem::UserType + 210}; int type() const override { return Type;} - virtual void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; - virtual QPainterPath shape() const override; - virtual QRectF boundingRect() const override; + void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = nullptr ) override; + QPainterPath shape() const override; + QRectF boundingRect() const override; void onMousePress(QPointF); void onMouseMove(QPointF pos); @@ -70,27 +72,24 @@ public: void setSquareFromPoints(std::vector pts); void setCircleFromPoints(std::vector pts); void setPoint(std::vector pts); - std::vector convertPoints(void); - void terminateDrawing(void); + std::vector convertPoints(); + void terminateDrawing(); void sleep(bool b); - TrackerMode getTrackerMode(void) { return m_trackerMode; } + TrackerMode getTrackerMode() { return m_trackerMode; } void setTrackerMode(TrackerMode m) { m_trackerMode = m; } QPointF snapToAngle(QPointF pt); Q_SIGNALS: - void drawingFinished(std::vector pts, QGIView* qgParent); - void qViewPicked(QPointF pos, QGIView* qgParent); + void drawingFinished(std::vector pts, TechDrawGui::QGIView* qgParent); + void qViewPicked(QPointF pos, TechDrawGui::QGIView* qgParent); protected: - virtual void mousePressEvent(QGraphicsSceneMouseEvent *event) override; - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; - virtual void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; - virtual void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverLeaveEvent(QGraphicsSceneHoverEvent *event) override; - virtual void hoverMoveEvent(QGraphicsSceneHoverEvent* event) override; - virtual void keyPressEvent(QKeyEvent * event) override; + void mousePressEvent(QGraphicsSceneMouseEvent *event) override; + void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override; + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) override; + void hoverMoveEvent(QGraphicsSceneHoverEvent* event) override; + void keyPressEvent(QKeyEvent * event) override; - virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; void getPickedQGIV(QPointF pos); QColor getTrackerColor(); diff --git a/src/Mod/TechDraw/Gui/QGVNavStyle.cpp b/src/Mod/TechDraw/Gui/QGVNavStyle.cpp index de31576e05..d3606b933f 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyle.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyle.cpp @@ -85,7 +85,7 @@ void QGVNavStyle::initialize() void QGVNavStyle::setAnchor() { - if (m_viewer != nullptr) { + if (m_viewer) { if (zoomAtCursor) { m_viewer->setResizeAnchor(QGraphicsView::AnchorUnderMouse); m_viewer->setTransformationAnchor(QGraphicsView::AnchorUnderMouse); @@ -366,7 +366,7 @@ void QGVNavStyle::startClick(Qt::MouseButton b) m_clickButton = b; } -void QGVNavStyle::stopClick(void) +void QGVNavStyle::stopClick() { m_clickPending = false; m_clickButton = Qt::MouseButton::NoButton; diff --git a/src/Mod/TechDraw/Gui/QGVNavStyle.h b/src/Mod/TechDraw/Gui/QGVNavStyle.h index a64c43e829..7622869d4d 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyle.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyle.h @@ -22,11 +22,12 @@ #ifndef TECHDRAW_NAVIGATIONSTYLE_H -#include #define TECHDRAW_NAVIGATIONSTYLE_H #include + #include +#include class QEvent; class QFocusEvent; @@ -61,8 +62,8 @@ private: class TechDrawGuiExport QGVNavStyle : public Base::BaseClass { public: - QGVNavStyle(QGVPage* qgvp); - virtual ~QGVNavStyle(); + explicit QGVNavStyle(QGVPage* qgvp); + ~QGVNavStyle() override; void setViewer(QGVPage* qgvp) { m_viewer = qgvp;} ; QGVPage* getViewer() { return m_viewer;}; @@ -90,7 +91,7 @@ public: virtual void stopPan(); virtual void startClick(Qt::MouseButton b); - virtual void stopClick(void); + virtual void stopClick(); virtual void placeBalloon(QPoint p); diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleBlender.h b/src/Mod/TechDraw/Gui/QGVNavStyleBlender.h index 8551166727..0d16d33462 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleBlender.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleBlender.h @@ -35,16 +35,16 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleBlender : public QGVNavStyle { public: - QGVNavStyleBlender(QGVPage* qgvp); - virtual ~QGVNavStyleBlender(); + explicit QGVNavStyleBlender(QGVPage* qgvp); + ~QGVNavStyleBlender() override; - virtual void handleKeyReleaseEvent(QKeyEvent *event) override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleKeyReleaseEvent(QKeyEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; //context menu (RMB) prevents pan mode 2 (LMB + RMB) - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleCAD.h b/src/Mod/TechDraw/Gui/QGVNavStyleCAD.h index 94bccfb2f9..6d27bcbf7a 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleCAD.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleCAD.h @@ -35,16 +35,16 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleCAD : public QGVNavStyle { public: - QGVNavStyleCAD(QGVPage* qgvp); - virtual ~QGVNavStyleCAD(); + explicit QGVNavStyleCAD(QGVPage* qgvp); + ~QGVNavStyleCAD() override; - virtual void handleKeyReleaseEvent(QKeyEvent *event) override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleKeyReleaseEvent(QKeyEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; //context menu (RMB) prevents pan mode 2 (LMB + RMB) - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleGesture.h b/src/Mod/TechDraw/Gui/QGVNavStyleGesture.h index cea5684aba..47571390ac 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleGesture.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleGesture.h @@ -35,14 +35,14 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleGesture : public QGVNavStyle { public: - QGVNavStyleGesture(QGVPage* qgvp); - virtual ~QGVNavStyleGesture(); + explicit QGVNavStyleGesture(QGVPage* qgvp); + ~QGVNavStyleGesture() override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleInventor.h b/src/Mod/TechDraw/Gui/QGVNavStyleInventor.h index e0219d006a..3d9ed0c33d 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleInventor.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleInventor.h @@ -35,12 +35,12 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleInventor : public QGVNavStyle { public: - QGVNavStyleInventor(QGVPage* qgvp); - virtual ~QGVNavStyleInventor(); + explicit QGVNavStyleInventor(QGVPage* qgvp); + ~QGVNavStyleInventor() override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleMaya.h b/src/Mod/TechDraw/Gui/QGVNavStyleMaya.h index 58dddc72fe..4d9b2afad7 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleMaya.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleMaya.h @@ -35,15 +35,15 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleMaya : public QGVNavStyle { public: - QGVNavStyleMaya(QGVPage* qgvp); - virtual ~QGVNavStyleMaya(); + explicit QGVNavStyleMaya(QGVPage* qgvp); + ~QGVNavStyleMaya() override; - virtual void handleKeyReleaseEvent(QKeyEvent *event) override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleKeyReleaseEvent(QKeyEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleOCC.h b/src/Mod/TechDraw/Gui/QGVNavStyleOCC.h index 8cc34b6dd9..71b4825075 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleOCC.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleOCC.h @@ -35,16 +35,16 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleOCC : public QGVNavStyle { public: - QGVNavStyleOCC(QGVPage* qgvp); - virtual ~QGVNavStyleOCC(); + explicit QGVNavStyleOCC(QGVPage* qgvp); + ~QGVNavStyleOCC() override; - virtual void handleKeyReleaseEvent(QKeyEvent *event) override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleKeyReleaseEvent(QKeyEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; //context menu (RMB) prevents pan mode 2 (RMB or CNTL+RMB) - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.h b/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.h index 187fbce11b..0417da9432 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleOpenSCAD.h @@ -35,15 +35,15 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleOpenSCAD : public QGVNavStyle { public: - QGVNavStyleOpenSCAD(QGVPage* qgvp); - virtual ~QGVNavStyleOpenSCAD(); + explicit QGVNavStyleOpenSCAD(QGVPage* qgvp); + ~QGVNavStyleOpenSCAD() override; - virtual void handleKeyReleaseEvent(QKeyEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleKeyReleaseEvent(QKeyEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleRevit.h b/src/Mod/TechDraw/Gui/QGVNavStyleRevit.h index 8b0e896aa5..07608270d3 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleRevit.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleRevit.h @@ -35,14 +35,14 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleRevit : public QGVNavStyle { public: - QGVNavStyleRevit(QGVPage* qgvp); - virtual ~QGVNavStyleRevit(); + explicit QGVNavStyleRevit(QGVPage* qgvp); + ~QGVNavStyleRevit() override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; - virtual bool allowContextMenu(QContextMenuEvent *event) override; + bool allowContextMenu(QContextMenuEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleTinkerCAD.h b/src/Mod/TechDraw/Gui/QGVNavStyleTinkerCAD.h index 499fd01258..84c4ce00f7 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleTinkerCAD.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleTinkerCAD.h @@ -37,12 +37,12 @@ class TechDrawGuiExport QGVNavStyleTinkerCAD : public QGVNavStyle // TYPESYSTEM_HEADER(); public: - QGVNavStyleTinkerCAD(QGVPage* qgvp); - virtual ~QGVNavStyleTinkerCAD(); + explicit QGVNavStyleTinkerCAD(QGVPage* qgvp); + ~QGVNavStyleTinkerCAD() override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; - virtual void handleMousePressEvent(QMouseEvent *event) override; - virtual void handleMouseReleaseEvent(QMouseEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; + void handleMousePressEvent(QMouseEvent *event) override; + void handleMouseReleaseEvent(QMouseEvent *event) override; protected: private: diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.cpp b/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.cpp index 4967851d0a..4d6006e53d 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.cpp +++ b/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.cpp @@ -113,7 +113,7 @@ void QGVNavStyleTouchpad::handleMouseMoveEvent(QMouseEvent *event) void QGVNavStyleTouchpad::setAnchor() { //this navigation style can not anchor under mouse since mouse is moving as part of zoom action - if (m_viewer != nullptr) { + if (m_viewer) { m_viewer->setResizeAnchor(QGraphicsView::AnchorViewCenter); m_viewer->setTransformationAnchor(QGraphicsView::AnchorViewCenter); } diff --git a/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.h b/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.h index 39cd10215a..9968580966 100644 --- a/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.h +++ b/src/Mod/TechDraw/Gui/QGVNavStyleTouchpad.h @@ -35,15 +35,15 @@ class QGVPage; class TechDrawGuiExport QGVNavStyleTouchpad : public QGVNavStyle { public: - QGVNavStyleTouchpad(QGVPage* qgvp); - virtual ~QGVNavStyleTouchpad(); + explicit QGVNavStyleTouchpad(QGVPage* qgvp); + ~QGVNavStyleTouchpad() override; - virtual void handleKeyPressEvent(QKeyEvent *event) override; - virtual void handleKeyReleaseEvent(QKeyEvent *event) override; - virtual void handleMouseMoveEvent(QMouseEvent *event) override; + void handleKeyPressEvent(QKeyEvent *event) override; + void handleKeyReleaseEvent(QKeyEvent *event) override; + void handleMouseMoveEvent(QMouseEvent *event) override; protected: - virtual void setAnchor() override; + void setAnchor() override; private: diff --git a/src/Mod/TechDraw/Gui/QGVPage.cpp b/src/Mod/TechDraw/Gui/QGVPage.cpp index b8b21abe99..97212bc769 100644 --- a/src/Mod/TechDraw/Gui/QGVPage.cpp +++ b/src/Mod/TechDraw/Gui/QGVPage.cpp @@ -22,27 +22,28 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include -# include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include -# include +#include #include #include #include #include #include #include -#include #endif #include @@ -89,6 +90,7 @@ #include "Rez.h" #include "PreferencesGui.h" +#include "DrawGuiUtil.h" #include "QGIDrawingTemplate.h" #include "QGITemplate.h" #include "QGISVGTemplate.h" @@ -187,7 +189,7 @@ public: /// handle to the viewer parameter group ParameterGrp::handle hGrp; QGVPage* page; - Private(QGVPage* page) : page(page) { + explicit Private(QGVPage* page) : page(page) { // attach parameter Observer hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); hGrp->Attach(this); @@ -241,7 +243,6 @@ QGVPage::QGVPage(ViewProviderPage *vp, QGSPage* s, QWidget *parent) m_vpPage = vp; const char* name = vp->getDrawPage()->getNameInDocument(); setObjectName(QString::fromLocal8Bit(name)); - m_vpPage->setGraphicsView(this); setScene(s); setMouseTracking(true); @@ -250,11 +251,10 @@ QGVPage::QGVPage(ViewProviderPage *vp, QGSPage* s, QWidget *parent) m_parentMDI = static_cast(parent); m_saveContextEvent = nullptr; - setViewportUpdateMode(QGraphicsView::FullViewportUpdate); //this prevents crash when deleting dims. - //scene(view?) indices of dirty regions gets - //out of sync. missing prepareGeometryChange - //somewhere???? QTBUG-18021???? setCacheMode(QGraphicsView::CacheBackground); + setRenderer(Native); +// setRenderer(OpenGL); //gives rotten quality, don't use this + setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); d->init(); if (m_atCursor) { @@ -269,7 +269,6 @@ QGVPage::QGVPage(ViewProviderPage *vp, QGSPage* s, QWidget *parent) // setDragMode(ScrollHandDrag); setDragMode(QGraphicsView::NoDrag); resetCursor(); - setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); bkgBrush = new QBrush(getBackgroundColor()); @@ -277,8 +276,6 @@ QGVPage::QGVPage(ViewProviderPage *vp, QGSPage* s, QWidget *parent) balloonCursor->setPixmap(prepareCursorPixmap("TechDraw_Balloon.svg", balloonHotspot = QPoint(8, 59))); balloonCursor->hide(); - resetCachedContent(); - initNavigationStyle(); createStandardCursors(devicePixelRatio()); @@ -290,6 +287,11 @@ QGVPage::~QGVPage() delete m_navStyle; } +void QGVPage::centerOnPage(void) +{ + centerOn(m_vpPage->getQGSPage()->getTemplateCenter()); +} + void QGVPage::initNavigationStyle() { std::string navParm = getNavStyleParameter(); @@ -299,7 +301,7 @@ void QGVPage::initNavigationStyle() void QGVPage::setNavigationStyle(std::string navParm) { // Base::Console().Message("QGVP::setNavigationStyle(%s)\n", navParm.c_str()); - if (m_navStyle != nullptr) { + if (m_navStyle) { delete m_navStyle; } @@ -339,7 +341,7 @@ void QGVPage::setNavigationStyle(std::string navParm) } } -void QGVPage::startBalloonPlacing(void) +void QGVPage::startBalloonPlacing() { balloonPlacing = true; #if QT_VERSION >= QT_VERSION_CHECK(5,15,0) @@ -349,7 +351,7 @@ void QGVPage::startBalloonPlacing(void) #endif } -void QGVPage::cancelBalloonPlacing(void) +void QGVPage::cancelBalloonPlacing() { balloonPlacing = false; balloonCursor->hide(); @@ -367,14 +369,13 @@ void QGVPage::drawBackground(QPainter *p, const QRectF &) } if (!m_vpPage->getDrawPage()) { - //Base::Console().Log("TROUBLE - QGVP::drawBackground - no Page Object!\n"); +// Base::Console().Message("QGVP::drawBackground - no Page Feature!\n"); return; } p->save(); p->resetTransform(); - p->setBrush(*bkgBrush); p->drawRect(viewport()->rect().adjusted(-2,-2,2,2)); //just bigger than viewport to prevent artifacts @@ -400,17 +401,19 @@ void QGVPage::drawBackground(QPainter *p, const QRectF &) p->restore(); } - void QGVPage::setRenderer(RendererType type) { m_renderer = type; if (m_renderer == OpenGL) { #ifndef QT_NO_OPENGL - setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); +// setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); //QGLWidget is obsolete + setViewport(new QOpenGLWidget); + setViewportUpdateMode(QGraphicsView::SmartViewportUpdate); #endif } else { setViewport(new QWidget); + setViewportUpdateMode(QGraphicsView::FullViewportUpdate); } } @@ -451,7 +454,7 @@ void QGVPage::contextMenuEvent(QContextMenuEvent *event) //delete the old saved event before creating a new one to avoid memory leak //NOTE: saving the actual event doesn't work as the event gets deleted somewhere in Qt - if (m_saveContextEvent != nullptr) { + if (m_saveContextEvent) { delete m_saveContextEvent; } m_saveContextEvent = new QContextMenuEvent(QContextMenuEvent::Mouse, @@ -461,7 +464,7 @@ void QGVPage::contextMenuEvent(QContextMenuEvent *event) void QGVPage::pseudoContextEvent() { - if (m_saveContextEvent != nullptr) { + if (m_saveContextEvent) { m_parentMDI->contextMenuEvent(m_saveContextEvent); } } diff --git a/src/Mod/TechDraw/Gui/QGVPage.h b/src/Mod/TechDraw/Gui/QGVPage.h index bd96c3d12b..d5b29e1d04 100644 --- a/src/Mod/TechDraw/Gui/QGVPage.h +++ b/src/Mod/TechDraw/Gui/QGVPage.h @@ -23,9 +23,10 @@ #ifndef TECHDRAWGUI_QGVIEW_H #define TECHDRAWGUI_QGVIEW_H -#include #include +#include + #include #include #include @@ -77,15 +78,15 @@ public: enum RendererType { Native, OpenGL, Image }; QGVPage(ViewProviderPage *vp, QGSPage* s, QWidget *parent = nullptr); - virtual ~QGVPage(); + ~QGVPage() override; void setRenderer(RendererType type = Native); void drawBackground(QPainter *p, const QRectF &rect) override; QGSPage* getScene() {return m_scene; } - void startBalloonPlacing(void); - void cancelBalloonPlacing(void); + void startBalloonPlacing(); + void cancelBalloonPlacing(); TechDraw::DrawPage * getDrawPage(); @@ -93,7 +94,7 @@ public: void makeGrid(int width, int height, double step); void showGrid(bool state) {m_showGrid = state;} - void updateViewport(void) {viewport()->repaint();} + void updateViewport() {viewport()->repaint();} bool isBalloonPlacing() {return balloonPlacing; } void setBalloonPlacing(bool s) {balloonPlacing = s;} @@ -112,6 +113,8 @@ public: void pseudoContextEvent(); + void centerOnPage(void); + public Q_SLOTS: void setHighQualityAntialiasing(bool highQualityAntialiasing); diff --git a/src/Mod/TechDraw/Gui/Resources/TechDraw.qrc b/src/Mod/TechDraw/Gui/Resources/TechDraw.qrc index 6d07c93fd5..9092f93518 100644 --- a/src/Mod/TechDraw/Gui/Resources/TechDraw.qrc +++ b/src/Mod/TechDraw/Gui/Resources/TechDraw.qrc @@ -45,6 +45,7 @@ icons/actions/TechDraw_ToggleFrame.svg icons/actions/TechDraw_View.svg icons/actions/TechDraw_WeldSymbol.svg + icons/actions/TechDraw_SurfaceFinishSymbols.svg icons/arrow-ccw.svg icons/arrow-cw.svg icons/arrow-down.svg diff --git a/src/Mod/TechDraw/Gui/Resources/icons/MRTE/edit-cut.svg b/src/Mod/TechDraw/Gui/Resources/icons/MRTE/edit-cut.svg index fb051257b8..b9ac930c91 100644 --- a/src/Mod/TechDraw/Gui/Resources/icons/MRTE/edit-cut.svg +++ b/src/Mod/TechDraw/Gui/Resources/icons/MRTE/edit-cut.svg @@ -2,26 +2,34 @@ + inkscape:export-ydpi="90" + inkscape:output_extension="org.inkscape.output.svg.inkscape"> + @@ -362,14 +370,26 @@ showgrid="true" inkscape:document-units="px" inkscape:grid-bbox="true" - gridempspacing="4" gridtolerance="0.5px" inkscape:window-width="1011" - inkscape:window-height="1110" - inkscape:window-x="378" - inkscape:window-y="0" + inkscape:window-height="818" + inkscape:window-x="177" + inkscape:window-y="30" stroke="#a40000" - inkscape:showpageshadow="false" /> + inkscape:showpageshadow="false"> + + @@ -392,7 +412,7 @@ + rdf:resource="http://creativecommons.org/licenses/publicdomain/" /> Jakub Steiner @@ -400,21 +420,13 @@ + rdf:about="http://creativecommons.org/licenses/publicdomain/"> + rdf:resource="http://creativecommons.org/ns#Reproduction" /> - - - + rdf:resource="http://creativecommons.org/ns#Distribution" /> - + rdf:resource="http://creativecommons.org/ns#DerivativeWorks" /> diff --git a/src/Mod/TechDraw/Gui/Resources/icons/actions/TechDraw_SurfaceFinishSymbols.svg b/src/Mod/TechDraw/Gui/Resources/icons/actions/TechDraw_SurfaceFinishSymbols.svg new file mode 100644 index 0000000000..cab769fccc --- /dev/null +++ b/src/Mod/TechDraw/Gui/Resources/icons/actions/TechDraw_SurfaceFinishSymbols.svg @@ -0,0 +1,347 @@ + +image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Ra + + + \ No newline at end of file diff --git a/src/Mod/TechDraw/Gui/Rez.h b/src/Mod/TechDraw/Gui/Rez.h index a981f01222..e09e6e4e67 100644 --- a/src/Mod/TechDraw/Gui/Rez.h +++ b/src/Mod/TechDraw/Gui/Rez.h @@ -23,9 +23,12 @@ #ifndef DRAWINGGUI_REZ_H #define DRAWINGGUI_REZ_H +#include + #include #include #include + #include #include diff --git a/src/Mod/TechDraw/Gui/SymbolChooser.cpp b/src/Mod/TechDraw/Gui/SymbolChooser.cpp index 11689b6668..88f37a0706 100644 --- a/src/Mod/TechDraw/Gui/SymbolChooser.cpp +++ b/src/Mod/TechDraw/Gui/SymbolChooser.cpp @@ -21,7 +21,9 @@ ***************************************************************************/ #include "PreCompiled.h" +#ifndef _PreComp_ #include +#endif #include #include diff --git a/src/Mod/TechDraw/Gui/SymbolChooser.h b/src/Mod/TechDraw/Gui/SymbolChooser.h index f5b7dfb462..c8dddfab66 100644 --- a/src/Mod/TechDraw/Gui/SymbolChooser.h +++ b/src/Mod/TechDraw/Gui/SymbolChooser.h @@ -22,6 +22,8 @@ #ifndef TECHDRAWGUI_SYMBOLCHOOSER_H #define TECHDRAWGUI_SYMBOLCHOOSER_H +#include + #include class QListWidgetItem; diff --git a/src/Mod/TechDraw/Gui/TaskActiveView.cpp b/src/Mod/TechDraw/Gui/TaskActiveView.cpp index 409ca9fa3b..f9ac4b84aa 100644 --- a/src/Mod/TechDraw/Gui/TaskActiveView.cpp +++ b/src/Mod/TechDraw/Gui/TaskActiveView.cpp @@ -112,7 +112,7 @@ void TaskActiveView::blockButtons(bool b) } //****************************************************************************** -TechDraw::DrawViewSymbol* TaskActiveView::createActiveView(void) +TechDraw::DrawViewSymbol* TaskActiveView::createActiveView() { // Base::Console().Message("TAV::createActiveView()\n"); @@ -155,8 +155,7 @@ TechDraw::DrawViewSymbol* TaskActiveView::createActiveView(void) App::DocumentObject* newObj = m_pageFeat->getDocument()->getObject(symbolName.c_str()); TechDraw::DrawViewSymbol* newSym = dynamic_cast(newObj); - if ( (newObj == nullptr) || - (newSym == nullptr) ) { + if (!newObj || !newSym) { throw Base::RuntimeError("TaskActiveView - new symbol object not found"); } diff --git a/src/Mod/TechDraw/Gui/TaskActiveView.h b/src/Mod/TechDraw/Gui/TaskActiveView.h index ce98255493..bd746497f9 100644 --- a/src/Mod/TechDraw/Gui/TaskActiveView.h +++ b/src/Mod/TechDraw/Gui/TaskActiveView.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKACTIVEVIEW_H #define TECHDRAWGUI_TASKACTIVEVIEW_H +#include + #include #include @@ -89,25 +91,25 @@ class TaskDlgActiveView : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgActiveView(TechDraw::DrawPage* pageFeat); - ~TaskDlgActiveView(); + explicit TaskDlgActiveView(TechDraw::DrawPage* pageFeat); + ~TaskDlgActiveView() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TaskBalloon.cpp b/src/Mod/TechDraw/Gui/TaskBalloon.cpp index 6830c8ab21..c42de7f8c8 100644 --- a/src/Mod/TechDraw/Gui/TaskBalloon.cpp +++ b/src/Mod/TechDraw/Gui/TaskBalloon.cpp @@ -95,7 +95,7 @@ TaskBalloon::TaskBalloon(QGIViewBalloon *parent, ViewProviderBalloon *balloonVP) // negative kink length is allowed, thus no minimum ui->qsbKinkLength->setUnit(Base::Unit::Length); - if (balloonVP != nullptr) { + if (balloonVP) { ui->textColor->setColor(balloonVP->Color.getValue().asValue()); connect(ui->textColor, SIGNAL(changed()), this, SLOT(onColorChanged())); ui->qsbFontSize->setValue(balloonVP->Fontsize.getValue()); diff --git a/src/Mod/TechDraw/Gui/TaskBalloon.h b/src/Mod/TechDraw/Gui/TaskBalloon.h index 15c029fb42..6503604165 100644 --- a/src/Mod/TechDraw/Gui/TaskBalloon.h +++ b/src/Mod/TechDraw/Gui/TaskBalloon.h @@ -24,6 +24,8 @@ #ifndef GUI_TASKVIEW_TASKBALLOON_H #define GUI_TASKVIEW_TASKBALLOON_H +#include + #include #include @@ -39,7 +41,7 @@ class TaskBalloon : public QWidget public: TaskBalloon(QGIViewBalloon *parent, ViewProviderBalloon *balloonVP); - ~TaskBalloon(); + ~TaskBalloon() override; public: virtual bool accept(); @@ -70,20 +72,20 @@ class TaskDlgBalloon : public Gui::TaskView::TaskDialog public: TaskDlgBalloon(QGIViewBalloon *parent, ViewProviderBalloon *balloonVP); - ~TaskDlgBalloon(); + ~TaskDlgBalloon() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskCenterLine.cpp b/src/Mod/TechDraw/Gui/TaskCenterLine.cpp index 309a067641..8b547e3535 100644 --- a/src/Mod/TechDraw/Gui/TaskCenterLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskCenterLine.cpp @@ -184,7 +184,7 @@ void TaskCenterLine::setUiPrimary() { setWindowTitle(QObject::tr("Create Center Line")); - if (m_partFeat != nullptr) { + if (m_partFeat) { std::string baseName = m_partFeat->getNameInDocument(); ui->leBaseView->setText(Base::Tools::fromStdString(baseName)); for (auto& s: m_subNames) { @@ -213,7 +213,7 @@ void TaskCenterLine::setUiPrimary() void TaskCenterLine::setUiEdit() { setWindowTitle(QObject::tr("Edit Center Line")); - if (m_partFeat != nullptr) { + if (m_partFeat) { std::string baseName = m_partFeat->getNameInDocument(); ui->leBaseView->setText(Base::Tools::fromStdString(baseName)); QString listItem = Base::Tools::fromStdString(m_edgeName); @@ -311,7 +311,7 @@ void TaskCenterLine::onStyleChanged() } //****************************************************************************** -void TaskCenterLine::createCenterLine(void) +void TaskCenterLine::createCenterLine() { Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create CenterLine")); @@ -320,9 +320,9 @@ void TaskCenterLine::createCenterLine(void) // the centerline creation can fail if m_type is edge and both selected edges are horizontal // because we attempt by default to create a vertical centerline - if (cl == nullptr) { // try a horizontal line + if (!cl) { // try a horizontal line cl = CenterLine::CenterLineBuilder(m_partFeat, m_subNames, CenterLine::CLMODE::HORIZONTAL, false); - if (cl != nullptr) { + if (cl) { m_mode = CenterLine::CLMODE::HORIZONTAL; ui->rbHorizontal->blockSignals(true); ui->rbHorizontal->setChecked(true); @@ -330,7 +330,7 @@ void TaskCenterLine::createCenterLine(void) } } - if (cl == nullptr) { + if (!cl) { Base::Console().Log("TCL::createCenterLine - CenterLine creation failed!\n"); Gui::Command::abortCommand(); return; @@ -361,7 +361,7 @@ void TaskCenterLine::createCenterLine(void) m_cl = cl; } -void TaskCenterLine::updateOrientation(void) +void TaskCenterLine::updateOrientation() { // When the orientation was changed, it can be that the centerline becomes invalid // this can lead to a crash, see e.g. @@ -379,13 +379,13 @@ void TaskCenterLine::updateOrientation(void) CenterLine* cl = CenterLine::CenterLineBuilder(m_partFeat, m_subNames, orientation, m_cl->m_flip2Line); - if (cl == nullptr) { // try another orientation + if (!cl) { // try another orientation if (orientation == CenterLine::CLMODE::VERTICAL) orientation = CenterLine::CLMODE::HORIZONTAL; else if (orientation == CenterLine::CLMODE::HORIZONTAL) orientation = CenterLine::CLMODE::VERTICAL; cl = CenterLine::CenterLineBuilder(m_partFeat, m_subNames, orientation, m_cl->m_flip2Line); - if (cl != nullptr) { + if (cl) { if (orientation == CenterLine::CLMODE::VERTICAL) { m_cl->m_mode = CenterLine::CLMODE::VERTICAL; ui->rbVertical->blockSignals(true); @@ -404,7 +404,7 @@ void TaskCenterLine::updateOrientation(void) } } - if (cl != nullptr) { // we succeeded + if (cl) { // we succeeded // reset the flip for existing centerline that might use the flip feature (when created with FC 0.19) m_cl->m_flip2Line = false; m_partFeat->recomputeFeature(); @@ -426,17 +426,12 @@ void TaskCenterLine::enableTaskButtons(bool b) double TaskCenterLine::getCenterWidth() { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - - double width = lg->getWeight("Graphic"); - delete lg; Gui::ViewProvider* vp = QGIView::getViewProvider(m_partFeat); auto partVP = dynamic_cast(vp); - if ( partVP != nullptr ) { - width = partVP->IsoWidth.getValue(); + if (!partVP) { + return TechDraw::LineGroup::getDefaultWidth("Graphic"); } - return width; + return partVP->IsoWidth.getValue(); } Qt::PenStyle TaskCenterLine::getCenterStyle() @@ -452,7 +447,7 @@ QColor TaskCenterLine::getCenterColor() return PreferencesGui::centerQColor(); } -double TaskCenterLine::getExtendBy(void) +double TaskCenterLine::getExtendBy() { Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); diff --git a/src/Mod/TechDraw/Gui/TaskCenterLine.h b/src/Mod/TechDraw/Gui/TaskCenterLine.h index d32695479b..c2a50e154c 100644 --- a/src/Mod/TechDraw/Gui/TaskCenterLine.h +++ b/src/Mod/TechDraw/Gui/TaskCenterLine.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKCENTERLINE_H #define TECHDRAWGUI_TASKCENTERLINE_H +#include + #include #include @@ -68,7 +70,7 @@ public: TechDraw::DrawPage* page, std::string edgeName, bool editMode); - ~TaskCenterLine(); + ~TaskCenterLine() override; public Q_SLOTS: @@ -76,7 +78,7 @@ public: virtual bool accept(); virtual bool reject(); virtual void setCreateMode(bool b) { m_createMode = b; } - virtual bool getCreateMode(void) { return m_createMode; } + virtual bool getCreateMode() { return m_createMode; } void updateTask(); void saveButtons(QPushButton* btnOK, QPushButton* btnCancel); @@ -85,12 +87,12 @@ public: protected Q_SLOTS: protected: - void changeEvent(QEvent *e); - void setUiConnect(void); - void setUiPrimary(void); - void setUiEdit(void); - void createCenterLine(void); - void updateOrientation(void); + void changeEvent(QEvent *e) override; + void setUiConnect(); + void setUiPrimary(); + void setUiEdit(); + void createCenterLine(); + void updateOrientation(); double getCenterWidth(); QColor getCenterColor(); @@ -140,24 +142,24 @@ public: TechDraw::DrawPage* page, std::string edgeName, bool editMode); - ~TaskDlgCenterLine(); + ~TaskDlgCenterLine() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TaskCosVertex.cpp b/src/Mod/TechDraw/Gui/TaskCosVertex.cpp index 6aef6e97bb..761093ee6c 100644 --- a/src/Mod/TechDraw/Gui/TaskCosVertex.cpp +++ b/src/Mod/TechDraw/Gui/TaskCosVertex.cpp @@ -74,9 +74,6 @@ TaskCosVertex::TaskCosVertex(TechDraw::DrawViewPart* baseFeat, ui(new Ui_TaskCosVertex), blockUpdate(false), m_tracker(nullptr), - m_mdi(nullptr), - m_scene(nullptr), - m_view(nullptr), m_baseFeat(baseFeat), m_basePage(page), m_qgParent(nullptr), @@ -94,10 +91,7 @@ TaskCosVertex::TaskCosVertex(TechDraw::DrawViewPart* baseFeat, Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_basePage->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* vpp = static_cast(vp); - m_mdi = vpp->getMDIViewPage(); - m_scene = m_mdi->getQGSPage(); - m_view = m_mdi->getQGVPage(); + m_vpp = static_cast(vp); setUiPrimary(); @@ -130,7 +124,7 @@ void TaskCosVertex::setUiPrimary() // Base::Console().Message("TCV::setUiPrimary()\n"); setWindowTitle(QObject::tr("New Cosmetic Vertex")); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { std::string baseName = m_baseFeat->getNameInDocument(); ui->leBaseView->setText(Base::Tools::fromStdString(baseName)); } @@ -145,7 +139,7 @@ void TaskCosVertex::setUiPrimary() ui->dsbY->setUnit(Base::Unit::Length); } -void TaskCosVertex::updateUi(void) +void TaskCosVertex::updateUi() { double x = m_savePoint.x(); double y = - m_savePoint.y(); @@ -186,8 +180,8 @@ void TaskCosVertex::onTrackerClicked(bool b) } m_inProgressLock = true; - m_saveContextPolicy = m_mdi->contextMenuPolicy(); - m_mdi->setContextMenuPolicy(Qt::PreventContextMenu); + m_saveContextPolicy = m_vpp->getMDIViewPage()->contextMenuPolicy(); + m_vpp->getMDIViewPage()->setContextMenuPolicy(Qt::PreventContextMenu); m_trackerMode = QGTracker::TrackerMode::Point; setEditCursor(Qt::CrossCursor); startTracker(); @@ -201,18 +195,18 @@ void TaskCosVertex::onTrackerClicked(bool b) enableTaskButtons(false); } -void TaskCosVertex::startTracker(void) +void TaskCosVertex::startTracker() { // Base::Console().Message("TCV::startTracker()\n"); if (m_trackerMode == QGTracker::TrackerMode::None) { return; } - if (m_tracker == nullptr) { - m_tracker = new QGTracker(m_scene, m_trackerMode); + if (!m_tracker) { + m_tracker = new QGTracker(m_vpp->getQGSPage(), m_trackerMode); QObject::connect( - m_tracker, SIGNAL(drawingFinished(std::vector, QGIView*)), - this, SLOT(onTrackerFinished(std::vector, QGIView*)) + m_tracker, &QGTracker::drawingFinished, + this, &TaskCosVertex::onTrackerFinished ); } else { @@ -242,9 +236,9 @@ void TaskCosVertex::onTrackerFinished(std::vector pts, QGIView* qgParen DrawViewPart* dvp = m_baseFeat; DrawProjGroupItem* dpgi = dynamic_cast(dvp); - if (dpgi != nullptr) { + if (dpgi) { DrawProjGroup* dpg = dpgi->getPGroup(); - if (dpg == nullptr) { + if (!dpg) { Base::Console().Message("TCV:onTrackerFinished - projection group is confused\n"); //TODO::throw something. return; @@ -268,16 +262,15 @@ void TaskCosVertex::onTrackerFinished(std::vector pts, QGIView* qgParen ui->pbTracker->setEnabled(true); enableTaskButtons(true); setEditCursor(Qt::ArrowCursor); - m_mdi->setContextMenuPolicy(m_saveContextPolicy); + m_vpp->getMDIViewPage()->setContextMenuPolicy(m_saveContextPolicy); } -void TaskCosVertex::removeTracker(void) +void TaskCosVertex::removeTracker() { // Base::Console().Message("TCV::removeTracker()\n"); - if ((m_tracker != nullptr) && - (m_tracker->scene() != nullptr)) { - m_scene->removeItem(m_tracker); + if (m_tracker && m_tracker->scene()) { + m_vpp->getQGSPage()->removeItem(m_tracker); delete m_tracker; m_tracker = nullptr; } @@ -285,13 +278,13 @@ void TaskCosVertex::removeTracker(void) void TaskCosVertex::setEditCursor(QCursor c) { - if (m_baseFeat != nullptr) { - QGIView* qgivBase = m_scene->findQViewForDocObj(m_baseFeat); + if (m_baseFeat) { + QGIView* qgivBase = m_vpp->getQGSPage()->findQViewForDocObj(m_baseFeat); qgivBase->setCursor(c); } } -void TaskCosVertex::abandonEditSession(void) +void TaskCosVertex::abandonEditSession() { QString msg = tr("In progress edit abandoned. Start over."); getMainWindow()->statusBar()->show(); @@ -330,7 +323,7 @@ bool TaskCosVertex::accept() m_baseFeat->recomputeFeature(); m_baseFeat->requestPaint(); - m_mdi->setContextMenuPolicy(m_saveContextPolicy); + m_vpp->getMDIViewPage()->setContextMenuPolicy(m_saveContextPolicy); m_trackerMode = QGTracker::TrackerMode::None; Gui::Command::doCommand(Gui::Command::Gui, "Gui.ActiveDocument.resetEdit()"); @@ -345,8 +338,8 @@ bool TaskCosVertex::reject() removeTracker(); m_trackerMode = QGTracker::TrackerMode::None; - if (m_mdi != nullptr) { - m_mdi->setContextMenuPolicy(m_saveContextPolicy); + if (m_vpp->getMDIViewPage()) { + m_vpp->getMDIViewPage()->setContextMenuPolicy(m_saveContextPolicy); } //make sure any dangling objects are cleaned up diff --git a/src/Mod/TechDraw/Gui/TaskCosVertex.h b/src/Mod/TechDraw/Gui/TaskCosVertex.h index 0e0116837a..3910a852f4 100644 --- a/src/Mod/TechDraw/Gui/TaskCosVertex.h +++ b/src/Mod/TechDraw/Gui/TaskCosVertex.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKCOSVERTEX_H #define TECHDRAWGUI_TASKCOSVERTEX_H +#include + #include #include @@ -46,14 +48,13 @@ class DrawCosVertex; namespace TechDrawGui { class QGSPage; -class QGVPage; class QGIView; class QGIPrimPath; -class MDIViewPage; class QGTracker; class QGEPath; class QGMText; class QGICosVertex; +class ViewProviderPage; class ViewProviderLeader; class Ui_TaskCosVertex; @@ -64,11 +65,11 @@ class TaskCosVertex : public QWidget public: TaskCosVertex(TechDraw::DrawViewPart* baseFeat, TechDraw::DrawPage* page); - ~TaskCosVertex(); + ~TaskCosVertex() override; public Q_SLOTS: void onTrackerClicked(bool b); - void onTrackerFinished(std::vector pts, QGIView* qgParent); + void onTrackerFinished(std::vector pts, TechDrawGui::QGIView* qgParent); public: virtual bool accept(); @@ -79,16 +80,16 @@ public: void enableTaskButtons(bool b); protected: - void changeEvent(QEvent *e); - void startTracker(void); - void removeTracker(void); - void abandonEditSession(void); + void changeEvent(QEvent *e) override; + void startTracker(); + void removeTracker(); + void abandonEditSession(); void addCosVertex(QPointF qPos); void blockButtons(bool b); - void setUiPrimary(void); - void updateUi(void); + void setUiPrimary(); + void updateUi(); void setEditCursor(QCursor c); QGIView* findParentQGIV(); @@ -99,9 +100,6 @@ private: QGTracker* m_tracker; - MDIViewPage* m_mdi; - QGSPage* m_scene; - QGVPage* m_view; TechDraw::DrawViewPart* m_baseFeat; TechDraw::DrawPage* m_basePage; QGIView* m_qgParent; @@ -117,6 +115,8 @@ private: int m_pbTrackerState; QPointF m_savePoint; bool pointFromTracker; + + ViewProviderPage* m_vpp; }; class TaskDlgCosVertex : public Gui::TaskView::TaskDialog @@ -126,24 +126,24 @@ class TaskDlgCosVertex : public Gui::TaskView::TaskDialog public: TaskDlgCosVertex(TechDraw::DrawViewPart* baseFeat, TechDraw::DrawPage* page); - ~TaskDlgCosVertex(); + ~TaskDlgCosVertex() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp b/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp index 75bdb29360..008e28b1bd 100644 --- a/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskCosmeticLine.cpp @@ -26,14 +26,11 @@ #include #include #include - -#endif // #ifndef _PreComp_ - -#include - #include #include -#include +#endif + +#include #include #include @@ -86,7 +83,7 @@ TaskCosmeticLine::TaskCosmeticLine(TechDraw::DrawViewPart* partFeat, //existence of partFeat is checked in calling command m_ce = m_partFeat->getCosmeticEdgeBySelection(m_edgeName); - if (m_ce == nullptr) { + if (!m_ce) { Base::Console().Error("TaskCosmeticLine - bad parameters. Can not proceed.\n"); return; } @@ -117,7 +114,7 @@ TaskCosmeticLine::TaskCosmeticLine(TechDraw::DrawViewPart* partFeat, TaskCosmeticLine::~TaskCosmeticLine() { - if (m_saveCE != nullptr) { + if (m_saveCE) { delete m_saveCE; } } diff --git a/src/Mod/TechDraw/Gui/TaskCosmeticLine.h b/src/Mod/TechDraw/Gui/TaskCosmeticLine.h index f188523459..706848d0ea 100644 --- a/src/Mod/TechDraw/Gui/TaskCosmeticLine.h +++ b/src/Mod/TechDraw/Gui/TaskCosmeticLine.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKCOSMETICLINE_H #define TECHDRAWGUI_TASKCOSMETICLINE_H +#include + #include #include #include @@ -58,7 +60,7 @@ public: std::vector is3d); TaskCosmeticLine(TechDraw::DrawViewPart* baseFeat, std::string edgeName); - ~TaskCosmeticLine(); + ~TaskCosmeticLine() override; public Q_SLOTS: @@ -70,13 +72,13 @@ public: protected Q_SLOTS: protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; - void setUiPrimary(void); - void setUiEdit(void); + void setUiPrimary(); + void setUiEdit(); - void createCosmeticLine(void); - void updateCosmeticLine(void); + void createCosmeticLine(); + void updateCosmeticLine(); private: std::unique_ptr ui; @@ -103,20 +105,20 @@ public: std::vector is3d); TaskDlgCosmeticLine(TechDraw::DrawViewPart* baseFeat, std::string edgeName); - ~TaskDlgCosmeticLine(); + ~TaskDlgCosmeticLine() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskCustomizeFormat.cpp b/src/Mod/TechDraw/Gui/TaskCustomizeFormat.cpp index 3f42cb67c1..42c0bd7614 100644 --- a/src/Mod/TechDraw/Gui/TaskCustomizeFormat.cpp +++ b/src/Mod/TechDraw/Gui/TaskCustomizeFormat.cpp @@ -25,15 +25,12 @@ #ifndef _PreComp_ #include #include -#include - -#endif // #ifndef _PreComp_ - #include - +#include #include #include #include +#endif #include #include @@ -51,9 +48,9 @@ #include #include -# include -# include -# include +#include +#include +#include #include "PreferencesGui.h" #include "QGVPage.h" diff --git a/src/Mod/TechDraw/Gui/TaskCustomizeFormat.h b/src/Mod/TechDraw/Gui/TaskCustomizeFormat.h index 96ba6e3479..ef052ee3ec 100644 --- a/src/Mod/TechDraw/Gui/TaskCustomizeFormat.h +++ b/src/Mod/TechDraw/Gui/TaskCustomizeFormat.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKCUSTOMIZEFORMAT_H #define TECHDRAWGUI_TASKCUSTOMIZEFORMAT_H +#include + #include #include @@ -60,8 +62,8 @@ class TaskCustomizeFormat : public QWidget Q_OBJECT public: - TaskCustomizeFormat(App::DocumentObject * object); - ~TaskCustomizeFormat(); + explicit TaskCustomizeFormat(App::DocumentObject * object); + ~TaskCustomizeFormat() override; public Q_SLOTS: @@ -77,9 +79,9 @@ private Q_SLOTS: protected Q_SLOTS: protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; - void setUiEdit(void); + void setUiEdit(); private: App::DocumentObject* selectedObject; @@ -93,21 +95,21 @@ class TaskDlgCustomizeFormat : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgCustomizeFormat(App::DocumentObject * object); - ~TaskDlgCustomizeFormat(); + explicit TaskDlgCustomizeFormat(App::DocumentObject * object); + ~TaskDlgCustomizeFormat() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskDetail.cpp b/src/Mod/TechDraw/Gui/TaskDetail.cpp index 483b3a6297..101a7b06ee 100644 --- a/src/Mod/TechDraw/Gui/TaskDetail.cpp +++ b/src/Mod/TechDraw/Gui/TaskDetail.cpp @@ -55,7 +55,6 @@ #include #include "QGSPage.h" -#include "QGVPage.h" #include "QGIView.h" #include "QGIPrimPath.h" #include "QGIGhostHighlight.h" @@ -78,9 +77,6 @@ TaskDetail::TaskDetail(TechDraw::DrawViewPart* baseFeat): ui(new Ui_TaskDetail), blockUpdate(false), m_ghost(nullptr), - m_mdi(nullptr), - m_scene(nullptr), - m_view(nullptr), m_detailFeat(nullptr), m_baseFeat(baseFeat), m_basePage(nullptr), @@ -102,7 +98,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 == nullptr) { + if (!m_basePage) { Base::Console().Error("TaskDetail - bad parameters - base page. Can not proceed.\n"); return; } @@ -115,10 +111,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewPart* baseFeat): Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_doc); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* vpp = static_cast(vp); - m_mdi = vpp->getMDIViewPage(); - m_scene = m_mdi->getQGSPage(); - m_view = m_mdi->getQGVPage(); + m_vpp = static_cast(vp); createDetail(); setUiFromFeat(); @@ -143,7 +136,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewPart* baseFeat): this, SLOT(onReferenceEdit())); m_ghost = new QGIGhostHighlight(); - m_scene->addItem(m_ghost); + m_vpp->getQGSPage()->addItem(m_ghost); m_ghost->hide(); connect(m_ghost, SIGNAL(positionChange(QPointF)), this, SLOT(onHighlightMoved(QPointF))); @@ -154,9 +147,6 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): ui(new Ui_TaskDetail), blockUpdate(false), m_ghost(nullptr), - m_mdi(nullptr), - m_scene(nullptr), - m_view(nullptr), m_detailFeat(detailFeat), m_baseFeat(nullptr), m_basePage(nullptr), @@ -174,7 +164,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): m_mode(EDITMODE), m_created(false) { - if (m_detailFeat == nullptr) { + if (!m_detailFeat) { //should be caught in CMD caller Base::Console().Error("TaskDetail - bad parameters. Can not proceed.\n"); return; @@ -184,13 +174,13 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): m_detailName = m_detailFeat->getNameInDocument(); m_basePage = m_detailFeat->findParentPage(); - if (m_basePage != nullptr) { + if (m_basePage) { m_pageName = m_basePage->getNameInDocument(); } App::DocumentObject* baseObj = m_detailFeat->BaseView.getValue(); m_baseFeat = dynamic_cast(baseObj); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { m_baseName = m_baseFeat->getNameInDocument(); } else { Base::Console().Error("TaskDetail - no BaseView. Can not proceed.\n"); @@ -201,10 +191,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_basePage->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* vpp = static_cast(vp); - m_mdi = vpp->getMDIViewPage(); - m_scene = m_mdi->getQGSPage(); - m_view = m_mdi->getQGVPage(); + m_vpp = static_cast(vp); saveDetailState(); setUiFromFeat(); @@ -229,7 +216,7 @@ TaskDetail::TaskDetail(TechDraw::DrawViewDetail* detailFeat): this, SLOT(onReferenceEdit())); m_ghost = new QGIGhostHighlight(); - m_scene->addItem(m_ghost); + m_vpp->getQGSPage()->addItem(m_ghost); m_ghost->hide(); connect(m_ghost, SIGNAL(positionChange(QPointF)), this, SLOT(onHighlightMoved(QPointF))); @@ -276,7 +263,7 @@ void TaskDetail::restoreDetailState() void TaskDetail::setUiFromFeat() { // Base::Console().Message("TD::setUIFromFeat()\n"); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { std::string baseName = getBaseFeat()->getNameInDocument(); ui->leBaseView->setText(Base::Tools::fromStdString(baseName)); } @@ -357,7 +344,7 @@ void TaskDetail::onScaleTypeEdit() ui->qsbScale->setEnabled(false); detailFeat->ScaleType.setValue(0.0); // set the page scale if there is a valid page - if (m_basePage != nullptr) { + if (m_basePage) { // set the page scale detailFeat->Scale.setValue(m_basePage->Scale.getValue()); ui->qsbScale->setValue(m_basePage->Scale.getValue()); @@ -402,13 +389,13 @@ void TaskDetail::onDraggerClicked(bool b) void TaskDetail::editByHighlight() { // Base::Console().Message("TD::editByHighlight()\n"); - if (m_ghost == nullptr) { + if (!m_ghost) { Base::Console().Error("TaskDetail::editByHighlight - no ghost object\n"); return; } double scale = getBaseFeat()->getScale(); - m_scene->clearSelection(); + m_vpp->getQGSPage()->clearSelection(); m_ghost->setSelected(true); m_ghost->setRadius(ui->qsbRadius->rawValue() * scale); m_ghost->setPos(getAnchorScene()); @@ -429,9 +416,9 @@ void TaskDetail::onHighlightMoved(QPointF dragEnd) DrawViewPart* dvp = getBaseFeat(); DrawProjGroupItem* dpgi = dynamic_cast(dvp); - if (dpgi != nullptr) { + if (dpgi) { DrawProjGroup* dpg = dpgi->getPGroup(); - if (dpg == nullptr) { + if (!dpg) { Base::Console().Message("TD::getAnchorScene - projection group is confused\n"); //TODO::throw something. return; @@ -543,7 +530,7 @@ QPointF TaskDetail::getAnchorScene() Base::Vector3d basePos; double scale = 1; - if (dpgi == nullptr) { //base is normal view + if (!dpgi) { //base is normal view double x = dvp->X.getValue(); double y = dvp->Y.getValue(); basePos = Base::Vector3d (x, -y, 0.0); @@ -551,7 +538,7 @@ QPointF TaskDetail::getAnchorScene() } else { //part of projection group DrawProjGroup* dpg = dpgi->getPGroup(); - if (dpg == nullptr) { + if (!dpg) { Base::Console().Message("TD::getAnchorScene - projection group is confused\n"); //TODO::throw something. return QPointF(0.0, 0.0); @@ -576,9 +563,9 @@ DrawViewPart* TaskDetail::getBaseFeat() { // Base::Console().Message("TD::getBaseFeat()\n"); - if (m_doc != nullptr) { + if (m_doc) { App::DocumentObject* baseObj = m_doc->getObject(m_baseName.c_str()); - if (baseObj != nullptr) { + if (baseObj) { return static_cast(baseObj); } } @@ -595,9 +582,9 @@ DrawViewDetail* TaskDetail::getDetailFeat() { // Base::Console().Message("TD::getDetailFeat()\n"); - if (m_doc != nullptr) { + if (m_doc) { App::DocumentObject* detailObj = m_doc->getObject(m_detailName.c_str()); - if (detailObj != nullptr) { + if (detailObj) { return static_cast(detailObj); } } diff --git a/src/Mod/TechDraw/Gui/TaskDetail.h b/src/Mod/TechDraw/Gui/TaskDetail.h index 2cc1d43d84..5b54e1fb13 100644 --- a/src/Mod/TechDraw/Gui/TaskDetail.h +++ b/src/Mod/TechDraw/Gui/TaskDetail.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKDETAIL_H #define TECHDRAWGUI_TASKDETAIL_H +#include + #include #include #include @@ -45,14 +47,12 @@ class DrawViewPart; namespace TechDrawGui { class QGSPage; -class QGVPage; class QGIView; class QGIPrimPath; -class MDIViewPage; class QGEPath; class QGIDetail; class QGIGhostHighlight; -class ViewProviderLeader; +class ViewProviderPage; class Ui_TaskDetail; class TaskDetail : public QWidget @@ -60,9 +60,9 @@ class TaskDetail : public QWidget Q_OBJECT public: - TaskDetail(TechDraw::DrawViewPart* baseFeat); - TaskDetail(TechDraw::DrawViewDetail* detailFeat); - ~TaskDetail(); + explicit TaskDetail(TechDraw::DrawViewPart* baseFeat); + explicit TaskDetail(TechDraw::DrawViewDetail* detailFeat); + ~TaskDetail() override; public Q_SLOTS: void onDraggerClicked(bool b); @@ -83,8 +83,8 @@ public: void enableTaskButtons(bool b); protected: - void changeEvent(QEvent *e); - void startDragger(void); + void changeEvent(QEvent *e) override; + void startDragger(); void createDetail(); void updateDetail(); @@ -92,7 +92,7 @@ protected: void editByHighlight(); void blockButtons(bool b); - void setUiFromFeat(void); + void setUiFromFeat(); void updateUi(QPointF p); void enableInputFields(bool b); @@ -109,9 +109,7 @@ private: QGIGhostHighlight* m_ghost; - MDIViewPage* m_mdi; - QGSPage* m_scene; - QGVPage* m_view; + ViewProviderPage* m_vpp; TechDraw::DrawViewDetail* m_detailFeat; TechDraw::DrawViewPart* m_baseFeat; TechDraw::DrawPage* m_basePage; @@ -142,26 +140,26 @@ class TaskDlgDetail : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgDetail(TechDraw::DrawViewPart* baseFeat); - TaskDlgDetail(TechDraw::DrawViewDetail* detailFeat); - ~TaskDlgDetail(); + explicit TaskDlgDetail(TechDraw::DrawViewPart* baseFeat); + explicit TaskDlgDetail(TechDraw::DrawViewDetail* detailFeat); + ~TaskDlgDetail() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TaskDimension.cpp b/src/Mod/TechDraw/Gui/TaskDimension.cpp index 31e23ac0fb..c9f212b4be 100644 --- a/src/Mod/TechDraw/Gui/TaskDimension.cpp +++ b/src/Mod/TechDraw/Gui/TaskDimension.cpp @@ -119,7 +119,7 @@ TaskDimension::TaskDimension(QGIViewDimension *parent, ViewProviderDimension *di connect(ui->cbArbitraryTolerances, SIGNAL(stateChanged(int)), this, SLOT(onArbitraryTolerancesChanged())); // Display Style - if (dimensionVP != nullptr) { + if (dimensionVP) { ui->cbArrowheads->setChecked(dimensionVP->FlipArrowheads.getValue()); connect(ui->cbArrowheads, SIGNAL(stateChanged(int)), this, SLOT(onFlipArrowheadsChanged())); ui->dimensionColor->setColor(dimensionVP->Color.getValue().asValue()); diff --git a/src/Mod/TechDraw/Gui/TaskDimension.h b/src/Mod/TechDraw/Gui/TaskDimension.h index 77028ed10a..fdbc163e2a 100644 --- a/src/Mod/TechDraw/Gui/TaskDimension.h +++ b/src/Mod/TechDraw/Gui/TaskDimension.h @@ -23,6 +23,8 @@ #ifndef GUI_TASKVIEW_TASKDIMENSION_H #define GUI_TASKVIEW_TASKDIMENSION_H +#include + #include #include @@ -38,7 +40,7 @@ class TaskDimension : public QWidget public: TaskDimension(QGIViewDimension *parent, ViewProviderDimension *dimensionVP); - ~TaskDimension(); + ~TaskDimension() override; public: virtual bool accept(); @@ -80,20 +82,20 @@ class TaskDlgDimension : public Gui::TaskView::TaskDialog public: TaskDlgDimension(QGIViewDimension *parent, ViewProviderDimension *dimensionVP); - ~TaskDlgDimension(); + ~TaskDlgDimension() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp b/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp index 53c63c2961..9249478558 100644 --- a/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp +++ b/src/Mod/TechDraw/Gui/TaskGeomHatch.cpp @@ -97,7 +97,7 @@ void TaskGeomHatch::initUi() connect(ui->ccColor, SIGNAL(changed()), this, SLOT(onColorChanged())); } -void TaskGeomHatch::onFileChanged(void) +void TaskGeomHatch::onFileChanged() { m_file = ui->fcFile->fileName().toUtf8().constData(); std::vector names = PATLineSpec::getPatternList(m_file); diff --git a/src/Mod/TechDraw/Gui/TaskGeomHatch.h b/src/Mod/TechDraw/Gui/TaskGeomHatch.h index dee2997ae5..6f8dd70058 100644 --- a/src/Mod/TechDraw/Gui/TaskGeomHatch.h +++ b/src/Mod/TechDraw/Gui/TaskGeomHatch.h @@ -23,6 +23,8 @@ #ifndef GUI_TASKVIEW_TASKGEOMHATCH_H #define GUI_TASKVIEW_TASKGEOMHATCH_H +#include + #include #include @@ -49,7 +51,7 @@ class TaskGeomHatch : public QWidget public: TaskGeomHatch(TechDraw::DrawGeomHatch* inHatch,TechDrawGui::ViewProviderGeomHatch* inVp, bool mode); - ~TaskGeomHatch(); + ~TaskGeomHatch() override; public: virtual bool accept(); @@ -58,10 +60,10 @@ public: bool getCreateMode() { return m_createMode; } protected Q_SLOTS: - void onFileChanged(void); + void onFileChanged(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void initUi(); // bool resetUi(); void updateValues(); @@ -100,21 +102,21 @@ class TaskDlgGeomHatch : public Gui::TaskView::TaskDialog public: TaskDlgGeomHatch(TechDraw::DrawGeomHatch* inHatch,TechDrawGui::ViewProviderGeomHatch* inVp, bool mode); - ~TaskDlgGeomHatch(); + ~TaskDlgGeomHatch() override; const ViewProviderGeomHatch * getViewProvider() const { return viewProvider; } public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void setCreateMode(bool b); diff --git a/src/Mod/TechDraw/Gui/TaskHatch.cpp b/src/Mod/TechDraw/Gui/TaskHatch.cpp index 24bb98d715..c5fe6a6f88 100644 --- a/src/Mod/TechDraw/Gui/TaskHatch.cpp +++ b/src/Mod/TechDraw/Gui/TaskHatch.cpp @@ -127,14 +127,14 @@ void TaskHatch::saveHatchState() void TaskHatch::restoreHatchState() { // Base::Console().Message("TH::restoreHatchState()\n"); - if (m_hatch != nullptr) { + if (m_hatch) { m_hatch->HatchPattern.setValue(m_saveFile); m_vp->HatchScale.setValue(m_saveScale); m_vp->HatchColor.setValue(m_saveColor); } } -void TaskHatch::onFileChanged(void) +void TaskHatch::onFileChanged() { m_file = Base::Tools::toStdString(ui->fcFile->fileName()); apply(); @@ -156,14 +156,14 @@ void TaskHatch::apply(bool forceUpdate) { Q_UNUSED(forceUpdate) // Base::Console().Message("TH::apply() - m_hatch: %X\n", m_hatch); - if (m_hatch == nullptr) { + if (!m_hatch) { createHatch(); } - if (m_hatch != nullptr) { + if (m_hatch) { updateHatch(); } - if (m_dvp != nullptr) { + if (m_dvp) { //only need requestPaint to hatch the face // m_dvp->requestPaint(); //need a recompute in order to claimChildren in tree diff --git a/src/Mod/TechDraw/Gui/TaskHatch.h b/src/Mod/TechDraw/Gui/TaskHatch.h index 716aed3434..776a5b2758 100644 --- a/src/Mod/TechDraw/Gui/TaskHatch.h +++ b/src/Mod/TechDraw/Gui/TaskHatch.h @@ -24,6 +24,8 @@ #ifndef GUI_TASKVIEW_TASKHATCH_H #define GUI_TASKVIEW_TASKHATCH_H +#include + #include #include #include @@ -49,24 +51,24 @@ class TaskHatch : public QWidget public: TaskHatch(TechDraw::DrawViewPart* inDvp, std::vector subs); - TaskHatch(TechDrawGui::ViewProviderHatch* inVp); - ~TaskHatch(); + explicit TaskHatch(TechDrawGui::ViewProviderHatch* inVp); + ~TaskHatch() override; public: virtual bool accept(); virtual bool reject(); protected Q_SLOTS: - void onFileChanged(void); + void onFileChanged(); void onScaleChanged(); void onColorChanged(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void apply(bool forceUpdate = false); - void createHatch(void); - void updateHatch(void); + void createHatch(); + void updateHatch(); void setUiPrimary(); void setUiEdit(); @@ -98,21 +100,21 @@ class TaskDlgHatch : public Gui::TaskView::TaskDialog public: TaskDlgHatch(TechDraw::DrawViewPart* inDvp, std::vector subs); - TaskDlgHatch(TechDrawGui::ViewProviderHatch* inVp); - ~TaskDlgHatch(); + explicit TaskDlgHatch(TechDrawGui::ViewProviderHatch* inVp); + ~TaskDlgHatch() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp b/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp index f3426e9572..f10f4113c4 100644 --- a/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp +++ b/src/Mod/TechDraw/Gui/TaskLeaderLine.cpp @@ -24,10 +24,10 @@ #ifndef _PreComp_ #include -#endif - #include #include +#endif + #include #include @@ -77,9 +77,6 @@ TaskLeaderLine::TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP) : ui(new Ui_TaskLeaderLine), blockUpdate(false), m_tracker(nullptr), - m_mdi(nullptr), - m_scene(nullptr), - m_view(nullptr), m_lineVP(leadVP), m_baseFeat(nullptr), m_basePage(nullptr), @@ -95,20 +92,19 @@ TaskLeaderLine::TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP) : m_btnCancel(nullptr), m_pbTrackerState(TRACKEREDIT), m_saveX(0.0), - m_saveY(0.0), - m_haveMdi(false) + m_saveY(0.0) { //existence of leadVP is guaranteed by caller being ViewProviderLeaderLine.setEdit m_lineFeat = m_lineVP->getFeature(); m_basePage = m_lineFeat->findParentPage(); - if ( m_basePage == nullptr ) { + if (!m_basePage) { Base::Console().Error("TaskRichAnno - bad parameters (2). Can not proceed.\n"); return; } App::DocumentObject* obj = m_lineFeat->LeaderParent.getValue(); - if (obj != nullptr) { + if (obj) { if (obj->isDerivedFrom(TechDraw::DrawView::getClassTypeId()) ) { m_baseFeat = static_cast(m_lineFeat->LeaderParent.getValue()); } @@ -116,24 +112,15 @@ TaskLeaderLine::TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP) : Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_basePage->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* vpp = static_cast(vp); + m_vpp = static_cast(vp); m_qgParent = nullptr; - m_haveMdi = true; - m_mdi = vpp->getMDIViewPage(); - if (m_mdi != nullptr) { - m_scene = m_mdi->getQGSPage(); - m_view = m_mdi->getQGVPage(); - if (m_baseFeat != nullptr) { - m_qgParent = m_scene->findQViewForDocObj(m_baseFeat); - } - } else { - m_haveMdi = false; + if (m_baseFeat) { + m_qgParent = m_vpp->getQGSPage()->findQViewForDocObj(m_baseFeat); } //TODO: when/if leaders are allowed to be parented to Page, check for m_baseFeat will be removed - if ( (m_baseFeat == nullptr) || - (m_basePage == nullptr) ) { + if (!m_baseFeat || !m_basePage) { Base::Console().Error("TaskLeaderLine - bad parameters (2). Can not proceed.\n"); return; } @@ -155,8 +142,8 @@ TaskLeaderLine::TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP) : saveState(); m_trackerMode = QGTracker::TrackerMode::Line; - if (m_haveMdi) { - m_saveContextPolicy = m_mdi->contextMenuPolicy(); + if (m_vpp->getMDIViewPage() != nullptr) { + m_saveContextPolicy = m_vpp->getMDIViewPage()->contextMenuPolicy(); } } @@ -166,9 +153,6 @@ TaskLeaderLine::TaskLeaderLine(TechDraw::DrawView* baseFeat, ui(new Ui_TaskLeaderLine), blockUpdate(false), m_tracker(nullptr), - m_mdi(nullptr), - m_scene(nullptr), - m_view(nullptr), m_lineVP(nullptr), m_baseFeat(baseFeat), m_basePage(page), @@ -184,27 +168,17 @@ TaskLeaderLine::TaskLeaderLine(TechDraw::DrawView* baseFeat, m_btnCancel(nullptr), m_pbTrackerState(TRACKERPICK), m_saveX(0.0), - m_saveY(0.0), - m_haveMdi(false) + m_saveY(0.0) { //existence of basePage and baseFeat is checked in CmdTechDrawLeaderLine (CommandAnnotate.cpp) Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_basePage->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* vpp = static_cast(vp); -// vpp->show(); + m_vpp = static_cast(vp); m_qgParent = nullptr; - m_haveMdi = true; - m_mdi = vpp->getMDIViewPage(); - if (m_mdi != nullptr) { - m_scene = m_mdi->getQGSPage(); - m_view = m_mdi->getQGVPage(); - if (baseFeat != nullptr) { - m_qgParent = m_scene->findQViewForDocObj(baseFeat); - } - } else { - m_haveMdi = false; + if (m_baseFeat) { + m_qgParent = m_vpp->getQGSPage()->findQViewForDocObj(baseFeat); } ui->setupUi(this); @@ -218,8 +192,8 @@ TaskLeaderLine::TaskLeaderLine(TechDraw::DrawView* baseFeat, ui->pbCancelEdit->setEnabled(false); m_trackerMode = QGTracker::TrackerMode::Line; - if (m_haveMdi) { - m_saveContextPolicy = m_mdi->contextMenuPolicy(); + if (m_vpp->getMDIViewPage() != nullptr) { + m_saveContextPolicy = m_vpp->getMDIViewPage()->contextMenuPolicy(); } } @@ -230,7 +204,7 @@ TaskLeaderLine::~TaskLeaderLine() void TaskLeaderLine::saveState() { - if (m_lineFeat != nullptr) { + if (m_lineFeat) { m_savePoints = m_lineFeat->WayPoints.getValues(); m_saveX = m_lineFeat->X.getValue(); m_saveY = m_lineFeat->Y.getValue(); @@ -239,7 +213,7 @@ void TaskLeaderLine::saveState() void TaskLeaderLine::restoreState() { - if (m_lineFeat != nullptr) { + if (m_lineFeat) { m_lineFeat->WayPoints.setValues(m_savePoints); m_lineFeat->X.setValue(m_saveX); m_lineFeat->Y.setValue(m_saveY); @@ -266,13 +240,13 @@ void TaskLeaderLine::setUiPrimary() enableVPUi(true); setWindowTitle(QObject::tr("New Leader Line")); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { std::string baseName = m_baseFeat->getNameInDocument(); ui->tbBaseView->setText(Base::Tools::fromStdString(baseName)); } ui->pbTracker->setText(tr("Pick points")); - if (m_haveMdi) { + if (m_vpp->getMDIViewPage() != nullptr) { ui->pbTracker->setEnabled(true); ui->pbCancelEdit->setEnabled(true); } else { @@ -309,7 +283,7 @@ void TaskLeaderLine::setUiEdit() enableVPUi(true); setWindowTitle(QObject::tr("Edit Leader Line")); - if (m_lineFeat != nullptr) { + if (m_lineFeat) { std::string baseName = m_lineFeat->LeaderParent.getValue()->getNameInDocument(); ui->tbBaseView->setText(Base::Tools::fromStdString(baseName)); @@ -321,7 +295,7 @@ void TaskLeaderLine::setUiEdit() connect(ui->cboxEndSym, SIGNAL(currentIndexChanged(int)), this, SLOT(onEndSymbolChanged())); ui->pbTracker->setText(tr("Edit points")); - if (m_haveMdi) { + if (m_vpp->getMDIViewPage() != nullptr) { ui->pbTracker->setEnabled(true); ui->pbCancelEdit->setEnabled(true); } else { @@ -330,7 +304,7 @@ void TaskLeaderLine::setUiEdit() } } - if (m_lineVP != nullptr) { + if (m_lineVP) { ui->cpLineColor->setColor(m_lineVP->Color.getValue().asValue()); ui->dsbWeight->setValue(m_lineVP->LineWidth.getValue()); ui->cboxStyle->setCurrentIndex(m_lineVP->LineStyle.getValue()); @@ -395,15 +369,14 @@ void TaskLeaderLine::createLeaderFeature(std::vector converted) m_leaderType.c_str(),m_leaderName.c_str()); Command::doCommand(Command::Doc,"App.activeDocument().%s.addView(App.activeDocument().%s)", PageName.c_str(),m_leaderName.c_str()); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { Command::doCommand(Command::Doc,"App.activeDocument().%s.LeaderParent = App.activeDocument().%s", m_leaderName.c_str(),m_baseFeat->getNameInDocument()); } App::DocumentObject* obj = m_basePage->getDocument()->getObject(m_leaderName.c_str()); - if (obj == nullptr) { + if (!obj) throw Base::RuntimeError("TaskLeaderLine - new markup object not found"); - } if (obj->isDerivedFrom(TechDraw::DrawLeaderLine::getClassTypeId())) { m_lineFeat = static_cast(obj); m_lineFeat->setPosition(Rez::appX(m_attachPoint.x),Rez::appX(- m_attachPoint.y), true); @@ -416,10 +389,10 @@ void TaskLeaderLine::createLeaderFeature(std::vector converted) commonFeatureUpdate(); } - if (m_lineFeat != nullptr) { + if (m_lineFeat) { Gui::ViewProvider* vp = QGIView::getViewProvider(m_lineFeat); auto leadVP = dynamic_cast(vp); - if ( leadVP != nullptr ) { + if (leadVP) { App::Color ac; ac.setValue(ui->cpLineColor->color()); leadVP->Color.setValue(ac); @@ -432,18 +405,18 @@ void TaskLeaderLine::createLeaderFeature(std::vector converted) Gui::Command::commitCommand(); //trigger claimChildren in tree - if (m_baseFeat != nullptr) { + if (m_baseFeat) { m_baseFeat->touch(); } m_basePage->touch(); - if (m_lineFeat != nullptr) { + if (m_lineFeat) { m_lineFeat->requestPaint(); } } -void TaskLeaderLine::updateLeaderFeature(void) +void TaskLeaderLine::updateLeaderFeature() { // Base::Console().Message("TTL::updateLeaderFeature()\n"); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit Leader")); @@ -458,13 +431,13 @@ void TaskLeaderLine::updateLeaderFeature(void) Gui::Command::updateActive(); Gui::Command::commitCommand(); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { m_baseFeat->requestPaint(); } m_lineFeat->requestPaint(); } -void TaskLeaderLine::commonFeatureUpdate(void) +void TaskLeaderLine::commonFeatureUpdate() { int start = ui->cboxStartSym->currentIndex(); int end = ui->cboxEndSym->currentIndex(); @@ -472,10 +445,10 @@ void TaskLeaderLine::commonFeatureUpdate(void) m_lineFeat->EndSymbol.setValue(end); } -void TaskLeaderLine::removeFeature(void) +void TaskLeaderLine::removeFeature() { // Base::Console().Message("TTL::removeFeature()\n"); - if (m_lineFeat == nullptr) + if (!m_lineFeat) return; if (m_createMode) { @@ -506,14 +479,14 @@ void TaskLeaderLine::onTrackerClicked(bool b) Q_UNUSED(b); // Base::Console().Message("TTL::onTrackerClicked() m_pbTrackerState: %d\n", // m_pbTrackerState); - if (!m_haveMdi) { + if (m_vpp->getMDIViewPage() == nullptr) { Base::Console().Message("TLL::onTrackerClicked - no Mdi, no Tracker!\n"); return; } if ( (m_pbTrackerState == TRACKERSAVE) && (getCreateMode()) ){ - if (m_tracker != nullptr) { + if (m_tracker) { m_tracker->terminateDrawing(); } m_pbTrackerState = TRACKERPICK; @@ -525,7 +498,7 @@ void TaskLeaderLine::onTrackerClicked(bool b) return; } else if ( (m_pbTrackerState == TRACKERSAVE) && (!getCreateMode()) ) { //edit mode - if (m_qgLine != nullptr) { + if (m_qgLine) { m_qgLine->closeEdit(); } m_pbTrackerState = TRACKERPICK; @@ -540,8 +513,8 @@ void TaskLeaderLine::onTrackerClicked(bool b) //TRACKERPICK or TRACKEREDIT if (getCreateMode()) { m_inProgressLock = true; - m_saveContextPolicy = m_mdi->contextMenuPolicy(); - m_mdi->setContextMenuPolicy(Qt::PreventContextMenu); + m_saveContextPolicy = m_vpp->getMDIViewPage()->contextMenuPolicy(); + m_vpp->getMDIViewPage()->setContextMenuPolicy(Qt::PreventContextMenu); m_trackerMode = QGTracker::TrackerMode::Line; setEditCursor(Qt::CrossCursor); startTracker(); @@ -558,13 +531,12 @@ void TaskLeaderLine::onTrackerClicked(bool b) m_trackerPoints = m_lineFeat->WayPoints.getValues(); if (!m_trackerPoints.empty()) { //regular edit session m_inProgressLock = true; - m_saveContextPolicy = m_mdi->contextMenuPolicy(); - m_mdi->setContextMenuPolicy(Qt::PreventContextMenu); - QGSPage* qgsp = m_mdi->getQGSPage(); - QGIView* qgiv = qgsp->findQViewForDocObj(m_lineFeat); + m_saveContextPolicy = m_vpp->getMDIViewPage()->contextMenuPolicy(); + m_vpp->getMDIViewPage()->setContextMenuPolicy(Qt::PreventContextMenu); + QGIView* qgiv = m_vpp->getQGSPage()->findQViewForDocObj(m_lineFeat); QGILeaderLine* qgLead = dynamic_cast(qgiv); - if (qgLead == nullptr) { + if (!qgLead) { //tarfu Base::Console().Error("TaskLeaderLine - can't find leader graphic\n"); //now what? throw will generate "unknown unhandled exception" @@ -584,8 +556,8 @@ void TaskLeaderLine::onTrackerClicked(bool b) } } else { // need to recreate leaderline m_inProgressLock = true; - m_saveContextPolicy = m_mdi->contextMenuPolicy(); - m_mdi->setContextMenuPolicy(Qt::PreventContextMenu); + m_saveContextPolicy = m_vpp->getMDIViewPage()->contextMenuPolicy(); + m_vpp->getMDIViewPage()->setContextMenuPolicy(Qt::PreventContextMenu); m_trackerMode = QGTracker::TrackerMode::Line; setEditCursor(Qt::CrossCursor); startTracker(); @@ -602,21 +574,21 @@ void TaskLeaderLine::onTrackerClicked(bool b) } } -void TaskLeaderLine::startTracker(void) +void TaskLeaderLine::startTracker() { // Base::Console().Message("TTL::startTracker()\n"); - if (!m_haveMdi) { + if (m_vpp->getQGSPage() == nullptr) { return; } if (m_trackerMode == QGTracker::TrackerMode::None) { return; } - if (m_tracker == nullptr) { - m_tracker = new QGTracker(m_scene, m_trackerMode); + if (!m_tracker) { + m_tracker = new QGTracker(m_vpp->getQGSPage(), m_trackerMode); QObject::connect( - m_tracker, SIGNAL(drawingFinished(std::vector, QGIView*)), - this , SLOT (onTrackerFinished(std::vector, QGIView*)) + m_tracker, &QGTracker::drawingFinished, + this , &TaskLeaderLine::onTrackerFinished ); } else { //this is too harsh. but need to avoid restarting process @@ -638,7 +610,7 @@ void TaskLeaderLine::onTrackerFinished(std::vector pts, QGIView* qgPare return; } - if (m_qgParent != nullptr) { + if (m_qgParent) { double scale = m_qgParent->getScale(); QPointF mapped = m_qgParent->mapFromScene(pts.front()) / scale; m_attachPoint = Base::Vector3d(mapped.x(), mapped.y(), 0.0); @@ -662,15 +634,14 @@ void TaskLeaderLine::onTrackerFinished(std::vector pts, QGIView* qgPare setEditCursor(Qt::ArrowCursor); } -void TaskLeaderLine::removeTracker(void) +void TaskLeaderLine::removeTracker() { // Base::Console().Message("TTL::removeTracker()\n"); - if (!m_haveMdi) { + if (m_vpp->getQGSPage() == nullptr) { return; } - if ( (m_tracker != nullptr) && - (m_tracker->scene() != nullptr) ) { - m_scene->removeItem(m_tracker); + if (m_tracker && m_tracker->scene()) { + m_vpp->getQGSPage()->removeItem(m_tracker); delete m_tracker; m_tracker = nullptr; } @@ -682,7 +653,7 @@ void TaskLeaderLine::onCancelEditClicked(bool b) // Base::Console().Message("TTL::onCancelEditClicked() m_pbTrackerState: %d\n", // m_pbTrackerState); abandonEditSession(); - if (m_lineFeat != nullptr) { + if (m_lineFeat) { m_lineFeat->requestPaint(); } @@ -697,12 +668,12 @@ void TaskLeaderLine::onCancelEditClicked(bool b) QGIView* TaskLeaderLine::findParentQGIV() { - if (m_baseFeat == nullptr) + if (!m_baseFeat) return nullptr; Gui::ViewProvider* gvp = QGIView::getViewProvider(m_baseFeat); ViewProviderDrawingView* vpdv = dynamic_cast(gvp); - if (vpdv == nullptr) + if (!vpdv) return nullptr; return vpdv->getQView();; @@ -710,11 +681,13 @@ QGIView* TaskLeaderLine::findParentQGIV() void TaskLeaderLine::setEditCursor(QCursor c) { - if (!m_haveMdi || m_baseFeat == nullptr) { + if (!m_vpp->getQGSPage()) { return; } - QGIView* qgivBase = m_scene->findQViewForDocObj(m_baseFeat); - qgivBase->setCursor(c); + if (m_baseFeat) { + QGIView* qgivBase = m_vpp->getQGSPage()->findQViewForDocObj(m_baseFeat); + qgivBase->setCursor(c); + } } //from 1:1 scale scene QPointF to zero origin Vector3d points @@ -731,7 +704,7 @@ void TaskLeaderLine::trackerPointsFromQPoints(std::vector pts) //****************************************************************************** //void TaskLeaderLine::onPointEditComplete(std::vector pts, QGIView* parent) -void TaskLeaderLine::onPointEditComplete(void) +void TaskLeaderLine::onPointEditComplete() { // Base::Console().Message("TTL::onPointEditComplete()\n"); m_inProgressLock = false; @@ -743,10 +716,10 @@ void TaskLeaderLine::onPointEditComplete(void) enableTaskButtons(true); } -void TaskLeaderLine::abandonEditSession(void) +void TaskLeaderLine::abandonEditSession() { // Base::Console().Message("TTL::abandonEditSession()\n"); - if (m_qgLine != nullptr) { + if (m_qgLine) { m_qgLine->abandonEdit(); } QString msg = tr("In progress edit abandoned. Start over."); @@ -782,14 +755,10 @@ int TaskLeaderLine::getPrefArrowStyle() double TaskLeaderLine::prefWeight() const { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double weight = lg->getWeight("Thin"); - delete lg; //Coverity CID 174670 - return weight; + return TechDraw::LineGroup::getDefaultWidth("Thin"); } -App::Color TaskLeaderLine::prefLineColor(void) +App::Color TaskLeaderLine::prefLineColor() { return PreferencesGui::leaderColor(); } @@ -822,8 +791,8 @@ bool TaskLeaderLine::accept() Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); - if (m_haveMdi) { - m_mdi->setContextMenuPolicy(m_saveContextPolicy); + if (m_vpp->getMDIViewPage() != nullptr) { + m_vpp->getMDIViewPage()->setContextMenuPolicy(m_saveContextPolicy); } return true; } @@ -842,8 +811,7 @@ bool TaskLeaderLine::reject() if (!doc) return false; - if (getCreateMode() && - (m_lineFeat != nullptr) ) { + if (getCreateMode() && m_lineFeat) { removeFeature(); } else { @@ -857,8 +825,8 @@ bool TaskLeaderLine::reject() Gui::Command::doCommand(Gui::Command::Gui,"App.activeDocument().recompute()"); Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); - if (m_mdi != nullptr) { - m_mdi->setContextMenuPolicy(m_saveContextPolicy); + if (m_vpp->getMDIViewPage()) { + m_vpp->getMDIViewPage()->setContextMenuPolicy(m_saveContextPolicy); } return false; diff --git a/src/Mod/TechDraw/Gui/TaskLeaderLine.h b/src/Mod/TechDraw/Gui/TaskLeaderLine.h index 8e6694ae75..939866356b 100644 --- a/src/Mod/TechDraw/Gui/TaskLeaderLine.h +++ b/src/Mod/TechDraw/Gui/TaskLeaderLine.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKTEXTLEADER_H #define TECHDRAWGUI_TASKTEXTLEADER_H +#include + #include #include #include @@ -46,15 +48,13 @@ class DrawLeaderLine; namespace TechDrawGui { -class QGSPage; -class QGVPage; class QGIView; class QGIPrimPath; -class MDIViewPage; class QGTracker; class QGEPath; class QGMText; class QGILeaderLine; +class ViewProviderPage; class ViewProviderLeader; class Ui_TaskLeaderLine; @@ -65,19 +65,19 @@ class TaskLeaderLine : public QWidget public: TaskLeaderLine(TechDraw::DrawView* baseFeat, TechDraw::DrawPage* page); - TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP); - ~TaskLeaderLine(); + explicit TaskLeaderLine(TechDrawGui::ViewProviderLeader* leadVP); + ~TaskLeaderLine() override; public Q_SLOTS: void onTrackerClicked(bool b); void onCancelEditClicked(bool b); - void onTrackerFinished(std::vector pts, QGIView* qgParent); + void onTrackerFinished(std::vector pts, TechDrawGui::QGIView* qgParent); public: virtual bool accept(); virtual bool reject(); virtual void setCreateMode(bool b) { m_createMode = b; } - virtual bool getCreateMode(void) { return m_createMode; } + virtual bool getCreateMode() { return m_createMode; } void updateTask(); void saveButtons(QPushButton* btnOK, QPushButton* btnCancel); @@ -86,23 +86,23 @@ public: protected Q_SLOTS: - void onPointEditComplete(void); + void onPointEditComplete(); protected: void trackerPointsFromQPoints(std::vector pts); - void changeEvent(QEvent *e); - void startTracker(void); - void removeTracker(void); - void abandonEditSession(void); + void changeEvent(QEvent *e) override; + void startTracker(); + void removeTracker(); + void abandonEditSession(); void createLeaderFeature(std::vector converted); void updateLeaderFeature(); - void commonFeatureUpdate(void); - void removeFeature(void); + void commonFeatureUpdate(); + void removeFeature(); void blockButtons(bool b); - void setUiPrimary(void); - void setUiEdit(void); + void setUiPrimary(); + void setUiEdit(); void enableTextUi(bool b); void enableVPUi(bool b); void setEditCursor(QCursor c); @@ -110,10 +110,10 @@ protected: QGIView* findParentQGIV(); int getPrefArrowStyle(); double prefWeight() const; - App::Color prefLineColor(void); + App::Color prefLineColor(); - void saveState(void); - void restoreState(void); + void saveState(); + void restoreState(); private Q_SLOTS: void onStartSymbolChanged(); @@ -128,9 +128,7 @@ private: QGTracker* m_tracker; - MDIViewPage* m_mdi; - QGSPage* m_scene; - QGVPage* m_view; + ViewProviderPage* m_vpp; ViewProviderLeader* m_lineVP; TechDraw::DrawView* m_baseFeat; TechDraw::DrawPage* m_basePage; @@ -170,25 +168,25 @@ class TaskDlgLeaderLine : public Gui::TaskView::TaskDialog public: TaskDlgLeaderLine(TechDraw::DrawView* baseFeat, TechDraw::DrawPage* page); - TaskDlgLeaderLine(TechDrawGui::ViewProviderLeader* leadVP); - ~TaskDlgLeaderLine(); + explicit TaskDlgLeaderLine(TechDrawGui::ViewProviderLeader* leadVP); + ~TaskDlgLeaderLine() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TaskLineDecor.cpp b/src/Mod/TechDraw/Gui/TaskLineDecor.cpp index 98852dd7b4..cdad561925 100644 --- a/src/Mod/TechDraw/Gui/TaskLineDecor.cpp +++ b/src/Mod/TechDraw/Gui/TaskLineDecor.cpp @@ -104,7 +104,7 @@ void TaskLineDecor::initUi() ui->cb_Visible->setCurrentIndex(m_visible); } -void TaskLineDecor::getDefaults(void) +void TaskLineDecor::getDefaults() { // Base::Console().Message("TLD::getDefaults()\n"); m_style = LineFormat::getDefEdgeStyle(); @@ -116,7 +116,7 @@ void TaskLineDecor::getDefaults(void) if (!m_edges.empty()) { int num = DrawUtil::getIndexFromName(m_edges.front()); BaseGeomPtr bg = m_partFeat->getGeomByIndex(num); - if (bg != nullptr) { + if (bg) { if (bg->cosmetic) { if (bg->source() == 1) { TechDraw::CosmeticEdge* ce = m_partFeat->getCosmeticEdgeBySelection(m_edges.front()); @@ -134,7 +134,7 @@ void TaskLineDecor::getDefaults(void) } } else { TechDraw::GeomFormat* gf = m_partFeat->getGeomFormatBySelection(num); - if (gf != nullptr) { + if (gf) { m_style = gf->m_format.m_style; m_color = gf->m_format.m_color; m_weight = gf->m_format.m_weight; @@ -142,7 +142,7 @@ void TaskLineDecor::getDefaults(void) } else { Gui::ViewProvider* vp = QGIView::getViewProvider(m_partFeat); auto partVP = dynamic_cast(vp); - if ( partVP != nullptr ) { + if (partVP) { m_weight = partVP->LineWidth.getValue(); m_style = Qt::SolidLine; // = 1 m_color = LineFormat::getDefEdgeColor(); @@ -154,41 +154,41 @@ void TaskLineDecor::getDefaults(void) } } -void TaskLineDecor::onStyleChanged(void) +void TaskLineDecor::onStyleChanged() { m_style = ui->cb_Style->currentIndex() + 1; applyDecorations(); m_partFeat->requestPaint(); } -void TaskLineDecor::onColorChanged(void) +void TaskLineDecor::onColorChanged() { m_color.setValue(ui->cc_Color->color()); applyDecorations(); m_partFeat->requestPaint(); } -void TaskLineDecor::onWeightChanged(void) +void TaskLineDecor::onWeightChanged() { m_weight = ui->dsb_Weight->value().getValue(); applyDecorations(); m_partFeat->requestPaint(); } -void TaskLineDecor::onVisibleChanged(void) +void TaskLineDecor::onVisibleChanged() { m_visible = ui->cb_Visible->currentIndex(); applyDecorations(); m_partFeat->requestPaint(); } -void TaskLineDecor::applyDecorations(void) +void TaskLineDecor::applyDecorations() { // Base::Console().Message("TLD::applyDecorations()\n"); for (auto& e: m_edges) { int num = DrawUtil::getIndexFromName(e); BaseGeomPtr bg = m_partFeat->getGeomByIndex(num); - if (bg != nullptr) { + if (bg) { if (bg->cosmetic) { if (bg->source() == 1) { TechDraw::CosmeticEdge* ce = m_partFeat->getCosmeticEdgeBySelection(e); @@ -206,7 +206,7 @@ void TaskLineDecor::applyDecorations(void) } } else { TechDraw::GeomFormat* gf = m_partFeat->getGeomFormatBySelection(num); - if (gf != nullptr) { + if (gf) { gf->m_format.m_style = m_style; gf->m_format.m_color = m_color; gf->m_format.m_weight = m_weight; @@ -291,7 +291,7 @@ void TaskRestoreLines::initUi() ui->l_Center->setText(QString::number(countInvisibleCenters())); } -void TaskRestoreLines::onAllPressed(void) +void TaskRestoreLines::onAllPressed() { // Base::Console().Message("TRL::onAllPressed()\n"); onGeometryPressed(); @@ -299,7 +299,7 @@ void TaskRestoreLines::onAllPressed(void) onCenterPressed(); } -void TaskRestoreLines::onGeometryPressed(void) +void TaskRestoreLines::onGeometryPressed() { // Base::Console().Message("TRL::onGeometryPressed()\n"); restoreInvisibleGeoms(); @@ -307,7 +307,7 @@ void TaskRestoreLines::onGeometryPressed(void) ui->l_All->setText(QString::number(countInvisibleLines())); } -void TaskRestoreLines::onCosmeticPressed(void) +void TaskRestoreLines::onCosmeticPressed() { // Base::Console().Message("TRL::onCosmeticPressed()\n"); restoreInvisibleCosmetics(); @@ -315,7 +315,7 @@ void TaskRestoreLines::onCosmeticPressed(void) ui->l_All->setText(QString::number(countInvisibleLines())); } -void TaskRestoreLines::onCenterPressed(void) +void TaskRestoreLines::onCenterPressed() { // Base::Console().Message("TRL::onCenterPressed()\n"); restoreInvisibleCenters(); @@ -323,7 +323,7 @@ void TaskRestoreLines::onCenterPressed(void) ui->l_All->setText(QString::number(countInvisibleLines())); } -int TaskRestoreLines::countInvisibleLines(void) +int TaskRestoreLines::countInvisibleLines() { int result = 0; result += countInvisibleGeoms(); @@ -332,7 +332,7 @@ int TaskRestoreLines::countInvisibleLines(void) return result; } -int TaskRestoreLines::countInvisibleGeoms(void) +int TaskRestoreLines::countInvisibleGeoms() { int iGeoms = 0; const std::vector geoms = m_partFeat->GeomFormats.getValues(); @@ -344,7 +344,7 @@ int TaskRestoreLines::countInvisibleGeoms(void) return iGeoms; } -int TaskRestoreLines::countInvisibleCosmetics(void) +int TaskRestoreLines::countInvisibleCosmetics() { int iCosmos = 0; const std::vector cosmos = m_partFeat->CosmeticEdges.getValues(); @@ -356,7 +356,7 @@ int TaskRestoreLines::countInvisibleCosmetics(void) return iCosmos++; } -int TaskRestoreLines::countInvisibleCenters(void) +int TaskRestoreLines::countInvisibleCenters() { int iCenter = 0; const std::vector centers = m_partFeat->CenterLines.getValues(); @@ -368,14 +368,14 @@ int TaskRestoreLines::countInvisibleCenters(void) return iCenter++; } -void TaskRestoreLines::restoreInvisibleLines(void) +void TaskRestoreLines::restoreInvisibleLines() { restoreInvisibleGeoms(); restoreInvisibleCosmetics(); restoreInvisibleCenters(); } -void TaskRestoreLines::restoreInvisibleGeoms(void) +void TaskRestoreLines::restoreInvisibleGeoms() { const std::vector geoms = m_partFeat->GeomFormats.getValues(); for (auto& g : geoms) { @@ -387,7 +387,7 @@ void TaskRestoreLines::restoreInvisibleGeoms(void) m_parent->apply(false); //don't undo the work we just did } -void TaskRestoreLines::restoreInvisibleCosmetics(void) +void TaskRestoreLines::restoreInvisibleCosmetics() { const std::vector cosmos = m_partFeat->CosmeticEdges.getValues(); for (auto& c : cosmos) { @@ -399,7 +399,7 @@ void TaskRestoreLines::restoreInvisibleCosmetics(void) m_parent->apply(false); //don't undo the work we just did } -void TaskRestoreLines::restoreInvisibleCenters(void) +void TaskRestoreLines::restoreInvisibleCenters() { const std::vector centers = m_partFeat->CenterLines.getValues(); for (auto& c : centers) { @@ -446,7 +446,7 @@ TaskDlgLineDecor::TaskDlgLineDecor(TechDraw::DrawViewPart* partFeat, } TaskLineDecor* parent = dynamic_cast(widget); - if (parent != nullptr) { + if (parent) { restore = new TaskRestoreLines(partFeat, parent); restoreBox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_DecorateLine"), tr("Restore Invisible Lines"), true, nullptr); diff --git a/src/Mod/TechDraw/Gui/TaskLineDecor.h b/src/Mod/TechDraw/Gui/TaskLineDecor.h index 76661ff2e7..99c5fb107c 100644 --- a/src/Mod/TechDraw/Gui/TaskLineDecor.h +++ b/src/Mod/TechDraw/Gui/TaskLineDecor.h @@ -23,6 +23,8 @@ #ifndef GUI_TASKVIEW_TASKLINEDECOR_H #define GUI_TASKVIEW_TASKLINEDECOR_H +#include + #include #include @@ -45,25 +47,25 @@ class TaskLineDecor : public QWidget public: TaskLineDecor(TechDraw::DrawViewPart* partFeat, std::vector edgeNames); - ~TaskLineDecor(); + ~TaskLineDecor() override; public: virtual bool accept(); virtual bool reject(); - bool apply(void) { return m_apply; } + bool apply() { return m_apply; } void apply(bool b) { m_apply = b; } protected Q_SLOTS: - void onStyleChanged(void); - void onColorChanged(void); - void onWeightChanged(void); - void onVisibleChanged(void); + void onStyleChanged(); + void onColorChanged(); + void onWeightChanged(); + void onVisibleChanged(); protected: - void changeEvent(QEvent *e); - void initUi(void); - void applyDecorations(void); - void getDefaults(void); + void changeEvent(QEvent *e) override; + void initUi(); + void applyDecorations(); + void getDefaults(); private: std::unique_ptr ui; @@ -83,29 +85,29 @@ class TaskRestoreLines : public QWidget public: TaskRestoreLines(TechDraw::DrawViewPart* partFeat, TechDrawGui::TaskLineDecor* parent); - ~TaskRestoreLines(); + ~TaskRestoreLines() override; public: virtual bool accept(); virtual bool reject(); protected Q_SLOTS: - void onAllPressed(void); - void onGeometryPressed(void); - void onCosmeticPressed(void); - void onCenterPressed(void); + void onAllPressed(); + void onGeometryPressed(); + void onCosmeticPressed(); + void onCenterPressed(); protected: - void changeEvent(QEvent *e); - void initUi(void); - int countInvisibleLines(void); - int countInvisibleGeoms(void); - int countInvisibleCosmetics(void); - int countInvisibleCenters(void); - void restoreInvisibleLines(void); - void restoreInvisibleGeoms(void); - void restoreInvisibleCosmetics(void); - void restoreInvisibleCenters(void); + void changeEvent(QEvent *e) override; + void initUi(); + int countInvisibleLines(); + int countInvisibleGeoms(); + int countInvisibleCosmetics(); + int countInvisibleCenters(); + void restoreInvisibleLines(); + void restoreInvisibleGeoms(); + void restoreInvisibleCosmetics(); + void restoreInvisibleCenters(); private: std::unique_ptr ui; @@ -121,20 +123,20 @@ class TaskDlgLineDecor : public Gui::TaskView::TaskDialog public: TaskDlgLineDecor(TechDraw::DrawViewPart* partFeat, std::vector edgeNames); - ~TaskDlgLineDecor(); + ~TaskDlgLineDecor() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } protected: diff --git a/src/Mod/TechDraw/Gui/TaskLinkDim.cpp b/src/Mod/TechDraw/Gui/TaskLinkDim.cpp index cab406b9fb..7cc34ac1ca 100644 --- a/src/Mod/TechDraw/Gui/TaskLinkDim.cpp +++ b/src/Mod/TechDraw/Gui/TaskLinkDim.cpp @@ -154,7 +154,7 @@ bool TaskLinkDim::dimReferencesSelection(const TechDraw::DrawViewDimension* dim) return false; } - if(refParts.size() == 0) { + if(refParts.empty()) { //shouldn't happen! } else if (refParts.size() == 1) { if ((refParts[0] == m_parts[0]) && diff --git a/src/Mod/TechDraw/Gui/TaskLinkDim.h b/src/Mod/TechDraw/Gui/TaskLinkDim.h index a329acc079..11c5221326 100644 --- a/src/Mod/TechDraw/Gui/TaskLinkDim.h +++ b/src/Mod/TechDraw/Gui/TaskLinkDim.h @@ -22,6 +22,8 @@ #ifndef GUI_TASKVIEW_TASKLINKDIM_H #define GUI_TASKVIEW_TASKLINKDIM_H + +#include #include #include @@ -46,7 +48,7 @@ class TaskLinkDim : public QWidget public: TaskLinkDim(std::vector parts,std::vector& subs, TechDraw::DrawPage* page); - ~TaskLinkDim(); + ~TaskLinkDim() override; public: bool accept(); @@ -56,7 +58,7 @@ protected Q_SLOTS: void onCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void loadAvailDims(); void updateDims(); void loadToTree(const TechDraw::DrawViewDimension* dim, const bool selected, Gui::Document* guiDoc); @@ -75,20 +77,20 @@ class TaskDlgLinkDim : public Gui::TaskView::TaskDialog public: TaskDlgLinkDim(std::vector parts,std::vector& subs, TechDraw::DrawPage* page); - ~TaskDlgLinkDim(); + ~TaskDlgLinkDim() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskProjGroup.cpp b/src/Mod/TechDraw/Gui/TaskProjGroup.cpp index 7b3c6e6085..8da0ecd39e 100644 --- a/src/Mod/TechDraw/Gui/TaskProjGroup.cpp +++ b/src/Mod/TechDraw/Gui/TaskProjGroup.cpp @@ -144,9 +144,8 @@ TaskProjGroup::~TaskProjGroup() void TaskProjGroup::saveGroupState() { // Base::Console().Message("TPG::saveGroupState()\n"); - if (multiView == nullptr) { + if (!multiView) return; - } m_saveSource = multiView->Source.getValues(); m_saveProjType = multiView->ProjectionType.getValueAsString(); @@ -160,8 +159,8 @@ void TaskProjGroup::saveGroupState() for( const auto it : multiView->Views.getValues() ) { auto view( dynamic_cast(it) ); - if (view != nullptr) { - m_saveViewNames.push_back(view->Type.getValueAsString()); + if (view) { + m_saveViewNames.emplace_back(view->Type.getValueAsString()); } } } @@ -170,9 +169,8 @@ void TaskProjGroup::saveGroupState() void TaskProjGroup::restoreGroupState() { Base::Console().Message("TPG::restoreGroupState()\n"); - if (multiView == nullptr) { + if (!multiView) return; - } multiView->ProjectionType.setValue(m_saveProjType.c_str()); multiView->ScaleType.setValue(m_saveScaleType.c_str()); @@ -194,7 +192,7 @@ void TaskProjGroup::viewToggled(bool toggle) bool changed = false; // Obtain name of checkbox QString viewName = sender()->objectName(); - int index = viewName.mid(7).toInt(); + int index = viewName.midRef(7).toInt(); const char *viewNameCStr = viewChkIndexToCStr(index); if ( toggle && !multiView->hasProjection( viewNameCStr ) ) { Gui::Command::doCommand(Gui::Command::Doc, @@ -214,7 +212,7 @@ void TaskProjGroup::viewToggled(bool toggle) wc.restoreCursor(); } -void TaskProjGroup::rotateButtonClicked(void) +void TaskProjGroup::rotateButtonClicked() { if ( multiView && ui ) { const QObject *clicked = sender(); @@ -266,7 +264,7 @@ void TaskProjGroup::scaleTypeChanged(int index) // Automatic Scale Type //block recompute multiView->ScaleType.setValue("Automatic"); - double autoScale = multiView->calculateAutomaticScale(); + double autoScale = multiView->autoScale(); multiView->Scale.setValue(autoScale); //unblock recompute @@ -297,7 +295,7 @@ void TaskProjGroup::AutoDistributeClicked(bool b) multiView->recomputeFeature(); } -void TaskProjGroup::spacingChanged(void) +void TaskProjGroup::spacingChanged() { if (blockUpdate) { return; @@ -441,7 +439,7 @@ const char * TaskProjGroup::viewChkIndexToCStr(int index) // First Angle: FBRight B FBL // Right F L Rear // FTRight T FTL - assert (multiView != nullptr); + assert (multiView); bool thirdAngle = multiView->usedProjectionType().isValue("Third Angle"); switch(index) { @@ -460,9 +458,8 @@ const char * TaskProjGroup::viewChkIndexToCStr(int index) } void TaskProjGroup::setupViewCheckboxes(bool addConnections) { - if ( multiView == nullptr ) { + if (!multiView) return; - } // There must be a better way to construct this list... QCheckBox * viewCheckboxes[] = { ui->chkView0, @@ -484,7 +481,7 @@ void TaskProjGroup::setupViewCheckboxes(bool addConnections) } const char *viewStr = viewChkIndexToCStr(i); - if ( viewStr != nullptr && multiView->hasProjection(viewStr) ) { + if (viewStr && multiView->hasProjection(viewStr)) { box->setCheckState(Qt::Checked); } else { box->setCheckState(Qt::Unchecked); @@ -501,9 +498,9 @@ void TaskProjGroup::setUiPrimary() QString TaskProjGroup::formatVector(Base::Vector3d v) { QString data = QString::fromLatin1("[%1 %2 %3]") - .arg(QLocale().toString(v.x, 'f', 2)) - .arg(QLocale().toString(v.y, 'f', 2)) - .arg(QLocale().toString(v.z, 'f', 2)); + .arg(QLocale().toString(v.x, 'f', 2), + QLocale().toString(v.y, 'f', 2), + QLocale().toString(v.z, 'f', 2)); return data; } diff --git a/src/Mod/TechDraw/Gui/TaskProjGroup.h b/src/Mod/TechDraw/Gui/TaskProjGroup.h index 3f8633a05c..1f8c0a439e 100644 --- a/src/Mod/TechDraw/Gui/TaskProjGroup.h +++ b/src/Mod/TechDraw/Gui/TaskProjGroup.h @@ -23,6 +23,10 @@ #ifndef GUI_TASKVIEW_TASKVIEWGROUP_H #define GUI_TASKVIEW_TASKVIEWGROUP_H + +#include + +#include #include @@ -47,7 +51,7 @@ class TaskProjGroup : public QWidget public: TaskProjGroup(TechDraw::DrawProjGroup* featView, bool mode); - ~TaskProjGroup(); + ~TaskProjGroup() override; public: virtual bool accept(); @@ -69,7 +73,7 @@ protected Q_SLOTS: void viewToggled(bool toggle); /// Requests appropriate rotation of our DrawProjGroup - void rotateButtonClicked(void); + void rotateButtonClicked(); // void onResetClicked(void); /* void projectionTypeChanged(int index);*/ @@ -77,11 +81,11 @@ protected Q_SLOTS: void scaleTypeChanged(int index); void AutoDistributeClicked(bool b); /// Updates item spacing - void spacingChanged(void); + void spacingChanged(); void scaleManuallyChanged(int i); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; /// Connects and updates state of view checkboxes to match the state of multiView /*! @@ -89,7 +93,7 @@ protected: * between checkboxes and viewToggled() */ void setupViewCheckboxes(bool addConnections = false); - void setUiPrimary(void); + void setUiPrimary(); void saveGroupState(); void restoreGroupState(); @@ -129,27 +133,27 @@ class TaskDlgProjGroup : public Gui::TaskView::TaskDialog public: TaskDlgProjGroup(TechDraw::DrawProjGroup* featView,bool mode); - ~TaskDlgProjGroup(); + ~TaskDlgProjGroup() override; const ViewProviderProjGroup * getViewProvider() const { return viewProvider; } TechDraw::DrawProjGroup * getMultiView() const { return multiView; } - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel; } - virtual void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void setCreateMode(bool b); diff --git a/src/Mod/TechDraw/Gui/TaskProjGroup.ui b/src/Mod/TechDraw/Gui/TaskProjGroup.ui index 60750a5cde..15850454f0 100644 --- a/src/Mod/TechDraw/Gui/TaskProjGroup.ui +++ b/src/Mod/TechDraw/Gui/TaskProjGroup.ui @@ -196,7 +196,7 @@ - + 0 0 @@ -302,7 +302,7 @@ - + Rotate down @@ -336,7 +336,7 @@ - + @@ -384,7 +384,7 @@ height: 24px; - + Top @@ -572,7 +572,7 @@ height: 24px; - + @@ -693,7 +693,7 @@ using the given X/Y Spacing - + 0 @@ -709,13 +709,13 @@ using the given X/Y Spacing Horizontal space between border of projections - + false - + 0.000000000000000 @@ -740,7 +740,7 @@ using the given X/Y Spacing - + 0 @@ -756,13 +756,13 @@ using the given X/Y Spacing Vertical space between border of projections - + false - + 0.000000000000000 diff --git a/src/Mod/TechDraw/Gui/TaskProjection.h b/src/Mod/TechDraw/Gui/TaskProjection.h index 57553aec93..72fe56eb0d 100644 --- a/src/Mod/TechDraw/Gui/TaskProjection.h +++ b/src/Mod/TechDraw/Gui/TaskProjection.h @@ -19,14 +19,17 @@ * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ -//this file originally part of TechDraw workbench +//this file originally part of Drawing workbench //migrated to TechDraw workbench 2022-01-26 by Wandererfan #ifndef TECHDRAWGUI_TASKDIALOG #define TECHDRAWGUI_TASKDIALOG + +#include #include + #include #include @@ -45,13 +48,13 @@ class TaskProjection : public QWidget public: TaskProjection(); - ~TaskProjection(); + ~TaskProjection() override; public: bool accept(); bool reject(); - virtual bool isAllowedAlterDocument(void) const + virtual bool isAllowedAlterDocument() const { return true; } private: @@ -66,19 +69,19 @@ class TaskDlgProjection : public Gui::TaskView::TaskDialog public: TaskDlgProjection(); - ~TaskDlgProjection(); + ~TaskDlgProjection() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if a button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} + void helpRequested() override { return;} void update(); diff --git a/src/Mod/TechDraw/Gui/TaskRichAnno.cpp b/src/Mod/TechDraw/Gui/TaskRichAnno.cpp index 8fd8a5a8bd..d73a03f3cc 100644 --- a/src/Mod/TechDraw/Gui/TaskRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/TaskRichAnno.cpp @@ -77,8 +77,6 @@ using namespace TechDrawGui; TaskRichAnno::TaskRichAnno(TechDrawGui::ViewProviderRichAnno* annoVP) : ui(new Ui_TaskRichAnno), blockUpdate(false), - m_mdi(nullptr), - m_view(nullptr), m_annoVP(annoVP), m_baseFeat(nullptr), m_basePage(nullptr), @@ -92,22 +90,21 @@ TaskRichAnno::TaskRichAnno(TechDrawGui::ViewProviderRichAnno* annoVP) : m_btnOK(nullptr), m_btnCancel(nullptr), m_textDialog(nullptr), - m_rte(nullptr), - m_haveMdi(false) + m_rte(nullptr) { //existence of annoVP is guaranteed by caller being ViewProviderRichAnno.setEdit m_annoFeat = m_annoVP->getFeature(); m_basePage = m_annoFeat->findParentPage(); - if ( m_basePage == nullptr ) { + if (!m_basePage) { Base::Console().Error("TaskRichAnno - bad parameters (2). Can not proceed.\n"); return; } //m_baseFeat can be null App::DocumentObject* obj = m_annoFeat->AnnoParent.getValue(); - if (obj != nullptr) { + if (obj) { if ( obj->isDerivedFrom(TechDraw::DrawView::getClassTypeId()) ) { m_baseFeat = static_cast(m_annoFeat->AnnoParent.getValue()); } @@ -115,21 +112,13 @@ TaskRichAnno::TaskRichAnno(TechDrawGui::ViewProviderRichAnno* annoVP) : Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_basePage->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* dvp = static_cast(vp); + m_vpp = static_cast(vp); - m_mdi = dvp->getMDIViewPage(); m_qgParent = nullptr; - m_haveMdi = true; - if (m_mdi != nullptr) { - m_scene = m_mdi->getQGSPage(); - if (m_baseFeat != nullptr) { - m_qgParent = m_scene->findQViewForDocObj(m_baseFeat); - } - } else { - m_haveMdi = false; + if (m_baseFeat) { + m_qgParent = m_vpp->getQGSPage()->findQViewForDocObj(m_baseFeat); } - ui->setupUi(this); m_title = QObject::tr("Rich text editor"); @@ -148,8 +137,6 @@ TaskRichAnno::TaskRichAnno(TechDraw::DrawView* baseFeat, TechDraw::DrawPage* page) : ui(new Ui_TaskRichAnno), blockUpdate(false), - m_mdi(nullptr), - m_view(nullptr), m_annoVP(nullptr), m_baseFeat(baseFeat), m_basePage(page), @@ -163,24 +150,18 @@ TaskRichAnno::TaskRichAnno(TechDraw::DrawView* baseFeat, m_btnOK(nullptr), m_btnCancel(nullptr), m_textDialog(nullptr), - m_rte(nullptr), - m_haveMdi(false) + m_rte(nullptr) { //existence of baseFeat and page guaranteed by CmdTechDrawRichTextAnnotation (CommandAnnotate.cpp) - Gui::Document* activeGui = Gui::Application::Instance->getDocument(m_basePage->getDocument()); Gui::ViewProvider* vp = activeGui->getViewProvider(m_basePage); - ViewProviderPage* dvp = static_cast(vp); + m_vpp = static_cast(vp); m_qgParent = nullptr; - m_haveMdi = true; - m_mdi = dvp->getMDIViewPage(); - if (m_mdi != nullptr) { - m_scene= m_mdi->getQGSPage(); - m_qgParent = m_scene->findQViewForDocObj(baseFeat); - } else { - m_haveMdi = false; + if (m_vpp->getQGSPage()) { + m_qgParent = m_vpp->getQGSPage()->findQViewForDocObj(baseFeat); } + ui->setupUi(this); m_title = QObject::tr("Rich text creator"); @@ -214,7 +195,7 @@ void TaskRichAnno::setUiPrimary() enableVPUi(false); setWindowTitle(m_title); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { std::string baseName = m_baseFeat->getNameInDocument(); ui->leBaseView->setText(Base::Tools::fromStdString(baseName)); } @@ -253,10 +234,10 @@ void TaskRichAnno::setUiEdit() setWindowTitle(m_title); enableTextUi(true); - if (m_annoFeat != nullptr) { + if (m_annoFeat) { std::string baseName("None"); App::DocumentObject* docObj = m_annoFeat->AnnoParent.getValue(); - if (docObj != nullptr) { + if (docObj) { baseName = docObj->getNameInDocument(); } ui->leBaseView->setText(Base::Tools::fromStdString(baseName)); @@ -265,7 +246,7 @@ void TaskRichAnno::setUiEdit() ui->cbShowFrame->setChecked(m_annoFeat->ShowFrame.getValue()); } - if (m_annoVP != nullptr) { + if (m_annoVP) { ui->cpFrameColor->setColor(m_annoVP->LineColor.getValue().asValue()); ui->dsbWidth->setValue(m_annoVP->LineWidth.getValue()); ui->cFrameStyle->setCurrentIndex(m_annoVP->LineStyle.getValue()); @@ -295,8 +276,8 @@ void TaskRichAnno::onEditorClicked(bool b) connect(m_rte, SIGNAL(saveText(QString)), this, SLOT(onSaveAndExit(QString))); - connect(m_rte, SIGNAL(editorFinished(void)), - this, SLOT(onEditorExit(void))); + connect(m_rte, SIGNAL(editorFinished()), + this, SLOT(onEditorExit())); m_textDialog->show(); } @@ -310,7 +291,7 @@ void TaskRichAnno::onSaveAndExit(QString qs) m_rte = nullptr; } -void TaskRichAnno::onEditorExit(void) +void TaskRichAnno::onEditorExit() { m_textDialog->reject(); m_textDialog = nullptr; @@ -319,14 +300,10 @@ void TaskRichAnno::onEditorExit(void) double TaskRichAnno::prefWeight() const { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double weight = lg->getWeight("Graphic"); - delete lg; //Coverity CID 174670 - return weight; + return TechDraw::LineGroup::getDefaultWidth("Graphic"); } -App::Color TaskRichAnno::prefLineColor(void) +App::Color TaskRichAnno::prefLineColor() { return PreferencesGui::leaderColor(); } @@ -347,33 +324,33 @@ void TaskRichAnno::createAnnoFeature() Command::doCommand(Command::Doc,"App.activeDocument().%s.addView(App.activeDocument().%s)", PageName.c_str(),annoName.c_str()); - if (m_baseFeat != nullptr) { + if (m_baseFeat) { Command::doCommand(Command::Doc,"App.activeDocument().%s.AnnoParent = App.activeDocument().%s", annoName.c_str(),m_baseFeat->getNameInDocument()); } App::DocumentObject* obj = m_basePage->getDocument()->getObject(annoName.c_str()); - if (obj == nullptr) { + if (!obj) { throw Base::RuntimeError("TaskRichAnno - new RichAnno object not found"); } if (obj->isDerivedFrom(TechDraw::DrawRichAnno::getClassTypeId())) { m_annoFeat = static_cast(obj); commonFeatureUpdate(); - if (m_haveMdi) { + if (m_baseFeat != nullptr) { QPointF qTemp = calcTextStartPos(m_annoFeat->getScale()); Base::Vector3d vTemp(qTemp.x(), qTemp.y()); m_annoFeat->X.setValue(Rez::appX(vTemp.x)); m_annoFeat->Y.setValue(Rez::appX(vTemp.y)); } else { - //if we don't have a mdi, we can't calculate start position, so just put it mid-page + //if we don't have a base featrue, we can't calculate start position, so just put it mid-page m_annoFeat->X.setValue(m_basePage->getPageWidth()/2.0); m_annoFeat->Y.setValue(m_basePage->getPageHeight()/2.0); } } - if (m_annoFeat != nullptr) { + if (m_annoFeat) { Gui::ViewProvider* vp = QGIView::getViewProvider(m_annoFeat); auto annoVP = dynamic_cast(vp); - if (annoVP != nullptr) { + if (annoVP) { App::Color ac; ac.setValue(ui->cpFrameColor->color()); annoVP->LineColor.setValue(ac); @@ -382,17 +359,17 @@ void TaskRichAnno::createAnnoFeature() } } - Gui::Command::updateActive(); Gui::Command::commitCommand(); + Gui::Command::updateActive(); - //trigger collectChildren in tree - if (m_baseFeat != nullptr) { + //trigger claimChildren in tree + if (m_baseFeat) { m_baseFeat->touch(); } m_basePage->touch(); - if (m_annoFeat != nullptr) { + if (m_annoFeat) { m_annoFeat->requestPaint(); } } @@ -409,10 +386,10 @@ void TaskRichAnno::updateAnnoFeature() m_annoVP->LineStyle.setValue(ui->cFrameStyle->currentIndex()); Gui::Command::commitCommand(); - m_annoFeat->requestPaint(); + Gui::Command::updateActive(); } -void TaskRichAnno::commonFeatureUpdate(void) +void TaskRichAnno::commonFeatureUpdate() { // Base::Console().Message("TRA::commonFeatureUpdate()\n"); m_annoFeat->setPosition(Rez::appX(m_attachPoint.x),Rez::appX(- m_attachPoint.y), true); @@ -421,10 +398,10 @@ void TaskRichAnno::commonFeatureUpdate(void) m_annoFeat->ShowFrame.setValue(ui->cbShowFrame->isChecked()); } -void TaskRichAnno::removeFeature(void) +void TaskRichAnno::removeFeature() { // Base::Console().Message("TRA::removeFeature()\n"); - if (m_annoFeat == nullptr) + if (!m_annoFeat) return; if (m_createMode) { @@ -454,6 +431,7 @@ void TaskRichAnno::removeFeature(void) //guess at the size of the text block. QPointF TaskRichAnno::calcTextStartPos(double scale) { + Q_UNUSED(scale) // Base::Console().Message("TRA::calcTextStartPos(%.3f)\n", scale); double textWidth = 100.0; double textHeight = 20.0; @@ -467,7 +445,7 @@ QPointF TaskRichAnno::calcTextStartPos(double scale) } std::vector points; - if (m_baseFeat != nullptr) { + if (m_baseFeat) { if (m_baseFeat->isDerivedFrom(TechDraw::DrawLeaderLine::getClassTypeId())) { TechDraw::DrawLeaderLine* dll = static_cast(m_baseFeat); points = dll->WayPoints.getValues(); @@ -477,7 +455,7 @@ QPointF TaskRichAnno::calcTextStartPos(double scale) } } else { // Base::Console().Message("TRA::calcStartPos - no m_baseFeat\n"); - if (m_basePage != nullptr) { + 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); @@ -489,9 +467,7 @@ QPointF TaskRichAnno::calcTextStartPos(double scale) if (!points.empty()) { QPointF lastPoint(points.back().x, points.back().y); QPointF firstPoint(points.front().x, points.front().y); - QPointF lastOffset = lastPoint; - lastPoint = m_qgParent->mapFromScene(lastPoint) * scale; - firstPoint = m_qgParent->mapFromScene(firstPoint) * scale; + QPointF lastOffset = lastPoint - firstPoint; if (lastPoint.x() < firstPoint.x()) { //last is left of first tPosX = lastOffset.x() - horizGap - textWidth; //left of last @@ -537,7 +513,9 @@ bool TaskRichAnno::accept() } else { updateAnnoFeature(); } -// m_mdi->setContextMenuPolicy(m_saveContextPolicy); + + m_annoFeat->requestPaint(); + Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); return true; @@ -551,13 +529,12 @@ bool TaskRichAnno::reject() return false; } - if (m_basePage != nullptr) { + if (m_basePage) { Gui::Document* doc = Gui::Application::Instance->getDocument(m_basePage->getDocument()); if (!doc) { return false; } - if (getCreateMode() && - (m_annoFeat != nullptr) ) { + if (getCreateMode() && m_annoFeat) { removeFeature(); } } diff --git a/src/Mod/TechDraw/Gui/TaskRichAnno.h b/src/Mod/TechDraw/Gui/TaskRichAnno.h index 2936ff0ab5..06a42a2125 100644 --- a/src/Mod/TechDraw/Gui/TaskRichAnno.h +++ b/src/Mod/TechDraw/Gui/TaskRichAnno.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKRICHANNO_H #define TECHDRAWGUI_TASKRICHANNO_H +#include + #include #include #include @@ -41,14 +43,13 @@ class DrawRichAnno; namespace TechDrawGui { -class QGSPage; -class QGVPage; class QGIView; class QGIPrimPath; class MDIViewPage; class QGMText; class QGIRichAnno; class ViewProviderRichAnno; +class ViewProviderPage; class TaskRichAnno : public QWidget { @@ -57,8 +58,8 @@ class TaskRichAnno : public QWidget public: TaskRichAnno(TechDraw::DrawView* baseFeat, TechDraw::DrawPage* page); - TaskRichAnno(TechDrawGui::ViewProviderRichAnno* leadVP); - ~TaskRichAnno(); + explicit TaskRichAnno(TechDrawGui::ViewProviderRichAnno* leadVP); + ~TaskRichAnno() override; public Q_SLOTS: void onEditorClicked(bool b); @@ -68,7 +69,7 @@ public: virtual bool accept(); virtual bool reject(); virtual void setCreateMode(bool b) { m_createMode = b; } - virtual bool getCreateMode(void) { return m_createMode; } + virtual bool getCreateMode() { return m_createMode; } void updateTask(); void saveButtons(QPushButton* btnOK, QPushButton* btnCancel); @@ -77,33 +78,31 @@ public: protected Q_SLOTS: void onSaveAndExit(QString); - void onEditorExit(void); + void onEditorExit(); protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; - void createAnnoFeature(void); - void updateAnnoFeature(void); - void commonFeatureUpdate(void); - void removeFeature(void); + void createAnnoFeature(); + void updateAnnoFeature(); + void commonFeatureUpdate(); + void removeFeature(); QPointF calcTextStartPos(double scale); void blockButtons(bool b); - void setUiPrimary(void); - void setUiEdit(void); + void setUiPrimary(); + void setUiEdit(); void enableTextUi(bool b); void enableVPUi(bool b); double prefWeight() const; - App::Color prefLineColor(void); + App::Color prefLineColor(); private: std::unique_ptr ui; bool blockUpdate; - MDIViewPage* m_mdi; - QGSPage* m_scene; - QGVPage* m_view; + ViewProviderPage* m_vpp; ViewProviderRichAnno* m_annoVP; TechDraw::DrawView* m_baseFeat; TechDraw::DrawPage* m_basePage; @@ -126,7 +125,6 @@ private: QDialog* m_textDialog; MRichTextEdit* m_rte; QString m_title; - bool m_haveMdi; }; class TaskDlgRichAnno : public Gui::TaskView::TaskDialog @@ -136,25 +134,25 @@ class TaskDlgRichAnno : public Gui::TaskView::TaskDialog public: TaskDlgRichAnno(TechDraw::DrawView* baseFeat, TechDraw::DrawPage* page); - TaskDlgRichAnno(TechDrawGui::ViewProviderRichAnno* leadVP); - ~TaskDlgRichAnno(); + explicit TaskDlgRichAnno(TechDrawGui::ViewProviderRichAnno* leadVP); + ~TaskDlgRichAnno() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TaskSectionView.cpp b/src/Mod/TechDraw/Gui/TaskSectionView.cpp index 19bfa8080a..cd06546cbc 100644 --- a/src/Mod/TechDraw/Gui/TaskSectionView.cpp +++ b/src/Mod/TechDraw/Gui/TaskSectionView.cpp @@ -24,12 +24,12 @@ #ifndef _PreComp_ #include -#endif // #ifndef _PreComp_ - #include #include #include #include +#endif // #ifndef _PreComp_ + #include #include @@ -76,7 +76,6 @@ TaskSectionView::TaskSectionView(TechDraw::DrawViewPart* base) : m_base(base), m_section(nullptr), m_saveScale(1.0), - m_dirName(""), m_doc(nullptr), m_createMode(true), m_saved(false), @@ -118,10 +117,8 @@ TaskSectionView::TaskSectionView(TechDraw::DrawViewSection* section) : m_sectionName = m_section->getNameInDocument(); App::DocumentObject* newObj = m_section->BaseView.getValue(); m_base = dynamic_cast(newObj); - if ( (newObj == nullptr) || - (m_base == nullptr) ) { + if (!newObj || !m_base) throw Base::RuntimeError("TaskSectionView - BaseView not found"); - } m_saveBaseName = m_base->getNameInDocument(); m_savePageName = m_base->findParentPage()->getNameInDocument(); @@ -217,9 +214,8 @@ void TaskSectionView::setUiEdit() void TaskSectionView::saveSectionState() { // Base::Console().Message("TSV::saveSectionState()\n"); - if (m_section == nullptr) { + if (!m_section) return; - } m_saveSymbol = m_section->SectionSymbol.getValue(); m_saveScale = m_section->getScale(); @@ -235,9 +231,8 @@ void TaskSectionView::saveSectionState() void TaskSectionView::restoreSectionState() { // Base::Console().Message("TSV::restoreSectionState()\n"); - if (m_section == nullptr) { + if (!m_section) return; - } m_section->SectionSymbol.setValue(m_saveSymbol); m_section->Scale.setValue(m_saveScale); @@ -355,7 +350,7 @@ void TaskSectionView::enableAll(bool b) } //****************************************************************************** -bool TaskSectionView::apply(void) +bool TaskSectionView::apply() { // Base::Console().Message("TSV::apply() - m_dirName: %s\n", m_dirName.c_str()); if (m_dirName.empty()) { @@ -364,11 +359,10 @@ bool TaskSectionView::apply(void) Base::Console().Error((msg + "\n").c_str()); return false; } - if (m_section == nullptr) { //didn't create the feature yet + if (!m_section) //didn't create the feature yet //this can't happen as applyQuick has to be called by the direction //setting process return false; - } checkAll(false); applyQuick(m_dirName); @@ -379,9 +373,8 @@ void TaskSectionView::applyQuick(std::string dir) { // Base::Console().Message("TSV::applyQuick(%s)\n", dir.c_str()); m_dirName = dir; - if (m_section == nullptr) { + if (!m_section) createSectionView(); - } if (!isSectionValid()) { failNoObject(m_sectionName); @@ -392,12 +385,11 @@ void TaskSectionView::applyQuick(std::string dir) enableAll(true); m_section->recomputeFeature(); - if (isBaseValid()) { + if (isBaseValid()) m_base->requestPaint(); - } } -void TaskSectionView::applyAligned(void) +void TaskSectionView::applyAligned() { Base::Console().Message("TSV::applyAligned() - not implemented yet\n"); // Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Apply Aligned")); @@ -408,7 +400,7 @@ void TaskSectionView::applyAligned(void) //********************************************************************* //pointer to created view is not returned, but stored in m_section -void TaskSectionView::createSectionView(void) +void TaskSectionView::createSectionView() { // Base::Console().Message("TSV::createSectionView()\n"); if (!isBaseValid()) { @@ -420,7 +412,7 @@ void TaskSectionView::createSectionView(void) std::string baseName = m_base->getNameInDocument(); Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Create SectionView")); - if (m_section == nullptr) { + if (!m_section) { m_sectionName = m_base->getDocument()->getUniqueObjectName("SectionView"); std::string sectionType = "TechDraw::DrawViewSection"; @@ -447,17 +439,15 @@ void TaskSectionView::createSectionView(void) App::DocumentObject* newObj = m_base->getDocument()->getObject(m_sectionName.c_str()); m_section = dynamic_cast(newObj); - if ( (newObj == nullptr) || - (m_section == nullptr) ) { + if (!newObj || !m_section) throw Base::RuntimeError("TaskSectionView - new section object not found"); - } } Gui::Command::commitCommand(); return; } -void TaskSectionView::updateSectionView(void) +void TaskSectionView::updateSectionView() { // Base::Console().Message("TSV::updateSectionView() - m_sectionName: %s\n", m_sectionName.c_str()); if (!isSectionValid()) { @@ -466,7 +456,7 @@ void TaskSectionView::updateSectionView(void) } Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Edit SectionView")); - if (m_section != nullptr) { + if (m_section) { Command::doCommand(Command::Doc,"App.ActiveDocument.%s.SectionDirection = '%s'", m_sectionName.c_str(),m_dirName.c_str()); Command::doCommand(Command::Doc, @@ -507,30 +497,26 @@ void TaskSectionView::failNoObject(std::string objectName) m_abort = true; } -bool TaskSectionView::isBaseValid(void) +bool TaskSectionView::isBaseValid() { - if (m_base == nullptr) { + if (!m_base) return false; - } App::DocumentObject* baseObj = m_doc->getObject(m_saveBaseName.c_str()); - if (baseObj == nullptr) { + if (!baseObj) return false; - } return true; } -bool TaskSectionView::isSectionValid(void) +bool TaskSectionView::isSectionValid() { - if (m_section == nullptr) { + if (!m_section) return false; - } App::DocumentObject* sectionObj = m_doc->getObject(m_sectionName.c_str()); - if (sectionObj == nullptr) { + if (!sectionObj) return false; - } return true; } @@ -552,7 +538,7 @@ bool TaskSectionView::accept() bool TaskSectionView::reject() { // Base::Console().Message("TSV::reject()\n"); - if (m_section == nullptr) { //no section created, nothing to undo + if (!m_section) { //no section created, nothing to undo Gui::Command::doCommand(Gui::Command::Gui,"Gui.ActiveDocument.resetEdit()"); return false; } diff --git a/src/Mod/TechDraw/Gui/TaskSectionView.h b/src/Mod/TechDraw/Gui/TaskSectionView.h index 03f013c60a..623fb1bfb7 100644 --- a/src/Mod/TechDraw/Gui/TaskSectionView.h +++ b/src/Mod/TechDraw/Gui/TaskSectionView.h @@ -23,6 +23,8 @@ #ifndef GUI_TASKVIEW_TASKSECTIONVIEW_H #define GUI_TASKVIEW_TASKSECTIONVIEW_H +#include + #include #include @@ -42,9 +44,9 @@ class TaskSectionView : public QWidget Q_OBJECT public: - TaskSectionView(TechDraw::DrawViewPart* base); - TaskSectionView(TechDraw::DrawViewSection* section); - ~TaskSectionView(); + explicit TaskSectionView(TechDraw::DrawViewPart* base); + explicit TaskSectionView(TechDraw::DrawViewSection* section); + ~TaskSectionView() override; public: virtual bool accept(); @@ -64,16 +66,16 @@ protected Q_SLOTS: protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; void saveSectionState(); void restoreSectionState(); - bool apply(void); + bool apply(); void applyQuick(std::string dir); - void applyAligned(void); + void applyAligned(); - void createSectionView(void); - void updateSectionView(void); + void createSectionView(); + void updateSectionView(); void setUiPrimary(); void setUiEdit(); @@ -82,8 +84,8 @@ protected: void enableAll(bool b); void failNoObject(std::string objName); - bool isBaseValid(void); - bool isSectionValid(void); + bool isBaseValid(); + bool isSectionValid(); private: std::unique_ptr ui; @@ -122,31 +124,31 @@ class TaskDlgSectionView : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgSectionView(TechDraw::DrawViewPart* base); - TaskDlgSectionView(TechDraw::DrawViewSection* section); - ~TaskDlgSectionView(); + explicit TaskDlgSectionView(TechDraw::DrawViewPart* base); + explicit TaskDlgSectionView(TechDraw::DrawViewSection* section); + ~TaskDlgSectionView() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role /* virtual void clicked(int);*/ /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} + void helpRequested() override { return;} - virtual QDialogButtonBox::StandardButtons getStandardButtons() const + QDialogButtonBox::StandardButtons getStandardButtons() const override { return QDialogButtonBox::Ok | QDialogButtonBox::Cancel; } /* virtual void modifyStandardButtons(QDialogButtonBox* box);*/ void update(); - virtual bool isAllowedAlterSelection(void) const + bool isAllowedAlterSelection() const override { return false; } - virtual bool isAllowedAlterDocument(void) const + bool isAllowedAlterDocument() const override { return false; } protected: diff --git a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp index 8d4a01aa5e..6a354d84d2 100644 --- a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp +++ b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.cpp @@ -97,7 +97,7 @@ enum class EdgeColor { // managing global line attributes //=========================================================================== -lineAttributes::lineAttributes(void) +lineAttributes::lineAttributes() { style = int(EdgeStyle::dotted); width = int(EdgeWidth::middle); @@ -114,7 +114,7 @@ void lineAttributes::setWidth(int newWidth) width = newWidth; } -float lineAttributes::getWidthValue(void) +float lineAttributes::getWidthValue() { switch(EdgeWidth(width)) { case EdgeWidth::small: @@ -136,7 +136,7 @@ void lineAttributes::setColor(int newColor) color = newColor; } -App::Color lineAttributes::getColorValue(void) +App::Color lineAttributes::getColorValue() { switch (EdgeColor(color)) { case EdgeColor::black: @@ -164,7 +164,7 @@ App::Color lineAttributes::getColorValue(void) // managing global dimension attributes //=========================================================================== -dimAttributes::dimAttributes(void) +dimAttributes::dimAttributes() { cascadeSpacing = 7.0; lineStretch = 2.0; diff --git a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h index 54e23c5f6d..c8c7362402 100644 --- a/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h +++ b/src/Mod/TechDraw/Gui/TaskSelectLineAttributes.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKSELECTLINEATTRIBUTES_H #define TECHDRAWGUI_TASKSELECTLINEATTRIBUTES_H +#include + #include #include @@ -33,11 +35,11 @@ class dimAttributes { public: - dimAttributes(void); + dimAttributes(); void setCascadeSpacing(double); - double getCascadeSpacing(void) {return cascadeSpacing;} + double getCascadeSpacing() {return cascadeSpacing;} void setLineStretch(double); - double getLineStretch(void) {return lineStretch;} + double getLineStretch() {return lineStretch;} }; // class dimAttributes @@ -74,15 +76,15 @@ class lineAttributes { public: - lineAttributes(void); + lineAttributes(); void setStyle(int); - int getStyle(void) const {return style;} + int getStyle() const {return style;} void setWidth(int); - int getWidth(void) const {return width;} - float getWidthValue(void); + int getWidth() const {return width;} + float getWidthValue(); void setColor(int); - int getColor(void) const {return color;} - App::Color getColorValue(void); + int getColor() const {return color;} + App::Color getColorValue(); }; // class lineAttributes @@ -91,8 +93,8 @@ class TaskSelectLineAttributes : public QWidget Q_OBJECT public: - TaskSelectLineAttributes(lineAttributes * ptActiveAttributes); - ~TaskSelectLineAttributes(); + explicit TaskSelectLineAttributes(lineAttributes * ptActiveAttributes); + ~TaskSelectLineAttributes() override; public Q_SLOTS: @@ -104,9 +106,9 @@ public: protected Q_SLOTS: protected: - void changeEvent(QEvent *e); + void changeEvent(QEvent *e) override; - void setUiEdit(void); + void setUiEdit(); private: lineAttributes* activeAttributes; @@ -118,21 +120,21 @@ class TaskDlgSelectLineAttributes : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgSelectLineAttributes(lineAttributes * ptActiveAttributes); - ~TaskDlgSelectLineAttributes(); + explicit TaskDlgSelectLineAttributes(lineAttributes * ptActiveAttributes); + ~TaskDlgSelectLineAttributes() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); diff --git a/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.cpp b/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.cpp new file mode 100644 index 0000000000..78d8cdb0cc --- /dev/null +++ b/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.cpp @@ -0,0 +1,386 @@ +/*************************************************************************** + * Copyright (c) 2022 edi * + * * + * 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 +#include +#endif + +#include +#include +#include +#include + +#include +#include + +#include "TaskSurfaceFinishSymbols.h" + +using namespace Gui; +using namespace TechDraw; +using namespace TechDrawGui; + +SvgString::SvgString(int width, int height) +{ + svgStream << "\n"; + svgStream << "\n"; +} + +void SvgString::addLine(int x1, int y1, int x2, int y2) +{ + svgStream << "\n"; +} + +void SvgString::addCircle(int xCenter, int yCenter, int radius) +{ + svgStream << "\n"; +} + +void SvgString::addText(int xText, int yText, std::string text) +{ + svgStream << "" << text << "\n"; +} + +std::string SvgString::finish() +{ + svgStream << "\n"; + return svgStream.str(); +} + +//=========================================================================== +// TaskSurfaceFinishSymbols +//=========================================================================== + +TaskSurfaceFinishSymbols::TaskSurfaceFinishSymbols(TechDraw::DrawViewPart* view) : + selectedView(view), + ui(new Ui_TaskSurfaceFinishSymbols) +{ + raValues = {"RA50","RA25","RA12,5","RA6,3", + "RA3,2","RA1,6","RA0,8","RA0,4", + "RA0,2","RA0,1","RA0,05","RA0,025"}; + laySymbols = {"","=","⟂","X","M","C","R"}; + roughGrades = {"","N1","N2","N3","N4","N5", + "N6","N7","N8","N9","N10","N11"}; + ui->setupUi(this); + setUiEdit(); +} + +QPixmap TaskSurfaceFinishSymbols::baseSymbol(symbolType type) +// return QPixmap showing a base symbol +{ + QImage img (50,64,QImage::Format_ARGB32_Premultiplied); + img.fill(QColor(240,240,240)); + QPainter painter; + painter.begin(&img); + painter.setPen(QPen(Qt::black, 2, Qt::SolidLine, + Qt::RoundCap, Qt::RoundJoin)); + painter.setRenderHints(QPainter::Antialiasing | + QPainter::SmoothPixmapTransform | + QPainter::TextAntialiasing); + painter.drawLine(QLine(0,44,12,64)); + painter.drawLine(QLine(12,64,42,14)); + if (type == removeProhibit || type == removeProhibitAll) + painter.drawEllipse(QPoint(12,46),9,9); + if (type == removeRequired || type == removeRequiredAll) + painter.drawLine(QLine(0,44,24,44)); + if (type > removeRequired) + painter.drawEllipse(QPoint(42,14),6,6); + painter.end(); + return QPixmap::fromImage(img); +} + +std::string TaskSurfaceFinishSymbols::completeSymbol() +// return string showing the complete symbol +{ + SvgString symbol(150,64); + symbol.addLine(0,44,12,64); + symbol.addLine(12,64,42,14); + int moveLeft(0), maxTextLength(0); + if (activeIcon == removeProhibit || activeIcon == removeProhibitAll) + symbol.addCircle(12,46,9); + if (activeIcon == removeRequired || activeIcon == removeRequiredAll) + symbol.addLine(0,44,24,44); + if (activeIcon > removeRequired) + { + symbol.addCircle(42,14,6); + moveLeft = 5 ; + } + std::string methodText = leMethod->text().toStdString(); + symbol.addText(42+moveLeft,11,methodText); + int methodTextLength = methodText.length(); + if (isISO) + { + std::string raText = cbRA->itemText(cbRA->currentIndex()).toStdString(); + symbol.addText(42+moveLeft,30,raText); + int raTextLength = raText.length(); + maxTextLength = std::max(methodTextLength,raTextLength)*9.25+moveLeft; + } + else + { + std::string sampleText = leSamLength->text().toStdString(); + symbol.addText(42+moveLeft,30,sampleText); + int sampleTextLength = sampleText.length(); + maxTextLength = std::max(methodTextLength,sampleTextLength)*9.25+moveLeft; + std::string minRoughtText = cbMinRought->itemText(cbMinRought->currentIndex()).toStdString(); + symbol.addText(-10,35,minRoughtText); + std::string maxRoughtText = cbMaxRought->itemText(cbMaxRought->currentIndex()).toStdString(); + symbol.addText(-10,20,maxRoughtText); + } + symbol.addLine(42,14,42+maxTextLength,14); + symbol.addText(20,60,cbLay->itemText(cbLay->currentIndex()).toStdString()); + symbol.addText(-25,60,leAddition->text().toStdString()); + std::string symbolAsString = symbol.finish(); + return symbolAsString; +} + +TaskSurfaceFinishSymbols::~TaskSurfaceFinishSymbols() +{ + +} + +void TaskSurfaceFinishSymbols::updateTask() +{ +// blockUpdate = true; + +// blockUpdate = false; +} + + +void TaskSurfaceFinishSymbols::changeEvent(QEvent *e) +{ + if (e->type() == QEvent::LanguageChange) { + ui->retranslateUi(this); + } +} + +void TaskSurfaceFinishSymbols::setUiEdit() +// arrange widget at tool start +{ + setWindowTitle(tr("Surface Finish Symbols")); + // create icon pixmaps of QPushButtons + ui->pbIcon01->setIcon(baseSymbol(anyMethod)); + ui->pbIcon02->setIcon(baseSymbol(removeProhibit)); + ui->pbIcon03->setIcon(baseSymbol(removeRequired)); + ui->pbIcon04->setIcon(baseSymbol(anyMethodAll)); + ui->pbIcon05->setIcon(baseSymbol(removeProhibitAll)); + ui->pbIcon06->setIcon(baseSymbol(removeRequiredAll)); + activeIcon = anyMethod ; + isISO = true; + + // Create scene and all items used in the scene + symbolScene = new(QGraphicsScene); + ui->graphicsView->setScene(symbolScene); + // QLineEdit showing method + leMethod = new(QLineEdit); + leMethod->resize(90,20); + leMethod->setToolTip(QObject::tr("Method")); + QGraphicsProxyWidget* proxyMethod = symbolScene->addWidget(leMethod); + proxyMethod->setPos(2,-142); + // QLineEdit showing addition + leAddition = new(QLineEdit); + leAddition->resize(25,20); + leAddition->setToolTip(QObject::tr("Addition")); + QGraphicsProxyWidget* proxyAddition = symbolScene->addWidget(leAddition); + proxyAddition->setPos(-80,-85); + proxyAddition->setZValue(-2); + // QComboBox showing RA values + cbRA = new(QComboBox); + cbRA->resize(90,20); + for (const std::string& nextValue : raValues) + cbRA->addItem(QString::fromStdString(nextValue)); + cbRA->setToolTip(QObject::tr("Average roughness")); + proxyRA = symbolScene->addWidget(cbRA); + proxyRA->setPos(2,-113); + // QLineEdit showing sampling length value + leSamLength = new(QLineEdit); + leSamLength->resize(90,20); + leSamLength->setToolTip(QObject::tr("Roughness sampling length")); + proxySamLength = symbolScene->addWidget(leSamLength); + proxySamLength->setPos(2,-113); + proxySamLength->hide(); + // QComboBox showing lay symbol + cbLay = new(QComboBox); + cbLay->resize(40,20); + for (const std::string& nextLay : laySymbols) + cbLay->addItem(QString::fromStdString(nextLay)); + cbLay->setToolTip(QObject::tr("Lay symbol")); + QGraphicsProxyWidget* proxyLay = symbolScene->addWidget(cbLay); + proxyLay->setPos(-23,-85); + // QComboBox showing minimal roughness grade + cbMinRought = new(QComboBox); + cbMinRought->resize(55,20); + for (const std::string& nextGrade : roughGrades) + cbMinRought->addItem(QString::fromStdString(nextGrade)); + cbMinRought->setToolTip(QObject::tr("Minimum roughness grade number")); + proxyMinRough = symbolScene->addWidget(cbMinRought); + proxyMinRough->setPos(-80,-118); + proxyMinRough-> setZValue(1); + proxyMinRough->hide(); + // QComboBox showing maximal roughness grade + cbMaxRought = new(QComboBox); + cbMaxRought->resize(55,20); + for (const std::string& nextGrade : roughGrades) + cbMaxRought->addItem(QString::fromStdString(nextGrade)); + cbMaxRought->setToolTip(QObject::tr("Maximum roughness grade number")); + proxyMaxRough = symbolScene->addWidget(cbMaxRought); + proxyMaxRough->setPos(-80,-143); + proxyMaxRough->setZValue(1); + proxyMaxRough->hide(); + // add horizontal line + symbolScene->addLine(QLine(-8,-116,90,-116), + QPen(Qt::black,2,Qt::SolidLine, + Qt::RoundCap, Qt::RoundJoin)); + // add pixmap of the surface finish symbol + QIcon symbolIcon = ui->pbIcon01->icon(); + QGraphicsPixmapItem* pixmapItem = new(QGraphicsPixmapItem); + pixmapItem->setPixmap(symbolIcon.pixmap(50,64)); + pixmapItem->setPos(-50,-130); + pixmapItem->setZValue(-1); + symbolScene->addItem(pixmapItem); + + connect(ui->pbIcon01, SIGNAL(clicked()), this, SLOT(onIconChanged())); + connect(ui->pbIcon02, SIGNAL(clicked()), this, SLOT(onIconChanged())); + connect(ui->pbIcon03, SIGNAL(clicked()), this, SLOT(onIconChanged())); + connect(ui->pbIcon04, SIGNAL(clicked()), this, SLOT(onIconChanged())); + connect(ui->pbIcon05, SIGNAL(clicked()), this, SLOT(onIconChanged())); + connect(ui->pbIcon06, SIGNAL(clicked()), this, SLOT(onIconChanged())); + connect(ui->rbISO, SIGNAL(clicked()), this, SLOT(onISO())); + connect(ui->rbASME, SIGNAL(clicked()), this, SLOT(onASME())); +} + +void TaskSurfaceFinishSymbols::onIconChanged() +// Slot: change icon of surface finish symbol +{ + QObject* senderObj(this->sender()); + QPushButton* pressedButton = qobject_cast(senderObj); + if (!pressedButton) { + return; + } + + if (ui->pbIcon01 == pressedButton) activeIcon = anyMethod; + if (ui->pbIcon02 == pressedButton) activeIcon = removeProhibit; + if (ui->pbIcon03 == pressedButton) activeIcon = removeRequired; + if (ui->pbIcon04 == pressedButton) activeIcon = anyMethodAll; + if (ui->pbIcon05 == pressedButton) activeIcon = removeProhibitAll; + if (ui->pbIcon06 == pressedButton) activeIcon = removeRequiredAll; + + QIcon symbolIcon = pressedButton->icon(); + QGraphicsPixmapItem* pixmapItem = new(QGraphicsPixmapItem); + pixmapItem->setPixmap(symbolIcon.pixmap(50,64)); + pixmapItem->setPos(-50,-130); + pixmapItem->setZValue(-1); + symbolScene->addItem(pixmapItem); +} + +void TaskSurfaceFinishSymbols::onISO() +// Slot: show ISO template in scene +{ + isISO = true; + proxySamLength->hide(); + proxyMinRough->hide(); + proxyMaxRough->hide(); + proxyRA->show(); +} + +void TaskSurfaceFinishSymbols::onASME() +// Slot: show ASME template in scene +{ + isISO = false; + proxySamLength->show(); + proxyMinRough->show(); + proxyMaxRough->show(); + proxyRA->hide(); +} + +bool TaskSurfaceFinishSymbols::accept() +// Slot: dialog finished using OK +{ + Gui::Command::openCommand(QT_TRANSLATE_NOOP("Command", "Surface Finish Symbols")); + App::Document *doc = Application::Instance->activeDocument()->getDocument(); + App::DocumentObject *docObject = doc->addObject("TechDraw::DrawViewSymbol","SurfaceSymbol"); + TechDraw::DrawViewSymbol *surfaceSymbol = dynamic_cast(docObject); + surfaceSymbol->Symbol.setValue(completeSymbol()); + surfaceSymbol->Rotation.setValue(ui->leAngle->text().toDouble()); + TechDraw::DrawPage* page = selectedView->findParentPage(); + page->addView(surfaceSymbol); + Gui::Command::commitCommand(); + return true; +} + +bool TaskSurfaceFinishSymbols::reject() +{ + return true; +} + +//=========================================================================== +// TaskDlgSurfaceFinishSymbols// +//=========================================================================== + +TaskDlgSurfaceFinishSymbols::TaskDlgSurfaceFinishSymbols(TechDraw::DrawViewPart* view) + : TaskDialog() +{ + widget = new TaskSurfaceFinishSymbols(view); + taskbox = new Gui::TaskView::TaskBox(Gui::BitmapFactory().pixmap("actions/TechDraw_SurfaceFinishSymbols"), + widget->windowTitle(), true, nullptr); + taskbox->groupLayout()->addWidget(widget); + Content.push_back(taskbox); +} + +TaskDlgSurfaceFinishSymbols::~TaskDlgSurfaceFinishSymbols() +{ +} + +void TaskDlgSurfaceFinishSymbols::update() +{ +// widget->updateTask(); +} + +//==== calls from the TaskView =============================================================== +void TaskDlgSurfaceFinishSymbols::open() +{ +} + +void TaskDlgSurfaceFinishSymbols::clicked(int) +{ +} + +bool TaskDlgSurfaceFinishSymbols::accept() +{ + widget->accept(); + return true; +} + +bool TaskDlgSurfaceFinishSymbols::reject() +{ + widget->reject(); + return true; +} + +#include diff --git a/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.h b/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.h new file mode 100644 index 0000000000..586791360b --- /dev/null +++ b/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.h @@ -0,0 +1,150 @@ +/*************************************************************************** + * Copyright (c) 2022 edi * + * * + * 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 TECHDRAWGUI_TASKSURFACEFINISHSYMBOLS_H +#define TECHDRAWGUI_TASKSURFACEFINISHSYMBOLS_H + +#include + +#include +#include + +class QComboBox; + +namespace App { +class DocumentObject; +} + +namespace TechDraw +{ +class DrawPage; +class DrawView; +class DrawViewPart; +class CosmeticEdge; +class LineFormat; +} + +namespace TechDraw +{ +class Face; +} + +namespace TechDrawGui +{ +class QGVPage; +class QGIView; +class QGIPrimPath; +class MDIViewPage; +class ViewProviderViewPart; +class Ui_TaskSurfaceFinishSymbols; + +class SvgString +// Class to create an SVG as a string +{ + std::stringstream svgStream; + +public: + + SvgString(int width, int height); + void addLine(int x1, int y1, int x2, int y2); + void addCircle(int xCenter, int yCenter, int radius); + void addText(int xText, int yText, std::string text); + std::string finish(); + +}; // SvgString + +class TaskSurfaceFinishSymbols : public QWidget +{ + Q_OBJECT + +public: + explicit TaskSurfaceFinishSymbols(TechDraw::DrawViewPart* view); + ~TaskSurfaceFinishSymbols() override; + +public Q_SLOTS: + +public: + virtual bool accept(); + virtual bool reject(); + void updateTask(); + +private Q_SLOTS: + void onIconChanged(); + void onISO(); + void onASME(); + +protected Q_SLOTS: + +protected: + void changeEvent(QEvent *e) override; + + void setUiEdit(); + +private: + enum symbolType {anyMethod=0, removeProhibit, removeRequired, + anyMethodAll, removeProhibitAll, removeRequiredAll}; + QPixmap baseSymbol(symbolType type); + std::string completeSymbol(); + TechDraw::DrawViewPart* selectedView; + QGraphicsScene* symbolScene; + std::vector raValues, laySymbols, roughGrades; + QGraphicsProxyWidget *proxyRA, *proxySamLength, *proxyMinRough, *proxyMaxRough; + QLineEdit *leMethod, *leSamLength, *leAddition; + QComboBox *cbRA, *cbMinRought, *cbMaxRought, *cbLay; + symbolType activeIcon; + bool isISO; + std::unique_ptr ui; +}; // class TaskSurfaceFinishSymbols + +class TaskDlgSurfaceFinishSymbols : public Gui::TaskView::TaskDialog +{ + Q_OBJECT + +public: + explicit TaskDlgSurfaceFinishSymbols(TechDraw::DrawViewPart* view); + ~TaskDlgSurfaceFinishSymbols() override; + +public: + /// is called the TaskView when the dialog is opened + void open() override; + /// is called by the framework if an button is clicked which has no accept or reject role + void clicked(int) override; + /// is called by the framework if the dialog is accepted (Ok) + bool accept() override; + /// is called by the framework if the dialog is rejected (Cancel) + bool reject() override; + /// is called by the framework if the user presses the help button + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override + { return false; } + void update(); + +protected: + +private: + TaskSurfaceFinishSymbols* widget; + Gui::TaskView::TaskBox* taskbox; +}; // class TaskDlgSurfaceFinishSymbols + +} // namespace TechDrawGui + +#endif // #ifndef TECHDRAWGUI_TASKSURFACEFINISHSYMBOLS_H diff --git a/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.ui b/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.ui new file mode 100644 index 0000000000..c29b10231c --- /dev/null +++ b/src/Mod/TechDraw/Gui/TaskSurfaceFinishSymbols.ui @@ -0,0 +1,188 @@ + + + TechDrawGui::TaskSurfaceFinishSymbols + + + + 0 + 0 + 274 + 454 + + + + + 0 + 0 + + + + + 250 + 0 + + + + Surface Finish Symbols + + + + + + + + <html><head/><body><p>Material removal prohibited, whole part</p></body></html> + + + + + + + + + + <html><head/><body><p>Any method allowed, whole part</p></body></html> + + + + + + + + + + <html><head/><body><p>Material removal required, whole part</p></body></html> + + + + + + + + + + <html><head/><body><p>Material removal required</p></body></html> + + + + + + + + + + <html><head/><body><p>Material removal prohibited</p></body></html> + + + + + + + + + + <html><head/><body><p>Any method allowed</p></body></html> + + + + + + + + + + + + + + Symbol angle: + + + + + + + <html><head/><body><p>Rotation angle</p></body></html> + + + 0 + + + + + + + <html><head/><body><p>Use ISO standard</p></body></html> + + + ISO + + + true + + + + + + + <html><head/><body><p>Use ASME standard</p></body></html> + + + ASME + + + + + + + + + + 0 + 0 + + + + + 0 + 300 + + + + ArrowCursor + + + false + + + QFrame::NoFrame + + + 0 + + + + + 240 + 240 + 240 + + + + + + 0.000000000000000 + 0.000000000000000 + 3.000000000000000 + 0.000000000000000 + + + + + + + + + + + diff --git a/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp b/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp index 0ef271276f..142f3c9399 100644 --- a/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp +++ b/src/Mod/TechDraw/Gui/TaskWeldingSymbol.cpp @@ -126,7 +126,7 @@ TaskWeldingSymbol::TaskWeldingSymbol(TechDraw::DrawWeldSymbol* weld) : // or ViewProviderWeld.setEdit App::DocumentObject* obj = m_weldFeat->Leader.getValue(); - if (obj == nullptr || + if (!obj || !obj->isDerivedFrom(TechDraw::DrawLeaderLine::getClassTypeId()) ) { Base::Console().Error("TaskWeldingSymbol - no leader for welding symbol. Can not proceed.\n"); return; @@ -225,7 +225,7 @@ void TaskWeldingSymbol::setUiEdit() ui->leTailText->setText(QString::fromUtf8(m_weldFeat->TailText.getValue())); getTileFeats(); - if (m_arrowFeat != nullptr) { + if (m_arrowFeat) { QString qTemp = QString::fromUtf8(m_arrowFeat->LeftText.getValue()); ui->leArrowTextL->setText(qTemp); qTemp = QString::fromUtf8(m_arrowFeat->RightText.getValue()); @@ -247,7 +247,7 @@ void TaskWeldingSymbol::setUiEdit() } } - if (m_otherFeat != nullptr) { + if (m_otherFeat) { QString qTemp = QString::fromUtf8(m_otherFeat->LeftText.getValue()); ui->leOtherTextL->setText(qTemp); qTemp = QString::fromUtf8(m_otherFeat->RightText.getValue()); @@ -429,7 +429,7 @@ void TaskWeldingSymbol::onSymbolSelected(QString symbolPath, } } -void TaskWeldingSymbol::collectArrowData(void) +void TaskWeldingSymbol::collectArrowData() { // Base::Console().Message("TWS::collectArrowData()\n"); m_arrowOut.toBeSaved = true; @@ -443,7 +443,7 @@ void TaskWeldingSymbol::collectArrowData(void) m_arrowOut.tileName = ""; } -void TaskWeldingSymbol::collectOtherData(void) +void TaskWeldingSymbol::collectOtherData() { // Base::Console().Message("TWS::collectOtherData()\n"); m_otherOut.toBeSaved = true; @@ -457,7 +457,7 @@ void TaskWeldingSymbol::collectOtherData(void) m_otherOut.tileName = ""; } -void TaskWeldingSymbol::getTileFeats(void) +void TaskWeldingSymbol::getTileFeats() { // Base::Console().Message("TWS::getTileFeats()\n"); std::vector tiles = m_weldFeat->getTiles(); @@ -485,7 +485,7 @@ void TaskWeldingSymbol::getTileFeats(void) } //****************************************************************************** -TechDraw::DrawWeldSymbol* TaskWeldingSymbol::createWeldingSymbol(void) +TechDraw::DrawWeldSymbol* TaskWeldingSymbol::createWeldingSymbol() { // Base::Console().Message("TWS::createWeldingSymbol()\n"); @@ -524,15 +524,13 @@ TechDraw::DrawWeldSymbol* TaskWeldingSymbol::createWeldingSymbol(void) App::DocumentObject* newObj = m_leadFeat->getDocument()->getObject(symbolName.c_str()); TechDraw::DrawWeldSymbol* newSym = dynamic_cast(newObj); - if ( (newObj == nullptr) || - (newSym == nullptr) ) { + if (!newObj || !newSym) throw Base::RuntimeError("TaskWeldingSymbol - new symbol object not found"); - } return newSym; } -void TaskWeldingSymbol::updateWeldingSymbol(void) +void TaskWeldingSymbol::updateWeldingSymbol() { // Base::Console().Message("TWS::updateWeldingSymbol()\n"); std::string symbolName = m_weldFeat->getNameInDocument(); @@ -558,12 +556,12 @@ void TaskWeldingSymbol::updateWeldingSymbol(void) symbolName.c_str(), tailText.c_str()); } -void TaskWeldingSymbol::updateTiles(void) +void TaskWeldingSymbol::updateTiles() { // Base::Console().Message("TWS::updateTiles()\n"); getTileFeats(); - if (m_arrowFeat == nullptr) { + if (!m_arrowFeat) { Base::Console().Message("TWS::updateTiles - no arrow tile!\n"); } else { collectArrowData(); @@ -587,7 +585,7 @@ void TaskWeldingSymbol::updateTiles(void) } } - if (m_otherFeat == nullptr) { + if (!m_otherFeat) { // Base::Console().Message("TWS::updateTiles - no other tile!\n"); } else { if (m_otherDirty) { diff --git a/src/Mod/TechDraw/Gui/TaskWeldingSymbol.h b/src/Mod/TechDraw/Gui/TaskWeldingSymbol.h index 8e5f4c0f8b..e541d05b9f 100644 --- a/src/Mod/TechDraw/Gui/TaskWeldingSymbol.h +++ b/src/Mod/TechDraw/Gui/TaskWeldingSymbol.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_TASKWELDINGSYMBOL_H #define TECHDRAWGUI_TASKWELDINGSYMBOL_H +#include + #include #include @@ -73,7 +75,7 @@ public: std::string symbolPath; std::string symbolString; std::string tileName; - void init(void) { + void init() { toBeSaved = false; arrowSide = true; row = 0; @@ -173,26 +175,26 @@ class TaskDlgWeldingSymbol : public Gui::TaskView::TaskDialog Q_OBJECT public: - TaskDlgWeldingSymbol(TechDraw::DrawLeaderLine* leader); - TaskDlgWeldingSymbol(TechDraw::DrawWeldSymbol* weld); - ~TaskDlgWeldingSymbol(); + explicit TaskDlgWeldingSymbol(TechDraw::DrawLeaderLine* leader); + explicit TaskDlgWeldingSymbol(TechDraw::DrawWeldSymbol* weld); + ~TaskDlgWeldingSymbol() override; public: /// is called the TaskView when the dialog is opened - virtual void open(); + void open() override; /// is called by the framework if an button is clicked which has no accept or reject role - virtual void clicked(int); + void clicked(int) override; /// is called by the framework if the dialog is accepted (Ok) - virtual bool accept(); + bool accept() override; /// is called by the framework if the dialog is rejected (Cancel) - virtual bool reject(); + bool reject() override; /// is called by the framework if the user presses the help button - virtual void helpRequested() { return;} - virtual bool isAllowedAlterDocument(void) const + void helpRequested() override { return;} + bool isAllowedAlterDocument() const override { return false; } void update(); - void modifyStandardButtons(QDialogButtonBox* box); + void modifyStandardButtons(QDialogButtonBox* box) override; protected: diff --git a/src/Mod/TechDraw/Gui/TemplateTextField.h b/src/Mod/TechDraw/Gui/TemplateTextField.h index 24960ba67b..b39ed90f83 100644 --- a/src/Mod/TechDraw/Gui/TemplateTextField.h +++ b/src/Mod/TechDraw/Gui/TemplateTextField.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_TEMPLATETEXTFIELD_H #define DRAWINGGUI_TEMPLATETEXTFIELD_H +#include + #include namespace TechDraw { diff --git a/src/Mod/TechDraw/Gui/ViewProviderAnnotation.cpp b/src/Mod/TechDraw/Gui/ViewProviderAnnotation.cpp index 6180ad9935..f1997f3a61 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderAnnotation.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderAnnotation.cpp @@ -24,9 +24,6 @@ #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include #include "ViewProviderAnnotation.h" #include "QGIView.h" @@ -47,25 +44,6 @@ ViewProviderAnnotation::~ViewProviderAnnotation() { } -void ViewProviderAnnotation::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderAnnotation::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderAnnotation::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - void ViewProviderAnnotation::updateData(const App::Property* prop) { if (prop == &(getViewObject()->Text) || diff --git a/src/Mod/TechDraw/Gui/ViewProviderAnnotation.h b/src/Mod/TechDraw/Gui/ViewProviderAnnotation.h index 1e9e77f7b8..e67446e59e 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderAnnotation.h +++ b/src/Mod/TechDraw/Gui/ViewProviderAnnotation.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERANNOTATION_H #define DRAWINGGUI_VIEWPROVIDERANNOTATION_H +#include + #include #include "ViewProviderDrawingView.h" @@ -34,23 +36,18 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderAnnotation : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderAnnotation); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderAnnotation); public: /// constructor ViewProviderAnnotation(); /// destructor - virtual ~ViewProviderAnnotation(); + ~ViewProviderAnnotation() override; + bool useNewSelectionModel() const override {return false;} + void updateData(const App::Property*) override; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - - virtual TechDraw::DrawViewAnnotation* getViewObject() const; + TechDraw::DrawViewAnnotation* getViewObject() const override; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp b/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp index dd2da129d0..a8a8f64e3d 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderBalloon.cpp @@ -60,10 +60,7 @@ ViewProviderBalloon::ViewProviderBalloon() ADD_PROPERTY_TYPE(Font, (Preferences::labelFont().c_str()), group, App::Prop_None, "The name of the font to use"); ADD_PROPERTY_TYPE(Fontsize, (Preferences::dimFontSizeMM()), group, (App::PropertyType)(App::Prop_None), "Balloon text size in units"); - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double weight = lg->getWeight("Thin"); - delete lg; //Coverity CID 174670 + double weight = TechDraw::LineGroup::getDefaultWidth("Thin"); ADD_PROPERTY_TYPE(LineWidth, (weight), group, (App::PropertyType)(App::Prop_None), "Leader line width"); ADD_PROPERTY_TYPE(LineVisible, (true), group, (App::PropertyType)(App::Prop_None), "Balloon line visible or hidden"); ADD_PROPERTY_TYPE(Color, (PreferencesGui::dimColor()), group, App::Prop_None, "Color of the balloon"); @@ -73,26 +70,7 @@ ViewProviderBalloon::~ViewProviderBalloon() { } -void ViewProviderBalloon::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderBalloon::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderBalloon::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - -bool ViewProviderBalloon::doubleClicked(void) +bool ViewProviderBalloon::doubleClicked() { startDefaultEditMode(); return true; @@ -125,16 +103,6 @@ bool ViewProviderBalloon::setEdit(int ModNum) return true; } -void ViewProviderBalloon::unsetEdit(int ModNum) -{ - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - void ViewProviderBalloon::updateData(const App::Property* p) { //Balloon handles X,Y updates differently that other QGIView diff --git a/src/Mod/TechDraw/Gui/ViewProviderBalloon.h b/src/Mod/TechDraw/Gui/ViewProviderBalloon.h index 70940f08bb..8cbd20c2bb 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderBalloon.h +++ b/src/Mod/TechDraw/Gui/ViewProviderBalloon.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERBALLOON_H #define DRAWINGGUI_VIEWPROVIDERBALLOON_H + +#include #include #include @@ -36,13 +38,13 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderBalloon : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderBalloon); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderBalloon); public: /// constructor ViewProviderBalloon(); /// destructor - virtual ~ViewProviderBalloon(); + ~ViewProviderBalloon() override; App::PropertyFont Font; App::PropertyLength Fontsize; @@ -50,23 +52,18 @@ public: App::PropertyBool LineVisible; App::PropertyColor Color; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property* p); - virtual void setupContextMenu(QMenu*, QObject*, const char*); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); - virtual bool canDelete(App::DocumentObject* obj) const; + bool useNewSelectionModel() const override {return false;} + void updateData(const App::Property*) override; + void onChanged(const App::Property* p) override; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool setEdit(int ModNum) override; + bool doubleClicked() override; + bool canDelete(App::DocumentObject* obj) const override; - virtual TechDraw::DrawViewBalloon* getViewObject() const; + TechDraw::DrawViewBalloon* getViewObject() const override; protected: - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.cpp b/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.cpp index 447b1ff4ed..8359f8a490 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.cpp @@ -50,11 +50,6 @@ QIcon ViewProviderCosmeticExtension::extensionMergeGreyableOverlayIcons(const QI return mergedicon; } -void ViewProviderCosmeticExtension::extensionUpdateData(const App::Property* prop) -{ - Gui::ViewProviderExtension::extensionUpdateData(prop); -} - namespace Gui { EXTENSION_PROPERTY_SOURCE_TEMPLATE(TechDrawGui::ViewProviderCosmeticExtensionPython, TechDrawGui::ViewProviderCosmeticExtension) diff --git a/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.h b/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.h index c20d6c48fd..e4956e0a5a 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.h +++ b/src/Mod/TechDraw/Gui/ViewProviderCosmeticExtension.h @@ -23,6 +23,8 @@ #ifndef GUI_VIEWPROVIDERCOSMETICEXTENSION_H #define GUI_VIEWPROVIDERCOSMETICEXTENSION_H +#include + #include namespace TechDrawGui @@ -38,9 +40,6 @@ public: virtual ~ViewProviderCosmeticExtension() = default; virtual QIcon extensionMergeGreyableOverlayIcons(const QIcon & orig) const override; - - virtual void extensionUpdateData(const App::Property*) override; - }; typedef Gui::ViewProviderExtensionPythonT ViewProviderCosmeticExtensionPython; diff --git a/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp b/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp index eeefcb7fb7..57b7e98977 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderDimension.cpp @@ -102,20 +102,7 @@ void ViewProviderDimension::attach(App::DocumentObject *pcFeat) } } -void ViewProviderDimension::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderDimension::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - -bool ViewProviderDimension::doubleClicked(void) +bool ViewProviderDimension::doubleClicked() { startDefaultEditMode(); return true; @@ -148,16 +135,6 @@ bool ViewProviderDimension::setEdit(int ModNum) return true; } -void ViewProviderDimension::unsetEdit(int ModNum) -{ - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - void ViewProviderDimension::updateData(const App::Property* p) { if (p == &(getViewObject()->Type)) { @@ -209,7 +186,7 @@ void ViewProviderDimension::onChanged(const App::Property* p) QGIView* qgiv = getQView(); if (qgiv) { QGIViewDimension* qgivd = dynamic_cast(qgiv); - if (qgivd != nullptr) { + if (qgivd) { qgivd->setNormalColorAll(); } } @@ -240,11 +217,7 @@ double ViewProviderDimension::prefFontSize() const double ViewProviderDimension::prefWeight() const { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double weight = lg->getWeight("Thin"); - delete lg; //Coverity CID 174670 - return weight; + return TechDraw::LineGroup::getDefaultWidth("Thin"); } int ViewProviderDimension::prefStandardAndStyle() const diff --git a/src/Mod/TechDraw/Gui/ViewProviderDimension.h b/src/Mod/TechDraw/Gui/ViewProviderDimension.h index a3b7ce27da..f583832cfe 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDimension.h +++ b/src/Mod/TechDraw/Gui/ViewProviderDimension.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERDIMENSION_H #define DRAWINGGUI_VIEWPROVIDERDIMENSION_H + +#include #include @@ -30,18 +32,17 @@ #include "ViewProviderDrawingView.h" - namespace TechDrawGui { class TechDrawGuiExport ViewProviderDimension : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderDimension); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderDimension); public: /// constructor ViewProviderDimension(); /// destructor - virtual ~ViewProviderDimension(); + ~ViewProviderDimension() override; App::PropertyFont Font; App::PropertyLength Fontsize; @@ -67,29 +68,25 @@ public: App::PropertyFloat GapFactorISO; App::PropertyFloat GapFactorASME; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property* p); - virtual void setupContextMenu(QMenu*, QObject*, const char*); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); + void attach(App::DocumentObject *) override; + bool useNewSelectionModel() const override {return false;} + void updateData(const App::Property*) override; + void onChanged(const App::Property* p) override; + void setupContextMenu(QMenu*, QObject*, const char*) override; + bool setEdit(int ModNum) override; + bool doubleClicked() override; - virtual TechDraw::DrawViewDimension* getViewObject() const; + TechDraw::DrawViewDimension* getViewObject() const override; App::Color prefColor() const; std::string prefFont() const; double prefFontSize() const; double prefWeight() const; int prefStandardAndStyle() const; - virtual bool canDelete(App::DocumentObject* obj) const; + bool canDelete(App::DocumentObject* obj) const override; protected: - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; private: static const char *StandardAndStyleEnums[]; diff --git a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp index e858cb1180..8cdd6df927 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.cpp @@ -29,9 +29,12 @@ #endif #include +#include +#include #include #include #include +#include #include #include @@ -40,7 +43,6 @@ #include "MDIViewPage.h" #include "QGIView.h" #include "QGSPage.h" -#include "QGVPage.h" #include "ViewProviderPage.h" using namespace TechDrawGui; @@ -59,7 +61,6 @@ ViewProviderDrawingView::ViewProviderDrawingView() // Do not show in property editor why? wf WF: because DisplayMode applies only to coin and we // don't use coin. DisplayMode.setStatus(App::Property::Hidden,true); - m_docReady = true; } ViewProviderDrawingView::~ViewProviderDrawingView() @@ -72,9 +73,11 @@ void ViewProviderDrawingView::attach(App::DocumentObject *pcFeat) ViewProviderDocumentObject::attach(pcFeat); auto bnd = boost::bind(&ViewProviderDrawingView::onGuiRepaint, this, bp::_1); + auto bndProgressMessage = boost::bind(&ViewProviderDrawingView::onProgressMessage, this, bp::_1, bp::_2, bp::_3); auto feature = getViewObject(); - if (feature != nullptr) { + if (feature) { connectGuiRepaint = feature->signalGuiPaint.connect(bnd); + connectProgressMessage = feature->signalProgressMessage.connect(bndProgressMessage); //TODO: would be good to start the QGIV creation process here, but no guarantee we actually have // MDIVP or QGVP yet. // but parent page might. we may not be part of the document yet though! @@ -84,17 +87,6 @@ void ViewProviderDrawingView::attach(App::DocumentObject *pcFeat) } } -void ViewProviderDrawingView::setDisplayMode(const char* ModeName) -{ - ViewProviderDocumentObject::setDisplayMode(ModeName); -} - -std::vector ViewProviderDrawingView::getDisplayModes(void) const -{ - std::vector StrList = ViewProviderDocumentObject::getDisplayModes(); - return StrList; -} - void ViewProviderDrawingView::onChanged(const App::Property *prop) { App::DocumentObject* obj = getObject(); @@ -104,11 +96,7 @@ void ViewProviderDrawingView::onChanged(const App::Property *prop) } if (prop == &Visibility) { -// if(Visibility.getValue()) { -// show(); -// } else { -// hide(); -// } + //handled by ViewProviderDocumentObject } else if (prop == &KeepLabel) { QGIView* qgiv = getQView(); if (qgiv) { @@ -119,7 +107,7 @@ void ViewProviderDrawingView::onChanged(const App::Property *prop) Gui::ViewProviderDocumentObject::onChanged(prop); } -void ViewProviderDrawingView::show(void) +void ViewProviderDrawingView::show() { TechDraw::DrawView* obj = getViewObject(); if (!obj || obj->isRestoring()) @@ -135,7 +123,7 @@ void ViewProviderDrawingView::show(void) ViewProviderDocumentObject::show(); } -void ViewProviderDrawingView::hide(void) +void ViewProviderDrawingView::hide() { TechDraw::DrawView* obj = getViewObject(); if (!obj || obj->isRestoring()) @@ -150,7 +138,7 @@ void ViewProviderDrawingView::hide(void) // in FC Tree hiding does not change selection state. // block/unblock selection protects against crash in Gui::SelectionSingleton::setVisible MDIViewPage* mdi = getMDIViewPage(); - if (mdi != nullptr) { //if there is no mdivp, there is nothing to hide! + if (mdi) { //if there is no mdivp, there is nothing to hide! mdi->blockSceneSelection(true); qView->hide(); ViewProviderDocumentObject::hide(); @@ -160,44 +148,42 @@ void ViewProviderDrawingView::hide(void) } } -QGIView* ViewProviderDrawingView::getQView(void) +QGIView* ViewProviderDrawingView::getQView() { - QGIView *qView = nullptr; - if (m_docReady){ - TechDraw::DrawView* dv = getViewObject(); - if (dv) { - Gui::Document* guiDoc = Gui::Application::Instance->getDocument(getViewObject()->getDocument()); - if (guiDoc != nullptr) { - Gui::ViewProvider* vp = guiDoc->getViewProvider(getViewObject()->findParentPage()); - ViewProviderPage* dvp = dynamic_cast(vp); - if (dvp) { - if (dvp->getMDIViewPage()) { - if (dvp->getMDIViewPage()->getQGSPage()) { - qView = dynamic_cast(dvp->getMDIViewPage()-> - getQGSPage()->findQViewForDocObj(getViewObject())); - } - } - } - } - } + TechDraw::DrawView* dv = getViewObject(); + if (!dv) { + return nullptr; } - return qView; + + Gui::Document* guiDoc = Gui::Application::Instance->getDocument(dv->getDocument()); + if (!guiDoc) { + return nullptr; + } + + ViewProviderPage* vpp = getViewProviderPage(); + if (!vpp) { + return nullptr; + } + + if (vpp->getQGSPage()) { + return dynamic_cast(vpp->getQGSPage()->findQViewForDocObj(getViewObject())); + } + + return nullptr; } -bool ViewProviderDrawingView::isShow(void) const +bool ViewProviderDrawingView::isShow() const { return Visibility.getValue(); } void ViewProviderDrawingView::startRestoring() { - m_docReady = false; Gui::ViewProviderDocumentObject::startRestoring(); } void ViewProviderDrawingView::finishRestoring() { - m_docReady = true; if (Visibility.getValue()) { show(); } else { @@ -220,28 +206,23 @@ void ViewProviderDrawingView::updateData(const App::Property* prop) Gui::ViewProviderDocumentObject::updateData(prop); } -void ViewProviderDrawingView::unsetEdit(int ModNum) +ViewProviderPage* ViewProviderDrawingView::getViewProviderPage() const { - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - Gui::ViewProviderDocumentObject::unsetEdit(ModNum); + Gui::Document* guiDoc = Gui::Application::Instance->getDocument(getViewObject()->getDocument()); + if (guiDoc) { + Gui::ViewProvider* vp = guiDoc->getViewProvider(getViewObject()->findParentPage()); + return dynamic_cast(vp); } + return nullptr; } MDIViewPage* ViewProviderDrawingView::getMDIViewPage() const { - MDIViewPage* result = nullptr; - Gui::Document* guiDoc = Gui::Application::Instance->getDocument(getViewObject()->getDocument()); - if (guiDoc != nullptr) { - Gui::ViewProvider* vp = guiDoc->getViewProvider(getViewObject()->findParentPage()); - ViewProviderPage* dvp = dynamic_cast(vp); - if (dvp) { - result = dvp->getMDIViewPage(); - } + ViewProviderPage* vpp = getViewProviderPage(); + if (vpp) { + return vpp->getMDIViewPage(); } - return result; + return nullptr; } Gui::MDIView *ViewProviderDrawingView::getMDIView() const @@ -252,55 +233,88 @@ Gui::MDIView *ViewProviderDrawingView::getMDIView() const void ViewProviderDrawingView::onGuiRepaint(const TechDraw::DrawView* dv) { // Base::Console().Message("VPDV::onGuiRepaint(%s) - this: %x\n", dv->getNameInDocument(), this); + Gui::Document* guiDoc = Gui::Application::Instance->getDocument(getViewObject()->getDocument()); + if (guiDoc == nullptr) { + return; + } + std::vector pages = getViewObject()->findAllParentPages(); if (pages.size() > 1) { - Gui::Document* guiDoc = Gui::Application::Instance->getDocument(getViewObject()->getDocument()); - if (guiDoc == nullptr) { - return; - } - for (auto& p : pages) { - std::vector views = p->Views.getValues(); - for (auto& v: views) { - if (v == getViewObject()) { - //view v belongs to this page p - Gui::ViewProvider* vp = guiDoc->getViewProvider(p); - ViewProviderPage* vpPage = dynamic_cast(vp); - if (vpPage != nullptr) { - if (vpPage->getMDIViewPage() != nullptr) { - if (vpPage->getMDIViewPage()->getQGSPage()) { - QGIView* qView = dynamic_cast(vpPage->getMDIViewPage()-> - getQGSPage()->findQViewForDocObj(v)); - if (qView != nullptr) { - qView->updateView(true); - } - } - } - } - } - } - } + multiParentPaint(pages); } else if (dv == getViewObject()) { - //original logic for 1 view on 1 page - if (!dv->isRemoving() && - !dv->isRestoring()) { - QGIView* qgiv = getQView(); - if (qgiv) { - qgiv->updateView(true); - } else { //we are not part of the Gui page yet. ask page to add us. - //TODO: this bit causes trouble. Should move QGIV creation to attach? - // is MDIVP/QGVP available at attach time? - // wf: mdivp/qgvp is not necessarily directly available at attach time. It should be available - // via the parent DrawPage since the DP is created before any views. -// Base::Console().Message("VPDV::onGuiRepaint - no QGIV for: %s\n",dv->getNameInDocument()); - MDIViewPage* page = getMDIViewPage(); - if (page != nullptr) { - page->addView(dv); + singleParentPaint(dv); + } +} + +void ViewProviderDrawingView::multiParentPaint(std::vector& pages) +{ + for (auto& p : pages) { + std::vector views = p->Views.getValues(); + for (auto& v: views) { + if (v != getViewObject()) { //should this be dv from onGuiRepaint? + continue; + } + //view v belongs to this page p + ViewProviderPage* vpPage = getViewProviderPage(); + if (!vpPage) { + continue; + } + if (vpPage->getQGSPage()) { + QGIView* qView = dynamic_cast(vpPage->getQGSPage()->findQViewForDocObj(v)); + if (qView) { + qView->updateView(true); } } } } } +void ViewProviderDrawingView::singleParentPaint(const TechDraw::DrawView* dv) +{ + //original logic for 1 view on 1 page + if (dv->isRemoving() || + dv->isRestoring()) { + return; + } + QGIView* qgiv = getQView(); + if (qgiv) { + qgiv->updateView(true); + } else { //we are not part of the Gui page yet. ask page to add us. + ViewProviderPage* vpPage = getViewProviderPage(); + if (vpPage) { + if (vpPage->getQGSPage()) { + vpPage->getQGSPage()->addView(dv); + } + } + } +} + +//handle status updates from App/DrawView +void ViewProviderDrawingView::onProgressMessage(const TechDraw::DrawView* dv, + const std::string featureName, + const std::string text) +{ +// Q_UNUSED(featureName) + Q_UNUSED(dv) +// Q_UNUSED(text) + showProgressMessage(featureName, text); +} + +void ViewProviderDrawingView::showProgressMessage(const std::string featureName, const std::string text) const +{ + QString msg = QString::fromUtf8("%1 %2") + .arg(Base::Tools::fromStdString(featureName), + Base::Tools::fromStdString(text)); + if (Gui::getMainWindow()) { + //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)); + } +} + TechDraw::DrawView* ViewProviderDrawingView::getViewObject() const { return dynamic_cast(pcObject); diff --git a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h index a8b30c8cbb..2acdb899d3 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h +++ b/src/Mod/TechDraw/Gui/ViewProviderDrawingView.h @@ -39,6 +39,7 @@ class DrawView; namespace TechDrawGui { class QGIView; class MDIViewPage; +class ViewProviderPage; class TechDrawGuiExport ViewProviderDrawingView : public Gui::ViewProviderDocumentObject { @@ -48,44 +49,47 @@ public: /// constructor ViewProviderDrawingView(); /// destructor - virtual ~ViewProviderDrawingView(); + ~ViewProviderDrawingView() override; App::PropertyBool KeepLabel; - virtual void attach(App::DocumentObject *) override; - virtual void setDisplayMode(const char* ModeName) override; - virtual bool useNewSelectionModel(void) const override {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const override; + void attach(App::DocumentObject *) override; + bool useNewSelectionModel() const override {return false;} /// Hide the object in the view - virtual void hide(void) override; + void hide() override; /// Show the object in the view - virtual void show(void) override; - virtual bool isShow(void) const override; + void show() override; + bool isShow() const override; - virtual void onChanged(const App::Property *prop) override; - virtual void updateData(const App::Property*) override; - virtual void unsetEdit(int ModNum) override; + void onChanged(const App::Property *prop) override; + void updateData(const App::Property*) override; - QGIView* getQView(void); + QGIView* getQView(); MDIViewPage* getMDIViewPage() const; - virtual Gui::MDIView *getMDIView() const override; + Gui::MDIView *getMDIView() const override; + ViewProviderPage* getViewProviderPage() const; /** @name Restoring view provider from document load */ //@{ - virtual void startRestoring() override; - virtual void finishRestoring() override; + void startRestoring() override; + void finishRestoring() override; //@} virtual TechDraw::DrawView* getViewObject() const; + void showProgressMessage(const std::string featureName, const std::string text) const; - void onGuiRepaint(const TechDraw::DrawView* dv); + void onGuiRepaint(const TechDraw::DrawView* dv); + void onProgressMessage(const TechDraw::DrawView* dv, + const std::string featureName, + const std::string text); typedef boost::signals2::scoped_connection Connection; Connection connectGuiRepaint; - + Connection connectProgressMessage; private: - bool m_docReady; //sb MDI + QGraphicsScene ready + void multiParentPaint(std::vector& pages); + void singleParentPaint(const TechDraw::DrawView* dv); + }; diff --git a/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.cpp b/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.cpp index e2760d1592..a1da58b78e 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.cpp @@ -70,25 +70,6 @@ ViewProviderGeomHatch::~ViewProviderGeomHatch() { } -void ViewProviderGeomHatch::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDocumentObject::attach(pcFeat); -} - -void ViewProviderGeomHatch::setDisplayMode(const char* ModeName) -{ - ViewProviderDocumentObject::setDisplayMode(ModeName); -} - -std::vector ViewProviderGeomHatch::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDocumentObject::getDisplayModes(); - - return StrList; -} - bool ViewProviderGeomHatch::setEdit(int ModNum) { Q_UNUSED(ModNum); @@ -111,17 +92,7 @@ bool ViewProviderGeomHatch::setEdit(int ModNum) return true; } -void ViewProviderGeomHatch::unsetEdit(int ModNum) -{ - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDocumentObject::unsetEdit(ModNum); - } -} - -bool ViewProviderGeomHatch::doubleClicked(void) +bool ViewProviderGeomHatch::doubleClicked() { setEdit(0); return true; @@ -133,7 +104,7 @@ void ViewProviderGeomHatch::onChanged(const App::Property* p) if ((p == &WeightPattern) || (p == &ColorPattern) ) { auto gHatch = getViewObject(); - if (gHatch != nullptr) { + if (gHatch) { TechDraw::DrawViewPart* parent = gHatch->getSourceView(); if (parent) { parent->requestPaint(); @@ -150,7 +121,7 @@ void ViewProviderGeomHatch::updateData(const App::Property* prop) Gui::ViewProviderDocumentObject::updateData(prop); } -void ViewProviderGeomHatch::updateGraphic(void) +void ViewProviderGeomHatch::updateGraphic() { TechDraw::DrawGeomHatch* dc = getViewObject(); if (!dc) { @@ -176,12 +147,9 @@ void ViewProviderGeomHatch::updateGraphic(void) qgiv->updateView(true); } -void ViewProviderGeomHatch::getParameters(void) +void ViewProviderGeomHatch::getParameters() { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double weight = lg->getWeight("Graphic"); - delete lg; //Coverity CID 174667 + double weight = TechDraw::LineGroup::getDefaultWidth("Graphic"); WeightPattern.setValue(weight); } diff --git a/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.h b/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.h index a34f34595b..6a424fa850 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.h +++ b/src/Mod/TechDraw/Gui/ViewProviderGeomHatch.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERCROSSHATCH_H #define DRAWINGGUI_VIEWPROVIDERCROSSHATCH_H +#include + #include #include @@ -51,15 +53,11 @@ public: App::PropertyFloat WeightPattern; App::PropertyColor ColorPattern; - virtual void attach(App::DocumentObject *) override; virtual void updateData(const App::Property*) override; virtual void onChanged(const App::Property *prop) override; virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; virtual bool doubleClicked(void) override; virtual bool useNewSelectionModel(void) const override {return false;} - virtual void setDisplayMode(const char* ModeName) override; - virtual std::vector getDisplayModes(void) const override; void updateGraphic(void); void getParameters(void); virtual bool canDelete(App::DocumentObject* obj) const override; diff --git a/src/Mod/TechDraw/Gui/ViewProviderHatch.cpp b/src/Mod/TechDraw/Gui/ViewProviderHatch.cpp index f093edd14c..19c1bced86 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderHatch.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderHatch.cpp @@ -71,25 +71,6 @@ ViewProviderHatch::~ViewProviderHatch() { } -void ViewProviderHatch::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDocumentObject::attach(pcFeat); -} - -void ViewProviderHatch::setDisplayMode(const char* ModeName) -{ - ViewProviderDocumentObject::setDisplayMode(ModeName); -} - -std::vector ViewProviderHatch::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDocumentObject::getDisplayModes(); - - return StrList; -} - bool ViewProviderHatch::setEdit(int ModNum) { if (ModNum != ViewProvider::Default) { @@ -105,17 +86,7 @@ bool ViewProviderHatch::setEdit(int ModNum) return true; } -void ViewProviderHatch::unsetEdit(int ModNum) -{ - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDocumentObject::unsetEdit(ModNum); - } -} - -bool ViewProviderHatch::doubleClicked(void) +bool ViewProviderHatch::doubleClicked() { setEdit(0); return true; @@ -134,11 +105,6 @@ void ViewProviderHatch::onChanged(const App::Property* prop) } } -void ViewProviderHatch::updateData(const App::Property* prop) -{ - Gui::ViewProviderDocumentObject::updateData(prop); -} - TechDraw::DrawHatch* ViewProviderHatch::getViewObject() const { return dynamic_cast(pcObject); diff --git a/src/Mod/TechDraw/Gui/ViewProviderHatch.h b/src/Mod/TechDraw/Gui/ViewProviderHatch.h index dfa04bb505..236edb67ab 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderHatch.h +++ b/src/Mod/TechDraw/Gui/ViewProviderHatch.h @@ -44,26 +44,20 @@ public: /// constructor ViewProviderHatch(); /// destructor - virtual ~ViewProviderHatch(); + ~ViewProviderHatch() override; App::PropertyColor HatchColor; App::PropertyFloatConstraint HatchScale; - virtual void attach(App::DocumentObject *) override; - virtual void setDisplayMode(const char* ModeName) override; - virtual bool useNewSelectionModel(void) const override {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const override; - virtual void onChanged(const App::Property* prop) override; - virtual bool setEdit(int ModNum) override; - virtual void unsetEdit(int ModNum) override; - virtual bool doubleClicked(void) override; - virtual void updateData(const App::Property*) override; - virtual bool canDelete(App::DocumentObject* obj) const override; + bool useNewSelectionModel() const override {return false;} + void onChanged(const App::Property* prop) override; + bool setEdit(int ModNum) override; + bool doubleClicked() override; + bool canDelete(App::DocumentObject* obj) const override; TechDraw::DrawHatch* getViewObject() const; - virtual Gui::MDIView *getMDIView() const override; + Gui::MDIView *getMDIView() const override; private: static App::PropertyFloatConstraint::Constraints scaleRange; diff --git a/src/Mod/TechDraw/Gui/ViewProviderImage.cpp b/src/Mod/TechDraw/Gui/ViewProviderImage.cpp index c669b2fb0c..d109d6b4e2 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderImage.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderImage.cpp @@ -20,12 +20,8 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include #include "ViewProviderImage.h" @@ -49,25 +45,6 @@ ViewProviderImage::~ViewProviderImage() { } -void ViewProviderImage::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderImage::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderImage::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - void ViewProviderImage::updateData(const App::Property* prop) { if (prop == &(getViewObject()->Width) || diff --git a/src/Mod/TechDraw/Gui/ViewProviderImage.h b/src/Mod/TechDraw/Gui/ViewProviderImage.h index e176883a46..c362047148 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderImage.h +++ b/src/Mod/TechDraw/Gui/ViewProviderImage.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERIMAGE_H #define DRAWINGGUI_VIEWPROVIDERIMAGE_H +#include + #include #include "ViewProviderDrawingView.h" @@ -33,25 +35,22 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderImage : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderImage); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderImage); public: /// constructor ViewProviderImage(); /// destructor - virtual ~ViewProviderImage(); + ~ViewProviderImage() override; App::PropertyBool Crop; //crop to feature width x height - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} + bool useNewSelectionModel() const override {return false;} /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property *prop); + void updateData(const App::Property*) override; + void onChanged(const App::Property *prop) override; - virtual TechDraw::DrawViewImage* getViewObject() const; + TechDraw::DrawViewImage* getViewObject() const override; }; diff --git a/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp b/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp index 2471f97b50..2c9e8c4640 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderLeader.cpp @@ -77,11 +77,6 @@ ViewProviderLeader::~ViewProviderLeader() { } -void ViewProviderLeader::attach(App::DocumentObject *pcFeat) -{ - ViewProviderDrawingView::attach(pcFeat); -} - bool ViewProviderLeader::setEdit(int ModNum) { // Base::Console().Message("VPL::setEdit(%d)\n",ModNum); @@ -97,18 +92,7 @@ bool ViewProviderLeader::setEdit(int ModNum) return true; } -void ViewProviderLeader::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - -bool ViewProviderLeader::doubleClicked(void) +bool ViewProviderLeader::doubleClicked() { // Base::Console().Message("VPL::doubleClicked()\n"); setEdit(ViewProvider::Default); @@ -121,7 +105,7 @@ void ViewProviderLeader::updateData(const App::Property* p) if (p == &getFeature()->LeaderParent) { App::DocumentObject* docObj = getFeature()->LeaderParent.getValue(); TechDraw::DrawView* dv = dynamic_cast(docObj); - if (dv != nullptr) { + if (dv) { QGIView* qgiv = getQView(); if (qgiv) { qgiv->onSourceChange(dv); @@ -145,7 +129,7 @@ void ViewProviderLeader::onChanged(const App::Property* p) ViewProviderDrawingView::onChanged(p); } -std::vector ViewProviderLeader::claimChildren(void) const +std::vector ViewProviderLeader::claimChildren() const { // Collect any child Document Objects and put them in the right place in the Feature tree // valid children of a ViewLeader are: @@ -179,16 +163,12 @@ TechDraw::DrawLeaderLine* ViewProviderLeader::getFeature() const return dynamic_cast(pcObject); } -double ViewProviderLeader::getDefLineWeight(void) +double ViewProviderLeader::getDefLineWeight() { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double result = lg->getWeight("Thin"); - delete lg; //Coverity CID 174670 - return result; + return TechDraw::LineGroup::getDefaultWidth("Thin"); } -App::Color ViewProviderLeader::getDefLineColor(void) +App::Color ViewProviderLeader::getDefLineColor() { return PreferencesGui::leaderColor(); } diff --git a/src/Mod/TechDraw/Gui/ViewProviderLeader.h b/src/Mod/TechDraw/Gui/ViewProviderLeader.h index 66973e49fe..ad11733c84 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderLeader.h +++ b/src/Mod/TechDraw/Gui/ViewProviderLeader.h @@ -25,6 +25,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERLEADER_H #define DRAWINGGUI_VIEWPROVIDERLEADER_H +#include + #include #include @@ -40,41 +42,39 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderLeader : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderLeader); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderLeader); public: /// constructor ViewProviderLeader(); /// destructor - virtual ~ViewProviderLeader(); + ~ViewProviderLeader() override; App::PropertyLength LineWidth; App::PropertyEnumeration LineStyle; App::PropertyColor Color; - virtual void attach(App::DocumentObject *); /* virtual void setDisplayMode(const char* ModeName);*/ - virtual bool useNewSelectionModel(void) const {return false;} + bool useNewSelectionModel() const override {return false;} /* virtual std::vector getDisplayModes(void) const;*/ - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property* p); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); - virtual bool onDelete(const std::vector &); - virtual bool canDelete(App::DocumentObject* obj) const; + void updateData(const App::Property*) override; + void onChanged(const App::Property* p) override; + bool setEdit(int ModNum) override; + bool doubleClicked() override; + bool onDelete(const std::vector &) override; + bool canDelete(App::DocumentObject* obj) const override; static const char* LineStyleEnums[]; - std::vector claimChildren(void) const; + std::vector claimChildren() const override; - virtual TechDraw::DrawLeaderLine* getViewObject() const; + TechDraw::DrawLeaderLine* getViewObject() const override; TechDraw::DrawLeaderLine* getFeature() const; protected: - double getDefLineWeight(void); - App::Color getDefLineColor(void); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + double getDefLineWeight(); + App::Color getDefLineColor(); + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; private: static App::PropertyIntegerConstraint::Constraints LineStyleRange; diff --git a/src/Mod/TechDraw/Gui/ViewProviderPage.cpp b/src/Mod/TechDraw/Gui/ViewProviderPage.cpp index 862efa54d7..e576eeedec 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderPage.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderPage.cpp @@ -78,7 +78,6 @@ PROPERTY_SOURCE(TechDrawGui::ViewProviderPage, Gui::ViewProviderDocumentObject) ViewProviderPage::ViewProviderPage() : m_mdiView(nullptr), - m_docReady(true), m_pageName(""), m_graphicsView(nullptr), m_graphicsScene(nullptr) @@ -86,19 +85,25 @@ ViewProviderPage::ViewProviderPage() sPixmap = "TechDraw_TreePage"; static const char *group = "Grid"; - ADD_PROPERTY_TYPE(ShowFrames ,(true),group,App::Prop_None,"NonGui! Show or hide View frames and Labels on this Page"); + ADD_PROPERTY_TYPE(ShowFrames ,(true),group,App::Prop_None,"Show or hide View frames and Labels on this Page"); ADD_PROPERTY_TYPE(ShowGrid ,(PreferencesGui::showGrid()),group,App::Prop_None,"Show or hide a grid on this Page"); ADD_PROPERTY_TYPE(GridSpacing, (PreferencesGui::gridSpacing()), group, (App::PropertyType)(App::Prop_None), "Grid line spacing in mm"); ShowFrames.setStatus(App::Property::Hidden,true); - Visibility.setStatus(App::Property::Hidden,true); DisplayMode.setStatus(App::Property::Hidden,true); + + m_graphicsScene = new QGSPage(this); + m_graphicsScene->setItemIndexMethod(QGraphicsScene::NoIndex); //this prevents crash when deleting dims. + //scene(view?) indices of dirty regions gets + //out of sync. missing prepareGeometryChange + //somewhere???? QTBUG-18021??? } ViewProviderPage::~ViewProviderPage() { removeMDIView(); //if the MDIViewPage is still in MainWindow, remove it. + m_graphicsScene->deleteLater(); } void ViewProviderPage::attach(App::DocumentObject *pcFeat) @@ -106,14 +111,14 @@ void ViewProviderPage::attach(App::DocumentObject *pcFeat) ViewProviderDocumentObject::attach(pcFeat); auto bnd = boost::bind(&ViewProviderPage::onGuiRepaint, this, bp::_1); - auto feature = getDrawPage(); - if (feature != nullptr) { + TechDraw::DrawPage* feature = dynamic_cast(pcFeat); + if (feature) { connectGuiRepaint = feature->signalGuiPaint.connect(bnd); m_pageName = feature->getNameInDocument(); + m_graphicsScene->setObjectName(QString::fromLocal8Bit(m_pageName.c_str())); } else { Base::Console().Log("VPP::attach has no Feature!\n"); } - } void ViewProviderPage::setDisplayMode(const char* ModeName) @@ -121,46 +126,25 @@ void ViewProviderPage::setDisplayMode(const char* ModeName) ViewProviderDocumentObject::setDisplayMode(ModeName); } -std::vector ViewProviderPage::getDisplayModes(void) const +std::vector ViewProviderPage::getDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderDocumentObject::getDisplayModes(); - StrList.push_back("Drawing"); + StrList.emplace_back("Drawing"); return StrList; } -void ViewProviderPage::show(void) +void ViewProviderPage::onChanged(const App::Property *prop) { - Visibility.setValue(true); - showMDIViewPage(); -} - -void ViewProviderPage::hide(void) -{ - Visibility.setValue(false); - removeMDIView(); - ViewProviderDocumentObject::hide(); -} - -void ViewProviderPage::removeMDIView(void) -{ - if (m_mdiView.isNull()) { - return; + if (prop == &(ShowGrid)) { + setGrid(); + } else if (prop == &(GridSpacing)) { + setGrid(); + } else if (prop == &Visibility) { + //Visibility changes are handled in VPDO::onChanged -> show() or hide() } - //m_mdiView is a QPointer - // https://forum.freecadweb.org/viewtopic.php?f=3&t=22797&p=182614#p182614 - //Gui::getMainWindow()->activatePreviousWindow(); - QList wList= Gui::getMainWindow()->windows(); - if (!wList.contains(m_mdiView)) - return; - - Gui::getMainWindow()->removeWindow(m_mdiView); - Gui::MDIView* aw = Gui::getMainWindow()->activeWindow(); //WF: this bit should be in the remove window logic, not here. - if (aw == nullptr) { - return; - } - aw->showMaximized(); + Gui::ViewProviderDocumentObject::onChanged(prop); } void ViewProviderPage::updateData(const App::Property* prop) @@ -179,10 +163,10 @@ void ViewProviderPage::updateData(const App::Property* prop) signalChangeIcon(); //if the template is changed, rebuild the visual } else if (prop == &(page->Template)) { - if (m_mdiView && - !page->isUnsetting()) { - m_mdiView->matchSceneRectToTemplate(); - m_mdiView->updateTemplate(); + if (!page->isUnsetting()) { + //check if a template has been added to scene first? + m_graphicsScene->matchSceneRectToTemplate(); + m_graphicsScene->updateTemplate(); } } else if (prop == &(page->Label)) { if (m_mdiView && @@ -190,8 +174,8 @@ void ViewProviderPage::updateData(const App::Property* prop) m_mdiView->setTabText(page->Label.getValue()); } } else if (prop == &page->Views) { - if (m_mdiView && !page->isUnsetting()) - m_mdiView->fixOrphans(); + if (!page->isUnsetting()) + m_graphicsScene->fixOrphans(); } Gui::ViewProviderDocumentObject::updateData(prop); @@ -255,12 +239,11 @@ void ViewProviderPage::setupContextMenu(QMenu* menu, QObject* receiver, const ch bool ViewProviderPage::setEdit(int ModNum) { if (ModNum == _SHOWDRAWING) { - Visibility.setValue(true); showMDIViewPage(); // show the drawing return false; //finished editing } else if (ModNum == _TOGGLEUPDATE) { auto page = getDrawPage(); - if (page != nullptr) { + if (page) { page->KeepUpdated.setValue(!page->KeepUpdated.getValue()); page->recomputeFeature(); } @@ -270,44 +253,107 @@ bool ViewProviderPage::setEdit(int ModNum) } } +void ViewProviderPage::unsetEdit(int ModNum) +{ + Q_UNUSED(ModNum); + return; +} + bool ViewProviderPage::doubleClicked(void) { show(); - Gui::getMainWindow()->setActiveWindow(m_mdiView); + if (m_mdiView) { + Gui::getMainWindow()->setActiveWindow(m_mdiView); + } return true; } +void ViewProviderPage::show(void) +{ + showMDIViewPage(); + ViewProviderDocumentObject::show(); +} + +void ViewProviderPage::hide(void) +{ + if (getMDIView()) { + getMDIView()->hide(); //this doesn't remove the mdiViewPage from the mainWindow + removeMDIView(); + } + ViewProviderDocumentObject::hide(); +} + bool ViewProviderPage::showMDIViewPage() { - if (isRestoring() || !Visibility.getValue()) - return true; - if (m_mdiView.isNull()){ - Gui::Document* doc = Gui::Application::Instance->getDocument - (pcObject->getDocument()); - m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow()); - QString tabTitle = QString::fromUtf8(getDrawPage()->Label.getValue()); - - m_mdiView->setDocumentObject(getDrawPage()->getNameInDocument()); - m_mdiView->setDocumentName(pcObject->getDocument()->getName()); - - m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]")); - m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_TreePage")); - Gui::getMainWindow()->addWindow(m_mdiView); - m_mdiView->viewAll(); - m_mdiView->showMaximized(); - m_mdiView->addChildrenToPage(); - m_mdiView->fixOrphans(true); + createMDIViewPage(); + m_graphicsScene->addChildrenToPage(); + m_graphicsScene->updateTemplate(true); + m_graphicsScene->redrawAllViews(); + m_graphicsScene->fixOrphans(true); } else { - m_mdiView->updateTemplate(true); - m_mdiView->redrawAllViews(); - m_mdiView->fixOrphans(true); + m_graphicsScene->redrawAllViews(); + m_graphicsScene->fixOrphans(true); } + m_graphicsView->centerOnPage(); + + m_mdiView->viewAll(); + m_mdiView->showMaximized(); + setGrid(); + Visibility.setValue(true); + return true; } +void ViewProviderPage::createMDIViewPage() +{ + Gui::Document* doc = Gui::Application::Instance->getDocument + (pcObject->getDocument()); + m_mdiView = new MDIViewPage(this, doc, Gui::getMainWindow()); + if (m_graphicsView == nullptr) { + m_graphicsView = new QGVPage(this, m_graphicsScene, m_mdiView); + std::string objName = m_pageName + "View"; + m_graphicsView->setObjectName(QString::fromLocal8Bit(objName.c_str())); + } + m_mdiView->setScene(m_graphicsScene, m_graphicsView); + QString tabTitle = QString::fromUtf8(getDrawPage()->Label.getValue()); + + m_mdiView->setDocumentObject(getDrawPage()->getNameInDocument()); + m_mdiView->setDocumentName(pcObject->getDocument()->getName()); + + m_mdiView->setWindowTitle(tabTitle + QString::fromLatin1("[*]")); + m_mdiView->setWindowIcon(Gui::BitmapFactory().pixmap("TechDraw_TreePage")); + Gui::getMainWindow()->addWindow(m_mdiView); + Gui::getMainWindow()->setActiveWindow(m_mdiView); +} + +//NOTE: removing MDIViewPage (parent) destroys QGVPage (eventually) +void ViewProviderPage::removeMDIView(void) +{ + if (!m_mdiView.isNull()) { //m_mdiView is a QPointer + QList wList= Gui::getMainWindow()->windows(); + if (wList.contains(m_mdiView)) { + Gui::getMainWindow()->removeWindow(m_mdiView); + m_mdiView = nullptr; //m_mdiView will eventually be deleted and + m_graphicsView = nullptr; //will take m_graphicsView with it + Gui::MDIView* aw = Gui::getMainWindow()->activeWindow(); //WF: this bit should be in the remove window logic, not here. + if (aw != nullptr) { + aw->showMaximized(); + } + } + } +} + +MDIViewPage* ViewProviderPage::getMDIViewPage() const +{ + if (m_mdiView.isNull()) { + return nullptr; + } + return m_mdiView; +} + std::vector ViewProviderPage::claimChildren(void) const { std::vector temp; @@ -337,8 +383,8 @@ std::vector ViewProviderPage::claimChildren(void) const App::DocumentObject *docObj = *it; //DrawRichAnno with no parent is child of Page TechDraw::DrawRichAnno* dra = dynamic_cast (*it); - if (dra != nullptr) { - if (dra->AnnoParent.getValue() == nullptr) { + if (dra) { + if (!dra->AnnoParent.getValue()) { temp.push_back(*it); //no parent, belongs to page } continue; //has a parent somewhere else @@ -363,56 +409,12 @@ std::vector ViewProviderPage::claimChildren(void) const } } -void ViewProviderPage::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - static_cast(showMDIViewPage()); - return; -} - - -MDIViewPage* ViewProviderPage::getMDIViewPage() const -{ - if (m_mdiView.isNull()) { - Base::Console().Log("INFO - ViewProviderPage::getMDIViewPage has no m_mdiView!\n"); - return nullptr; - } - - return m_mdiView; -} - - -void ViewProviderPage::onChanged(const App::Property *prop) -{ - if (prop == &(ShowGrid) || prop == &(GridSpacing)) { - setGrid(); - } - Gui::ViewProviderDocumentObject::onChanged(prop); -} - -void ViewProviderPage::startRestoring() -{ - m_docReady = false; - Gui::ViewProviderDocumentObject::startRestoring(); -} - -void ViewProviderPage::finishRestoring() -{ - m_docReady = true; - //control drawing opening on restore based on Preference - //mantis #2967 ph2 - don't even show blank page - if (getDrawPage()->canUpdate()) { - static_cast(showMDIViewPage()); - } - Gui::ViewProviderDocumentObject::finishRestoring(); -} - bool ViewProviderPage::isShow(void) const { return Visibility.getValue(); } -bool ViewProviderPage::getFrameState(void) +bool ViewProviderPage::getFrameState() { return ShowFrames.getValue(); } @@ -422,10 +424,10 @@ void ViewProviderPage::setFrameState(bool state) ShowFrames.setValue(state); } -void ViewProviderPage::toggleFrameState(void) +void ViewProviderPage::toggleFrameState() { // Base::Console().Message("VPP::toggleFrameState()\n"); - if (m_graphicsScene != nullptr) { + if (m_graphicsScene) { setFrameState(!getFrameState()); m_graphicsScene->refreshViews(); setTemplateMarkers(getFrameState()); @@ -443,22 +445,12 @@ void ViewProviderPage::setTemplateMarkers(bool state) if (vpt) { vpt->setMarkers(state); QGITemplate* t = vpt->getQTemplate(); - if (t != nullptr) { + if (t) { t->updateView(true); } } } -void ViewProviderPage::setGraphicsView(QGVPage* gv) -{ - m_graphicsView = gv; -} - -void ViewProviderPage::setGraphicsScene(QGSPage* gs) -{ - m_graphicsScene = gs; -} - bool ViewProviderPage::canDelete(App::DocumentObject *obj) const { // deletions from a page don't necessarily destroy anything @@ -473,9 +465,9 @@ bool ViewProviderPage::canDelete(App::DocumentObject *obj) const void ViewProviderPage::onGuiRepaint(const TechDraw::DrawPage* dp) { if (dp == getDrawPage()) { - if (!m_mdiView.isNull() && - !getDrawPage()->isUnsetting()) { - m_mdiView->fixOrphans(); + //this signal is for us + if (!getDrawPage()->isUnsetting()) { + m_graphicsScene->fixOrphans(); } } } @@ -484,7 +476,7 @@ TechDraw::DrawPage* ViewProviderPage::getDrawPage() const { //during redo, pcObject can become invalid, but non-zero?? if (!pcObject) { - Base::Console().Message("TROUBLE - VPPage::getDrawPage - no Page Object!\n"); + Base::Console().Log("VPP::getDrawPage - no Page Object!\n"); return nullptr; } return dynamic_cast(pcObject); @@ -492,11 +484,10 @@ TechDraw::DrawPage* ViewProviderPage::getDrawPage() const Gui::MDIView *ViewProviderPage::getMDIView() const { - const_cast(this)->showMDIViewPage(); return m_mdiView.data(); } -void ViewProviderPage::setGrid(void) +void ViewProviderPage::setGrid() { TechDraw::DrawPage* dp = getDrawPage(); if (!dp) { @@ -509,7 +500,7 @@ void ViewProviderPage::setGrid(void) pageWidth = dp->getPageWidth(); pageHeight = dp->getPageHeight(); } - QGVPage* widget = getGraphicsView(); + QGVPage* widget = getQGVPage(); if (widget) { if (ShowGrid.getValue()) { widget->showGrid(true); diff --git a/src/Mod/TechDraw/Gui/ViewProviderPage.h b/src/Mod/TechDraw/Gui/ViewProviderPage.h index 5c6e4cef7d..546171a3e4 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderPage.h +++ b/src/Mod/TechDraw/Gui/ViewProviderPage.h @@ -26,13 +26,13 @@ #include -#include +#include #include +#include #include #include - namespace TechDraw{ class DrawPage; } @@ -51,37 +51,36 @@ public: /// constructor ViewProviderPage(); /// destructor - virtual ~ViewProviderPage(); + ~ViewProviderPage() override; App::PropertyBool ShowFrames; App::PropertyBool ShowGrid; App::PropertyDistance GridSpacing; - virtual void attach(App::DocumentObject *) override; - virtual void setDisplayMode(const char* ModeName) override; - virtual bool useNewSelectionModel(void) const override {return false;} + void attach(App::DocumentObject *) override; + void setDisplayMode(const char* ModeName) override; + bool useNewSelectionModel() const override {return false;} /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const override; + std::vector getDisplayModes() const override; /// Hides the view provider - virtual void hide(void) override; + void hide() override; /// Shows the view provider - virtual void show(void) override; - virtual bool isShow(void) const override; + void show() override; + bool isShow() const override; /// Claim all the views for the page - std::vector claimChildren(void) const override; + std::vector claimChildren() const override; /// Is called by the tree if the user double click on the object - virtual bool doubleClicked(void) override; + bool doubleClicked() override; void setupContextMenu(QMenu*, QObject*, const char*) override; - virtual bool onDelete(const std::vector &) override; - virtual void onChanged(const App::Property *prop) override; - virtual void updateData(const App::Property* prop) override; - virtual void startRestoring() override; - virtual void finishRestoring() override; - bool isRestoring(void) {return !m_docReady;} + bool onDelete(const std::vector &) override; + void onChanged(const App::Property *prop) override; + void updateData(const App::Property* prop) override; TechDraw::DrawPage* getDrawPage() const; + + //slots & connections void onGuiRepaint(const TechDraw::DrawPage* dp); typedef boost::signals2::scoped_connection Connection; Connection connectGuiRepaint; @@ -89,27 +88,28 @@ public: void unsetEdit(int ModNum) override; MDIViewPage* getMDIViewPage() const; bool showMDIViewPage(); - void removeMDIView(void); + void removeMDIView(); - virtual Gui::MDIView *getMDIView() const override; + Gui::MDIView *getMDIView() const override; - bool getFrameState(void); + bool getFrameState(); void setFrameState(bool state); - void toggleFrameState(void); + void toggleFrameState(); void setTemplateMarkers(bool state); - QGVPage *getGraphicsView() { return m_graphicsView; } - QGSPage* getGraphicsScene() { return m_graphicsScene; } - void setGraphicsView(QGVPage* gv); - void setGraphicsScene(QGSPage* gs); - virtual bool canDelete(App::DocumentObject* obj) const override; - void setGrid(void); + + bool canDelete(App::DocumentObject* obj) const override; + + void setGrid(); + + QGSPage* getQGSPage(void) {return m_graphicsScene;} + QGVPage* getQGVPage(void) {return m_graphicsView;} protected: bool setEdit(int ModNum) override; + void createMDIViewPage(); private: QPointer m_mdiView; - bool m_docReady; std::string m_pageName; QGVPage* m_graphicsView; QGSPage* m_graphicsScene; diff --git a/src/Mod/TechDraw/Gui/ViewProviderProjGroup.cpp b/src/Mod/TechDraw/Gui/ViewProviderProjGroup.cpp index bf777f9964..31b23ab2d9 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderProjGroup.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderProjGroup.cpp @@ -59,35 +59,14 @@ ViewProviderProjGroup::~ViewProviderProjGroup() { } -void ViewProviderProjGroup::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderProjGroup::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderProjGroup::getDisplayModes(void) const +std::vector ViewProviderProjGroup::getDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - StrList.push_back("Drawing"); + StrList.emplace_back("Drawing"); return StrList; } -void ViewProviderProjGroup::updateData(const App::Property* prop) -{ - ViewProviderDrawingView::updateData(prop); - } - -void ViewProviderProjGroup::onChanged(const App::Property *prop) -{ - ViewProviderDrawingView::onChanged(prop); -} - void ViewProviderProjGroup::setupContextMenu(QMenu* menu, QObject* receiver, const char* member) { Q_UNUSED(menu); @@ -120,18 +99,7 @@ bool ViewProviderProjGroup::setEdit(int ModNum) return true; } -void ViewProviderProjGroup::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - -bool ViewProviderProjGroup::doubleClicked(void) +bool ViewProviderProjGroup::doubleClicked() { setEdit(0); return true; @@ -158,21 +126,21 @@ bool ViewProviderProjGroup::onDelete(const std::vector &) // add names to a list if (!viewSection.empty()) { for (auto SecIterator : viewSection) { - ViewList.push_back(SecIterator->Label.getValue()); + ViewList.emplace_back(SecIterator->Label.getValue()); } } // get its detail views auto viewDetail = Item->getDetailRefs(); if (!viewDetail.empty()) { for (auto DetIterator : viewDetail) { - ViewList.push_back(DetIterator->Label.getValue()); + ViewList.emplace_back(DetIterator->Label.getValue()); } } // get its leader lines auto viewLead = Item->getLeaders(); if (!viewLead.empty()) { for (auto LeadIterator : viewLead) { - ViewList.push_back(LeadIterator->Label.getValue()); + ViewList.emplace_back(LeadIterator->Label.getValue()); } } } @@ -182,7 +150,7 @@ bool ViewProviderProjGroup::onDelete(const std::vector &) bodyMessageStream << qApp->translate("Std_Delete", "The group cannot be deleted because its items have the following\nsection or detail views, or leader lines that would get broken:"); bodyMessageStream << '\n'; - for (auto ListIterator : ViewList) + for (const auto& ListIterator : ViewList) bodyMessageStream << '\n' << QString::fromUtf8(ListIterator.c_str()); QMessageBox::warning(Gui::getMainWindow(), qApp->translate("Std_Delete", "Object dependencies"), bodyMessage, @@ -221,7 +189,7 @@ bool ViewProviderProjGroup::canDelete(App::DocumentObject *obj) const return true; } -std::vector ViewProviderProjGroup::claimChildren(void) const +std::vector ViewProviderProjGroup::claimChildren() const { // Collect any child fields std::vector temp; diff --git a/src/Mod/TechDraw/Gui/ViewProviderProjGroup.h b/src/Mod/TechDraw/Gui/ViewProviderProjGroup.h index a8cbd6c612..bf4799323e 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderProjGroup.h +++ b/src/Mod/TechDraw/Gui/ViewProviderProjGroup.h @@ -22,6 +22,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERVIEWGROUP_H #define DRAWINGGUI_VIEWPROVIDERVIEWGROUP_H + +#include #include @@ -32,36 +34,31 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderProjGroup : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderProjGroup); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderProjGroup); public: ViewProviderProjGroup(); /// constructor - ~ViewProviderProjGroup(); /// destructor + ~ViewProviderProjGroup() override; /// destructor - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} + bool useNewSelectionModel() const override {return false;} /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; /// Claim all the views for the page - std::vector claimChildren(void) const; + std::vector claimChildren() const override; /// Is called by the tree if the user double click on the object - virtual bool doubleClicked(void); - void setupContextMenu(QMenu*, QObject*, const char*); - virtual void updateData(const App::Property*); + bool doubleClicked() override; + void setupContextMenu(QMenu*, QObject*, const char*) override; TechDraw::DrawProjGroup* getObject() const; - virtual TechDraw::DrawProjGroup* getViewObject() const; - void unsetEdit(int ModNum); - virtual void onChanged(const App::Property *prop); - virtual bool onDelete(const std::vector &); - virtual bool canDelete(App::DocumentObject* obj) const; + TechDraw::DrawProjGroup* getViewObject() const override; + bool onDelete(const std::vector &) override; + bool canDelete(App::DocumentObject* obj) const override; protected: - bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; diff --git a/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.cpp b/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.cpp index 5122385c74..ee0ff441d5 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.cpp @@ -51,22 +51,11 @@ ViewProviderProjGroupItem::~ViewProviderProjGroupItem() { } -void ViewProviderProjGroupItem::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderViewPart::attach(pcFeat); -} - -void ViewProviderProjGroupItem::setDisplayMode(const char* ModeName) -{ - ViewProviderViewPart::setDisplayMode(ModeName); -} - -std::vector ViewProviderProjGroupItem::getDisplayModes(void) const +std::vector ViewProviderProjGroupItem::getDisplayModes() const { // get the modes of the father std::vector StrList = ViewProviderViewPart::getDisplayModes(); - StrList.push_back("Drawing"); + StrList.emplace_back("Drawing"); return StrList; } @@ -129,7 +118,7 @@ void ViewProviderProjGroupItem::unsetEdit(int ModNum) Gui::Control().closeDialog(); } -bool ViewProviderProjGroupItem::doubleClicked(void) +bool ViewProviderProjGroupItem::doubleClicked() { return true; } @@ -149,7 +138,7 @@ bool ViewProviderProjGroupItem::onDelete(const std::vector &) // get the projection TechDraw::DrawProjGroupItem* proj = getObject(); // check if it is the anchor projection - if ((dpg != nullptr) && (dpg->hasProjection(proj->Type.getValueAsString())) + if (dpg && (dpg->hasProjection(proj->Type.getValueAsString())) && (dpg->getAnchor() == dpgi)) isAnchor = true; diff --git a/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.h b/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.h index a374bd591f..238d686dc5 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.h +++ b/src/Mod/TechDraw/Gui/ViewProviderProjGroupItem.h @@ -22,6 +22,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERVIEWGROUPITEM_H #define DRAWINGGUI_VIEWPROVIDERVIEWGROUPITEM_H + +#include #include @@ -33,32 +35,30 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderProjGroupItem: public ViewProviderViewPart { - PROPERTY_HEADER(TechDrawGui::ViewProviderProjGroupItem); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderProjGroupItem); public: ViewProviderProjGroupItem(); - ~ViewProviderProjGroupItem(); + ~ViewProviderProjGroupItem() override; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} + bool useNewSelectionModel() const override {return false;} /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; + std::vector getDisplayModes() const override; /// Is called by the tree if the user double click on the object - virtual bool doubleClicked(void); - void setupContextMenu(QMenu*, QObject*, const char*); - virtual void updateData(const App::Property*); + bool doubleClicked() override; + void setupContextMenu(QMenu*, QObject*, const char*) override; + void updateData(const App::Property*) override; - virtual TechDraw::DrawProjGroupItem* getViewObject() const; + TechDraw::DrawProjGroupItem* getViewObject() const override; TechDraw::DrawProjGroupItem* getObject() const; - void unsetEdit(int ModNum); - virtual bool onDelete(const std::vector &); - virtual bool canDelete(App::DocumentObject* obj) const; + void unsetEdit(int ModNum) override; + bool onDelete(const std::vector &) override; + bool canDelete(App::DocumentObject* obj) const override; protected: - bool setEdit(int ModNum); + bool setEdit(int ModNum) override; }; diff --git a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp index 1d31f2c45a..4a3ccc77c8 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.cpp @@ -21,12 +21,8 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include #include #include @@ -37,6 +33,8 @@ #include "PreferencesGui.h" #include "QGIView.h" #include "TaskRichAnno.h" +#include "QGSPage.h" +#include "ViewProviderPage.h" #include "ViewProviderRichAnno.h" using namespace TechDrawGui; @@ -72,37 +70,7 @@ ViewProviderRichAnno::~ViewProviderRichAnno() { } -void ViewProviderRichAnno::attach(App::DocumentObject *pcFeat) -{ - ViewProviderDrawingView::attach(pcFeat); -} - -bool ViewProviderRichAnno::setEdit(int ModNum) -{ -// Base::Console().Message("VPRA::setEdit(%d)\n",ModNum); - if (ModNum != ViewProvider::Default ) { - return ViewProviderDrawingView::setEdit(ModNum); - } - if (Gui::Control().activeDialog()) { //TaskPanel already open! - return false; - } - Gui::Selection().clearSelection(); - Gui::Control().showDialog(new TaskDlgRichAnno(this)); - return true; -} - -void ViewProviderRichAnno::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - -bool ViewProviderRichAnno::doubleClicked(void) +bool ViewProviderRichAnno::doubleClicked() { // Base::Console().Message("VPRA::doubleClicked()\n"); setEdit(ViewProvider::Default); @@ -112,7 +80,7 @@ bool ViewProviderRichAnno::doubleClicked(void) void ViewProviderRichAnno::updateData(const App::Property* p) { // only if there is a frame we can enable the frame line parameters - if (getViewObject() != nullptr) { + if (getViewObject()) { if (getViewObject()->ShowFrame.getValue()) { LineWidth.setStatus(App::Property::ReadOnly, false); LineStyle.setStatus(App::Property::ReadOnly, false); @@ -124,6 +92,15 @@ void ViewProviderRichAnno::updateData(const App::Property* p) LineColor.setStatus(App::Property::ReadOnly, true); } } + + if (p == &(getViewObject()->AnnoParent)) { +// Base::Console().Message("VPRA::updateData(AnnoParent) - vpp: %X\n", getViewProviderPage()); + if (getViewProviderPage() && + getViewProviderPage()->getQGSPage()) { + getViewProviderPage()->getQGSPage()->setRichAnnoGroups(); + } + } + ViewProviderDrawingView::updateData(p); } @@ -151,12 +128,12 @@ TechDraw::DrawRichAnno* ViewProviderRichAnno::getFeature() const return dynamic_cast(pcObject); } -App::Color ViewProviderRichAnno::getDefLineColor(void) +App::Color ViewProviderRichAnno::getDefLineColor() { return PreferencesGui::leaderColor(); } -std::string ViewProviderRichAnno::getDefFont(void) +std::string ViewProviderRichAnno::getDefFont() { return Preferences::labelFont(); } @@ -166,13 +143,9 @@ double ViewProviderRichAnno::getDefFontSize() return Preferences::dimFontSizeMM(); } -double ViewProviderRichAnno::getDefLineWeight(void) +double ViewProviderRichAnno::getDefLineWeight() { - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double result = lg->getWeight("Graphics"); - delete lg; - return result; + return TechDraw::LineGroup::getDefaultWidth("Graphics"); } void ViewProviderRichAnno::handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property *prop) diff --git a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h index b58b235bf8..2d3e37998c 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h +++ b/src/Mod/TechDraw/Gui/ViewProviderRichAnno.h @@ -24,6 +24,8 @@ #ifndef TECHDRAWGUI_VIEWPROVIDERRICHANNO_H #define TECHDRAWGUI_VIEWPROVIDERRICHANNO_H +#include + #include #include @@ -38,38 +40,37 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderRichAnno : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderRichAnno); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderRichAnno); public: /// constructor ViewProviderRichAnno(); /// destructor - virtual ~ViewProviderRichAnno(); + ~ViewProviderRichAnno() override; App::PropertyLength LineWidth; App::PropertyEnumeration LineStyle; App::PropertyColor LineColor; - virtual void attach(App::DocumentObject *); - virtual bool useNewSelectionModel(void) const {return false;} - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property* p); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); - virtual bool canDelete(App::DocumentObject* obj) const; + bool useNewSelectionModel() const override {return false;} + void updateData(const App::Property*) override; + void onChanged(const App::Property* p) override; + bool doubleClicked() override; + bool canDelete(App::DocumentObject* obj) const override; static const char* LineStyleEnums[]; - virtual TechDraw::DrawRichAnno* getViewObject() const; + TechDraw::DrawRichAnno* getViewObject() const override; TechDraw::DrawRichAnno* getFeature() const; protected: - App::Color getDefLineColor(void); - std::string getDefFont(void); - double getDefFontSize(void); - double getDefLineWeight(void); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + App::Color getDefLineColor(); + std::string getDefFont(); + double getDefFontSize(); + double getDefLineWeight(); + void handleChangedPropertyType(Base::XMLReader &reader, + const char *TypeName, + App::Property * prop) override; private: static App::PropertyIntegerConstraint::Constraints LineStyleRange; diff --git a/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.cpp b/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.cpp index 30128fd422..650530e595 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.cpp @@ -20,12 +20,8 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include #include "ViewProviderSpreadsheet.h" @@ -45,30 +41,6 @@ ViewProviderSpreadsheet::~ViewProviderSpreadsheet() { } -void ViewProviderSpreadsheet::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderSymbol::attach(pcFeat); -} - -void ViewProviderSpreadsheet::setDisplayMode(const char* ModeName) -{ - ViewProviderSymbol::setDisplayMode(ModeName); -} - -std::vector ViewProviderSpreadsheet::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderSymbol::getDisplayModes(); - - return StrList; -} - -void ViewProviderSpreadsheet::updateData(const App::Property* prop) -{ - ViewProviderSymbol::updateData(prop); -} - TechDraw::DrawViewSpreadsheet* ViewProviderSpreadsheet::getViewObject() const { return dynamic_cast(pcObject); diff --git a/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.h b/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.h index fe67fffeee..6675cc0d30 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.h +++ b/src/Mod/TechDraw/Gui/ViewProviderSpreadsheet.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERSPREADSHEET_H #define DRAWINGGUI_VIEWPROVIDERSPREADSHEET_H +#include + #include #include "ViewProviderSymbol.h" @@ -33,23 +35,17 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderSpreadsheet : public ViewProviderSymbol { - PROPERTY_HEADER(TechDrawGui::ViewProviderSpreadsheet); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderSpreadsheet); public: /// constructor ViewProviderSpreadsheet(); /// destructor - virtual ~ViewProviderSpreadsheet(); + ~ViewProviderSpreadsheet() override; + bool useNewSelectionModel() const override {return false;} - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - - virtual TechDraw::DrawViewSpreadsheet* getViewObject() const; + TechDraw::DrawViewSpreadsheet* getViewObject() const override; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp b/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp index b9f3f25c90..44ce3d8dbf 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderSymbol.cpp @@ -21,12 +21,8 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include #include "ViewProviderSymbol.h" @@ -46,27 +42,17 @@ ViewProviderSymbol::~ViewProviderSymbol() { } -void ViewProviderSymbol::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderSymbol::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderSymbol::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - void ViewProviderSymbol::updateData(const App::Property* prop) { + if (prop == &getViewObject()->Scale) { + onGuiRepaint(getViewObject()); + } else if (prop == &getViewObject()->Rotation) { + onGuiRepaint(getViewObject()); + } else if (prop == &getViewObject()->Symbol) { + onGuiRepaint(getViewObject()); + } else if (prop == &getViewObject()->EditableTexts) { + onGuiRepaint(getViewObject()); + } ViewProviderDrawingView::updateData(prop); } diff --git a/src/Mod/TechDraw/Gui/ViewProviderSymbol.h b/src/Mod/TechDraw/Gui/ViewProviderSymbol.h index ed634c41ff..23053c601f 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderSymbol.h +++ b/src/Mod/TechDraw/Gui/ViewProviderSymbol.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERSYMBOL_H #define DRAWINGGUI_VIEWPROVIDERSYMBOL_H +#include + #include #include "ViewProviderDrawingView.h" @@ -33,45 +35,40 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderSymbol : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderSymbol); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderSymbol); public: /// constructor ViewProviderSymbol(); /// destructor - virtual ~ViewProviderSymbol(); + ~ViewProviderSymbol() override; + bool useNewSelectionModel() const override {return false;} + void updateData(const App::Property*) override; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - - virtual TechDraw::DrawViewSymbol* getViewObject() const; + TechDraw::DrawViewSymbol* getViewObject() const override; }; class TechDrawGuiExport ViewProviderDraft : public ViewProviderSymbol { - PROPERTY_HEADER(TechDrawGui::ViewProviderDraft); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderDraft); public: /// constructor ViewProviderDraft(); /// destructor - virtual ~ViewProviderDraft(); + ~ViewProviderDraft() override; }; class TechDrawGuiExport ViewProviderArch : public ViewProviderSymbol { - PROPERTY_HEADER(TechDrawGui::ViewProviderArch); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderArch); public: /// constructor ViewProviderArch(); /// destructor - virtual ~ViewProviderArch(); + ~ViewProviderArch() override; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp b/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp index 76b4ee5536..c13f235085 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderTemplate.cpp @@ -67,35 +67,16 @@ ViewProviderTemplate::~ViewProviderTemplate() { } -void ViewProviderTemplate::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDocumentObject::attach(pcFeat); -} - -void ViewProviderTemplate::setDisplayMode(const char* ModeName) -{ - ViewProviderDocumentObject::setDisplayMode(ModeName); -} - -std::vector ViewProviderTemplate::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDocumentObject::getDisplayModes(); - - return StrList; -} - void ViewProviderTemplate::updateData(const App::Property* prop) { if (getTemplate()->isDerivedFrom(TechDraw::DrawSVGTemplate::getClassTypeId())) { auto t = static_cast(getTemplate()); if (prop == &(t->Template)) { - MDIViewPage* mdi = getMDIViewPage(); - if (mdi != nullptr) { - mdi->attachTemplate(t); - mdi->viewAll(); - mdi->getViewProviderPage()->setGrid(); + auto page = t->getParentPage(); + Gui::ViewProvider* vp = Gui::Application::Instance->getDocument(t->getDocument())->getViewProvider(page); + TechDrawGui::ViewProviderPage* vpp = dynamic_cast(vp); + if (vpp) { + vpp->getQGSPage()->attachTemplate(t); } } } @@ -121,38 +102,40 @@ void ViewProviderTemplate::onChanged(const App::Property *prop) Gui::ViewProviderDocumentObject::onChanged(prop); } -void ViewProviderTemplate::show(void) +void ViewProviderTemplate::show() { QGITemplate* qTemplate = getQTemplate(); - if (qTemplate != nullptr) { + if (qTemplate) { qTemplate->show(); } ViewProviderDocumentObject::show(); } -void ViewProviderTemplate::hide(void) +void ViewProviderTemplate::hide() { QGITemplate* qTemplate = getQTemplate(); - if (qTemplate != nullptr) { + if (qTemplate) { qTemplate->hide(); } ViewProviderDocumentObject::hide(); } -bool ViewProviderTemplate::isShow(void) const +bool ViewProviderTemplate::isShow() const { return Visibility.getValue(); } -QGITemplate* ViewProviderTemplate::getQTemplate(void) +QGITemplate* ViewProviderTemplate::getQTemplate() { TechDraw::DrawTemplate* dt = getTemplate(); if (dt) { - MDIViewPage* mdi = getMDIViewPage(); - if (mdi != nullptr) { - return mdi->getQGSPage()->getTemplate(); + auto page = dt->getParentPage(); + Gui::ViewProvider* vp = Gui::Application::Instance->getDocument(dt->getDocument())->getViewProvider(page); + TechDrawGui::ViewProviderPage* vpp = dynamic_cast(vp); + if (vpp != nullptr) { + return vpp->getQGSPage()->getTemplate(); } } return nullptr; @@ -163,7 +146,7 @@ void ViewProviderTemplate::setMarkers(bool state) // Base::Console().Message("VPT::setMarkers(%d)\n",state); QGITemplate* qTemplate = getQTemplate(); QGISVGTemplate* qSvgTemplate = dynamic_cast (qTemplate); - if (qSvgTemplate != nullptr) { + if (qSvgTemplate) { std::vector textFields = qSvgTemplate->getTextFields(); for (auto& t:textFields) { if (state) { @@ -205,7 +188,7 @@ bool ViewProviderTemplate::onDelete(const std::vector &) return false; } -MDIViewPage* ViewProviderTemplate::getMDIViewPage(void) const +MDIViewPage* ViewProviderTemplate::getMDIViewPage() const { auto t = getTemplate(); auto page = t->getParentPage(); diff --git a/src/Mod/TechDraw/Gui/ViewProviderTemplate.h b/src/Mod/TechDraw/Gui/ViewProviderTemplate.h index 2fbb149ef2..b06ca8832a 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderTemplate.h +++ b/src/Mod/TechDraw/Gui/ViewProviderTemplate.h @@ -22,7 +22,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERTEMPLATE_H #define DRAWINGGUI_VIEWPROVIDERTEMPLATE_H - + +#include namespace TechDraw{ class DrawTemplate; @@ -42,11 +43,7 @@ public: /// destructor virtual ~ViewProviderTemplate(); - virtual void attach(App::DocumentObject *) override; - virtual void setDisplayMode(const char* ModeName) override; virtual bool useNewSelectionModel(void) const override {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const override; virtual void updateData(const App::Property*) override; virtual void onChanged(const App::Property *prop) override; virtual void hide(void) override; diff --git a/src/Mod/TechDraw/Gui/ViewProviderTile.cpp b/src/Mod/TechDraw/Gui/ViewProviderTile.cpp index fd8c0dfc0c..885300e727 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderTile.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderTile.cpp @@ -20,12 +20,8 @@ * * ***************************************************************************/ - #include "PreCompiled.h" -#ifndef _PreComp_ -#endif - #include #include "ViewProviderTile.h" @@ -45,30 +41,6 @@ ViewProviderTile::~ViewProviderTile() { } -void ViewProviderTile::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDocumentObject::attach(pcFeat); -} - -void ViewProviderTile::setDisplayMode(const char* ModeName) -{ - ViewProviderDocumentObject::setDisplayMode(ModeName); -} - -std::vector ViewProviderTile::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDocumentObject::getDisplayModes(); - - return StrList; -} - -void ViewProviderTile::updateData(const App::Property* prop) -{ - ViewProviderDocumentObject::updateData(prop); -} - //TechDraw::DrawTile* ViewProviderTile::getViewObject() const //{ // return dynamic_cast(pcObject); diff --git a/src/Mod/TechDraw/Gui/ViewProviderTile.h b/src/Mod/TechDraw/Gui/ViewProviderTile.h index 815a9ec67b..4e1e6d0ccf 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderTile.h +++ b/src/Mod/TechDraw/Gui/ViewProviderTile.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERTILE_H #define DRAWINGGUI_VIEWPROVIDERTILE_H +#include + #include #include @@ -30,22 +32,16 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderTile : public Gui::ViewProviderDocumentObject { - PROPERTY_HEADER(TechDrawGui::ViewProviderTile); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderTile); public: /// constructor ViewProviderTile(); /// destructor - virtual ~ViewProviderTile(); + ~ViewProviderTile() override; - - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - virtual bool canDelete(App::DocumentObject *obj) const; + bool useNewSelectionModel() const override {return false;} + bool canDelete(App::DocumentObject *obj) const override; /* virtual TechDraw::DrawTile* getViewObject() const;*/ virtual TechDraw::DrawTile* getFeature() const; diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewClip.cpp b/src/Mod/TechDraw/Gui/ViewProviderViewClip.cpp index fbd4736f3b..30369092d5 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewClip.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderViewClip.cpp @@ -50,30 +50,7 @@ ViewProviderViewClip::~ViewProviderViewClip() { } -void ViewProviderViewClip::updateData(const App::Property* prop) -{ - ViewProviderDrawingView::updateData(prop); -} - -void ViewProviderViewClip::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderViewClip::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderViewClip::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList; - return StrList; -} - -std::vector ViewProviderViewClip::claimChildren(void) const +std::vector ViewProviderViewClip::claimChildren() const { // Collect any child views // for Clip, valid children are any View in Views @@ -81,7 +58,7 @@ std::vector ViewProviderViewClip::claimChildren(void) cons return views; } -void ViewProviderViewClip::show(void) +void ViewProviderViewClip::show() { //TODO: not sure that clip members need to be touched when hiding clip group App::DocumentObject* obj = getObject(); @@ -96,7 +73,7 @@ void ViewProviderViewClip::show(void) } -void ViewProviderViewClip::hide(void) +void ViewProviderViewClip::hide() { //TODO: not sure that clip members need to be touched when hiding clip group App::DocumentObject* obj = getObject(); @@ -110,11 +87,6 @@ void ViewProviderViewClip::hide(void) ViewProviderDrawingView::hide(); } -bool ViewProviderViewClip::isShow(void) const -{ - return Visibility.getValue(); -} - bool ViewProviderViewClip::canDelete(App::DocumentObject *obj) const { // deletions of Clip objects don't destroy anything diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewClip.h b/src/Mod/TechDraw/Gui/ViewProviderViewClip.h index dfe78f3fc2..123b33bafd 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewClip.h +++ b/src/Mod/TechDraw/Gui/ViewProviderViewClip.h @@ -24,6 +24,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERCLIP_H #define DRAWINGGUI_VIEWPROVIDERCLIP_H +#include + #include #include "ViewProviderDrawingView.h" @@ -33,32 +35,26 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderViewClip : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderViewClip); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderViewClip); public: /// constructor ViewProviderViewClip(); /// destructor - virtual ~ViewProviderViewClip(); + ~ViewProviderViewClip() override; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; + bool useNewSelectionModel() const override {return false;} - virtual TechDraw::DrawViewClip* getViewObject() const; + TechDraw::DrawViewClip* getViewObject() const override; TechDraw::DrawViewClip* getObject() const; - virtual void updateData(const App::Property* prop); /// Hide the object in the view - virtual void hide(void); + void hide() override; /// Show the object in the view - virtual void show(void); - virtual bool isShow(void) const; - std::vector claimChildren(void) const; + void show() override; + std::vector claimChildren() const override; - virtual bool canDelete(App::DocumentObject* obj) const; + bool canDelete(App::DocumentObject* obj) const override; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp b/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp index 52ff4c2c20..085aa4eda2 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderViewPart.cpp @@ -78,21 +78,18 @@ ViewProviderViewPart::ViewProviderViewPart() static const char *hgroup = "Highlight"; //default line weights - int lgNumber = Preferences::lineGroup(); - auto lg = TechDraw::LineGroup::lineGroupFactory(lgNumber); - double weight = lg->getWeight("Thick"); + double weight = TechDraw::LineGroup::getDefaultWidth("Thick"); ADD_PROPERTY_TYPE(LineWidth,(weight),group,App::Prop_None,"The thickness of visible lines (line groups xx.2"); - weight = lg->getWeight("Thin"); + weight = TechDraw::LineGroup::getDefaultWidth("Thin"); ADD_PROPERTY_TYPE(HiddenWidth,(weight),group,App::Prop_None,"The thickness of hidden lines, if enabled (line groups xx.1)"); - weight = lg->getWeight("Graphic"); + weight = TechDraw::LineGroup::getDefaultWidth("Graphic"); ADD_PROPERTY_TYPE(IsoWidth,(weight),group,App::Prop_None,"The thickness of isoparameter lines, if enabled"); - weight = lg->getWeight("Extra"); + weight = TechDraw::LineGroup::getDefaultWidth("Extra"); ADD_PROPERTY_TYPE(ExtraWidth,(weight),group,App::Prop_None,"The thickness of LineGroup Extra lines, if enabled"); - delete lg; //Coverity CID 174664 Base::Reference hGrp = App::GetApplication().GetUserParameter().GetGroup("BaseApp")-> GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); @@ -130,11 +127,6 @@ ViewProviderViewPart::~ViewProviderViewPart() } -void ViewProviderViewPart::updateData(const App::Property* prop) -{ - ViewProviderDrawingView::updateData(prop); -} - void ViewProviderViewPart::onChanged(const App::Property* prop) { if (prop == &(LineWidth) || @@ -166,30 +158,16 @@ void ViewProviderViewPart::attach(App::DocumentObject *pcFeat) { TechDraw::DrawViewMulti* dvm = dynamic_cast(pcFeat); TechDraw::DrawViewDetail* dvd = dynamic_cast(pcFeat); - if (dvm != nullptr) { + if (dvm) { sPixmap = "TechDraw_TreeMulti"; - } else if (dvd != nullptr) { + } else if (dvd) { sPixmap = "actions/TechDraw_DetailView"; } ViewProviderDrawingView::attach(pcFeat); } -void ViewProviderViewPart::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderViewPart::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - - -std::vector ViewProviderViewPart::claimChildren(void) const +std::vector ViewProviderViewPart::claimChildren() const { // Collect any child Document Objects and put them in the right place in the Feature tree // valid children of a ViewPart are: @@ -244,7 +222,7 @@ bool ViewProviderViewPart::setEdit(int ModNum) } TechDraw::DrawViewPart* dvp = getViewObject(); TechDraw::DrawViewDetail* dvd = dynamic_cast(dvp); - if (dvd != nullptr) { + if (dvd) { // clear the selection (convenience) Gui::Selection().clearSelection(); Gui::Control().showDialog(new TaskDlgDetail(dvd)); @@ -268,18 +246,7 @@ bool ViewProviderViewPart::setEdit(int ModNum) return true; } -void ViewProviderViewPart::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - -bool ViewProviderViewPart::doubleClicked(void) +bool ViewProviderViewPart::doubleClicked() { setEdit(ViewProvider::Default); return true; @@ -377,12 +344,12 @@ bool ViewProviderViewPart::canDelete(App::DocumentObject *obj) const return true; } -App::Color ViewProviderViewPart::prefSectionColor(void) +App::Color ViewProviderViewPart::prefSectionColor() { return PreferencesGui::sectionLineColor(); } -App::Color ViewProviderViewPart::prefHighlightColor(void) +App::Color ViewProviderViewPart::prefHighlightColor() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); @@ -391,7 +358,7 @@ App::Color ViewProviderViewPart::prefHighlightColor(void) return fcColor; } -int ViewProviderViewPart::prefHighlightStyle(void) +int ViewProviderViewPart::prefHighlightStyle() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Decorations"); diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewPart.h b/src/Mod/TechDraw/Gui/ViewProviderViewPart.h index efa468d4c0..c0ec6602ac 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewPart.h +++ b/src/Mod/TechDraw/Gui/ViewProviderViewPart.h @@ -22,6 +22,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERVIEWPART_H #define DRAWINGGUI_VIEWPROVIDERVIEWPART_H + +#include #include @@ -34,13 +36,13 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderViewPart : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderViewPart); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderViewPart); public: /// constructor ViewProviderViewPart(); /// destructor - virtual ~ViewProviderViewPart(); + ~ViewProviderViewPart() override; App::PropertyLength LineWidth; App::PropertyLength HiddenWidth; @@ -60,29 +62,24 @@ public: static const char* LineStyleEnums[]; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual bool onDelete(const std::vector &); - virtual bool canDelete(App::DocumentObject* obj) const; - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); + void attach(App::DocumentObject *) override; + bool useNewSelectionModel(void) const override {return false;} + bool onDelete(const std::vector &) override; + bool canDelete(App::DocumentObject* obj) const override; + bool setEdit(int ModNum) override; + bool doubleClicked(void) override; public: - virtual void onChanged(const App::Property *prop); - virtual void updateData(const App::Property*); - virtual void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop); + void onChanged(const App::Property *prop) override; + void handleChangedPropertyType(Base::XMLReader &reader, const char *TypeName, App::Property * prop) override; App::Color prefSectionColor(void); App::Color prefHighlightColor(void); int prefHighlightStyle(void); - virtual std::vector claimChildren(void) const; + std::vector claimChildren(void) const override; - virtual TechDraw::DrawViewPart* getViewObject() const; + TechDraw::DrawViewPart* getViewObject() const override; TechDraw::DrawViewPart* getViewPart() const; }; diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp b/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp index bfee0a20a5..5ec73fc945 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderViewSection.cpp @@ -76,25 +76,6 @@ ViewProviderViewSection::~ViewProviderViewSection() { } -void ViewProviderViewSection::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderViewPart::attach(pcFeat); -} - -void ViewProviderViewSection::setDisplayMode(const char* ModeName) -{ - ViewProviderViewPart::setDisplayMode(ModeName); -} - -std::vector ViewProviderViewSection::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderViewPart::getDisplayModes(); - - return StrList; -} - //for VP properties void ViewProviderViewSection::onChanged(const App::Property* prop) { @@ -123,12 +104,7 @@ void ViewProviderViewSection::updateData(const App::Property* prop) ViewProviderViewPart::updateData(prop); } -std::vector ViewProviderViewSection::claimChildren(void) const -{ - return ViewProviderViewPart::claimChildren(); -} - -void ViewProviderViewSection::updateGraphic(void) +void ViewProviderViewSection::updateGraphic() { // redraw QGIVP QGIView* qgiv = getQView(); @@ -151,25 +127,14 @@ bool ViewProviderViewSection::setEdit(int ModNum) return true; } -void ViewProviderViewSection::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - -bool ViewProviderViewSection::doubleClicked(void) +bool ViewProviderViewSection::doubleClicked() { setEdit(ViewProvider::Default); return true; } -void ViewProviderViewSection::getParameters(void) +void ViewProviderViewSection::getParameters() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")->GetGroup("Mod/TechDraw/Colors"); diff --git a/src/Mod/TechDraw/Gui/ViewProviderViewSection.h b/src/Mod/TechDraw/Gui/ViewProviderViewSection.h index c9873f7657..811fc13575 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderViewSection.h +++ b/src/Mod/TechDraw/Gui/ViewProviderViewSection.h @@ -23,6 +23,8 @@ #ifndef TECHDRAWGUI_VIEWPROVIDERVIEWSECTION_H #define TECHDRAWGUI_VIEWPROVIDERVIEWSECTION_H + +#include #include @@ -33,13 +35,13 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderViewSection : public ViewProviderViewPart { - PROPERTY_HEADER(TechDrawGui::ViewProviderViewSection); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderViewSection); public: /// constructor ViewProviderViewSection(); /// destructor - virtual ~ViewProviderViewSection(); + ~ViewProviderViewSection() override; App::PropertyBool ShowCutSurface; //obsolete - use CutSurfaceDisplay App::PropertyColor CutSurfaceColor; @@ -48,24 +50,16 @@ public: App::PropertyColor GeomHatchColor; App::PropertyFloat WeightPattern; + void updateData(const App::Property*) override; + void onChanged(const App::Property *prop) override; + bool setEdit(int ModNum) override; + bool doubleClicked() override; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property *prop); - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); + void updateGraphic(); + void getParameters(); + bool canDelete(App::DocumentObject* obj) const override; - virtual std::vector claimChildren(void) const; - - void updateGraphic(void); - void getParameters(void); - virtual bool canDelete(App::DocumentObject* obj) const; - - virtual TechDraw::DrawViewSection* getViewObject() const; + TechDraw::DrawViewSection* getViewObject() const override; }; } // namespace TechDrawGui diff --git a/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp b/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp index f682499697..5ee07c3494 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp +++ b/src/Mod/TechDraw/Gui/ViewProviderWeld.cpp @@ -63,30 +63,6 @@ ViewProviderWeld::~ViewProviderWeld() { } -void ViewProviderWeld::attach(App::DocumentObject *pcFeat) -{ - // call parent attach method - ViewProviderDrawingView::attach(pcFeat); -} - -void ViewProviderWeld::setDisplayMode(const char* ModeName) -{ - ViewProviderDrawingView::setDisplayMode(ModeName); -} - -std::vector ViewProviderWeld::getDisplayModes(void) const -{ - // get the modes of the father - std::vector StrList = ViewProviderDrawingView::getDisplayModes(); - - return StrList; -} - -void ViewProviderWeld::updateData(const App::Property* prop) -{ - ViewProviderDrawingView::updateData(prop); -} - void ViewProviderWeld::onChanged(const App::Property* p) { QGIView* qgiv = getQView(); @@ -97,7 +73,7 @@ void ViewProviderWeld::onChanged(const App::Property* p) ViewProviderDrawingView::onChanged(p); } -std::vector ViewProviderWeld::claimChildren(void) const +std::vector ViewProviderWeld::claimChildren() const { // Collect any child Document Objects and put them in the right place in the Feature tree // valid children of a DrawWeldSymbol are: @@ -131,35 +107,24 @@ bool ViewProviderWeld::setEdit(int ModNum) return true; } -void ViewProviderWeld::unsetEdit(int ModNum) -{ - Q_UNUSED(ModNum); - if (ModNum == ViewProvider::Default) { - Gui::Control().closeDialog(); - } - else { - ViewProviderDrawingView::unsetEdit(ModNum); - } -} - -bool ViewProviderWeld::doubleClicked(void) +bool ViewProviderWeld::doubleClicked() { // Base::Console().Message("VPW::doubleClicked()\n"); setEdit(ViewProvider::Default); return true; } -std::string ViewProviderWeld::prefFontName(void) +std::string ViewProviderWeld::prefFontName() { return Preferences::labelFont(); } -double ViewProviderWeld::prefFontSize(void) +double ViewProviderWeld::prefFontSize() { return Preferences::labelFontSizeMM(); } -double ViewProviderWeld::prefTileTextAdjust(void) +double ViewProviderWeld::prefTileTextAdjust() { Base::Reference hGrp = App::GetApplication().GetUserParameter() .GetGroup("BaseApp")->GetGroup("Preferences")-> diff --git a/src/Mod/TechDraw/Gui/ViewProviderWeld.h b/src/Mod/TechDraw/Gui/ViewProviderWeld.h index e2b08fd1e3..e3f3382e71 100644 --- a/src/Mod/TechDraw/Gui/ViewProviderWeld.h +++ b/src/Mod/TechDraw/Gui/ViewProviderWeld.h @@ -23,6 +23,8 @@ #ifndef DRAWINGGUI_VIEWPROVIDERWELD_H #define DRAWINGGUI_VIEWPROVIDERWELD_H +#include + #include #include "ViewProviderDrawingView.h" @@ -34,38 +36,32 @@ namespace TechDrawGui { class TechDrawGuiExport ViewProviderWeld : public ViewProviderDrawingView { - PROPERTY_HEADER(TechDrawGui::ViewProviderWeld); + PROPERTY_HEADER_WITH_OVERRIDE(TechDrawGui::ViewProviderWeld); public: /// constructor ViewProviderWeld(); /// destructor - virtual ~ViewProviderWeld(); + ~ViewProviderWeld() override; App::PropertyString Font; App::PropertyLength FontSize; App::PropertyLength TileFontSize; - virtual void attach(App::DocumentObject *); - virtual void setDisplayMode(const char* ModeName); - virtual bool useNewSelectionModel(void) const {return false;} - /// returns a list of all possible modes - virtual std::vector getDisplayModes(void) const; - virtual void updateData(const App::Property*); - virtual void onChanged(const App::Property* p); - virtual std::vector claimChildren(void) const; - virtual bool setEdit(int ModNum); - virtual void unsetEdit(int ModNum); - virtual bool doubleClicked(void); + bool useNewSelectionModel() const override {return false;} + void onChanged(const App::Property* p) override; + std::vector claimChildren() const override; + bool setEdit(int ModNum) override; + bool doubleClicked() override; - virtual TechDraw::DrawWeldSymbol* getViewObject() const; + TechDraw::DrawWeldSymbol* getViewObject() const override; virtual TechDraw::DrawWeldSymbol* getFeature() const; - std::string prefFontName(void); - double prefFontSize(void); - double prefTileTextAdjust(void); - virtual bool onDelete(const std::vector &); - virtual bool canDelete(App::DocumentObject* obj) const; + std::string prefFontName(); + double prefFontSize(); + double prefTileTextAdjust(); + bool onDelete(const std::vector &) override; + bool canDelete(App::DocumentObject* obj) const override; }; diff --git a/src/Mod/TechDraw/Gui/Workbench.cpp b/src/Mod/TechDraw/Gui/Workbench.cpp index cd5a800842..6f6da5d751 100644 --- a/src/Mod/TechDraw/Gui/Workbench.cpp +++ b/src/Mod/TechDraw/Gui/Workbench.cpp @@ -212,6 +212,7 @@ Gui::MenuItem* Workbench::setupMenuBar() const *draw << "TechDraw_DecorateLine"; *draw << "TechDraw_ShowAll"; *draw << "TechDraw_WeldSymbol"; + *draw << "TechDraw_SurfaceFinishSymbols"; *draw << "Separator"; *draw << "TechDraw_ProjectShape"; return root; @@ -352,6 +353,7 @@ Gui::ToolBarItem* Workbench::setupToolBars() const *anno << "TechDraw_DecorateLine"; *anno << "TechDraw_ShowAll"; *anno << "TechDraw_WeldSymbol"; + *anno << "TechDraw_SurfaceFinishSymbols"; return root; } @@ -491,6 +493,7 @@ Gui::ToolBarItem* Workbench::setupCommandBars() const *anno << "TechDraw_DecorateLine"; *anno << "TechDraw_ShowAll"; *anno << "TechDraw_WeldSymbol"; + *anno << "TechDraw_SurfaceFinishSymbols"; return root; } diff --git a/src/Mod/TechDraw/Gui/Workbench.h b/src/Mod/TechDraw/Gui/Workbench.h index 8a04d3116c..304014d2de 100644 --- a/src/Mod/TechDraw/Gui/Workbench.h +++ b/src/Mod/TechDraw/Gui/Workbench.h @@ -23,6 +23,8 @@ #ifndef TECHDRAW_WORKBENCH_H #define TECHDRAW_WORKBENCH_H + +#include #include diff --git a/src/Mod/TechDraw/Gui/mrichtextedit.cpp b/src/Mod/TechDraw/Gui/mrichtextedit.cpp index 294ea26a37..45bf671cae 100644 --- a/src/Mod/TechDraw/Gui/mrichtextedit.cpp +++ b/src/Mod/TechDraw/Gui/mrichtextedit.cpp @@ -25,8 +25,11 @@ * includes changes by wandererfan@gmail.com * for FreeCAD project https://www.freecadweb.org/ ********************************/ -#include "PreCompiled.h" +#include "PreCompiled.h" +#ifndef _PreComp_ +#include +#include #include #include #include @@ -44,16 +47,17 @@ #include #include #include - -#include -#include +#endif #include #include #include #include +#include + #include + #include "PreferencesGui.h" #include "mrichtextedit.h" @@ -201,7 +205,8 @@ MRichTextEdit::MRichTextEdit(QWidget *parent, QString textIn) : QWidget(parent) // font size QFontDatabase db; - for(int size: db.standardSizes()) { + const auto sizes = db.standardSizes(); + for(int size: sizes) { f_fontsize->addItem(QString::number(size)); } //TODO: void QComboBox::setEditText(const QString &text) to " " when multiple select @@ -536,7 +541,7 @@ void MRichTextEdit::slotCursorPositionChanged() { if (m_lastBlockList && (l == m_lastBlockList || - (l != nullptr && m_lastBlockList != nullptr && l->format().style() == m_lastBlockList->format().style()) ) ) { + (l && m_lastBlockList && l->format().style() == m_lastBlockList->format().style()) ) ) { return; } m_lastBlockList = l; diff --git a/src/Mod/TechDraw/Gui/mrichtextedit.h b/src/Mod/TechDraw/Gui/mrichtextedit.h index 17fba1c035..d38cdae4db 100644 --- a/src/Mod/TechDraw/Gui/mrichtextedit.h +++ b/src/Mod/TechDraw/Gui/mrichtextedit.h @@ -29,7 +29,10 @@ #ifndef _MRICHTEXTEDIT_H_ #define _MRICHTEXTEDIT_H_ +#include + #include + #include "ui_mrichtextedit.h" /** diff --git a/src/Mod/TechDraw/Gui/mtextedit.cpp b/src/Mod/TechDraw/Gui/mtextedit.cpp index 4fa6ac3ec4..a94e0beae3 100644 --- a/src/Mod/TechDraw/Gui/mtextedit.cpp +++ b/src/Mod/TechDraw/Gui/mtextedit.cpp @@ -20,15 +20,20 @@ ** ** $QT_END_LICENSE$ */ -#include "PreCompiled.h" +// clazy:excludeall=qstring-arg + +#include "PreCompiled.h" +#ifndef _PreComp_ +#include -#include "mtextedit.h" #include #include #include #include #include -#include +#endif + +#include "mtextedit.h" MTextEdit::MTextEdit(QWidget *parent) : QTextEdit(parent) { diff --git a/src/Mod/TechDraw/Gui/mtextedit.h b/src/Mod/TechDraw/Gui/mtextedit.h index 0a2fd2becb..398ca2e41d 100644 --- a/src/Mod/TechDraw/Gui/mtextedit.h +++ b/src/Mod/TechDraw/Gui/mtextedit.h @@ -23,6 +23,8 @@ #ifndef _MTEXTEDIT_H_ #define _MTEXTEDIT_H_ +#include + #include #include #include diff --git a/src/Mod/TechDraw/TDTest/DHatchTest.py b/src/Mod/TechDraw/TDTest/DHatchTest.py deleted file mode 100644 index d08bbf17e5..0000000000 --- a/src/Mod/TechDraw/TDTest/DHatchTest.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# test script for TechDraw module -# creates a page and 1 views -# adds a hatch area to view1 -from __future__ import print_function - -import FreeCAD -import os - - -def DHatchTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDHatch path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - hatchFileSpec = path + "/TestHatch.svg" - - FreeCAD.newDocument("TDHatch") - FreeCAD.setActiveDocument("TDHatch") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDHatch") - - # make source feature - box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") - - # make a page - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - page.Scale = 5.0 - # page.ViewObject.show() #unit tests run in console mode - - # make Views - view1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") - FreeCAD.ActiveDocument.View.Source = [box] - page.addView(view1) - FreeCAD.ActiveDocument.recompute() - - # make hatch - print("making hatch") - hatch = FreeCAD.ActiveDocument.addObject("TechDraw::DrawHatch", "Hatch") - hatch.Source = (view1, ["Face0"]) - hatch.HatchPattern = hatchFileSpec # comment out to use default from preferences - print("adding hatch to page") - page.addView(hatch) - print("finished hatch") - - FreeCAD.ActiveDocument.recompute() - - rc = False - if "Up-to-date" in hatch.State: - rc = True - - FreeCAD.closeDocument("TDHatch") - return rc - - -if __name__ == "__main__": - DHatchTest() diff --git a/src/Mod/TechDraw/TDTest/DProjGroupTest.py b/src/Mod/TechDraw/TDTest/DProjGroupTest.py deleted file mode 100644 index 24ac0ea9c2..0000000000 --- a/src/Mod/TechDraw/TDTest/DProjGroupTest.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# test script for TechDraw module -# creates a Box and a Sphere and makes a Fusions from them -# creates a page -# creates a Projection Group -# adds Front,Left,Top projections to the group -# a template in the source folder -from __future__ import print_function - -import FreeCAD -import os - - -def DProjGroupTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDGroup path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - - FreeCAD.newDocument("TDGroup") - FreeCAD.setActiveDocument("TDGroup") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDGroup") - doc = FreeCAD.ActiveDocument - print("document created") - - # make Fusion feature - box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") - box.recompute() - print("box created") - sphere = FreeCAD.ActiveDocument.addObject("Part::Sphere", "Sphere") - sphere.recompute() - print("sphere created") - fusion = FreeCAD.ActiveDocument.addObject("Part::MultiFuse", "Fusion") - FreeCAD.ActiveDocument.Fusion.Shapes = [box, sphere] - fusion.recompute() - print("Fusion created") - - # make a page - print("making a page") - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - # page.ViewObject.show() # for debugging. unit tests run in console mode - print("Page created") - - # make projection group - print("making a projection group") - doc.openTransaction("Create Proj Group") - groupName = "ProjGroup" - group = FreeCAD.ActiveDocument.addObject("TechDraw::DrawProjGroup", groupName) - page.addView(group) - print("Group created") - group.Source = [fusion] - - print("adding views") - group.addProjection("Front") # need an Anchor - print("added Front") - - # update group - anchorDir = FreeCAD.Vector(0.0, 0.0, 1.0) - anchorRot = FreeCAD.Vector(1.0, 0.0, 0.0) - group.Anchor.Direction = anchorDir - group.Anchor.RotationVector = anchorRot - print("Anchor values set") - group.Anchor.recompute() - doc.commitTransaction() - print("Front/Anchor recomputed") - - print("adding left") - group.addProjection("Left") - print("added Left") - group.addProjection("Top") - print("added Top") - group.addProjection("Right") - print("added Right") - group.addProjection("Rear") - print("added Rear") - group.addProjection("Bottom") - print("added Bottom") - - # remove a view from projection group - group.removeProjection("Left") - print("removed Left") - - # test getItemByLabel method - print("testing getItemByLabel") - label = "Top" - item = group.getItemByLabel(label) - print("Item Label: " + label + " Item Name: " + item.Name) - - print("recomputing document") - FreeCAD.ActiveDocument.recompute() - - for v in group.Views: - print("View: " + v.Label + " " + v.TypeId) - v.autoPosition() - - rc = False - if "Up-to-date" in group.State: - rc = True - - FreeCAD.closeDocument("TDGroup") - return rc - - -if __name__ == "__main__": - DProjGroupTest() diff --git a/src/Mod/TechDraw/TDTest/DVAnnoSymImageTest.py b/src/Mod/TechDraw/TDTest/DVAnnoSymImageTest.py deleted file mode 100644 index 66de7a6132..0000000000 --- a/src/Mod/TechDraw/TDTest/DVAnnoSymImageTest.py +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# annotation & symbol test script for TechDraw module -# creates a page, 1 annotation and import 1 symbol -from __future__ import print_function - -import FreeCAD -import os - - -def DVAnnoSymImageTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDTestAnno path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - symbolFileSpec = path + "/TestSymbol.svg" - imageFileSpec = path + "/TestImage.png" - - FreeCAD.newDocument("TDAnno") - FreeCAD.setActiveDocument("TDAnno") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDAnno") - - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - # page.ViewObject.show() # unit tests run in console mode - - # annotation - anno = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewAnnotation", "TestAnno") - s = "Different Text" - sl = list() - sl.append(s) - anno.Text = sl - anno.TextStyle = "Bold" - page.addView(anno) - anno.X = 30.0 - anno.Y = 150.0 - - # symbol - sym = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewSymbol", "TestSymbol") - f = open(symbolFileSpec, "r") - svg = f.read() - f.close() - sym.Symbol = svg - page.addView(sym) - sym.X = 220.0 - sym.Y = 150.0 - - # image - img = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewImage", "TestImage") - img.ImageFile = imageFileSpec - page.addView(img) - - FreeCAD.ActiveDocument.recompute() - rc = False - if ( - ("Up-to-date" in anno.State) - and ("Up-to-date" in sym.State) - and ("Up-to-date" in img.State) - ): - rc = True - - FreeCAD.closeDocument("TDAnno") - return rc - - -if __name__ == "__main__": - DVAnnoSymImageTest() diff --git a/src/Mod/TechDraw/TDTest/DVBalloonTest.py b/src/Mod/TechDraw/TDTest/DVBalloonTest.py deleted file mode 100644 index b02bce17ea..0000000000 --- a/src/Mod/TechDraw/TDTest/DVBalloonTest.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# test script for TechDraw module -# creates a page and 2 views -# adds 1 length dimension to view1 -# adds 1 radius dimension to view2 -from __future__ import print_function - -import FreeCAD -from FreeCAD import Units -import os - - -def DVBalloonTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDBalloon path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - - FreeCAD.newDocument("TDBalloon") - FreeCAD.setActiveDocument("TDBalloon") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDBalloon") - - # make source feature - FreeCAD.ActiveDocument.addObject("Part::Box", "Box") - FreeCAD.ActiveDocument.addObject("Part::Sphere", "Sphere") - - # make a page - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - page.Scale = 5.0 - # page.ViewObject.show() # unit tests run in console mode - - # make Views - view1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") - FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] - page.addView(view1) - view1.X = Units.Quantity(30.0, Units.Length) - view1.Y = Units.Quantity(150.0, Units.Length) - view2 = FreeCAD.activeDocument().addObject("TechDraw::DrawViewPart", "View001") - FreeCAD.activeDocument().View001.Source = [FreeCAD.activeDocument().Sphere] - page.addView(view2) - view2.X = Units.Quantity(220.0, Units.Length) - view2.Y = Units.Quantity(150.0, Units.Length) - FreeCAD.ActiveDocument.recompute() - - print("Place balloon") - balloon1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewBalloon", "Balloon1") - balloon1.SourceView = view1 - # balloon1.OriginIsSet = 1 # OriginIsSet property removed March 2020 - balloon1.OriginX = view1.X + Units.Quantity(20.0, Units.Length) - balloon1.OriginY = view1.Y + Units.Quantity(20.0, Units.Length) - balloon1.Text = "1" - balloon1.Y = balloon1.OriginX + Units.Quantity(20.0, Units.Length) - balloon1.X = balloon1.OriginY + Units.Quantity(20.0, Units.Length) - - print("adding balloon1 to page") - page.addView(balloon1) - - balloon2 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewBalloon", "Balloon2") - balloon2.SourceView = view2 - # balloon2.OriginIsSet = 1 - balloon2.OriginX = view2.X + Units.Quantity(20.0, Units.Length) - balloon2.OriginY = view2.Y + Units.Quantity(20.0, Units.Length) - balloon2.Text = "2" - balloon2.Y = balloon2.OriginX + Units.Quantity(20.0, Units.Length) - balloon2.X = balloon2.OriginY + Units.Quantity(20.0, Units.Length) - - print("adding balloon2 to page") - page.addView(balloon2) - - FreeCAD.ActiveDocument.recompute() - - rc = False - if ("Up-to-date" in balloon1.State) and ("Up-to-date" in balloon2.State): - rc = True - - FreeCAD.closeDocument("TDBalloon") - return rc - - -if __name__ == "__main__": - DVBalloonTest() diff --git a/src/Mod/TechDraw/TDTest/DVDimensionTest.py b/src/Mod/TechDraw/TDTest/DVDimensionTest.py deleted file mode 100644 index 20c706b038..0000000000 --- a/src/Mod/TechDraw/TDTest/DVDimensionTest.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# test script for TechDraw module -# creates a page and 2 views -# adds 1 length dimension to view1 -# adds 1 radius dimension to view2 -from __future__ import print_function - -import FreeCAD -import os - - -def DVDimensionTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDDim path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - - FreeCAD.newDocument("TDDim") - FreeCAD.setActiveDocument("TDDim") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDDim") - - # make source feature - FreeCAD.ActiveDocument.addObject("Part::Box", "Box") - FreeCAD.ActiveDocument.addObject("Part::Sphere", "Sphere") - - # make a page - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - page.Scale = 5.0 - # page.ViewObject.show() # unit tests run in console mode - - # make Views - view1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") - FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] - page.addView(view1) - view1.X = 30 - view1.Y = 150 - view2 = FreeCAD.activeDocument().addObject("TechDraw::DrawViewPart", "View001") - FreeCAD.activeDocument().View001.Source = [FreeCAD.activeDocument().Sphere] - page.addView(view2) - view2.X = 220 - view2.Y = 150 - FreeCAD.ActiveDocument.recompute() - - # make length dimension - print("making length dimension") - dim1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewDimension", "Dimension") - dim1.Type = "Distance" - objs = list() - objs.append(view1) - subObjs = list() - subObjs.append("Edge1") - dim1.References2D = [(view1, "Edge1")] - print("adding dim1 to page") - page.addView(dim1) - print("finished length dimension") - - # make radius dimension - print("making radius dimension") - dim2 = FreeCAD.ActiveDocument.addObject( - "TechDraw::DrawViewDimension", "Dimension001" - ) - dim2.Type = "Radius" - dim2.MeasureType = "Projected" - dim2.References2D = [(view2, "Edge0")] - page.addView(dim2) - - FreeCAD.ActiveDocument.recompute() - - rc = False - if ("Up-to-date" in dim1.State) and ("Up-to-date" in dim2.State): - rc = True - - FreeCAD.closeDocument("TDDim") - return rc - - -if __name__ == "__main__": - DVDimensionTest() diff --git a/src/Mod/TechDraw/TDTest/DVPartTest.py b/src/Mod/TechDraw/TDTest/DVPartTest.py deleted file mode 100644 index fdc5ed7c10..0000000000 --- a/src/Mod/TechDraw/TDTest/DVPartTest.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# basic test script for TechDraw module -# creates a page and 1 view -from __future__ import print_function - -import FreeCAD -import os - - -def DVPartTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDPart path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - - FreeCAD.newDocument("TDPart") - FreeCAD.setActiveDocument("TDPart") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDPart") - - FreeCAD.ActiveDocument.addObject("Part::Box", "Box") - - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - page.Scale = 5.0 - # page.ViewObject.show() # unit tests run in console mode - print("page created") - - view = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") - page.addView(view) - - FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] - - FreeCAD.ActiveDocument.recompute() - - rc = False - if "Up-to-date" in view.State: - rc = True - - FreeCAD.closeDocument("TDPart") - return rc - - -if __name__ == "__main__": - DVPartTest() diff --git a/src/Mod/TechDraw/TDTest/DVSectionTest.py b/src/Mod/TechDraw/TDTest/DVSectionTest.py deleted file mode 100644 index 15a1624b74..0000000000 --- a/src/Mod/TechDraw/TDTest/DVSectionTest.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# test script for TechDraw module -# creates a page, 1 view and 1 section view -from __future__ import print_function - -import FreeCAD -import os - - -def DVSectionTest(): - path = os.path.dirname(os.path.abspath(__file__)) - print("TDSection path: " + path) - templateFileSpec = path + "/TestTemplate.svg" - - FreeCAD.newDocument("TDSection") - FreeCAD.setActiveDocument("TDSection") - FreeCAD.ActiveDocument = FreeCAD.getDocument("TDSection") - - box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") - - page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") - FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") - FreeCAD.ActiveDocument.Template.Template = templateFileSpec - FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template - page.Scale = 5.0 - # page.ViewObject.show() # unit tests run in console mode - print("page created") - - view = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") - rc = page.addView(view) - view.Source = [box] - view.Direction = (0.0, 0.0, 1.0) - view.Rotation = 0.0 - view.X = 30.0 - view.Y = 150.0 - print("view created") - - section = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewSection", "Section") - rc = page.addView(section) - section.Source = [box] - section.BaseView = view - section.Direction = (0.0, 1.0, 0.0) - section.SectionNormal = (0.0, 1.0, 0.0) - section.SectionOrigin = (5.0, 5.0, 5.0) - view.touch() - print("section created") - - FreeCAD.ActiveDocument.recompute() - rc = False - if ("Up-to-date" in view.State) and ("Up-to-date" in section.State): - rc = True - - FreeCAD.closeDocument("TDSection") - return rc - - -if __name__ == "__main__": - DVSectionTest() diff --git a/src/Mod/TechDraw/TDTest/DrawHatchTest.py b/src/Mod/TechDraw/TDTest/DrawHatchTest.py new file mode 100644 index 0000000000..c28f0653ba --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawHatchTest.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import print_function + +import FreeCAD +import os +import unittest + + +class DrawHatchTest(unittest.TestCase): + def setUp(self): + """Creates a page and view""" + self.path = os.path.dirname(os.path.abspath(__file__)) + print("TDHatch path: " + self.path) + templateFileSpec = self.path + "/TestTemplate.svg" + + FreeCAD.newDocument("TDHatch") + FreeCAD.setActiveDocument("TDHatch") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDHatch") + + # make source feature + box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") + + # make a page + self.page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") + FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") + FreeCAD.ActiveDocument.Template.Template = templateFileSpec + FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template + self.page.Scale = 5.0 + # page.ViewObject.show() #unit tests run in console mode + + # make Views + self.view = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") + FreeCAD.ActiveDocument.View.Source = [box] + self.page.addView(self.view) + FreeCAD.ActiveDocument.recompute() + + def tearDown(self): + FreeCAD.closeDocument("TDHatch") + + def testMakeHatchCase(self): + """Tests if hatch area can be added to view""" + # make hatch + print("making hatch") + hatch = FreeCAD.ActiveDocument.addObject("TechDraw::DrawHatch", "Hatch") + hatch.Source = (self.view, ["Face0"]) + hatchFileSpec = self.path + "/TestHatch.svg" + # comment out to use default from preferences + hatch.HatchPattern = ( + hatchFileSpec + ) + print("adding hatch to page") + self.page.addView(hatch) + print("finished hatch") + FreeCAD.ActiveDocument.recompute() + + self.assertTrue("Up-to-date" in hatch.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawProjectionGroupTest.py b/src/Mod/TechDraw/TDTest/DrawProjectionGroupTest.py new file mode 100644 index 0000000000..4779484a68 --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawProjectionGroupTest.py @@ -0,0 +1,94 @@ +import FreeCAD +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawProjectionGroupTest(unittest.TestCase): + def setUp(self): + """Creates a box and sphere to make a fusions from them. + Then creates a page and projection group""" + FreeCAD.newDocument("TDGroup") + FreeCAD.setActiveDocument("TDGroup") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDGroup") + self.document = FreeCAD.ActiveDocument + print("document created") + + # make Fusion feature + box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") + box.recompute() + print("box created") + sphere = FreeCAD.ActiveDocument.addObject("Part::Sphere", "Sphere") + sphere.recompute() + print("sphere created") + self.fusion = FreeCAD.ActiveDocument.addObject("Part::MultiFuse", "Fusion") + FreeCAD.ActiveDocument.Fusion.Shapes = [box, sphere] + self.fusion.recompute() + print("Fusion created") + + # make a page + print("making a page") + self.page = createPageWithSVGTemplate() + print("Page created") + + def tearDown(self): + FreeCAD.closeDocument("TDGroup") + + def testMakeProjectionGroup(self): + """Tests if a projection group can be added to view1""" + # make projection group + print("making a projection group") + self.document.openTransaction("Create Proj Group") + groupName = "ProjGroup" + group = FreeCAD.ActiveDocument.addObject("TechDraw::DrawProjGroup", groupName) + self.page.addView(group) + print("Group created") + group.Source = [self.fusion] + + print("adding views") + group.addProjection("Front") # need an Anchor + print("added Front") + + # update group + anchorDir = FreeCAD.Vector(0.0, 0.0, 1.0) + anchorRot = FreeCAD.Vector(1.0, 0.0, 0.0) + group.Anchor.Direction = anchorDir + group.Anchor.RotationVector = anchorRot + print("Anchor values set") + group.Anchor.recompute() + self.document.commitTransaction() + print("Front/Anchor recomputed") + group.addProjection("Left") + print("added Left") + group.addProjection("Top") + print("added Top") + group.addProjection("Right") + print("added Right") + group.addProjection("Rear") + print("added Rear") + group.addProjection("Bottom") + print("added Bottom") + + # remove a view from projection group + group.removeProjection("Left") + print("removed Left") + + # test getItemByLabel method + print("testing getItemByLabel") + label = "Top" + item = group.getItemByLabel(label) + print("Item Label: " + label + " Item Name: " + item.Name) + + print("recomputing document") + FreeCAD.ActiveDocument.recompute() + + for v in group.Views: + print("View: " + v.Label + " " + v.TypeId) + v.autoPosition() + + group.recompute() + + self.assertTrue("Up-to-date" in group.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewAnnotationTest.py b/src/Mod/TechDraw/TDTest/DrawViewAnnotationTest.py new file mode 100644 index 0000000000..7c3d1df957 --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewAnnotationTest.py @@ -0,0 +1,38 @@ +from __future__ import print_function + +import FreeCAD +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewAnnotationTest(unittest.TestCase): + def setUp(self): + """Creates a page""" + FreeCAD.newDocument("TDAnno") + FreeCAD.setActiveDocument("TDAnno") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDAnno") + self.page = createPageWithSVGTemplate() + + def tearDown(self): + FreeCAD.closeDocument("TDAnno") + + def testMakeAnnotation(self): + """Tests if an annotation can be added to page""" + anno = FreeCAD.ActiveDocument.addObject( + "TechDraw::DrawViewAnnotation", "TestAnno" + ) + s = "Different Text" + sl = list() + sl.append(s) + anno.Text = sl + anno.TextStyle = "Bold" + self.page.addView(anno) + anno.X = 30.0 + anno.Y = 150.0 + FreeCAD.ActiveDocument.recompute() + + self.assertTrue("Up-to-date" in anno.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewBalloonTest.py b/src/Mod/TechDraw/TDTest/DrawViewBalloonTest.py new file mode 100644 index 0000000000..e5dcfbaa0d --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewBalloonTest.py @@ -0,0 +1,80 @@ +import FreeCAD +from FreeCAD import Units +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewBalloonTest(unittest.TestCase): + def setUp(self): + """Creates a page and 2 views""" + FreeCAD.newDocument("TDBalloon") + FreeCAD.setActiveDocument("TDBalloon") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDBalloon") + + # make source feature + FreeCAD.ActiveDocument.addObject("Part::Box", "Box") + FreeCAD.ActiveDocument.addObject("Part::Sphere", "Sphere") + + # make a page + self.page = createPageWithSVGTemplate() + self.page.Scale = 5.0 + # page.ViewObject.show() # unit tests run in console mode + + # make Views + self.view1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") + FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] + self.page.addView(self.view1) + self.view1.X = Units.Quantity(30.0, Units.Length) + self.view1.Y = Units.Quantity(150.0, Units.Length) + self.view2 = FreeCAD.activeDocument().addObject( + "TechDraw::DrawViewPart", "View001" + ) + FreeCAD.activeDocument().View001.Source = [FreeCAD.activeDocument().Sphere] + self.page.addView(self.view2) + self.view2.X = Units.Quantity(220.0, Units.Length) + self.view2.Y = Units.Quantity(150.0, Units.Length) + FreeCAD.ActiveDocument.recompute() + + def tearDown(self): + FreeCAD.closeDocument("TDBalloon") + + def testMakeDrawViewBalloon(self): + """Tests if a DrawViewBalloon can be added to view""" + print("Place balloon") + balloon1 = FreeCAD.ActiveDocument.addObject( + "TechDraw::DrawViewBalloon", "Balloon1" + ) + balloon1.SourceView = self.view1 + # balloon1.OriginIsSet = 1 # OriginIsSet property removed March 2020 + balloon1.OriginX = self.view1.X + Units.Quantity(20.0, Units.Length) + balloon1.OriginY = self.view1.Y + Units.Quantity(20.0, Units.Length) + balloon1.Text = "1" + balloon1.Y = balloon1.OriginX + Units.Quantity(20.0, Units.Length) + balloon1.X = balloon1.OriginY + Units.Quantity(20.0, Units.Length) + + print("adding balloon1 to page") + self.page.addView(balloon1) + + FreeCAD.ActiveDocument.recompute() + self.assertTrue("Up-to-date" in balloon1.State) + + balloon2 = FreeCAD.ActiveDocument.addObject( + "TechDraw::DrawViewBalloon", "Balloon2" + ) + balloon2.SourceView = self.view2 + # balloon2.OriginIsSet = 1 + balloon2.OriginX = self.view2.X + Units.Quantity(20.0, Units.Length) + balloon2.OriginY = self.view2.Y + Units.Quantity(20.0, Units.Length) + balloon2.Text = "2" + balloon2.Y = balloon2.OriginX + Units.Quantity(20.0, Units.Length) + balloon2.X = balloon2.OriginY + Units.Quantity(20.0, Units.Length) + + print("adding balloon2 to page") + self.page.addView(balloon2) + + FreeCAD.ActiveDocument.recompute() + self.assertTrue("Up-to-date" in balloon2.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewDimensionTest.py b/src/Mod/TechDraw/TDTest/DrawViewDimensionTest.py new file mode 100644 index 0000000000..bba244cea4 --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewDimensionTest.py @@ -0,0 +1,70 @@ +import FreeCAD +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewDimensionTest(unittest.TestCase): + def setUp(self): + """Creates a page and 2 views""" + FreeCAD.newDocument("TDDim") + FreeCAD.setActiveDocument("TDDim") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDDim") + + # make source feature + FreeCAD.ActiveDocument.addObject("Part::Box", "Box") + FreeCAD.ActiveDocument.addObject("Part::Sphere", "Sphere") + + # make a page + self.page = createPageWithSVGTemplate() + self.page.Scale = 5.0 + # page.ViewObject.show() # unit tests run in console mode + + # make Views + self.view1 = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") + FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] + self.page.addView(self.view1) + self.view1.X = 30 + self.view1.Y = 150 + self.view2 = FreeCAD.activeDocument().addObject( + "TechDraw::DrawViewPart", "View001" + ) + FreeCAD.activeDocument().View001.Source = [FreeCAD.activeDocument().Sphere] + self.page.addView(self.view2) + self.view2.X = 220 + self.view2.Y = 150 + FreeCAD.ActiveDocument.recompute() + + def tearDown(self): + FreeCAD.closeDocument("TDDim") + + def testLengthDimension(self): + """Tests if a length dimension can be added to view1""" + # make length dimension + print("making length dimension") + dimension = FreeCAD.ActiveDocument.addObject( + "TechDraw::DrawViewDimension", "Dimension" + ) + dimension.Type = "Distance" + dimension.References2D = [(self.view1, "Edge1")] + print("adding dim1 to page") + self.page.addView(dimension) + print("finished length dimension") + FreeCAD.ActiveDocument.recompute() + self.assertTrue("Up-to-date" in dimension.State) + + def testRadiusDimension(self): + """Tests if a radius dimension can be added to view2""" + print("making radius dimension") + dimension = FreeCAD.ActiveDocument.addObject( + "TechDraw::DrawViewDimension", "Dimension001" + ) + dimension.Type = "Radius" + dimension.MeasureType = "Projected" + dimension.References2D = [(self.view2, "Edge0")] + self.page.addView(dimension) + FreeCAD.ActiveDocument.recompute() + self.assertTrue("Up-to-date" in dimension.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewImageTest.py b/src/Mod/TechDraw/TDTest/DrawViewImageTest.py new file mode 100644 index 0000000000..a82166a49b --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewImageTest.py @@ -0,0 +1,34 @@ +from __future__ import print_function + +import FreeCAD +import os +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewImageTest(unittest.TestCase): + def setUp(self): + """Creates a page""" + FreeCAD.newDocument("TDAnno") + FreeCAD.setActiveDocument("TDAnno") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDAnno") + self.page = createPageWithSVGTemplate() + + def tearDown(self): + FreeCAD.closeDocument("TDAnno") + + def testMakeImage(self): + """Tests if an image can be added to page""" + path = os.path.dirname(os.path.abspath(__file__)) + imageFileSpec = path + "/TestImage.png" + img = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewImage", "TestImage") + img.ImageFile = imageFileSpec + self.page.addView(img) + + FreeCAD.ActiveDocument.recompute() + + self.assertTrue("Up-to-date" in img.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewPartTest.py b/src/Mod/TechDraw/TDTest/DrawViewPartTest.py new file mode 100644 index 0000000000..d605c4a51f --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewPartTest.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# basic test script for TechDraw module +# creates a page and 1 view + +import FreeCAD +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewPartTest(unittest.TestCase): + def setUp(self): + """Creates a page""" + FreeCAD.newDocument("TDPart") + FreeCAD.setActiveDocument("TDPart") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDPart") + + FreeCAD.ActiveDocument.addObject("Part::Box", "Box") + + self.page = createPageWithSVGTemplate() + self.page.Scale = 5.0 + # page.ViewObject.show() # unit tests run in console mode + print("page created") + + def tearDown(self): + FreeCAD.closeDocument("TDPart") + + def testMakeDrawViewPart(self): + """Tests if a view can be added to page""" + view = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") + self.page.addView(view) + FreeCAD.ActiveDocument.View.Source = [FreeCAD.ActiveDocument.Box] + FreeCAD.ActiveDocument.recompute() + self.assertTrue("Up-to-date" in view.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewSectionTest.py b/src/Mod/TechDraw/TDTest/DrawViewSectionTest.py new file mode 100644 index 0000000000..43a5158fe8 --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewSectionTest.py @@ -0,0 +1,51 @@ +import FreeCAD +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewSectionTest(unittest.TestCase): + def setUp(self): + """Creates a page and a view""" + FreeCAD.newDocument("TDSection") + FreeCAD.setActiveDocument("TDSection") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDSection") + + self.box = FreeCAD.ActiveDocument.addObject("Part::Box", "Box") + + self.page = createPageWithSVGTemplate() + self.page.Scale = 5.0 + # page.ViewObject.show() # unit tests run in console mode + print("page created") + + self.view = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewPart", "View") + self.page.addView(self.view) + self.view.Source = [self.box] + self.view.Direction = (0.0, 0.0, 1.0) + self.view.Rotation = 0.0 + self.view.X = 30.0 + self.view.Y = 150.0 + print("view created") + + def tearDown(self): + FreeCAD.closeDocument("TDSection") + + def testMakeDrawViewSection(self): + """Tests if a DrawViewSection can be added to page""" + section = FreeCAD.ActiveDocument.addObject( + "TechDraw::DrawViewSection", "Section" + ) + self.page.addView(section) + section.Source = [self.box] + section.BaseView = self.view + section.Direction = (0.0, 1.0, 0.0) + section.SectionNormal = (0.0, 1.0, 0.0) + section.SectionOrigin = (5.0, 5.0, 5.0) + self.view.touch() + print("section created") + + FreeCAD.ActiveDocument.recompute() + self.assertTrue("Up-to-date" in section.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/DrawViewSymbolTest.py b/src/Mod/TechDraw/TDTest/DrawViewSymbolTest.py new file mode 100644 index 0000000000..ed172f1273 --- /dev/null +++ b/src/Mod/TechDraw/TDTest/DrawViewSymbolTest.py @@ -0,0 +1,39 @@ +from __future__ import print_function + +import FreeCAD +import os +import unittest +from .TechDrawTestUtilities import createPageWithSVGTemplate + + +class DrawViewSymbolTest(unittest.TestCase): + def setUp(self): + """Creates a page""" + FreeCAD.newDocument("TDAnno") + FreeCAD.setActiveDocument("TDAnno") + FreeCAD.ActiveDocument = FreeCAD.getDocument("TDAnno") + self.page = createPageWithSVGTemplate() + + def tearDown(self): + FreeCAD.closeDocument("TDAnno") + + def testMakeSymbol(self): + """Tests if an symbol can be added to page""" + sym = FreeCAD.ActiveDocument.addObject("TechDraw::DrawViewSymbol", "TestSymbol") + path = os.path.dirname(os.path.abspath(__file__)) + symbolFileSpec = path + "/TestSymbol.svg" + f = open(symbolFileSpec, "r") + svg = f.read() + f.close() + sym.Symbol = svg + self.page.addView(sym) + sym.X = 220.0 + sym.Y = 150.0 + + FreeCAD.ActiveDocument.recompute() + + self.assertTrue("Up-to-date" in sym.State) + + +if __name__ == "__main__": + unittest.main() diff --git a/src/Mod/TechDraw/TDTest/TechDrawTestUtilities.py b/src/Mod/TechDraw/TDTest/TechDrawTestUtilities.py new file mode 100644 index 0000000000..41fa866faa --- /dev/null +++ b/src/Mod/TechDraw/TDTest/TechDrawTestUtilities.py @@ -0,0 +1,15 @@ +from __future__ import print_function +import FreeCAD +import os + + +def createPageWithSVGTemplate(): + """Returns a page with an SVGTemplate added on the ActiveDocument""" + path = os.path.dirname(os.path.abspath(__file__)) + templateFileSpec = path + "/TestTemplate.svg" + + page = FreeCAD.ActiveDocument.addObject("TechDraw::DrawPage", "Page") + FreeCAD.ActiveDocument.addObject("TechDraw::DrawSVGTemplate", "Template") + FreeCAD.ActiveDocument.Template.Template = templateFileSpec + FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template + return page diff --git a/src/Mod/TechDraw/Templates/zh_CN/landscape/A0_Landscape_CN_CLIP.svg b/src/Mod/TechDraw/Templates/zh_CN/landscape/A0_Landscape_CN_CLIP.svg index 83c1f05aa7..8141517921 100644 --- a/src/Mod/TechDraw/Templates/zh_CN/landscape/A0_Landscape_CN_CLIP.svg +++ b/src/Mod/TechDraw/Templates/zh_CN/landscape/A0_Landscape_CN_CLIP.svg @@ -275,7 +275,7 @@ e"> - + diff --git a/src/Mod/TechDraw/Templates/zh_CN/landscape/A1_Landscape_CN_CLIP.svg b/src/Mod/TechDraw/Templates/zh_CN/landscape/A1_Landscape_CN_CLIP.svg index b5851b0c6b..202ac15f99 100644 --- a/src/Mod/TechDraw/Templates/zh_CN/landscape/A1_Landscape_CN_CLIP.svg +++ b/src/Mod/TechDraw/Templates/zh_CN/landscape/A1_Landscape_CN_CLIP.svg @@ -253,7 +253,7 @@ e"> - + diff --git a/src/Mod/TechDraw/Templates/zh_CN/landscape/A2_Landscape_CN_CLIP.svg b/src/Mod/TechDraw/Templates/zh_CN/landscape/A2_Landscape_CN_CLIP.svg index 1f5e85a5f2..2aef60ed8d 100644 --- a/src/Mod/TechDraw/Templates/zh_CN/landscape/A2_Landscape_CN_CLIP.svg +++ b/src/Mod/TechDraw/Templates/zh_CN/landscape/A2_Landscape_CN_CLIP.svg @@ -233,7 +233,7 @@ nter;fill:#000000;"> - + diff --git a/src/Mod/TechDraw/Templates/zh_CN/landscape/A3_Landscape_CN_CLIP.svg b/src/Mod/TechDraw/Templates/zh_CN/landscape/A3_Landscape_CN_CLIP.svg index ae1b902c2f..be6535d4dc 100644 --- a/src/Mod/TechDraw/Templates/zh_CN/landscape/A3_Landscape_CN_CLIP.svg +++ b/src/Mod/TechDraw/Templates/zh_CN/landscape/A3_Landscape_CN_CLIP.svg @@ -183,7 +183,7 @@ - + diff --git a/src/Mod/TechDraw/Templates/zh_CN/landscape/A4_Landscape_CN_CLIP.svg b/src/Mod/TechDraw/Templates/zh_CN/landscape/A4_Landscape_CN_CLIP.svg index 96da06f6e0..7b21fab3cd 100644 --- a/src/Mod/TechDraw/Templates/zh_CN/landscape/A4_Landscape_CN_CLIP.svg +++ b/src/Mod/TechDraw/Templates/zh_CN/landscape/A4_Landscape_CN_CLIP.svg @@ -166,7 +166,7 @@ - + diff --git a/src/Mod/TechDraw/Templates/zh_CN/portrait/A4_Portrait_CN_CLIP.svg b/src/Mod/TechDraw/Templates/zh_CN/portrait/A4_Portrait_CN_CLIP.svg index 908f381763..434f8b7c50 100644 --- a/src/Mod/TechDraw/Templates/zh_CN/portrait/A4_Portrait_CN_CLIP.svg +++ b/src/Mod/TechDraw/Templates/zh_CN/portrait/A4_Portrait_CN_CLIP.svg @@ -167,7 +167,7 @@ - + diff --git a/src/Mod/TechDraw/TestTechDrawApp.py b/src/Mod/TechDraw/TestTechDrawApp.py index 75ca9bc258..b4b277655c 100644 --- a/src/Mod/TechDraw/TestTechDrawApp.py +++ b/src/Mod/TechDraw/TestTechDrawApp.py @@ -20,74 +20,12 @@ # USA * # ************************************************************************** -import unittest - -from TDTest.DHatchTest import DHatchTest -from TDTest.DProjGroupTest import DProjGroupTest -from TDTest.DVAnnoSymImageTest import DVAnnoSymImageTest -from TDTest.DVDimensionTest import DVDimensionTest -from TDTest.DVPartTest import DVPartTest -from TDTest.DVSectionTest import DVSectionTest -from TDTest.DVBalloonTest import DVBalloonTest - -# --------------------------------------------------------------------------- -# define the test cases to test the FreeCAD TechDraw module -# --------------------------------------------------------------------------- - - -class TechDrawTestCases(unittest.TestCase): - def testViewPartCase(self): - print("starting TD DrawViewPart test") - rc = DVPartTest() - if rc: - print("TD DrawViewPart test passed") - else: - print("TD DrawViewPart test failed") - - def testHatchCase(self): - print("starting TD DrawHatch test") - rc = DHatchTest() - if rc: - print("TD DrawHatch test passed") - else: - print("TD DrawHatch test failed") - - def testAnnoSymImageCase(self): - print("starting TD DrawAnno/Sym/Image test") - rc = DVAnnoSymImageTest() - if rc: - print("TD DrawAnno/Sym/Image test passed") - else: - print("TD DrawAnno/Sym/Image test failed") - - def testProjGroupCase(self): - print("starting TD DrawProjGroup test") - rc = DProjGroupTest() - if rc: - print("TD DrawProjGroup test passed") - else: - print("TD DrawProjGroup test failed") - - def testDimensionCase(self): - print("starting TD DrawViewDimension test") - rc = DVDimensionTest() - if rc: - print("TD DrawViewDimension test passed") - else: - print("TD DrawViewDimension test failed") - - def testSectionCase(self): - print("starting TD DrawViewSection test") - rc = DVSectionTest() - if rc: - print("TD DrawViewSection test passed") - else: - print("TD DrawViewSection test failed") - - def testBalloonCase(self): - print("starting TD DrawViewBalloon test") - rc = DVBalloonTest() - if rc: - print("TD DrawViewBalloon test passed") - else: - print("TD DrawViewBalloon test failed") +from TDTest.DrawHatchTest import DrawHatchTest # noqa: F401 +from TDTest.DrawViewAnnotationTest import DrawViewAnnotationTest # noqa: F401 +from TDTest.DrawViewBalloonTest import DrawViewBalloonTest # noqa: F401 +from TDTest.DrawViewDimensionTest import DrawViewDimensionTest # noqa: F401 +from TDTest.DrawViewImageTest import DrawViewImageTest # noqa: F401 +from TDTest.DrawViewSectionTest import DrawViewSectionTest # noqa: F401 +from TDTest.DrawViewSymbolTest import DrawViewSymbolTest # noqa: F401 +from TDTest.DrawViewPartTest import DrawViewPartTest # noqa: F401 +from TDTest.DrawProjectionGroupTest import DrawProjectionGroupTest # noqa: F401 diff --git a/src/Mod/TemplatePyMod/Commands.py b/src/Mod/TemplatePyMod/Commands.py index 8b7d70ffbc..b245b10174 100644 --- a/src/Mod/TemplatePyMod/Commands.py +++ b/src/Mod/TemplatePyMod/Commands.py @@ -142,7 +142,7 @@ class TemplatePyMod_Cmd4: FreeCAD.Console.PrintError('TemplatePyMod_Cmd4 was destroyed\n') def Activated(self): - if FreeCADGui.ActiveDocument != None: + if FreeCADGui.ActiveDocument is not None: self.sc.enter() else: FreeCAD.Console.PrintWarning('A 3d view must be created\n') diff --git a/src/Mod/TemplatePyMod/FeaturePython.py b/src/Mod/TemplatePyMod/FeaturePython.py index 52648ca4f5..88520b1389 100644 --- a/src/Mod/TemplatePyMod/FeaturePython.py +++ b/src/Mod/TemplatePyMod/FeaturePython.py @@ -547,7 +547,7 @@ class ViewProviderMolecule: sep2.addChild(coin.SoSphere()) obj.RootNode.addChild(sep1) obj.RootNode.addChild(sep2) - # triggers an updateData call so the the assignment at the end + # triggers an updateData call so the assignment at the end obj.Proxy = self def updateData(self, fp, prop): diff --git a/src/Mod/Test/BaseTests.py b/src/Mod/Test/BaseTests.py index b07323552d..6cb265abc8 100644 --- a/src/Mod/Test/BaseTests.py +++ b/src/Mod/Test/BaseTests.py @@ -22,6 +22,7 @@ #***************************************************************************/ import FreeCAD, os, unittest, tempfile, math +from FreeCAD import Base class ConsoleTestCase(unittest.TestCase): def setUp(self): @@ -381,6 +382,27 @@ class AlgebraTestCase(unittest.TestCase): self.assertFalse(b.intersected(FreeCAD.BoundBox(4,4,4,6,6,6)).isValid(),"Bbox should not intersect with Bbox outside") self.assertEqual(b.intersected(FreeCAD.BoundBox(-2,-2,-2,2,2,2)).Center, b.Center,"Bbox is not a full subset") + def testMultLeftOrRight(self): + doc = FreeCAD.newDocument() + obj = doc.addObject("App::FeatureTestPlacement") + + p1 = Base.Placement() + p1.Base = Base.Vector(10, 10, 10) + + p2 = Base.Placement() + p2.Rotation.Angle = math.radians(90) + + obj.Input1 = p1 + obj.Input2 = p2 + doc.recompute() + + self.assertTrue(obj.MultRight.isSame(p1 * p2)) + self.assertFalse(obj.MultRight.isSame(p2 * p1)) + self.assertTrue(obj.MultLeft.isSame(p2 * p1)) + self.assertFalse(obj.MultLeft.isSame(p1 * p2)) + + FreeCAD.closeDocument(doc.Name) + class MatrixTestCase(unittest.TestCase): def setUp(self): self.mat = FreeCAD.Matrix() diff --git a/src/Mod/Test/Document.py b/src/Mod/Test/Document.py index 6c09637bee..9cdd2ed827 100644 --- a/src/Mod/Test/Document.py +++ b/src/Mod/Test/Document.py @@ -47,7 +47,7 @@ class DocumentBasicCases(unittest.TestCase): def testCreateDestroy(self): #FIXME: Causes somehow a ref count error but it's _not_ FreeCAD.getDocument()!!! #If we remove the whole method no error appears. - self.failUnless(FreeCAD.getDocument("CreateTest")!= None,"Creating Document failed") + self.failUnless(FreeCAD.getDocument("CreateTest") is not None,"Creating Document failed") def testAddition(self): # Cannot write a real test case for that but when debugging the @@ -1092,7 +1092,7 @@ class DocumentGroupCases(unittest.TestCase): self.Doc.commitTransaction() self.failUnless(G1.getObject("Label_2") is None) self.Doc.undo() - self.failUnless(G1.getObject("Label_2") != None) + self.failUnless(G1.getObject("Label_2") is not None) # Remove first group and then the object self.Doc.openTransaction("Remove") @@ -1100,7 +1100,7 @@ class DocumentGroupCases(unittest.TestCase): self.Doc.removeObject("Label_2") self.Doc.commitTransaction() self.Doc.undo() - self.failUnless(G1.getObject("Label_2") != None) + self.failUnless(G1.getObject("Label_2") is not None) # Remove first object and then the group in two transactions self.Doc.openTransaction("Remove") @@ -1112,7 +1112,7 @@ class DocumentGroupCases(unittest.TestCase): self.Doc.commitTransaction() self.Doc.undo() self.Doc.undo() - self.failUnless(G1.getObject("Label_2") != None) + self.failUnless(G1.getObject("Label_2") is not None) # Remove first object and then the group in one transaction self.Doc.openTransaction("Remove") @@ -1122,7 +1122,7 @@ class DocumentGroupCases(unittest.TestCase): self.Doc.commitTransaction() self.Doc.undo() # FIXME: See bug #1820554 - self.failUnless(G1.getObject("Label_2") != None) + self.failUnless(G1.getObject("Label_2") is not None) # Add a second object to the group L3 = self.Doc.addObject("App::FeatureTest","Label_3") @@ -1135,8 +1135,8 @@ class DocumentGroupCases(unittest.TestCase): self.Doc.removeObject("Group") self.Doc.commitTransaction() self.Doc.undo() - self.failUnless(G1.getObject("Label_3") != None) - self.failUnless(G1.getObject("Label_2") != None) + self.failUnless(G1.getObject("Label_3") is not None) + self.failUnless(G1.getObject("Label_2") is not None) self.Doc.UndoMode = 0 @@ -2182,3 +2182,156 @@ class DocumentObserverCases(unittest.TestCase): #closing doc FreeCAD.removeDocumentObserver(self.Obs) self.Obs = None + +class FeatureTestColumn(unittest.TestCase): + def setUp(self): + doc = FreeCAD.newDocument("TestColumn") + self.obj = doc.addObject("App::FeatureTestColumn", "Column") + + def testEmpty(self): + value = self.obj.Value + self.obj.Column = "" + self.assertFalse(self.obj.recompute()) + self.assertEqual(self.obj.Value, value) + + def testA(self): + self.obj.Column = "A" + self.obj.recompute() + self.assertEqual(self.obj.Value, 0) + + def testZ(self): + self.obj.Column = "Z" + self.obj.recompute() + self.assertEqual(self.obj.Value, 25) + + def testAA(self): + self.obj.Column = "AA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 26) + + def testAB(self): + self.obj.Column = "AB" + self.obj.recompute() + self.assertEqual(self.obj.Value, 27) + + def testAZ(self): + self.obj.Column = "AZ" + self.obj.recompute() + self.assertEqual(self.obj.Value, 51) + + def testBA(self): + self.obj.Column = "BA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 52) + + def testCB(self): + self.obj.Column = "CB" + self.obj.recompute() + self.assertEqual(self.obj.Value, 79) + + def testZA(self): + self.obj.Column = "ZA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 676) + + def testZZ(self): + self.obj.Column = "ZZ" + self.obj.recompute() + self.assertEqual(self.obj.Value, 701) + + def testAAA(self): + self.obj.Column = "AAA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 702) + + def testAAZ(self): + self.obj.Column = "AAZ" + self.obj.recompute() + self.assertEqual(self.obj.Value, 727) + + def testCBA(self): + self.obj.Column = "CBA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 2080) + + def testAZA(self): + self.obj.Column = "AZA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 1352) + + def testZZA(self): + self.obj.Column = "ZZA" + self.obj.recompute() + self.assertEqual(self.obj.Value, 18252) + + def testZZZ(self): + self.obj.Column = "ZZZ" + self.obj.recompute() + self.assertEqual(self.obj.Value, 18277) + + def testALL(self): + self.obj.Column = "ALL" + self.obj.recompute() + self.assertEqual(self.obj.Value, 999) + + def testAb(self): + value = self.obj.Value + self.obj.Column = "Ab" + self.assertFalse(self.obj.recompute()) + self.assertEqual(self.obj.Value, value) + + def testABCD(self): + value = self.obj.Value + self.obj.Column = "ABCD" + self.assertFalse(self.obj.recompute()) + self.assertEqual(self.obj.Value, value) + + def testEmptySilent(self): + self.obj.Column = "" + self.obj.Silent = True + self.assertTrue(self.obj.recompute()) + self.assertEqual(self.obj.Value, -1) + + def testAbSilent(self): + self.obj.Column = "Ab" + self.obj.Silent = True + self.assertTrue(self.obj.recompute()) + self.assertEqual(self.obj.Value, -1) + + def testABCDSilent(self): + self.obj.Column = "ABCD" + self.obj.Silent = True + self.assertTrue(self.obj.recompute()) + self.assertEqual(self.obj.Value, -1) + + def tearDown(self): + FreeCAD.closeDocument("TestColumn") + + +class FeatureTestAttribute(unittest.TestCase): + def setUp(self): + self.doc = FreeCAD.newDocument("TestAttribute") + self.doc.UndoMode = 0 + + def testValidAttribute(self): + obj = self.doc.addObject("App::FeatureTestAttribute", "Attribute") + obj.Object = obj + obj.Attribute = "Name" + self.doc.recompute() + self.assertIn("Up-to-date", obj.State) + + def testInvalidAttribute(self): + obj = self.doc.addObject("App::FeatureTestAttribute", "Attribute") + obj.Object = obj + obj.Attribute = "Name123" + self.doc.recompute() + self.assertIn("Invalid", obj.State) + self.assertIn("Touched", obj.State) + + def testRemoval(self): + obj = self.doc.addObject("App::FeatureTestAttribute", "Attribute") + obj.Object = obj + self.assertEqual(self.doc.removeObject("Attribute"), None) + + def tearDown(self): + FreeCAD.closeDocument("TestAttribute") diff --git a/src/Mod/Test/Gui/AppTestGui.cpp b/src/Mod/Test/Gui/AppTestGui.cpp index 01f2ea4202..fe65b5b73f 100644 --- a/src/Mod/Test/Gui/AppTestGui.cpp +++ b/src/Mod/Test/Gui/AppTestGui.cpp @@ -33,13 +33,13 @@ class ILoggerBlockerTest : public Base::ILogger { public: - virtual ~ILoggerBlockerTest() {Base::Console().DetachObserver(this);} + ~ILoggerBlockerTest() override {Base::Console().DetachObserver(this);} - virtual const char *Name() {return "ILoggerBlockerTest";} + const char *Name() override {return "ILoggerBlockerTest";} void flush() {buffer.str("");buffer.clear();} - void SendLog(const std::string& msg, Base::LogStyle level){ + void SendLog(const std::string& msg, Base::LogStyle level) override{ (void) msg; switch(level){ case Base::LogStyle::Warning: @@ -124,7 +124,7 @@ public: initialize("This module is the QtUnitGui module"); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object new_UnitTest(const Py::Tuple& args) diff --git a/src/Mod/Test/Gui/CMakeLists.txt b/src/Mod/Test/Gui/CMakeLists.txt index 23c86e686c..536662aa5b 100644 --- a/src/Mod/Test/Gui/CMakeLists.txt +++ b/src/Mod/Test/Gui/CMakeLists.txt @@ -3,6 +3,7 @@ include_directories( ${CMAKE_SOURCE_DIR}/src ${Boost_INCLUDE_DIRS} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) set(TestGui_LIBS diff --git a/src/Mod/Test/Gui/UnitTestImp.cpp b/src/Mod/Test/Gui/UnitTestImp.cpp index 6adc37262c..7c95cb39bf 100644 --- a/src/Mod/Test/Gui/UnitTestImp.cpp +++ b/src/Mod/Test/Gui/UnitTestImp.cpp @@ -58,7 +58,7 @@ UnitTestDialog* UnitTestDialog::instance() */ void UnitTestDialog::destruct () { - if (_instance != nullptr) { + if (_instance) { UnitTestDialog *pTmp = _instance; _instance = nullptr; delete pTmp; diff --git a/src/Mod/Test/Gui/UnitTestImp.h b/src/Mod/Test/Gui/UnitTestImp.h index fcd6e6c7f9..c8e460921d 100644 --- a/src/Mod/Test/Gui/UnitTestImp.h +++ b/src/Mod/Test/Gui/UnitTestImp.h @@ -53,15 +53,15 @@ public: void setErrorCount(int); void setRemainCount(int); void reset(); - void reject(); + void reject() override; static UnitTestDialog* instance(); static void destruct(); static bool hasInstance(); protected: - UnitTestDialog(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - ~UnitTestDialog(); + explicit UnitTestDialog(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); + ~UnitTestDialog() override; void setProgressColor(const QColor& col); public Q_SLOTS: diff --git a/src/Mod/Test/Gui/UnitTestPy.h b/src/Mod/Test/Gui/UnitTestPy.h index b3b5ab7df8..b5acfe492e 100644 --- a/src/Mod/Test/Gui/UnitTestPy.h +++ b/src/Mod/Test/Gui/UnitTestPy.h @@ -38,11 +38,11 @@ public: static void init_type(); // announce properties and methods UnitTestDialogPy(); - ~UnitTestDialogPy(); + ~UnitTestDialogPy() override; - Py::Object repr(); - Py::Object getattr(const char *); - int setattr(const char *, const Py::Object &); + Py::Object repr() override; + Py::Object getattr(const char *) override; + int setattr(const char *, const Py::Object &) override; Py::Object clearErrorList (const Py::Tuple&); Py::Object insertError (const Py::Tuple&); diff --git a/src/Mod/Test/Menu.py b/src/Mod/Test/Menu.py index 0933902dd6..5beb9f939a 100644 --- a/src/Mod/Test/Menu.py +++ b/src/Mod/Test/Menu.py @@ -56,10 +56,10 @@ class MenuCreateCases(unittest.TestCase): self.b = False for i in list: if i == 'TestMenu': self.b=True - self.failUnless(self.b==True,"Test menu not found") + self.failUnless(self.b,"Test menu not found") def tearDown(self): - if self.b == True: + if self.b: FreeCAD.Console.PrintLog ('Test menu successfully added\n') else: FreeCAD.Console.PrintLog ('Adding Test menu failed\n') @@ -84,7 +84,7 @@ class MenuDeleteCases(unittest.TestCase): self.failUnless(self.b==True,"Test menu still added") def tearDown(self): - if self.b == True: + if self.b: FreeCAD.Console.PrintLog ('Test menu successfully removed\n') else: FreeCAD.Console.PrintLog ('Removing Test menu failed\n') diff --git a/src/Mod/Test/TestGui.py b/src/Mod/Test/TestGui.py index 2c70a8a8e8..6284e52b67 100644 --- a/src/Mod/Test/TestGui.py +++ b/src/Mod/Test/TestGui.py @@ -159,7 +159,7 @@ class TestDeleteMenuCmd: class TestInsertFeatureCmd: "Base test commando object" def Activated(self): - if FreeCAD.activeDocument() != None: + if FreeCAD.activeDocument() is not None: FreeCAD.activeDocument().addObject("App::FeatureTest") else: FreeCAD.PrintMessage("No active document.\n") diff --git a/src/Mod/Test/TestPythonSyntax.py b/src/Mod/Test/TestPythonSyntax.py index b57cd287c6..b7764177a8 100644 --- a/src/Mod/Test/TestPythonSyntax.py +++ b/src/Mod/Test/TestPythonSyntax.py @@ -21,8 +21,6 @@ #* * #***************************************************************************/ - -import sys import os import ast import unittest @@ -35,8 +33,7 @@ def test_python_syntax(rootdir, whitelist=None): for sub_dir, dirs, files in os.walk(rootdir): for fn in files: kargs = {} - if sys.version_info.major >= 3: - kargs["encoding"] = "utf-8" + kargs["encoding"] = "utf-8" if (not fn in whitelist) and os.path.splitext(fn)[1] == '.py': with open(os.path.join(sub_dir, fn), **kargs) as py_file: try: diff --git a/src/Mod/Test/UnitTests.py b/src/Mod/Test/UnitTests.py index e35da07fef..575f6f5680 100644 --- a/src/Mod/Test/UnitTests.py +++ b/src/Mod/Test/UnitTests.py @@ -53,20 +53,20 @@ class UnitBasicCases(unittest.TestCase): def testConversions(self): #tu = FreeCAD.Units.translateUnit - self.failUnless(compare(tu('10 m'), 10000.0)) - self.failUnless(compare(tu('3/8 in'), 9.525)) - self.failUnless(compare(tu('100 km/h'), 27777.77777777)) - self.failUnless(compare(tu('m^2*kg*s^-3*A^-2'), 1000000.0)) - self.failUnless(compare(tu('(m^2*kg)/(A^2*s^3)'), 1000000.0)) - self.failUnless(compare(tu('2*pi rad'), 360.0)) - self.failUnless(compare(tu('2*pi rad') / tu('gon'), 400.0)) - self.failUnless(compare(tu('999 kg') / tu('1 m^3'), 0.000009999)) + self.assertTrue(compare(tu('10 m'), 10000.0)) + self.assertTrue(compare(tu('3/8 in'), 9.525)) + self.assertTrue(compare(tu('100 km/h'), 27777.77777777)) + self.assertTrue(compare(tu('m^2*kg*s^-3*A^-2'), 1000000.0)) + self.assertTrue(compare(tu('(m^2*kg)/(A^2*s^3)'), 1000000.0)) + self.assertTrue(compare(tu('2*pi rad'), 360.0)) + self.assertTrue(compare(tu('2*pi rad') / tu('gon'), 400.0)) + self.assertTrue(compare(tu('999 kg') / tu('1 m^3'), 0.000009999)) def testImperial(self): #tu = FreeCAD.Units.translateUnit - self.failUnless(compare(tu('3/8in'), 9.525)) - #self.failUnless(compare(tu('1fo(3+7/16)in'),392.112500))thisgivesaparsersyntaxerror!!! - self.failUnless(compare(tu('1\'(3+7/16)"'), 392.112500)) + self.assertTrue(compare(tu('3/8in'), 9.525)) + #self.assertTrue(compare(tu('1fo(3+7/16)in'),392.112500))thisgivesaparsersyntaxerror!!! + self.assertTrue(compare(tu('1\'(3+7/16)"'), 392.112500)) psi = FreeCAD.Units.parseQuantity("1psi") mpa = psi.getValueAs("MPa").Value @@ -109,6 +109,13 @@ class UnitBasicCases(unittest.TestCase): v = FreeCAD.Units.parseQuantity(t[0]).getValueAs("ksi") self.assertAlmostEqual(1, v.Value, msg="Failed with \"{0}\" scheme: {1} != 1 (delta: {2})".format(schemes[i], v.Value, self.delta), delta=self.delta) + vacuum_permittivity = FreeCAD.Units.parseQuantity("1F/m") + vacuum_permittivity.Format = {"NumberFormat" : FreeCAD.Units.NumberFormat.Scientific} + for i in range(num): + t = FreeCAD.Units.schemaTranslate(vacuum_permittivity, i) + v = FreeCAD.Units.parseQuantity(t[0]).getValueAs("F/m") + self.assertAlmostEqual(1, v.Value, msg="Failed with \"{0}\" scheme: {1} != 1 (delta: {2})".format(schemes[i], v.Value, self.delta), delta=self.delta) + def testSchemeTranslation(self): quantities = [] for i in dir(FreeCAD.Units): @@ -143,9 +150,9 @@ class UnitBasicCases(unittest.TestCase): def testTrigonometric(self): #tu=FreeCAD.Units.translateUnit - self.failUnless(compare(tu('sin(pi)'), math.sin(math.pi))) - self.failUnless(compare(tu('cos(pi)'), math.cos(math.pi))) - self.failUnless(compare(tu('tan(pi)'), math.tan(math.pi))) + self.assertTrue(compare(tu('sin(pi)'), math.sin(math.pi))) + self.assertTrue(compare(tu('cos(pi)'), math.cos(math.pi))) + self.assertTrue(compare(tu('tan(pi)'), math.tan(math.pi))) def testQuantity(self): length = FreeCAD.Units.Quantity(1, "m") diff --git a/src/Mod/Web/App/AppWeb.cpp b/src/Mod/Web/App/AppWeb.cpp index 41bc08c725..15c5c5c41c 100644 --- a/src/Mod/Web/App/AppWeb.cpp +++ b/src/Mod/Web/App/AppWeb.cpp @@ -80,7 +80,7 @@ public: initialize("This module is the Web module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object startServer(const Py::Tuple& args) diff --git a/src/Mod/Web/App/Server.h b/src/Mod/Web/App/Server.h index 6469238607..b1e9a2ac99 100644 --- a/src/Mod/Web/App/Server.h +++ b/src/Mod/Web/App/Server.h @@ -50,9 +50,9 @@ private: class FirewallPython : public Firewall { public: - FirewallPython(const Py::Object&); - virtual ~FirewallPython(); - virtual bool filter(const QByteArray&) const; + explicit FirewallPython(const Py::Object&); + ~FirewallPython() override; + bool filter(const QByteArray&) const override; private: Py::Object obj; @@ -62,7 +62,7 @@ class ServerEvent : public QEvent { public: ServerEvent(QTcpSocket* socket, const QByteArray&); - ~ServerEvent(); + ~ServerEvent() override; QTcpSocket* socket() const; const QByteArray& request() const; @@ -80,11 +80,11 @@ class AppServer : public QTcpServer Q_OBJECT public: - AppServer(bool direct = false, QObject* parent = nullptr); + explicit AppServer(bool direct = false, QObject* parent = nullptr); protected: - void incomingConnection(qintptr socket); - void customEvent(QEvent* e); + void incomingConnection(qintptr socket) override; + void customEvent(QEvent* e) override; private: std::string handleRequest(QByteArray); diff --git a/src/Mod/Web/Gui/AppWebGui.cpp b/src/Mod/Web/Gui/AppWebGui.cpp index 5fd356ae84..f872b334a2 100644 --- a/src/Mod/Web/Gui/AppWebGui.cpp +++ b/src/Mod/Web/Gui/AppWebGui.cpp @@ -38,7 +38,7 @@ // use a different name to CreateCommand() -void CreateWebCommands(void); +void CreateWebCommands(); void loadWebResource() { @@ -70,7 +70,7 @@ public: initialize("This module is the WebGui module."); // register with Python } - virtual ~Module() {} + ~Module() override {} private: Py::Object openBrowser(const Py::Tuple& args) diff --git a/src/Mod/Web/Gui/BrowserView.cpp b/src/Mod/Web/Gui/BrowserView.cpp index 1f65cb4ca4..40ef609db4 100644 --- a/src/Mod/Web/Gui/BrowserView.cpp +++ b/src/Mod/Web/Gui/BrowserView.cpp @@ -85,13 +85,13 @@ enum WebAction { class WebEngineUrlRequestInterceptor : public QWebEngineUrlRequestInterceptor { public: - WebEngineUrlRequestInterceptor(BrowserView *parent) : + explicit WebEngineUrlRequestInterceptor(BrowserView *parent) : QWebEngineUrlRequestInterceptor(parent), m_parent(parent) { } - void interceptRequest(QWebEngineUrlRequestInfo &info) + void interceptRequest(QWebEngineUrlRequestInfo &info) override { // do something with this resource, click or get img for example if (info.navigationType() == QWebEngineUrlRequestInfo::NavigationTypeLink) { @@ -156,11 +156,11 @@ public: using BaseType = Py::PythonExtension; static void init_type(); // announce properties and methods - BrowserViewPy(BrowserView* view); - ~BrowserViewPy(); + explicit BrowserViewPy(BrowserView* view); + ~BrowserViewPy() override; - Py::Object repr(); - Py::Object getattr(const char *); + Py::Object repr() override; + Py::Object getattr(const char *) override; Py::Object cast_to_base(const Py::Tuple&); Py::Object setHtml(const Py::Tuple&); @@ -231,7 +231,7 @@ Py::Object BrowserViewPy::getattr(const char * attr) if (name == "__dict__" || name == "__class__") { Py::Dict dict_self(BaseType::getattr("__dict__")); Py::Dict dict_base(base.getattr("__dict__")); - for (auto it : dict_base) { + for (const auto& it : dict_base) { dict_self.setItem(it.first, it.second); } return dict_self; @@ -405,10 +405,10 @@ void WebView::triggerContextMenuAction(int id) switch (id) { case WebAction::OpenLink: - openLinkInExternalBrowser(url); + Q_EMIT openLinkInExternalBrowser(url); break; case WebAction::OpenLinkInNewWindow: - openLinkInNewWindow(url); + Q_EMIT openLinkInNewWindow(url); break; case WebAction::ViewSource: Q_EMIT viewSource(url); @@ -533,8 +533,7 @@ void BrowserView::urlFilter(const QUrl & url) //QString username = url.userName(); // path handling - QString path = url.path(); - QFileInfo fi(path); + QString path = url.path(); QUrl exturl(url); // query @@ -735,7 +734,7 @@ void BrowserView::setHtml(const QString& HtmlCode,const QUrl & BaseUrl) #endif } -void BrowserView::stop(void) +void BrowserView::stop() { view->stop(); } @@ -868,12 +867,12 @@ bool BrowserView::onHasMsg(const char* pMsg) const } /** Checking on close state. */ -bool BrowserView::canClose(void) +bool BrowserView::canClose() { return true; } -PyObject* BrowserView::getPyObject(void) +PyObject* BrowserView::getPyObject() { static bool init = false; if (!init) { diff --git a/src/Mod/Web/Gui/BrowserView.h b/src/Mod/Web/Gui/BrowserView.h index 42b8107775..8b16e03de4 100644 --- a/src/Mod/Web/Gui/BrowserView.h +++ b/src/Mod/Web/Gui/BrowserView.h @@ -56,12 +56,12 @@ class WebGuiExport WebView : public QWebView Q_OBJECT public: - WebView(QWidget *parent = nullptr); + explicit WebView(QWidget *parent = nullptr); protected: - void mousePressEvent(QMouseEvent *event); - void wheelEvent(QWheelEvent *event); - void contextMenuEvent(QContextMenuEvent *event); + void mousePressEvent(QMouseEvent *event) override; + void wheelEvent(QWheelEvent *event) override; + void contextMenuEvent(QContextMenuEvent *event) override; private Q_SLOTS: void triggerContextMenuAction(int); @@ -81,27 +81,27 @@ class WebGuiExport BrowserView : public Gui::MDIView, { Q_OBJECT - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: - BrowserView(QWidget* parent); - ~BrowserView(); + explicit BrowserView(QWidget* parent); + ~BrowserView() override; void load(const char* URL); void load(const QUrl & url); void setHtml(const QString& HtmlCode,const QUrl & BaseUrl); - void stop(void); + void stop(); QUrl url() const; - void OnChange(Base::Subject &rCaller,const char* rcReason); + void OnChange(Base::Subject &rCaller,const char* rcReason) override; - const char *getName(void) const {return "BrowserView";} - virtual PyObject *getPyObject(void); + const char *getName() const override {return "BrowserView";} + PyObject *getPyObject() override; - bool onMsg(const char* pMsg,const char** ppReturn); - bool onHasMsg(const char* pMsg) const; + bool onMsg(const char* pMsg,const char** ppReturn) override; + bool onHasMsg(const char* pMsg) const override; - bool canClose (void); + bool canClose () override; #ifdef QTWEBENGINE public Q_SLOTS: @@ -145,10 +145,10 @@ class UrlWidget : public QLineEdit BrowserView *m_view; public: explicit UrlWidget(BrowserView *view); - ~UrlWidget(); + ~UrlWidget() override; void display(); protected: - void keyPressEvent(QKeyEvent *keyEvt); + void keyPressEvent(QKeyEvent *keyEvt) override; }; } // namespace WebGui diff --git a/src/Mod/Web/Gui/CMakeLists.txt b/src/Mod/Web/Gui/CMakeLists.txt index e1aac2d4ac..8167f35779 100644 --- a/src/Mod/Web/Gui/CMakeLists.txt +++ b/src/Mod/Web/Gui/CMakeLists.txt @@ -4,6 +4,7 @@ include_directories( ${COIN3D_INCLUDE_DIRS} ${ZLIB_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS} + ${XercesC_INCLUDE_DIRS} ) if (Qt5WebEngineWidgets_FOUND) diff --git a/src/Mod/Web/Gui/Command.cpp b/src/Mod/Web/Gui/Command.cpp index 2272b6d93b..88f87cb18f 100644 --- a/src/Mod/Web/Gui/Command.cpp +++ b/src/Mod/Web/Gui/Command.cpp @@ -83,7 +83,7 @@ void CmdWebBrowserBack::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('Back')"); } -bool CmdWebBrowserBack::isActive(void) +bool CmdWebBrowserBack::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Back"); } @@ -112,7 +112,7 @@ void CmdWebBrowserNext::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('Next')"); } -bool CmdWebBrowserNext::isActive(void) +bool CmdWebBrowserNext::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Next"); } @@ -141,7 +141,7 @@ void CmdWebBrowserRefresh::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('Refresh')"); } -bool CmdWebBrowserRefresh::isActive(void) +bool CmdWebBrowserRefresh::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Refresh"); } @@ -170,7 +170,7 @@ void CmdWebBrowserStop::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('Stop')"); } -bool CmdWebBrowserStop::isActive(void) +bool CmdWebBrowserStop::isActive() { return getGuiApplication()->sendHasMsgToActiveView("Stop"); } @@ -199,7 +199,7 @@ void CmdWebBrowserZoomIn::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('ZoomIn')"); } -bool CmdWebBrowserZoomIn::isActive(void) +bool CmdWebBrowserZoomIn::isActive() { return getGuiApplication()->sendHasMsgToActiveView("ZoomIn"); } @@ -228,7 +228,7 @@ void CmdWebBrowserZoomOut::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('ZoomOut')"); } -bool CmdWebBrowserZoomOut::isActive(void) +bool CmdWebBrowserZoomOut::isActive() { return getGuiApplication()->sendHasMsgToActiveView("ZoomOut"); } @@ -257,14 +257,14 @@ void CmdWebBrowserSetURL::activated(int iMsg) doCommand(Command::Gui,"Gui.SendMsgToActiveView('SetURL')"); } -bool CmdWebBrowserSetURL::isActive(void) +bool CmdWebBrowserSetURL::isActive() { return getGuiApplication()->sendHasMsgToActiveView("SetURL"); } -void CreateWebCommands(void) +void CreateWebCommands() { Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager(); diff --git a/src/Mod/Web/Gui/CookieJar.h b/src/Mod/Web/Gui/CookieJar.h index 7ccdaa43ec..4ac7a83838 100644 --- a/src/Mod/Web/Gui/CookieJar.h +++ b/src/Mod/Web/Gui/CookieJar.h @@ -38,9 +38,9 @@ namespace WebGui { Q_OBJECT public: - FcCookieJar(QObject* parent = nullptr); - virtual ~FcCookieJar(); - virtual bool setCookiesFromUrl(const QList&, const QUrl&); + explicit FcCookieJar(QObject* parent = nullptr); + ~FcCookieJar() override; + bool setCookiesFromUrl(const QList&, const QUrl&) override; public Q_SLOTS: void scheduleSaveToDisk(); diff --git a/src/Mod/Web/Gui/Workbench.h b/src/Mod/Web/Gui/Workbench.h index 88949dc294..fd8be1669e 100644 --- a/src/Mod/Web/Gui/Workbench.h +++ b/src/Mod/Web/Gui/Workbench.h @@ -33,24 +33,24 @@ namespace WebGui { */ class Workbench : public Gui::StdWorkbench { - TYPESYSTEM_HEADER(); + TYPESYSTEM_HEADER_WITH_OVERRIDE(); public: Workbench(); - virtual ~Workbench(); + ~Workbench() override; /** Defines the standard context menu. */ - virtual void setupContextMenu(const char* recipient,Gui::MenuItem*) const; + void setupContextMenu(const char* recipient,Gui::MenuItem*) const override; protected: /** Defines the standard menus. */ - virtual Gui::MenuItem* setupMenuBar() const; + Gui::MenuItem* setupMenuBar() const override; /** Defines the standard toolbars. */ - virtual Gui::ToolBarItem* setupToolBars() const; + Gui::ToolBarItem* setupToolBars() const override; /** Defines the standard command bars. */ - virtual Gui::ToolBarItem* setupCommandBars() const; + Gui::ToolBarItem* setupCommandBars() const override; /** Returns a DockWindowItems structure of dock windows this workbench. */ - virtual Gui::DockWindowItems* setupDockWindows() const; + Gui::DockWindowItems* setupDockWindows() const override; }; // namespace WebGui diff --git a/src/Tools/MakeMacBundleRelocatable.py b/src/Tools/MakeMacBundleRelocatable.py index 953cc28b10..6610021189 100755 --- a/src/Tools/MakeMacBundleRelocatable.py +++ b/src/Tools/MakeMacBundleRelocatable.py @@ -212,7 +212,7 @@ def build_deps_graph(graph, bundle_path, dirs_filter=None, search_paths=[]): visited = {} for root, dirs, files in os.walk(bundle_path): - if dirs_filter != None: + if dirs_filter is not None: dirs[:] = [d for d in dirs if should_visit(bundle_path, dirs_filter, os.path.join(root, d))] diff --git a/src/Tools/MemoryLeaks.py b/src/Tools/MemoryLeaks.py index 225b21a012..441d0f8843 100755 --- a/src/Tools/MemoryLeaks.py +++ b/src/Tools/MemoryLeaks.py @@ -14,10 +14,10 @@ d=dict() l=list() for line in lines: r=re.search("\\(#\\s*\\d+\\)",line) - if r != None: + if r is not None: s=line[r.start():r.end()] t=re.search("^Leak",line) - if t != None: + if t is not None: m=d[s] l.append(m) else: diff --git a/src/Tools/SubWCRev.py b/src/Tools/SubWCRev.py index 195d0facc3..388a4376f9 100644 --- a/src/Tools/SubWCRev.py +++ b/src/Tools/SubWCRev.py @@ -97,7 +97,7 @@ class DebianChangelog(VersionControl): c = f.readline() f.close() r=re.search("bzr(\\d+)",c) - if r != None: + if r is not None: self.rev = r.groups()[0] + " (Launchpad)" t = time.localtime() @@ -116,11 +116,11 @@ class BazaarControl(VersionControl): lines=info.split("\n") for i in lines: r = re.match("^revno: (\\d+)$", i) - if r != None: + if r is not None: self.rev = r.groups()[0] continue r=re.match("^timestamp: (\\w+ \\d+-\\d+-\\d+ \\d+:\\d+:\\d+)",i) - if r != None: + if r is not None: self.date = r.groups()[0] continue return True @@ -325,7 +325,7 @@ class GitControl(VersionControl): self.date = time.strftime("%Y/%m/%d %H:%M:%S",time.gmtime(\ float(info.strip().split(' ',1)[0]))) for self.branch in os.popen("git branch --no-color").read().split('\n'): - if re.match( "\*", self.branch ) != None: + if re.match( "\*", self.branch ) is not None: break self.branch=self.branch[2:] self.getremotes() #setup self.remotes and branchlst @@ -356,7 +356,7 @@ class GitControl(VersionControl): if self.url == "Unknown": for i in info: r = re.match("origin\\W+(\\S+)",i) - if r != None: + if r is not None: self.url = r.groups()[0] break return True @@ -421,12 +421,12 @@ class Subversion(VersionControl): # if version string ends with an 'M' r=re.search("M$",Ver) - if r != None: + if r is not None: self.mods = 'Src modified' # if version string contains a range r=re.match("^\\d+\\:\\d+",Ver) - if r != None: + if r is not None: self.mixed = 'Src mixed' self.range = Ver[:r.end()] return True diff --git a/src/Tools/fcbt/DistSetup.py b/src/Tools/fcbt/DistSetup.py index 76b357a533..2085caef14 100644 --- a/src/Tools/fcbt/DistSetup.py +++ b/src/Tools/fcbt/DistSetup.py @@ -7,7 +7,7 @@ DistInst = DistName + "_installer.msi" DistDir = "../../DistTemp/" #==================================================================== -# copy intaller file +# copy installer file FileTools.cpfile("../../Install/FreeCAD.msi",DistDir+DistInst) diff --git a/src/Tools/fcinfo b/src/Tools/fcinfo index 0e7e8412c8..4ce5f34036 100755 --- a/src/Tools/fcinfo +++ b/src/Tools/fcinfo @@ -1,4 +1,4 @@ -#!/usr/bin/python +#!/usr/bin/python3 # -*- coding: utf8 -*- diff --git a/src/Tools/generateTemplates/templateClassPyExport.py b/src/Tools/generateTemplates/templateClassPyExport.py index 0ea79f3a25..b0c1aab253 100644 --- a/src/Tools/generateTemplates/templateClassPyExport.py +++ b/src/Tools/generateTemplates/templateClassPyExport.py @@ -225,7 +225,7 @@ public: - //@} -+ if(self.export.CustomAttributes != None): ++ if(self.export.CustomAttributes is not None): /// getter method for special attributes (e.g. dynamic ones) PyObject *getCustomAttributes(const char* attr) const; /// setter for special attributes (e.g. dynamic ones) @@ -720,7 +720,7 @@ PyObject *@self.export.Name@::_repr() return Py_BuildValue("s", representation().c_str()); } -+ if(self.export.CustomAttributes != None): ++ if(self.export.CustomAttributes is not None): //-------------------------------------------------------------------------- // @self.export.Name@ Attributes //-------------------------------------------------------------------------- @@ -1119,7 +1119,7 @@ void @self.export.Name@::set@i.Name@(Py::@i.Parameter.Type@ arg) } - - -+ if(self.export.CustomAttributes != None): ++ if(self.export.CustomAttributes is not None): PyObject *@self.export.Name@::getCustomAttributes(const char* /*attr*/) const { @@ -1446,7 +1446,7 @@ void @self.export.Name@::set@i.Name@(Py::@i.Parameter.Type@ /*arg*/) } - - -+ if(self.export.CustomAttributes != None): ++ if(self.export.CustomAttributes is not None): PyObject *@self.export.Name@::getCustomAttributes(const char* /*attr*/) const { diff --git a/src/Tools/plugins/widget/customwidgets.h b/src/Tools/plugins/widget/customwidgets.h index 31a611cea8..ac31837653 100644 --- a/src/Tools/plugins/widget/customwidgets.h +++ b/src/Tools/plugins/widget/customwidgets.h @@ -204,22 +204,24 @@ private: /** * There is a bug in QtDesigner of Qt version 4.0, 4.1 and 4.2. If a class declaration - * is inside a namespace and it uses the Q_ENUMS macro then QtDesigner doesn't handle + * is inside a namespace and it uses the Q_ENUM macro then QtDesigner doesn't handle * the enum(s) correctly in its property editor. This bug is fixed since Qt 4.3.0. */ class FileChooser : public QWidget { Q_OBJECT - Q_ENUMS( Mode ) +public: + enum Mode { File, Directory }; + +private: + Q_ENUM( Mode ) Q_PROPERTY( Mode mode READ mode WRITE setMode ) Q_PROPERTY( QString fileName READ fileName WRITE setFileName ) Q_PROPERTY( QString filter READ filter WRITE setFilter ) Q_PROPERTY( QString buttonText READ buttonText WRITE setButtonText ) public: - enum Mode { File, Directory }; - FileChooser (QWidget *parent = 0); virtual ~FileChooser(); @@ -231,7 +233,7 @@ public: public Q_SLOTS: void setFileName( const QString &fn ); - void setMode( Mode m ); + void setMode( FileChooser::Mode m ); void setFilter ( const QString & ); void setButtonText ( const QString & ); diff --git a/src/XDGData/org.freecadweb.FreeCAD.xml b/src/XDGData/org.freecadweb.FreeCAD.xml index aa80562d15..cea07e7181 100644 --- a/src/XDGData/org.freecadweb.FreeCAD.xml +++ b/src/XDGData/org.freecadweb.FreeCAD.xml @@ -4,6 +4,6 @@ FreeCAD document files - + diff --git a/src/zipios++/collcoll.cpp b/src/zipios++/collcoll.cpp index 25f784bef9..92c25af1c8 100644 --- a/src/zipios++/collcoll.cpp +++ b/src/zipios++/collcoll.cpp @@ -31,7 +31,7 @@ bool CollectionCollection::addCollection( const FileCollection &collection ) { bool CollectionCollection::addCollection( FileCollection *collection ) { if ( ! _valid ) throw InvalidStateException( "Attempt to add a FileCollection to an invalid CollectionCollection" ) ; - if ( collection == nullptr || this == collection || ! collection->isValid() ) + if ( !collection || this == collection || ! collection->isValid() ) return false ; _collections.push_back( collection ) ; return true ; @@ -87,7 +87,7 @@ istream *CollectionCollection::getInputStream( const string &entry_name, getEntry( entry_name, cep, it, matchpath ) ; - if ( cep == nullptr ) + if ( !cep ) return nullptr ; else return (*it)->getInputStream( entry_name ) ; diff --git a/src/zipios++/dircoll.cpp b/src/zipios++/dircoll.cpp index 7460e0a598..024d56ab67 100644 --- a/src/zipios++/dircoll.cpp +++ b/src/zipios++/dircoll.cpp @@ -81,7 +81,7 @@ std::istream *DirectoryCollection::getInputStream( const string &entry_name, ConstEntryPointer ent = getEntry( entry_name, matchpath ) ; - if ( ent == nullptr ) + if ( !ent ) return nullptr ; else { string real_path( _filepath + entry_name ) ; diff --git a/src/zipios++/directory.cpp b/src/zipios++/directory.cpp index 34b70d7106..6d21e72483 100644 --- a/src/zipios++/directory.cpp +++ b/src/zipios++/directory.cpp @@ -85,7 +85,7 @@ struct boost::filesystem::dir_it::representation { m_stat_p = false; dirent *rc = readdir(m_handle); - if (rc != nullptr) + if (rc) m_current = rc->d_name; else { @@ -183,14 +183,14 @@ namespace boost template <> std::string get(dir_it const &it) { struct passwd *pw = getpwuid(it.rep->get_stat().st_uid); - if (pw == nullptr) + if (!pw) throw unknown_uid(it.rep->get_stat().st_uid); return pw->pw_name; } template <> void set(dir_it const &it, std::string name) { struct passwd *pw = getpwnam(name.c_str()); - if (pw != nullptr) + if (pw) it.rep->change_owner(pw->pw_uid); else throw unknown_uname(name); @@ -201,14 +201,14 @@ namespace boost template <> std::string get(dir_it const &it) { struct group *grp = getgrgid(it.rep->get_stat().st_gid); - if (grp == nullptr) + if (!grp) throw unknown_gid(it.rep->get_stat().st_gid); return grp->gr_name; } template <> void set(dir_it const &it, std::string name) { struct group *grp = getgrnam(name.c_str()); - if (grp != nullptr) + if (grp) it.rep->change_group(grp->gr_gid); else throw unknown_gname(name); diff --git a/src/zipios++/filterinputstreambuf.cpp b/src/zipios++/filterinputstreambuf.cpp index b7dc00d6bd..5119b84f34 100644 --- a/src/zipios++/filterinputstreambuf.cpp +++ b/src/zipios++/filterinputstreambuf.cpp @@ -10,14 +10,14 @@ FilterInputStreambuf::FilterInputStreambuf( streambuf *inbuf, bool del_inbuf ) _del_inbuf( del_inbuf ) { _s_pos = 0; - if ( _inbuf == nullptr ) { + if (!_inbuf) { // throw an exception } } FilterInputStreambuf::~FilterInputStreambuf() { - if ( _del_inbuf ) + if (_del_inbuf) delete _inbuf ; } diff --git a/src/zipios++/filteroutputstreambuf.cpp b/src/zipios++/filteroutputstreambuf.cpp index 7f2ed3707a..8e6ddbae44 100644 --- a/src/zipios++/filteroutputstreambuf.cpp +++ b/src/zipios++/filteroutputstreambuf.cpp @@ -9,14 +9,14 @@ FilterOutputStreambuf::FilterOutputStreambuf( streambuf *outbuf, bool del_outbuf : _outbuf( outbuf), _del_outbuf( del_outbuf ) { - if ( _outbuf == nullptr ) { + if (!_outbuf) { // throw an exception } } FilterOutputStreambuf::~FilterOutputStreambuf() { - if ( _del_outbuf ) + if (_del_outbuf) delete _outbuf ; } diff --git a/src/zipios++/zipfile.cpp b/src/zipios++/zipfile.cpp index 3fbd1605bf..1d8a241f4a 100644 --- a/src/zipios++/zipfile.cpp +++ b/src/zipios++/zipfile.cpp @@ -73,7 +73,7 @@ istream *ZipFile::getInputStream( const string &entry_name, ConstEntryPointer ent = getEntry( entry_name, matchpath ) ; - if ( ent == nullptr ) + if ( !ent ) return nullptr ; else return new ZipInputStream( _filename,