From 50bb81e6fc533b328436065b2645fc1767a03894 Mon Sep 17 00:00:00 2001 From: wmayer Date: Sun, 10 Sep 2023 13:07:23 +0200 Subject: [PATCH] Sheet: Apply clang format --- src/Mod/Spreadsheet/App/AppSpreadsheet.cpp | 12 +- src/Mod/Spreadsheet/App/Cell.cpp | 665 +++++---- src/Mod/Spreadsheet/App/Cell.h | 114 +- src/Mod/Spreadsheet/App/DisplayUnit.h | 26 +- src/Mod/Spreadsheet/App/PreCompiled.h | 14 +- .../Spreadsheet/App/PropertyColumnWidths.cpp | 52 +- .../Spreadsheet/App/PropertyColumnWidths.h | 51 +- .../App/PropertyColumnWidthsPy.xml | 1 - .../App/PropertyColumnWidthsPyImp.cpp | 6 +- .../Spreadsheet/App/PropertyRowHeights.cpp | 53 +- src/Mod/Spreadsheet/App/PropertyRowHeights.h | 51 +- .../Spreadsheet/App/PropertyRowHeightsPy.xml | 1 - .../App/PropertyRowHeightsPyImp.cpp | 6 +- src/Mod/Spreadsheet/App/PropertySheet.cpp | 1293 ++++++++++------- src/Mod/Spreadsheet/App/PropertySheet.h | 204 +-- src/Mod/Spreadsheet/App/PropertySheetPy.xml | 1 - .../Spreadsheet/App/PropertySheetPyImp.cpp | 8 +- src/Mod/Spreadsheet/App/Sheet.cpp | 1149 ++++++++------- src/Mod/Spreadsheet/App/Sheet.h | 150 +- src/Mod/Spreadsheet/App/SheetObserver.cpp | 69 +- src/Mod/Spreadsheet/App/SheetObserver.h | 22 +- src/Mod/Spreadsheet/App/SheetPy.xml | 11 +- src/Mod/Spreadsheet/App/SheetPyImp.cpp | 648 +++++---- src/Mod/Spreadsheet/App/Utils.cpp | 165 ++- src/Mod/Spreadsheet/App/Utils.h | 15 +- 25 files changed, 2733 insertions(+), 2054 deletions(-) diff --git a/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp b/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp index 8b1ac253ed..9923062171 100644 --- a/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp +++ b/src/Mod/Spreadsheet/App/AppSpreadsheet.cpp @@ -30,13 +30,15 @@ #include "Sheet.h" -namespace Spreadsheet { -class Module : public Py::ExtensionModule +namespace Spreadsheet +{ +class Module: public Py::ExtensionModule { public: - Module() : Py::ExtensionModule("Spreadsheet") + Module() + : Py::ExtensionModule("Spreadsheet") { - initialize("This module is the Spreadsheet module."); // register with Python + initialize("This module is the Spreadsheet module.");// register with Python } private: @@ -46,7 +48,7 @@ PyObject* initModule() { return Base::Interpreter().addModule(new Module); } -} // namespace Spreadsheet +}// namespace Spreadsheet /* Python entry */ PyMOD_INIT_FUNC(Spreadsheet) diff --git a/src/Mod/Spreadsheet/App/Cell.cpp b/src/Mod/Spreadsheet/App/Cell.cpp index 298250fac6..cfa099f8c1 100644 --- a/src/Mod/Spreadsheet/App/Cell.cpp +++ b/src/Mod/Spreadsheet/App/Cell.cpp @@ -23,11 +23,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #endif #include @@ -55,19 +55,22 @@ using namespace Spreadsheet; ///////////////////////////////////////////////////////// // expose the read() function for simpler partial xml reading in setExpression() -class ReaderPrivate: public Base::XMLReader { +class ReaderPrivate: public Base::XMLReader +{ public: - ReaderPrivate(const char* FileName, std::istream &is) - :XMLReader(FileName,is) + ReaderPrivate(const char* FileName, std::istream& is) + : XMLReader(FileName, is) {} - bool read() { + bool read() + { return XMLReader::read(); } }; /////////////////////////////////////////////////////////// +// clang-format off const int Cell::EXPRESSION_SET = 1; const int Cell::ALIGNMENT_SET = 4; const int Cell::STYLE_SET = 8; @@ -93,15 +96,16 @@ const int Cell::ALIGNMENT_VCENTER = 0x20; const int Cell::ALIGNMENT_BOTTOM = 0x40; const int Cell::ALIGNMENT_VIMPLIED = 0x80; const int Cell::ALIGNMENT_VERTICAL = 0xf0; +// clang-format on /** - * Construct a CellContent object. - * @param _address The address of the cell (i.e. row and column) - * @param _owner The spreadsheet that owns this cell. - * - */ + * Construct a CellContent object. + * @param _address The address of the cell (i.e. row and column) + * @param _owner The spreadsheet that owns this cell. + * + */ -Cell::Cell(const CellAddress &_address, PropertySheet *_owner) +Cell::Cell(const CellAddress& _address, PropertySheet* _owner) : address(_address) , owner(_owner) , used(0) @@ -119,7 +123,7 @@ Cell::Cell(const CellAddress &_address, PropertySheet *_owner) assert(address.isValid()); } -Cell::Cell(PropertySheet *_owner, const Cell &other) +Cell::Cell(PropertySheet* _owner, const Cell& other) : address(other.address) , owner(_owner) , used(other.used) @@ -138,7 +142,7 @@ Cell::Cell(PropertySheet *_owner, const Cell &other) setDirty(); } -Cell &Cell::operator =(const Cell &rhs) +Cell& Cell::operator=(const Cell& rhs) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -162,18 +166,18 @@ Cell &Cell::operator =(const Cell &rhs) } /** - * Destroy a CellContent object. - * - */ + * Destroy a CellContent object. + * + */ Cell::~Cell() = default; /** - * Set the expression tree to \a expr. - * - */ + * Set the expression tree to \a expr. + * + */ -void Cell::setExpression(App::ExpressionPtr &&expr) +void Cell::setExpression(App::ExpressionPtr&& expr) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -182,21 +186,23 @@ void Cell::setExpression(App::ExpressionPtr &&expr) /* Remove dependencies */ owner->removeDependencies(address); - if(expr && !expr->comment.empty()) { - if(!boost::starts_with(expr->comment,"sheet()->getFullName() << '.' << address.toString()); + if (expr && !expr->comment.empty()) { + if (!boost::starts_with(expr->comment, "sheet()->getFullName() << '.' + << address.toString()); + } else { try { std::istringstream in(expr->comment); ReaderPrivate reader("", in); reader.read(); - restore(reader,true); - }catch(Base::Exception &e) { + restore(reader, true); + } + catch (Base::Exception& e) { e.ReportException(); - FC_ERR("Failed to restore style of cell " - << owner->sheet()->getFullName() << '.' - << address.toString() << ": " << e.what()); + FC_ERR("Failed to restore style of cell " << owner->sheet()->getFullName() << '.' + << address.toString() << ": " + << e.what()); } } expr->comment.clear(); @@ -212,23 +218,18 @@ void Cell::setExpression(App::ExpressionPtr &&expr) } /** - * Get the expression tree. - * - */ + * Get the expression tree. + * + */ -const App::Expression *Cell::getExpression(bool withFormat) const +const App::Expression* Cell::getExpression(bool withFormat) const { - if(withFormat && expression) { - if((used & (ALIGNMENT_SET - | STYLE_SET - | FOREGROUND_COLOR_SET - | BACKGROUND_COLOR_SET - | DISPLAY_UNIT_SET - | ALIAS_SET - | SPANS_SET))) - { + if (withFormat && expression) { + if ((used + & (ALIGNMENT_SET | STYLE_SET | FOREGROUND_COLOR_SET | BACKGROUND_COLOR_SET + | DISPLAY_UNIT_SET | ALIAS_SET | SPANS_SET))) { std::ostringstream ss; - save(ss,"",true); + save(ss, "", true); expression->comment = ss.str(); } } @@ -236,26 +237,30 @@ const App::Expression *Cell::getExpression(bool withFormat) const } /** - * Get string content. - * - */ + * Get string content. + * + */ -bool Cell::getStringContent(std::string & s, bool persistent) const +bool Cell::getStringContent(std::string& s, bool persistent) const { if (expression) { s.clear(); - if(expression->hasComponent()) + if (expression->hasComponent()) { s = "=" + expression->toString(persistent); + } else if (freecad_dynamic_cast(expression.get())) { s = static_cast(expression.get())->getText(); s = "'" + s; } - else if (freecad_dynamic_cast(expression.get())) + else if (freecad_dynamic_cast(expression.get())) { s = "=" + expression->toString(); - else if (freecad_dynamic_cast(expression.get())) + } + else if (freecad_dynamic_cast(expression.get())) { s = expression->toString(); - else + } + else { s = "=" + expression->toString(persistent); + } return true; } @@ -265,13 +270,15 @@ bool Cell::getStringContent(std::string & s, bool persistent) const } } -void Cell::afterRestore() { +void Cell::afterRestore() +{ auto expr = freecad_dynamic_cast(expression.get()); - if(expr) + if (expr) { setContent(expr->getText().c_str()); + } } -void Cell::setContent(const char * value) +void Cell::setContent(const char* value) { PropertySheet::AtomicPropertyChange signaller(*owner); ExpressionPtr newExpr; @@ -279,8 +286,9 @@ void Cell::setContent(const char * value) clearException(); if (value) { if (owner->sheet()->isRestoring()) { - if (value[0] == '\0' || (value[0] == '\'' && value[1] == '\0')) + if (value[0] == '\0' || (value[0] == '\'' && value[1] == '\0')) { return; + } expression = std::make_unique(owner->sheet(), value); setUsed(EXPRESSION_SET, true); return; @@ -289,26 +297,29 @@ void Cell::setContent(const char * value) try { newExpr = ExpressionPtr(App::ExpressionParser::parse(owner->sheet(), value + 1)); } - catch (Base::Exception & e) { + catch (Base::Exception& e) { newExpr = std::make_unique(owner->sheet(), value); setParseException(e.what()); } } else if (*value == '\'') { - if (value[1] == '\0') + if (value[1] == '\0') { value = nullptr; - else + } + else { newExpr = std::make_unique(owner->sheet(), value + 1); + } } else if (*value != '\0') { // check if value is just a number - char * end; + char* end; errno = 0; const double float_value = strtod(value, &end); if (errno == 0) { const bool isEndEmpty = *end == '\0' || strspn(end, " \t\n\r") == strlen(end); if (isEndEmpty) { - newExpr = std::make_unique(owner->sheet(), Quantity(float_value)); + newExpr = std::make_unique(owner->sheet(), + Quantity(float_value)); } } @@ -318,10 +329,13 @@ void Cell::setContent(const char * value) try { ExpressionPtr parsedExpr(App::ExpressionParser::parse(owner->sheet(), value)); - if (const auto fraction = freecad_dynamic_cast(parsedExpr.get())) { + if (const auto fraction = + freecad_dynamic_cast(parsedExpr.get())) { if (fraction->getOperator() == OperatorExpression::UNIT) { - const auto left = freecad_dynamic_cast(fraction->getLeft()); - const auto right = freecad_dynamic_cast(fraction->getRight()); + const auto left = + freecad_dynamic_cast(fraction->getLeft()); + const auto right = + freecad_dynamic_cast(fraction->getRight()); if (left && right) { newExpr = std::move(parsedExpr); } @@ -331,33 +345,44 @@ void Cell::setContent(const char * value) // 1/2, 1m/2, 1/2s, 1m/2s, 1/m // check for numbers in (de)nominator - const bool isNumberNom = freecad_dynamic_cast(fraction->getLeft()); - const bool isNumberDenom = freecad_dynamic_cast(fraction->getRight()); + const bool isNumberNom = + freecad_dynamic_cast(fraction->getLeft()); + const bool isNumberDenom = + freecad_dynamic_cast(fraction->getRight()); // check for numbers with units in (de)nominator - const auto opNom = freecad_dynamic_cast(fraction->getLeft()); - const auto opDenom = freecad_dynamic_cast(fraction->getRight()); - const bool isQuantityNom = opNom && opNom->getOperator() == OperatorExpression::UNIT; - const bool isQuantityDenom = opDenom && opDenom->getOperator() == OperatorExpression::UNIT; + const auto opNom = + freecad_dynamic_cast(fraction->getLeft()); + const auto opDenom = + freecad_dynamic_cast(fraction->getRight()); + const bool isQuantityNom = + opNom && opNom->getOperator() == OperatorExpression::UNIT; + const bool isQuantityDenom = + opDenom && opDenom->getOperator() == OperatorExpression::UNIT; // check for units in denomainator - const auto uDenom = freecad_dynamic_cast(fraction->getRight()); - const bool isUnitDenom = uDenom && uDenom->getTypeId() == UnitExpression::getClassTypeId(); + const auto uDenom = + freecad_dynamic_cast(fraction->getRight()); + const bool isUnitDenom = + uDenom && uDenom->getTypeId() == UnitExpression::getClassTypeId(); const bool isNomValid = isNumberNom || isQuantityNom; - const bool isDenomValid = isNumberDenom || isQuantityDenom || isUnitDenom; + const bool isDenomValid = + isNumberDenom || isQuantityDenom || isUnitDenom; if (isNomValid && isDenomValid) { newExpr = std::move(parsedExpr); } } } - else if (const auto number = freecad_dynamic_cast(parsedExpr.get())) { + else if (const auto number = + freecad_dynamic_cast(parsedExpr.get())) { // NumbersExpressions can accept more than can be parsed with strtod. // Example: 12.34 and 12,34 are both valid NumberExpressions newExpr = std::move(parsedExpr); } } - catch (...) {} + catch (...) { + } } } @@ -368,17 +393,18 @@ void Cell::setContent(const char * value) // trying to add an empty string will make newExpr = nullptr } - // set expression, or delete the current expression by setting nullptr if empty string was entered + // set expression, or delete the current expression by setting nullptr if empty string was + // entered setExpression(std::move(newExpr)); signaller.tryInvoke(); } /** - * Set alignment of this cell. Alignment is the or'ed value of - * vertical and horizontal alignment, given by the constants - * defined in the class. - * - */ + * Set alignment of this cell. Alignment is the or'ed value of + * vertical and horizontal alignment, given by the constants + * defined in the class. + * + */ void Cell::setAlignment(int _alignment) { @@ -386,29 +412,32 @@ void Cell::setAlignment(int _alignment) PropertySheet::AtomicPropertyChange signaller(*owner); alignment = _alignment; - setUsed(ALIGNMENT_SET, alignment != (ALIGNMENT_HIMPLIED | ALIGNMENT_LEFT | ALIGNMENT_VIMPLIED | ALIGNMENT_VCENTER)); + setUsed( + ALIGNMENT_SET, + alignment + != (ALIGNMENT_HIMPLIED | ALIGNMENT_LEFT | ALIGNMENT_VIMPLIED | ALIGNMENT_VCENTER)); setDirty(); signaller.tryInvoke(); } } /** - * Get alignment. - * - */ + * Get alignment. + * + */ -bool Cell::getAlignment(int & _alignment) const +bool Cell::getAlignment(int& _alignment) const { _alignment = alignment; return isUsed(ALIGNMENT_SET); } /** - * Set style to the given set \a _style. - * - */ + * Set style to the given set \a _style. + * + */ -void Cell::setStyle(const std::set & _style) +void Cell::setStyle(const std::set& _style) { if (_style != style) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -422,22 +451,22 @@ void Cell::setStyle(const std::set & _style) } /** - * Get the style of the cell. - * - */ + * Get the style of the cell. + * + */ -bool Cell::getStyle(std::set & _style) const +bool Cell::getStyle(std::set& _style) const { _style = style; return isUsed(STYLE_SET); } /** - * Set foreground (i.e text) color of the cell to \a color. - * - */ + * Set foreground (i.e text) color of the cell to \a color. + * + */ -void Cell::setForeground(const App::Color &color) +void Cell::setForeground(const App::Color& color) { if (color != foregroundColor) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -451,22 +480,22 @@ void Cell::setForeground(const App::Color &color) } /** - * Get foreground color of the cell. - * - */ + * Get foreground color of the cell. + * + */ -bool Cell::getForeground(App::Color &color) const +bool Cell::getForeground(App::Color& color) const { color = foregroundColor; return isUsed(FOREGROUND_COLOR_SET); } /** - * Set background color of the cell to \a color. - * - */ + * Set background color of the cell to \a color. + * + */ -void Cell::setBackground(const App::Color &color) +void Cell::setBackground(const App::Color& color) { if (color != backgroundColor) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -480,31 +509,33 @@ void Cell::setBackground(const App::Color &color) } /** - * Get the background color of the cell into \a color. - * - * @returns true if the background color was previously set. - * - */ + * Get the background color of the cell into \a color. + * + * @returns true if the background color was previously set. + * + */ -bool Cell::getBackground(App::Color &color) const +bool Cell::getBackground(App::Color& color) const { color = backgroundColor; return isUsed(BACKGROUND_COLOR_SET); } /** - * Set the display unit for the cell. - * - */ + * Set the display unit for the cell. + * + */ -void Cell::setDisplayUnit(const std::string &unit) +void Cell::setDisplayUnit(const std::string& unit) { DisplayUnit newDisplayUnit; if (!unit.empty()) { - std::shared_ptr e(ExpressionParser::parseUnit(owner->sheet(), unit.c_str())); + std::shared_ptr e( + ExpressionParser::parseUnit(owner->sheet(), unit.c_str())); - if (!e) + if (!e) { throw Base::UnitsMismatchError("Invalid unit"); + } newDisplayUnit = DisplayUnit(unit, e->getUnit(), e->getScaler()); } @@ -520,19 +551,19 @@ void Cell::setDisplayUnit(const std::string &unit) } /** - * Get the display unit for the cell into unit. - * - * @returns true if the display unit was previously set. - * - */ + * Get the display unit for the cell into unit. + * + * @returns true if the display unit was previously set. + * + */ -bool Cell::getDisplayUnit(DisplayUnit &unit) const +bool Cell::getDisplayUnit(DisplayUnit& unit) const { unit = displayUnit; return isUsed(DISPLAY_UNIT_SET); } -void Cell::setAlias(const std::string &n) +void Cell::setAlias(const std::string& n) { if (alias != n) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -550,7 +581,7 @@ void Cell::setAlias(const std::string &n) if (!alias.empty()) { // The property may have been added in Sheet::updateAlias - auto * docObj = static_cast(owner->getContainer()); + auto* docObj = static_cast(owner->getContainer()); docObj->removeDynamicProperty(alias.c_str()); } @@ -563,18 +594,18 @@ void Cell::setAlias(const std::string &n) } } -bool Cell::getAlias(std::string &n) const +bool Cell::getAlias(std::string& n) const { n = alias; return isUsed(ALIAS_SET); } /** - * Set the computed unit for the cell to \a unit. - * - */ + * Set the computed unit for the cell to \a unit. + * + */ -void Cell::setComputedUnit(const Base::Unit &unit) +void Cell::setComputedUnit(const Base::Unit& unit) { PropertySheet::AtomicPropertyChange signaller(*owner); @@ -586,23 +617,23 @@ void Cell::setComputedUnit(const Base::Unit &unit) } /** - * Get the computed unit into \a unit. - * - * @returns true if the computed unit was previously set. - * - */ + * Get the computed unit into \a unit. + * + * @returns true if the computed unit was previously set. + * + */ -bool Cell::getComputedUnit(Base::Unit & unit) const +bool Cell::getComputedUnit(Base::Unit& unit) const { unit = computedUnit; return isUsed(COMPUTED_UNIT_SET); } /** - * Set the cell's row and column span to \a rows and \a columns. This - * is done when cells are merged. - * - */ + * Set the cell's row and column span to \a rows and \a columns. This + * is done when cells are merged. + * + */ void Cell::setSpans(int rows, int columns) { @@ -611,49 +642,46 @@ void Cell::setSpans(int rows, int columns) rowSpan = (rows == -1 ? 1 : rows); colSpan = (columns == -1 ? 1 : columns); - setUsed(SPANS_SET, (rowSpan != 1 || colSpan != 1) ); + setUsed(SPANS_SET, (rowSpan != 1 || colSpan != 1)); setDirty(); signaller.tryInvoke(); } } /** - * Get the row and column spans for the cell into \a rows and \a columns. - * - */ + * Get the row and column spans for the cell into \a rows and \a columns. + * + */ -bool Cell::getSpans(int &rows, int &columns) const +bool Cell::getSpans(int& rows, int& columns) const { rows = rowSpan; columns = colSpan; return isUsed(SPANS_SET); } -void Cell::setException(const std::string &e, bool silent) +void Cell::setException(const std::string& e, bool silent) { - if(!silent && !e.empty() && owner && owner->sheet()) { - FC_ERR(owner->sheet()->getFullName() << '.' - << address.toString() << ": " << e); + if (!silent && !e.empty() && owner && owner->sheet()) { + FC_ERR(owner->sheet()->getFullName() << '.' << address.toString() << ": " << e); } exceptionStr = e; setUsed(EXCEPTION_SET); } -void Cell::setParseException(const std::string &e) +void Cell::setParseException(const std::string& e) { - if(!e.empty() && owner && owner->sheet()) { - FC_ERR(owner->sheet()->getFullName() << '.' - << address.toString() << ": " << e); + if (!e.empty() && owner && owner->sheet()) { + FC_ERR(owner->sheet()->getFullName() << '.' << address.toString() << ": " << e); } exceptionStr = e; setUsed(PARSE_EXCEPTION_SET); } -void Cell::setResolveException(const std::string &e) +void Cell::setResolveException(const std::string& e) { - if(!e.empty() && owner && owner->sheet()) { - FC_LOG(owner->sheet()->getFullName() << '.' - << address.toString() << ": " << e); + if (!e.empty() && owner && owner->sheet()) { + FC_LOG(owner->sheet()->getFullName() << '.' << address.toString() << ": " << e); } exceptionStr = e; setUsed(RESOLVE_EXCEPTION_SET); @@ -674,20 +702,22 @@ void Cell::clearException() void Cell::clearDirty() { - if(owner) + if (owner) { owner->clearDirty(address); + } } void Cell::setDirty() { - if(owner) + if (owner) { owner->setDirty(address); + } } /** - * Move the cell to a new position given by \a _row and \a _col. - * - */ + * Move the cell to a new position given by \a _row and \a _col. + * + */ void Cell::moveAbsolute(CellAddress newAddress) { @@ -695,23 +725,28 @@ void Cell::moveAbsolute(CellAddress newAddress) } /** - * Restore cell contents from \a reader. - * - */ + * Restore cell contents from \a reader. + * + */ -void Cell::restore(Base::XMLReader &reader, bool checkAlias) +void Cell::restore(Base::XMLReader& reader, bool checkAlias) { const char* style = reader.hasAttribute("style") ? reader.getAttribute("style") : nullptr; - const char* alignment = reader.hasAttribute("alignment") ? reader.getAttribute("alignment") : nullptr; + const char* alignment = + reader.hasAttribute("alignment") ? reader.getAttribute("alignment") : nullptr; const char* content = reader.hasAttribute("content") ? reader.getAttribute("content") : ""; - const char* foregroundColor = reader.hasAttribute("foregroundColor") ? reader.getAttribute("foregroundColor") : nullptr; - const char* backgroundColor = reader.hasAttribute("backgroundColor") ? reader.getAttribute("backgroundColor") : nullptr; - const char* displayUnit = reader.hasAttribute("displayUnit") ? reader.getAttribute("displayUnit") : nullptr; + const char* foregroundColor = + reader.hasAttribute("foregroundColor") ? reader.getAttribute("foregroundColor") : nullptr; + const char* backgroundColor = + reader.hasAttribute("backgroundColor") ? reader.getAttribute("backgroundColor") : nullptr; + const char* displayUnit = + reader.hasAttribute("displayUnit") ? reader.getAttribute("displayUnit") : nullptr; const char* alias = reader.hasAttribute("alias") ? reader.getAttribute("alias") : nullptr; const char* rowSpan = reader.hasAttribute("rowSpan") ? reader.getAttribute("rowSpan") : nullptr; const char* colSpan = reader.hasAttribute("colSpan") ? reader.getAttribute("colSpan") : nullptr; - // Don't trigger multiple updates below; wait until everything is loaded by calling unfreeze() below. + // Don't trigger multiple updates below; wait until everything is loaded by calling unfreeze() + // below. PropertySheet::AtomicPropertyChange signaller(*owner); if (content) { @@ -723,10 +758,12 @@ void Cell::restore(Base::XMLReader &reader, bool checkAlias) escaped_list_separator e('\0', '|', '\0'); std::string line = std::string(style); - tokenizer > tok(line, e); + tokenizer> tok(line, e); - for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); + ++i) { styleSet.insert(*i); + } setStyle(styleSet); } if (alignment) { @@ -735,10 +772,12 @@ void Cell::restore(Base::XMLReader &reader, bool checkAlias) escaped_list_separator e('\0', '|', '\0'); std::string line = std::string(alignment); - tokenizer > tok(line, e); + tokenizer> tok(line, e); - for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); + ++i) { alignmentCode = decodeAlignment(*i, alignmentCode); + } setAlignment(alignmentCode); } @@ -752,10 +791,12 @@ void Cell::restore(Base::XMLReader &reader, bool checkAlias) setBackground(color); } - if (displayUnit) + if (displayUnit) { setDisplayUnit(displayUnit); - if (alias && (!checkAlias || !owner->revAliasProp.count(alias))) + } + if (alias && (!checkAlias || !owner->revAliasProp.count(alias))) { setAlias(alias); + } if (rowSpan || colSpan) { int rs = rowSpan ? atoi(rowSpan) : 1; @@ -766,75 +807,87 @@ void Cell::restore(Base::XMLReader &reader, bool checkAlias) } /** - * Save cell contents into \a writer. - * - */ + * Save cell contents into \a writer. + * + */ -void Cell::save(Base::Writer &writer) const { - save(writer.Stream(),writer.ind(),false); +void Cell::save(Base::Writer& writer) const +{ + save(writer.Stream(), writer.ind(), false); } -void Cell::save(std::ostream &os, const char *indent, bool noContent) const { - if (!isUsed()) +void Cell::save(std::ostream& os, const char* indent, bool noContent) const +{ + if (!isUsed()) { return; + } os << indent << ""; - if(!noContent) + if (!noContent) { os << std::endl; + } } /** - * Update the \a used member variable with mask (bitwise or'ed). - * - */ + * Update the \a used member variable with mask (bitwise or'ed). + * + */ void Cell::setUsed(int mask, bool state) { - if (state) + if (state) { used |= mask; - else + } + else { used &= ~mask; + } } /** - * Determine whether the bits in \a mask are set in the \a used member variable. - * - */ + * Determine whether the bits in \a mask are set in the \a used member variable. + * + */ bool Cell::isUsed(int mask) const { @@ -842,128 +895,148 @@ bool Cell::isUsed(int mask) const } /** - * Determine if the any of the contents of the cell is set a non-default value. - * - */ + * Determine if the any of the contents of the cell is set a non-default value. + * + */ bool Cell::isUsed() const { return used != 0; } -void Cell::visit(App::ExpressionVisitor &v) +void Cell::visit(App::ExpressionVisitor& v) { - if (expression) + if (expression) { expression->visit(v); + } } /** - * Decode alignment into its internal value. - * - * @param itemStr Alignment as a string - * @param alignment Current alignment. This is or'ed with the one in \a itemStr. - * - * @returns New alignment. - * - */ + * Decode alignment into its internal value. + * + * @param itemStr Alignment as a string + * @param alignment Current alignment. This is or'ed with the one in \a itemStr. + * + * @returns New alignment. + * + */ -int Cell::decodeAlignment(const std::string & itemStr, int alignment) +int Cell::decodeAlignment(const std::string& itemStr, int alignment) { if (itemStr == "himplied") { - if(!(alignment & ALIGNMENT_HORIZONTAL)) + if (!(alignment & ALIGNMENT_HORIZONTAL)) { alignment |= ALIGNMENT_LEFT; + } alignment |= Cell::ALIGNMENT_HIMPLIED; - } else if (itemStr == "left") + } + else if (itemStr == "left") { alignment = (alignment & ~Cell::ALIGNMENT_HORIZONTAL) | Cell::ALIGNMENT_LEFT; - else if (itemStr == "center") + } + else if (itemStr == "center") { alignment = (alignment & ~Cell::ALIGNMENT_HORIZONTAL) | Cell::ALIGNMENT_HCENTER; - else if (itemStr == "right") + } + else if (itemStr == "right") { alignment = (alignment & ~Cell::ALIGNMENT_HORIZONTAL) | Cell::ALIGNMENT_RIGHT; + } else if (itemStr == "vimplied") { - if(!(alignment & ALIGNMENT_VERTICAL)) + if (!(alignment & ALIGNMENT_VERTICAL)) { alignment |= ALIGNMENT_VCENTER; + } alignment |= Cell::ALIGNMENT_VIMPLIED; - } else if (itemStr == "top") + } + else if (itemStr == "top") { alignment = (alignment & ~Cell::ALIGNMENT_VERTICAL) | Cell::ALIGNMENT_TOP; - else if (itemStr == "vcenter") + } + else if (itemStr == "vcenter") { alignment = (alignment & ~Cell::ALIGNMENT_VERTICAL) | Cell::ALIGNMENT_VCENTER; - else if (itemStr == "bottom") + } + else if (itemStr == "bottom") { alignment = (alignment & ~Cell::ALIGNMENT_VERTICAL) | Cell::ALIGNMENT_BOTTOM; - else if(!itemStr.empty()) + } + else if (!itemStr.empty()) { throw Base::ValueError("Invalid alignment."); + } return alignment; } /** - * Encode internal alignment value as a string. - * - * @param alignment Alignment as a binary value. - * - * @returns Alignment represented as a string. - * - */ + * Encode internal alignment value as a string. + * + * @param alignment Alignment as a binary value. + * + * @returns Alignment represented as a string. + * + */ std::string Cell::encodeAlignment(int alignment) { std::string s; - if (alignment & Cell::ALIGNMENT_LEFT) + if (alignment & Cell::ALIGNMENT_LEFT) { s += "left"; - if (alignment & Cell::ALIGNMENT_HCENTER) + } + if (alignment & Cell::ALIGNMENT_HCENTER) { s += "center"; - if (alignment & Cell::ALIGNMENT_RIGHT) + } + if (alignment & Cell::ALIGNMENT_RIGHT) { s += "right"; - if (alignment & Cell::ALIGNMENT_HIMPLIED) + } + if (alignment & Cell::ALIGNMENT_HIMPLIED) { s += "|himplied"; + } - if (alignment & Cell::ALIGNMENT_VERTICAL) + if (alignment & Cell::ALIGNMENT_VERTICAL) { s += "|"; + } - if (alignment & Cell::ALIGNMENT_TOP) + if (alignment & Cell::ALIGNMENT_TOP) { s += "top"; - if (alignment & Cell::ALIGNMENT_VCENTER) + } + if (alignment & Cell::ALIGNMENT_VCENTER) { s += "vcenter"; - if (alignment & Cell::ALIGNMENT_BOTTOM) + } + if (alignment & Cell::ALIGNMENT_BOTTOM) { s += "bottom"; - if (alignment & Cell::ALIGNMENT_VIMPLIED) + } + if (alignment & Cell::ALIGNMENT_VIMPLIED) { s += "|vimplied"; + } return s; } /** - * Encode \a color as a \#rrggbbaa string. - * - * @param color Color to encode. - * - * @returns String with encoded color. - * - */ + * Encode \a color as a \#rrggbbaa string. + * + * @param color Color to encode. + * + * @returns String with encoded color. + * + */ -std::string Cell::encodeColor(const App::Color & color) +std::string Cell::encodeColor(const App::Color& color) { std::stringstream tmp; - tmp << "#" - << std::hex << std::setw(2) << std::setfill('0') << int(color.r * 255.0) - << std::hex << std::setw(2) << std::setfill('0') << int(color.g * 255.0) - << std::hex << std::setw(2) << std::setfill('0') << int(color.b * 255.0) - << std::hex << std::setw(2) << std::setfill('0') << int(color.a * 255.0); + tmp << "#" << std::hex << std::setw(2) << std::setfill('0') << int(color.r * 255.0) << std::hex + << std::setw(2) << std::setfill('0') << int(color.g * 255.0) << std::hex << std::setw(2) + << std::setfill('0') << int(color.b * 255.0) << std::hex << std::setw(2) + << std::setfill('0') << int(color.a * 255.0); return tmp.str(); } /** - * Encode set of styles as a string. - * - * @param style Set of string describing the style. - * - * @returns Set encoded as a string. - * - */ + * Encode set of styles as a string. + * + * @param style Set of string describing the style. + * + * @returns Set encoded as a string. + * + */ -std::string Cell::encodeStyle(const std::set & style) +std::string Cell::encodeStyle(const std::set& style) { std::string s; std::set::const_iterator j = style.begin(); @@ -972,43 +1045,47 @@ std::string Cell::encodeStyle(const std::set & style) while (j != j_end) { s += *j; ++j; - if (j != j_end) + if (j != j_end) { s += "|"; + } } return s; } /** - * Decode a string of the format \#rrggbb or \#rrggbbaa into a Color. - * - * @param color The color to decode. - * @param defaultColor A default color in case the decoding fails. - * - * @returns Decoded color. - * - */ + * Decode a string of the format \#rrggbb or \#rrggbbaa into a Color. + * + * @param color The color to decode. + * @param defaultColor A default color in case the decoding fails. + * + * @returns Decoded color. + * + */ -App::Color Cell::decodeColor(const std::string & color, const App::Color & defaultColor) +App::Color Cell::decodeColor(const std::string& color, const App::Color& defaultColor) { if (color.size() == 7 || color.size() == 9) { App::Color c; - if (color[0] != '#') + if (color[0] != '#') { return defaultColor; + } unsigned int value = strtoul(color.c_str() + 1, nullptr, 16); - if (color.size() == 7) + if (color.size() == 7) { value = (value << 8) | 0xff; + } c.setPackedValue(value); return c; } - else + else { return defaultColor; + } } -//roughly based on Spreadsheet/Gui/SheetModel.cpp +// roughly based on Spreadsheet/Gui/SheetModel.cpp std::string Cell::getFormattedQuantity() { std::string result; @@ -1017,36 +1094,38 @@ std::string Cell::getFormattedQuantity() Property* prop = owner->sheet()->getPropertyByName(thisCell.toString().c_str()); if (prop->isDerivedFrom(App::PropertyString::getClassTypeId())) { - const App::PropertyString * stringProp = static_cast(prop); + const App::PropertyString* stringProp = static_cast(prop); qFormatted = QString::fromUtf8(stringProp->getValue()); - - } else if (prop->isDerivedFrom(App::PropertyQuantity::getClassTypeId())) { + } + else if (prop->isDerivedFrom(App::PropertyQuantity::getClassTypeId())) { double rawVal = static_cast(prop)->getValue(); - const App::PropertyQuantity * floatProp = static_cast(prop); + const App::PropertyQuantity* floatProp = static_cast(prop); DisplayUnit du; bool hasDisplayUnit = getDisplayUnit(du); double duScale = du.scaler; const Base::Unit& computedUnit = floatProp->getUnit(); - qFormatted = QLocale().toString(rawVal,'f',Base::UnitsApi::getDecimals()); + qFormatted = QLocale().toString(rawVal, 'f', Base::UnitsApi::getDecimals()); if (hasDisplayUnit) { if (computedUnit.isEmpty() || computedUnit == du.unit) { QString number = - QLocale().toString(rawVal / duScale,'f',Base::UnitsApi::getDecimals()); + QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); qFormatted = number + Base::Tools::fromStdString(" " + displayUnit.stringRep); } } - - } else if (prop->isDerivedFrom(App::PropertyFloat::getClassTypeId())){ + } + else if (prop->isDerivedFrom(App::PropertyFloat::getClassTypeId())) { double rawVal = static_cast(prop)->getValue(); DisplayUnit du; bool hasDisplayUnit = getDisplayUnit(du); double duScale = du.scaler; - qFormatted = QLocale().toString(rawVal,'f',Base::UnitsApi::getDecimals()); + qFormatted = QLocale().toString(rawVal, 'f', Base::UnitsApi::getDecimals()); if (hasDisplayUnit) { - QString number = QLocale().toString(rawVal / duScale, 'f',Base::UnitsApi::getDecimals()); + QString number = + QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); qFormatted = number + Base::Tools::fromStdString(" " + displayUnit.stringRep); } - } else if (prop->isDerivedFrom(App::PropertyInteger::getClassTypeId())) { + } + else if (prop->isDerivedFrom(App::PropertyInteger::getClassTypeId())) { double rawVal = static_cast(prop)->getValue(); DisplayUnit du; bool hasDisplayUnit = getDisplayUnit(du); @@ -1054,11 +1133,11 @@ std::string Cell::getFormattedQuantity() int iRawVal = std::round(rawVal); qFormatted = QLocale().toString(iRawVal); if (hasDisplayUnit) { - QString number = QLocale().toString(rawVal / duScale, 'f',Base::UnitsApi::getDecimals()); + QString number = + QLocale().toString(rawVal / duScale, 'f', Base::UnitsApi::getDecimals()); qFormatted = number + Base::Tools::fromStdString(" " + displayUnit.stringRep); } } result = Base::Tools::toStdString(qFormatted); return result; } - diff --git a/src/Mod/Spreadsheet/App/Cell.h b/src/Mod/Spreadsheet/App/Cell.h index 214eebf48b..922b1e8379 100644 --- a/src/Mod/Spreadsheet/App/Cell.h +++ b/src/Mod/Spreadsheet/App/Cell.h @@ -23,8 +23,8 @@ #ifndef CELL_H #define CELL_H -#include #include +#include #include #include @@ -33,61 +33,64 @@ #include "Utils.h" -namespace Base { +namespace Base +{ class Unit; class XMLReader; class Writer; -} +}// namespace Base -namespace Spreadsheet { +namespace Spreadsheet +{ class PropertySheet; class DisplayUnit; -class SpreadsheetExport Cell { +class SpreadsheetExport Cell +{ private: - Cell(const Cell & other); + Cell(const Cell& other); + public: + Cell(const App::CellAddress& _address, PropertySheet* _owner); - Cell(const App::CellAddress & _address, PropertySheet * _owner); + Cell(PropertySheet* _owner, const Cell& other); - Cell(PropertySheet * _owner, const Cell & other); - - Cell& operator=( const Cell& rhs ); + Cell& operator=(const Cell& rhs); ~Cell(); - const App::Expression * getExpression(bool withFormat=false) const; + const App::Expression* getExpression(bool withFormat = false) const; - bool getStringContent(std::string & s, bool persistent=false) const; + bool getStringContent(std::string& s, bool persistent = false) const; - void setContent(const char * value); + void setContent(const char* value); void setAlignment(int _alignment); - bool getAlignment(int & _alignment) const; + bool getAlignment(int& _alignment) const; - void setStyle(const std::set & _style); - bool getStyle(std::set & style) const; + void setStyle(const std::set& _style); + bool getStyle(std::set& style) const; - void setForeground(const App::Color &color); - bool getForeground(App::Color &color) const; + void setForeground(const App::Color& color); + bool getForeground(App::Color& color) const; - void setBackground(const App::Color &color); - bool getBackground(App::Color &color) const; + void setBackground(const App::Color& color); + bool getBackground(App::Color& color) const; - void setDisplayUnit(const std::string & unit); - bool getDisplayUnit(DisplayUnit &unit) const; + void setDisplayUnit(const std::string& unit); + bool getDisplayUnit(DisplayUnit& unit) const; - void setAlias(const std::string & n); - bool getAlias(std::string & n ) const; + void setAlias(const std::string& n); + bool getAlias(std::string& n) const; - void setComputedUnit(const Base::Unit & unit); - bool getComputedUnit(Base::Unit & unit) const; + void setComputedUnit(const Base::Unit& unit); + bool getComputedUnit(Base::Unit& unit) const; void setSpans(int rows, int columns); - bool getSpans(int & rows, int & columns) const; + bool getSpans(int& rows, int& columns) const; - void setException(const std::string & e, bool silent=false); + void setException(const std::string& e, bool silent = false); void clearException(); @@ -95,32 +98,48 @@ public: void setDirty(); - void setResolveException(const std::string &e); + void setResolveException(const std::string& e); void clearResolveException(); - const std::string &getException() const { return exceptionStr; } + const std::string& getException() const + { + return exceptionStr; + } - bool hasException() const { return isUsed(EXCEPTION_SET) || isUsed(PARSE_EXCEPTION_SET) || isUsed(RESOLVE_EXCEPTION_SET); } + bool hasException() const + { + return isUsed(EXCEPTION_SET) || isUsed(PARSE_EXCEPTION_SET) + || isUsed(RESOLVE_EXCEPTION_SET); + } void moveAbsolute(App::CellAddress newAddress); - void restore(Base::XMLReader &reader, bool checkAlias=false); + void restore(Base::XMLReader& reader, bool checkAlias = false); void afterRestore(); - void save(Base::Writer &writer) const; - void save(std::ostream &os, const char *indent, bool noContent) const; + void save(Base::Writer& writer) const; + void save(std::ostream& os, const char* indent, bool noContent) const; bool isUsed() const; - void mark() { setUsed(MARK_SET); } + void mark() + { + setUsed(MARK_SET); + } - bool isMarked() const { return isUsed(MARK_SET); } + bool isMarked() const + { + return isUsed(MARK_SET); + } - void visit(App::ExpressionVisitor & v); + void visit(App::ExpressionVisitor& v); - App::CellAddress getAddress() const { return address; } + App::CellAddress getAddress() const + { + return address; + } std::string getFormattedQuantity(); @@ -137,19 +156,18 @@ public: static const int ALIGNMENT_VIMPLIED; /* Static functions */ - static int decodeAlignment(const std::string &itemStr, int alignment); + static int decodeAlignment(const std::string& itemStr, int alignment); static std::string encodeAlignment(int alignment); - static std::string encodeStyle(const std::set &style); + static std::string encodeStyle(const std::set& style); - static std::string encodeColor(const App::Color &color); - static App::Color decodeColor(const std::string &color, const App::Color &defaultColor); + static std::string encodeColor(const App::Color& color); + static App::Color decodeColor(const std::string& color, const App::Color& defaultColor); private: + void setParseException(const std::string& e); - void setParseException(const std::string & e); - - void setExpression(App::ExpressionPtr &&expr); + void setExpression(App::ExpressionPtr&& expr); void setUsed(int mask, bool state = true); @@ -175,7 +193,7 @@ private: static const int RESOLVE_EXCEPTION_SET; App::CellAddress address; - PropertySheet * owner; + PropertySheet* owner; int used; mutable App::ExpressionPtr expression; @@ -193,6 +211,6 @@ private: friend class PropertySheet; }; -} +}// namespace Spreadsheet -#endif // CELL_H +#endif// CELL_H diff --git a/src/Mod/Spreadsheet/App/DisplayUnit.h b/src/Mod/Spreadsheet/App/DisplayUnit.h index 25089e5fa7..cd8b2741e4 100644 --- a/src/Mod/Spreadsheet/App/DisplayUnit.h +++ b/src/Mod/Spreadsheet/App/DisplayUnit.h @@ -23,24 +23,26 @@ #ifndef DISPLAYUNIT_H #define DISPLAYUNIT_H -#include #include +#include -namespace Spreadsheet { +namespace Spreadsheet +{ -class DisplayUnit { +class DisplayUnit +{ public: - std::string stringRep; Base::Unit unit; double scaler; - explicit 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) - { - } + {} bool operator==(const DisplayUnit& c) const { @@ -52,10 +54,12 @@ public: return !operator==(c); } - bool isEmpty() const { return stringRep.empty(); } - + bool isEmpty() const + { + return stringRep.empty(); + } }; -} +}// namespace Spreadsheet -#endif // DISPLAYUNIT_H +#endif// DISPLAYUNIT_H diff --git a/src/Mod/Spreadsheet/App/PreCompiled.h b/src/Mod/Spreadsheet/App/PreCompiled.h index c9b558b336..39b92a5094 100644 --- a/src/Mod/Spreadsheet/App/PreCompiled.h +++ b/src/Mod/Spreadsheet/App/PreCompiled.h @@ -28,10 +28,10 @@ // point at which warnings of overly long specifiers disabled (needed for VC6) #ifdef _MSC_VER -# pragma warning( disable : 4251 ) -# pragma warning( disable : 4275 ) -# pragma warning( disable : 4503 ) -# pragma warning( disable : 4786 ) // specifier longer then 255 chars +#pragma warning(disable : 4251) +#pragma warning(disable : 4275) +#pragma warning(disable : 4503) +#pragma warning(disable : 4786)// specifier longer then 255 chars #endif #ifdef _PreComp_ @@ -47,15 +47,15 @@ #include // boost -#include -#include #include #include #include +#include +#include // Qt #include #endif//_PreComp_ -#endif // SPREADSHEET_PRECOMPILED_H +#endif// SPREADSHEET_PRECOMPILED_H diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp b/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp index 8f155e076d..293c8243a3 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidths.cpp @@ -36,12 +36,13 @@ using namespace Spreadsheet; const int PropertyColumnWidths::defaultWidth = 100; const int PropertyColumnWidths::defaultHeaderWidth = 50; -TYPESYSTEM_SOURCE(Spreadsheet::PropertyColumnWidths , App::Property) +TYPESYSTEM_SOURCE(Spreadsheet::PropertyColumnWidths, App::Property) PropertyColumnWidths::PropertyColumnWidths() = default; -PropertyColumnWidths::PropertyColumnWidths(const PropertyColumnWidths &other) - : Property(), std::map(other) +PropertyColumnWidths::PropertyColumnWidths(const PropertyColumnWidths& other) + : Property() + , std::map(other) { std::map::const_iterator i = other.begin(); @@ -51,19 +52,20 @@ PropertyColumnWidths::PropertyColumnWidths(const PropertyColumnWidths &other) } } -App::Property *PropertyColumnWidths::Copy() const +App::Property* PropertyColumnWidths::Copy() const { - PropertyColumnWidths * prop = new PropertyColumnWidths(*this); + PropertyColumnWidths* prop = new PropertyColumnWidths(*this); return prop; } -void PropertyColumnWidths::Paste(const App::Property &from) +void PropertyColumnWidths::Paste(const App::Property& from) { setValues(dynamic_cast(from).getValues()); } -void PropertyColumnWidths::setValues(const std::map &values) { +void PropertyColumnWidths::setValues(const std::map& values) +{ aboutToSetValue(); std::map::const_iterator i; @@ -89,12 +91,12 @@ void PropertyColumnWidths::setValues(const std::map &values) { } /** - * Set the width (in pixels) of column \a col to \a width. - * - * @param col Column to set - * @param width Width in pixels - * - */ + * Set the width (in pixels) of column \a col to \a width. + * + * @param col Column to set + * @param width Width in pixels + * + */ void PropertyColumnWidths::setValue(int col, int width) { @@ -106,21 +108,22 @@ void PropertyColumnWidths::setValue(int col, int width) } } -void PropertyColumnWidths::Save(Base::Writer &writer) const +void PropertyColumnWidths::Save(Base::Writer& writer) const { - // Save column information + // Save column information writer.Stream() << writer.ind() << "" << std::endl; - writer.incInd(); // indentation for 'ColumnInfo' + writer.incInd();// indentation for 'ColumnInfo' std::map::const_iterator coli = begin(); while (coli != end()) { - writer.Stream() << writer.ind() << "first) << "\" width=\"" << coli->second << "\" />" << std::endl; + writer.Stream() << writer.ind() << "first) + << "\" width=\"" << coli->second << "\" />" << std::endl; ++coli; } - writer.decInd(); // indentation for 'ColumnInfo' + writer.decInd();// indentation for 'ColumnInfo' writer.Stream() << writer.ind() << "" << std::endl; } -void PropertyColumnWidths::Restore(Base::XMLReader &reader) +void PropertyColumnWidths::Restore(Base::XMLReader& reader) { int Cnt; @@ -130,7 +133,7 @@ void PropertyColumnWidths::Restore(Base::XMLReader &reader) for (int i = 0; i < Cnt; i++) { reader.readElement("Column"); const char* name = reader.hasAttribute("name") ? reader.getAttribute("name") : nullptr; - const char * width = reader.hasAttribute("width") ? reader.getAttribute("width") : nullptr; + const char* width = reader.hasAttribute("width") ? reader.getAttribute("width") : nullptr; try { if (name && width) { @@ -143,16 +146,15 @@ void PropertyColumnWidths::Restore(Base::XMLReader &reader) catch (...) { // Something is wrong, skip this column } - } reader.readEndElement("ColumnInfo"); } -PyObject *PropertyColumnWidths::getPyObject() +PyObject* PropertyColumnWidths::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new PropertyColumnWidthsPy(this),true); + PythonObject = Py::Object(new PropertyColumnWidthsPy(this), true); } return Py::new_reference_to(PythonObject); } @@ -165,5 +167,5 @@ void PropertyColumnWidths::clear() dirty.insert(i->first); ++i; } - std::map::clear(); + std::map::clear(); } diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidths.h b/src/Mod/Spreadsheet/App/PropertyColumnWidths.h index 7426fcc05c..737d5c1362 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidths.h +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidths.h @@ -23,49 +23,63 @@ #ifndef PROPERTYCOLUMNWIDTHS_H #define PROPERTYCOLUMNWIDTHS_H -#include #include #include #include +#include -namespace Spreadsheet { +namespace Spreadsheet +{ -class SpreadsheetExport PropertyColumnWidths : public App::Property, std::map +class SpreadsheetExport PropertyColumnWidths: public App::Property, std::map { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: PropertyColumnWidths(); - void setValue() { } + void setValue() + {} void setValue(int col, int width); - void setValues(const std::map &); + void setValues(const std::map&); - std::map getValues() const { + std::map getValues() const + { return *this; } - int getValue(int column) const { + int getValue(int column) const + { std::map::const_iterator i = find(column); return i != end() ? i->second : defaultWidth; } - Property *Copy() const override; + Property* Copy() const override; - void Paste(const Property &from) override; + void Paste(const Property& from) override; - void Save (Base::Writer & writer) const override; + void Save(Base::Writer& writer) const override; - void Restore(Base::XMLReader & reader) override; + void Restore(Base::XMLReader& reader) override; - bool isDirty() const { return !dirty.empty(); } + bool isDirty() const + { + return !dirty.empty(); + } - void clearDirty() { dirty.clear(); } + void clearDirty() + { + dirty.clear(); + } - const std::set & getDirty() const { return dirty; } + const std::set& getDirty() const + { + return dirty; + } - PyObject *getPyObject() override; + PyObject* getPyObject() override; void clear(); @@ -73,14 +87,13 @@ public: static const int defaultHeaderWidth; private: - - PropertyColumnWidths(const PropertyColumnWidths & other); + PropertyColumnWidths(const PropertyColumnWidths& other); std::set dirty; Py::Object PythonObject; }; -} +}// namespace Spreadsheet -#endif // PROPERTYCOLUMNWIDTHS_H +#endif// PROPERTYCOLUMNWIDTHS_H diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPy.xml b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPy.xml index 36b7905a07..fb1fdce762 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPy.xml +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPy.xml @@ -10,7 +10,6 @@ FatherInclude="Base/PersistencePy.h" FatherNamespace="Base" Constructor="true"> - Internal spreadsheet object diff --git a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp index 62301901ef..f631966552 100644 --- a/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp +++ b/src/Mod/Spreadsheet/App/PropertyColumnWidthsPyImp.cpp @@ -24,8 +24,10 @@ #include "PropertyColumnWidths.h" // inclusion of the generated files (generated out of PropertyColumnWidthsPy.xml) +// clang-format off #include "PropertyColumnWidthsPy.h" #include "PropertyColumnWidthsPy.cpp" +// clang-format on using namespace Spreadsheet; @@ -36,7 +38,7 @@ std::string PropertyColumnWidthsPy::representation() const return {""}; } -PyObject *PropertyColumnWidthsPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PropertyColumnWidthsPy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of PropertyColumnWidthsPy and the Twin object return new PropertyColumnWidthsPy(new PropertyColumnWidths); @@ -48,7 +50,7 @@ int PropertyColumnWidthsPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject *PropertyColumnWidthsPy::getCustomAttributes(const char* /*attr*/) const +PyObject* PropertyColumnWidthsPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp b/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp index a07836dd70..cfb5f6ea19 100644 --- a/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp +++ b/src/Mod/Spreadsheet/App/PropertyRowHeights.cpp @@ -35,28 +35,29 @@ using namespace Spreadsheet; const int PropertyRowHeights::defaultHeight = 30; -TYPESYSTEM_SOURCE(Spreadsheet::PropertyRowHeights , App::Property) +TYPESYSTEM_SOURCE(Spreadsheet::PropertyRowHeights, App::Property) PropertyRowHeights::PropertyRowHeights() = default; -PropertyRowHeights::PropertyRowHeights(const PropertyRowHeights &other) - : Property(), std::map(other) -{ -} +PropertyRowHeights::PropertyRowHeights(const PropertyRowHeights& other) + : Property() + , std::map(other) +{} -App::Property *PropertyRowHeights::Copy() const +App::Property* PropertyRowHeights::Copy() const { - PropertyRowHeights * prop = new PropertyRowHeights(*this); + PropertyRowHeights* prop = new PropertyRowHeights(*this); return prop; } -void PropertyRowHeights::Paste(const Property &from) +void PropertyRowHeights::Paste(const Property& from) { setValues(dynamic_cast(from).getValues()); } -void PropertyRowHeights::setValues(const std::map &values) { +void PropertyRowHeights::setValues(const std::map& values) +{ aboutToSetValue(); std::map::const_iterator i; @@ -81,28 +82,29 @@ void PropertyRowHeights::setValues(const std::map &values) { hasSetValue(); } -void PropertyRowHeights::Save(Base::Writer &writer) const +void PropertyRowHeights::Save(Base::Writer& writer) const { // Save row information writer.Stream() << writer.ind() << "" << std::endl; - writer.incInd(); // indentation for 'RowInfo' + writer.incInd();// indentation for 'RowInfo' std::map::const_iterator ri = begin(); while (ri != end()) { - writer.Stream() << writer.ind() << "first) << "\" height=\"" << ri->second << "\" />" << std::endl; + writer.Stream() << writer.ind() << "first) << "\" height=\"" + << ri->second << "\" />" << std::endl; ++ri; } - writer.decInd(); // indentation for 'RowInfo' + writer.decInd();// indentation for 'RowInfo' writer.Stream() << writer.ind() << "" << std::endl; } /** - * Set height of row given by \a row to \a height in pixels. - * - * @param row Address of row - * @param height Height in pixels - * - */ + * Set height of row given by \a row to \a height in pixels. + * + * @param row Address of row + * @param height Height in pixels + * + */ void PropertyRowHeights::setValue(int row, int height) { @@ -114,7 +116,7 @@ void PropertyRowHeights::setValue(int row, int height) } } -void PropertyRowHeights::Restore(Base::XMLReader &reader) +void PropertyRowHeights::Restore(Base::XMLReader& reader) { int Cnt; @@ -124,7 +126,8 @@ void PropertyRowHeights::Restore(Base::XMLReader &reader) for (int i = 0; i < Cnt; i++) { reader.readElement("Row"); const char* name = reader.hasAttribute("name") ? reader.getAttribute("name") : nullptr; - const char * height = reader.hasAttribute("height") ? reader.getAttribute("height") : nullptr; + const char* height = + reader.hasAttribute("height") ? reader.getAttribute("height") : nullptr; try { if (name && height) { @@ -141,11 +144,11 @@ void PropertyRowHeights::Restore(Base::XMLReader &reader) reader.readEndElement("RowInfo"); } -PyObject *PropertyRowHeights::getPyObject() +PyObject* PropertyRowHeights::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new PropertyRowHeightsPy(this),true); + PythonObject = Py::Object(new PropertyRowHeightsPy(this), true); } return Py::new_reference_to(PythonObject); } @@ -158,5 +161,5 @@ void PropertyRowHeights::clear() dirty.insert(i->first); ++i; } - std::map::clear(); + std::map::clear(); } diff --git a/src/Mod/Spreadsheet/App/PropertyRowHeights.h b/src/Mod/Spreadsheet/App/PropertyRowHeights.h index 005ca185f4..735f633e4e 100644 --- a/src/Mod/Spreadsheet/App/PropertyRowHeights.h +++ b/src/Mod/Spreadsheet/App/PropertyRowHeights.h @@ -23,63 +23,76 @@ #ifndef PROPERTYROWHEIGHTS_H #define PROPERTYROWHEIGHTS_H -#include #include #include #include +#include -namespace Spreadsheet { +namespace Spreadsheet +{ -class SpreadsheetExport PropertyRowHeights : public App::Property, std::map +class SpreadsheetExport PropertyRowHeights: public App::Property, std::map { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: PropertyRowHeights(); - void setValue() { } + void setValue() + {} void setValue(int row, int height); - void setValues(const std::map &); + void setValues(const std::map&); - int getValue(int row) const { + int getValue(int row) const + { std::map::const_iterator i = find(row); return i != end() ? i->second : defaultHeight; } - std::map getValues() const { + std::map getValues() const + { return *this; } - App::Property *Copy() const override; + App::Property* Copy() const override; - void Paste(const App::Property &from) override; + void Paste(const App::Property& from) override; - void Save (Base::Writer & writer) const override; + void Save(Base::Writer& writer) const override; - void Restore(Base::XMLReader & reader) override; + void Restore(Base::XMLReader& reader) override; - bool isDirty() const { return dirty.size() > 0; } + bool isDirty() const + { + return dirty.size() > 0; + } - void clearDirty() { dirty.clear(); } + void clearDirty() + { + dirty.clear(); + } - const std::set & getDirty() const { return dirty; } + const std::set& getDirty() const + { + return dirty; + } - PyObject *getPyObject() override; + PyObject* getPyObject() override; static const int defaultHeight; void clear(); private: - - PropertyRowHeights(const PropertyRowHeights & other); + PropertyRowHeights(const PropertyRowHeights& other); std::set dirty; Py::Object PythonObject; }; -} +}// namespace Spreadsheet -#endif // PROPERTYROWHEIGHTS_H +#endif// PROPERTYROWHEIGHTS_H diff --git a/src/Mod/Spreadsheet/App/PropertyRowHeightsPy.xml b/src/Mod/Spreadsheet/App/PropertyRowHeightsPy.xml index 59779dfbb1..95b1c6e0ba 100644 --- a/src/Mod/Spreadsheet/App/PropertyRowHeightsPy.xml +++ b/src/Mod/Spreadsheet/App/PropertyRowHeightsPy.xml @@ -10,7 +10,6 @@ FatherInclude="Base/PersistencePy.h" FatherNamespace="Base" Constructor="true"> - Internal spreadsheet object diff --git a/src/Mod/Spreadsheet/App/PropertyRowHeightsPyImp.cpp b/src/Mod/Spreadsheet/App/PropertyRowHeightsPyImp.cpp index 8c0754b0ff..ae30e02b1e 100644 --- a/src/Mod/Spreadsheet/App/PropertyRowHeightsPyImp.cpp +++ b/src/Mod/Spreadsheet/App/PropertyRowHeightsPyImp.cpp @@ -24,8 +24,10 @@ #include "PropertyRowHeights.h" // inclusion of the generated files (generated out of PropertyRowHeightsPy.xml) +// clang-format off #include "PropertyRowHeightsPy.h" #include "PropertyRowHeightsPy.cpp" +// clang-format on using namespace Spreadsheet; @@ -36,7 +38,7 @@ std::string PropertyRowHeightsPy::representation() const return {""}; } -PyObject *PropertyRowHeightsPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PropertyRowHeightsPy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of PropertyRowHeightsPy and the Twin object return new PropertyRowHeightsPy(new PropertyRowHeights); @@ -48,7 +50,7 @@ int PropertyRowHeightsPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject *PropertyRowHeightsPy::getCustomAttributes(const char* /*attr*/) const +PyObject* PropertyRowHeightsPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Spreadsheet/App/PropertySheet.cpp b/src/Mod/Spreadsheet/App/PropertySheet.cpp index 78651564f1..d237363678 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.cpp +++ b/src/Mod/Spreadsheet/App/PropertySheet.cpp @@ -22,11 +22,11 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include -# include -# include -# include +#include +#include +#include #endif #include @@ -53,12 +53,12 @@ using namespace Base; using namespace Spreadsheet; namespace sp = std::placeholders; -TYPESYSTEM_SOURCE(Spreadsheet::PropertySheet , App::PropertyExpressionContainer) +TYPESYSTEM_SOURCE(Spreadsheet::PropertySheet, App::PropertyExpressionContainer) void PropertySheet::clear() { /* Clear cells */ - for (auto & it : data) { + for (auto& it : data) { delete it.second; setDirty(it.first); } @@ -78,75 +78,87 @@ void PropertySheet::clear() clearDeps(); } -Cell *PropertySheet::getValue(CellAddress key) +Cell* PropertySheet::getValue(CellAddress key) { std::map::const_iterator i = data.find(key); - if (i == data.end()) + if (i == data.end()) { return nullptr; - else + } + else { return i->second; + } } -const Cell *PropertySheet::getValue(CellAddress key) const +const Cell* PropertySheet::getValue(CellAddress key) const { std::map::const_iterator i = data.find(key); - if (i == data.end()) + if (i == data.end()) { return nullptr; - else + } + else { return i->second; + } } -Cell * PropertySheet::getValueFromAlias(const std::string &alias) +Cell* PropertySheet::getValueFromAlias(const std::string& alias) { std::map::const_iterator it = revAliasProp.find(alias); - if (it != revAliasProp.end()) + if (it != revAliasProp.end()) { return getValue(it->second); - else + } + else { return nullptr; + } } -const Cell * PropertySheet::getValueFromAlias(const std::string &alias) const +const Cell* PropertySheet::getValueFromAlias(const std::string& alias) const { std::map::const_iterator it = revAliasProp.find(alias); - if (it != revAliasProp.end()) + if (it != revAliasProp.end()) { return getValue(it->second); - else + } + else { return nullptr; + } } -bool PropertySheet::isValidAlias(const std::string &candidate) +bool PropertySheet::isValidAlias(const std::string& candidate) { static const boost::regex gen("^[A-Za-z][_A-Za-z0-9]*$"); boost::cmatch cm; /* Check if it is used before */ - if (getValueFromAlias(candidate)) + if (getValueFromAlias(candidate)) { return false; + } /* Check to make sure it doesn't clash with a predefined unit */ - if (ExpressionParser::isTokenAUnit(candidate)) + if (ExpressionParser::isTokenAUnit(candidate)) { return false; + } /* Check to make sure it doesn't match a cell reference */ if (boost::regex_match(candidate.c_str(), cm, gen)) { static const boost::regex e("\\${0,1}([A-Z]{1,2})\\${0,1}([0-9]{1,5})"); if (boost::regex_match(candidate.c_str(), cm, e)) { - const boost::sub_match colstr = cm[1]; - const boost::sub_match rowstr = cm[2]; + const boost::sub_match colstr = cm[1]; + const boost::sub_match rowstr = cm[2]; // A valid cell address? - if (App::validRow(rowstr.str()) >= 0 && App::validColumn(colstr.str())) + if (App::validRow(rowstr.str()) >= 0 && App::validColumn(colstr.str())) { return false; + } } return true; } - else + else { return false; + } } namespace @@ -157,11 +169,11 @@ namespace // has data in it, but operating on all cells in the inclusive range specified by the tuple // is guaranteed to include all cells in the passed-in vector, and no cells exist to the // left, right, above, or below the block specified. -std::tuple extractRange(const std::vector &cells) +std::tuple extractRange(const std::vector& cells) { CellAddress firstRowAndColumn; CellAddress lastRowAndColumn; - for (const auto & cell : cells) { + for (const auto& cell : cells) { int row = cell.row(); int column = cell.col(); if (row < firstRowAndColumn.row() || !firstRowAndColumn.isValid()) { @@ -186,8 +198,9 @@ std::vector PropertySheet::getUsedCells() const std::vector usedSet; for (const auto& i : data) { - if (i.second->isUsed()) + if (i.second->isUsed()) { usedSet.push_back(i.first); + } } return usedSet; @@ -206,8 +219,9 @@ std::vector PropertySheet::getNonEmptyCells() const std::string str; for (const auto& i : data) { str.clear(); - if (i.second->isUsed() && i.second->getStringContent(str) && !str.empty()) + if (i.second->isUsed() && i.second->getStringContent(str) && !str.empty()) { usedSet.push_back(i.first); + } } return usedSet; @@ -224,8 +238,9 @@ void PropertySheet::setDirty(CellAddress address) /* Merged cells will automatically force an update of the top left cell to be consistent. */ std::map::const_iterator i = mergedCells.find(address); - if (i != mergedCells.end()) + if (i != mergedCells.end()) { address = i->second; + } dirty.insert(address); } @@ -233,30 +248,29 @@ void PropertySheet::setDirty(CellAddress address) void PropertySheet::setDirty() { AtomicPropertyChange signaller(*this); - for(auto &address : getNonEmptyCells()) { + for (auto& address : getNonEmptyCells()) { auto cell = cellAt(address); std::string content; - if(cell && cell->getStringContent(content,false)) { + if (cell && cell->getStringContent(content, false)) { cell->setContent(content.c_str()); } } } -Cell * PropertySheet::createCell(CellAddress address) +Cell* PropertySheet::createCell(CellAddress address) { - Cell * cell = new Cell(address, this); + Cell* cell = new Cell(address, this); data[address] = cell; return cell; } -PropertySheet::PropertySheet(Sheet *_owner) +PropertySheet::PropertySheet(Sheet* _owner) : owner(_owner) -{ -} +{} -PropertySheet::PropertySheet(const PropertySheet &other) +PropertySheet::PropertySheet(const PropertySheet& other) : dirty(other.dirty) , mergedCells(other.mergedCells) , owner(other.owner) @@ -268,7 +282,7 @@ PropertySheet::PropertySheet(const PropertySheet &other) , revAliasProp(other.revAliasProp) , updateCount(other.updateCount) { - std::map::const_iterator i = other.data.begin(); + std::map::const_iterator i = other.data.begin(); /* Copy cells */ while (i != other.data.end()) { @@ -282,18 +296,18 @@ PropertySheet::~PropertySheet() clear(); } -App::Property *PropertySheet::Copy() const +App::Property* PropertySheet::Copy() const { return new PropertySheet(*this); } -void PropertySheet::Paste(const Property &from) +void PropertySheet::Paste(const Property& from) { - const PropertySheet &froms = dynamic_cast(from); + const PropertySheet& froms = dynamic_cast(from); AtomicPropertyChange signaller(*this); - std::map::iterator icurr = data.begin(); + std::map::iterator icurr = data.begin(); /* Mark all first */ while (icurr != data.end()) { @@ -301,24 +315,27 @@ void PropertySheet::Paste(const Property &from) ++icurr; } - std::map::const_iterator ifrom = froms.data.begin(); + std::map::const_iterator ifrom = froms.data.begin(); std::vector spanChanges; int rows, cols; while (ifrom != froms.data.end()) { - auto &cell = data[ifrom->first]; + auto& cell = data[ifrom->first]; if (cell) { - int r,c; - cell->getSpans(rows,cols); + int r, c; + cell->getSpans(rows, cols); ifrom->second->getSpans(r, c); - if (rows != r || cols != c) + if (rows != r || cols != c) { spanChanges.push_back(ifrom->first); - *cell = *(ifrom->second); // Exists; assign cell directly + } + *cell = *(ifrom->second);// Exists; assign cell directly } else { - cell = new Cell(this, *(ifrom->second)); // Doesn't exist, copy using Cell's copy constructor - if (cell->getSpans(rows, cols)) + cell = new Cell(this, + *(ifrom->second));// Doesn't exist, copy using Cell's copy constructor + if (cell->getSpans(rows, cols)) { spanChanges.push_back(ifrom->first); + } } recomputeDependencies(ifrom->first); @@ -330,46 +347,49 @@ void PropertySheet::Paste(const Property &from) /* Remove all that are still marked */ icurr = data.begin(); while (icurr != data.end()) { - Cell * cell = icurr->second; + Cell* cell = icurr->second; if (cell->isMarked()) { - if (cell->getSpans(rows, cols)) + if (cell->getSpans(rows, cols)) { spanChanges.push_back(icurr->first); + } - std::map::iterator next = icurr; + std::map::iterator next = icurr; ++next; clear(icurr->first); icurr = next; } - else + else { ++icurr; + } } if (!spanChanges.empty()) { mergedCells = froms.mergedCells; if (auto sheet = Base::freecad_dynamic_cast(getContainer())) { - for (const auto &addr : spanChanges) + for (const auto& addr : spanChanges) { sheet->cellSpanChanged(addr); + } } } signaller.tryInvoke(); } -void PropertySheet::Save(Base::Writer &writer) const +void PropertySheet::Save(Base::Writer& writer) const { // Save cell contents int count = 0; std::map::const_iterator ci = data.begin(); while (ci != data.end()) { - if (ci->second->isUsed()) + if (ci->second->isUsed()) { ++count; + } ++ci; } - writer.Stream() << writer.ind() << ")" << std::endl; + writer.Stream() << writer.ind() << ")" << std::endl; writer.incInd(); @@ -385,7 +405,7 @@ void PropertySheet::Save(Base::Writer &writer) const writer.Stream() << writer.ind() << "" << std::endl; } -void PropertySheet::Restore(Base::XMLReader &reader) +void PropertySheet::Restore(Base::XMLReader& reader) { int Cnt; @@ -394,26 +414,29 @@ void PropertySheet::Restore(Base::XMLReader &reader) reader.readElement("Cells"); Cnt = reader.getAttributeAsInteger("Count"); - if(reader.hasAttribute("xlink") && reader.getAttributeAsInteger("xlink")) + if (reader.hasAttribute("xlink") && reader.getAttributeAsInteger("xlink")) { PropertyExpressionContainer::Restore(reader); + } for (int i = 0; i < Cnt; i++) { reader.readElement("Cell"); - const char* strAddress = reader.hasAttribute("address") ? reader.getAttribute("address") : ""; + const char* strAddress = + reader.hasAttribute("address") ? reader.getAttribute("address") : ""; try { CellAddress address(strAddress); - Cell * cell = createCell(address); + Cell* cell = createCell(address); cell->restore(reader); int rows, cols; if (cell->getSpans(rows, cols) && (rows > 1 || cols > 1)) { - mergeCells(address, CellAddress(address.row() + rows - 1, address.col() + cols - 1)); + mergeCells(address, + CellAddress(address.row() + rows - 1, address.col() + cols - 1)); } } - catch (const Base::Exception &) { + catch (const Base::Exception&) { // Something is wrong, skip this cell } catch (...) { @@ -423,7 +446,8 @@ void PropertySheet::Restore(Base::XMLReader &reader) signaller.tryInvoke(); } -void PropertySheet::copyCells(Base::Writer& writer, const std::vector& ranges) const { +void PropertySheet::copyCells(Base::Writer& writer, const std::vector& ranges) const +{ writer.Stream() << "" << std::endl; writer.Stream() << "" << std::endl; writer.incInd(); @@ -432,11 +456,12 @@ void PropertySheet::copyCells(Base::Writer& writer, const std::vector& ra int count = 0; do { auto cell = getValue(*r); - if(cell && cell->isUsed()) + if (cell && cell->isUsed()) { ++count; - }while(r.next()); - writer.Stream() << writer.ind() << "" << std::endl; + } + } while (r.next()); + writer.Stream() << writer.ind() << "" << std::endl; writer.incInd(); do { auto cell = getValue(*range); @@ -451,59 +476,66 @@ void PropertySheet::copyCells(Base::Writer& writer, const std::vector& ra writer.Stream() << "" << std::endl; } -void PropertySheet::pasteCells(XMLReader &reader, Range dstRange) { +void PropertySheet::pasteCells(XMLReader& reader, Range dstRange) +{ reader.readElement("Cells"); int rangeCount = reader.getAttributeAsInteger("count"); - if(rangeCount<=0) + if (rangeCount <= 0) { return; + } int dstRows = dstRange.rowCount(); int dstCols = dstRange.colCount(); CellAddress dstFrom = dstRange.from(); - int roffset=0,coffset=0; + int roffset = 0, coffset = 0; AtomicPropertyChange signaller(*this); - for(int ri=0; ri < rangeCount; ++ri) { + for (int ri = 0; ri < rangeCount; ++ri) { reader.readElement("Range"); CellAddress from(reader.getAttribute("from")); CellAddress to(reader.getAttribute("to")); int cellCount = reader.getAttributeAsInteger("count"); - Range range(from,to); + Range range(from, to); CellAddress addr(dstFrom); - if(ri == 0) { + if (ri == 0) { roffset = addr.row() - from.row(); coffset = addr.col() - from.col(); } - int rcount,ccount; - if(rangeCount>1) { + int rcount, ccount; + if (rangeCount > 1) { rcount = 1; ccount = 1; - } else { - rcount = dstRows/range.rowCount(); - if(rcount == 0) - rcount = 1; - ccount = dstCols/range.colCount(); - if(ccount == 0) - ccount = 1; } - for(int ci=0; ci < cellCount; ++ci) { + else { + rcount = dstRows / range.rowCount(); + if (rcount == 0) { + rcount = 1; + } + ccount = dstCols / range.colCount(); + if (ccount == 0) { + ccount = 1; + } + } + for (int ci = 0; ci < cellCount; ++ci) { reader.readElement("Cell"); CellAddress src(reader.getAttribute("address")); - if(ci) + if (ci) { range.next(); + } - while(src!=*range) { - for(int r=0; r < rcount; ++r) { - for(int c=0; c < ccount; ++c) { - CellAddress dst(range.row()+roffset+r*range.rowCount(), - range.column()+coffset+c*range.colCount()); - if(!dst.isValid()) + while (src != *range) { + for (int r = 0; r < rcount; ++r) { + for (int c = 0; c < ccount; ++c) { + CellAddress dst(range.row() + roffset + r * range.rowCount(), + range.column() + coffset + c * range.colCount()); + if (!dst.isValid()) { continue; + } owner->clear(dst); } } @@ -511,63 +543,72 @@ void PropertySheet::pasteCells(XMLReader &reader, Range dstRange) { } CellAddress newCellAddr; - for(int r=0; r < rcount; ++r) { - for(int c=0; c < ccount; ++c) { - CellAddress dst(src.row()+roffset+r*range.rowCount(), - src.col()+coffset+c*range.colCount()); - if(!dst.isValid()) + for (int r = 0; r < rcount; ++r) { + for (int c = 0; c < ccount; ++c) { + CellAddress dst(src.row() + roffset + r * range.rowCount(), + src.col() + coffset + c * range.colCount()); + if (!dst.isValid()) { continue; + } auto cell = owner->getNewCell(dst); splitCell(dst); int roffset_cur, coffset_cur; - if(!newCellAddr.isValid()) { + if (!newCellAddr.isValid()) { roffset_cur = roffset; coffset_cur = coffset; newCellAddr = dst; - cell->restore(reader,true); - } else { - roffset_cur = r*range.rowCount(); - coffset_cur = c*range.colCount(); + cell->restore(reader, true); + } + else { + roffset_cur = r * range.rowCount(); + coffset_cur = c * range.colCount(); auto newCell = owner->getCell(newCellAddr); - const Expression *expr; - if(!newCell || !(expr=newCell->getExpression(true))) { - FC_THROWM(Base::RuntimeError, "Failed to copy cell " - << getFullName() << '.' << dst.toString() - << " from " << newCellAddr.toString()); + const Expression* expr; + if (!newCell || !(expr = newCell->getExpression(true))) { + FC_THROWM(Base::RuntimeError, + "Failed to copy cell " << getFullName() << '.' + << dst.toString() << " from " + << newCellAddr.toString()); } cell->setExpression(ExpressionPtr(expr->copy())); } int rows, cols; - if (cell->getSpans(rows, cols)) + if (cell->getSpans(rows, cols)) { mergeCells(dst, CellAddress(dst.row() + rows - 1, dst.col() + cols - 1)); - else + } + else { splitCell(dst); + } - if(roffset_cur || coffset_cur) { - OffsetCellsExpressionVisitor visitor(*this, roffset_cur, coffset_cur); + if (roffset_cur || coffset_cur) { + OffsetCellsExpressionVisitor visitor(*this, + roffset_cur, + coffset_cur); cell->visit(visitor); - if(visitor.changed()) + if (visitor.changed()) { recomputeDependencies(dst); + } } dirty.insert(dst); } } } - if(cellCount == 0 || range.next()) { + if (cellCount == 0 || range.next()) { do { - for(int r=0; r < rcount; ++r) { - for(int c=0; c < ccount; ++c) { - CellAddress dst(range.row()+roffset+r*range.rowCount(), - range.column()+coffset+c*range.colCount()); - if(!dst.isValid()) + for (int r = 0; r < rcount; ++r) { + for (int c = 0; c < ccount; ++c) { + CellAddress dst(range.row() + roffset + r * range.rowCount(), + range.column() + coffset + c * range.colCount()); + if (!dst.isValid()) { continue; + } owner->clear(dst); } } - }while(range.next()); + } while (range.next()); } owner->rangeUpdated(Range(from, to)); } @@ -575,7 +616,7 @@ void PropertySheet::pasteCells(XMLReader &reader, Range dstRange) { } -Cell * PropertySheet::cellAt(CellAddress address) +Cell* PropertySheet::cellAt(CellAddress address) { std::map::const_iterator j = mergedCells.find(address); @@ -589,13 +630,15 @@ Cell * PropertySheet::cellAt(CellAddress address) std::map::const_iterator i = data.find(address); - if (i == data.end()) + if (i == data.end()) { return nullptr; - else + } + else { return i->second; + } } -const Cell * PropertySheet::cellAt(CellAddress address) const +const Cell* PropertySheet::cellAt(CellAddress address) const { std::map::const_iterator j = mergedCells.find(address); @@ -609,101 +652,113 @@ const Cell * PropertySheet::cellAt(CellAddress address) const std::map::const_iterator i = data.find(address); - if (i == data.end()) + if (i == data.end()) { return nullptr; - else + } + else { return i->second; + } } -Cell * PropertySheet::nonNullCellAt(CellAddress address) +Cell* PropertySheet::nonNullCellAt(CellAddress address) { std::map::const_iterator j = mergedCells.find(address); if (j != mergedCells.end()) { std::map::const_iterator i = data.find(j->second); - if (i == data.end()) + if (i == data.end()) { return createCell(address); - else + } + else { return i->second; + } } std::map::const_iterator i = data.find(address); - if (i == data.end()) + if (i == data.end()) { return createCell(address); - else + } + else { return i->second; + } } -void PropertySheet::setContent(CellAddress address, const char *value) +void PropertySheet::setContent(CellAddress address, const char* value) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setContent(value); } void PropertySheet::setAlignment(CellAddress address, int _alignment) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); - if (cell->address != address) //Reject alignment change for merged cell except top-left one + if (cell->address != address) {// Reject alignment change for merged cell except top-left one return; + } cell->setAlignment(_alignment); } -void PropertySheet::setStyle(CellAddress address, const std::set &_style) +void PropertySheet::setStyle(CellAddress address, const std::set& _style) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setStyle(_style); } -void PropertySheet::setForeground(CellAddress address, const App::Color &color) +void PropertySheet::setForeground(CellAddress address, const App::Color& color) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setForeground(color); } -void PropertySheet::setBackground(CellAddress address, const App::Color &color) +void PropertySheet::setBackground(CellAddress address, const App::Color& color) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setBackground(color); } -void PropertySheet::setDisplayUnit(CellAddress address, const std::string &unit) +void PropertySheet::setDisplayUnit(CellAddress address, const std::string& unit) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setDisplayUnit(unit); } -void PropertySheet::setAlias(CellAddress address, const std::string &alias) +void PropertySheet::setAlias(CellAddress address, const std::string& alias) { - if (!alias.empty() && !isValidAlias(alias)) + if (!alias.empty() && !isValidAlias(alias)) { throw Base::ValueError("Invalid alias"); + } - const Cell * aliasedCell = getValueFromAlias(alias); - Cell * cell = nonNullCellAt(address); + const Cell* aliasedCell = getValueFromAlias(alias); + Cell* cell = nonNullCellAt(address); assert(cell); - if(aliasedCell == cell) + if (aliasedCell == cell) { return; + } - if (aliasedCell) + if (aliasedCell) { throw Base::ValueError("Alias already defined."); + } AtomicPropertyChange signaller(*this); - /* Mark cells depending on this cell dirty; they need to be resolved when an alias changes or disappears */ + /* Mark cells depending on this cell dirty; they need to be resolved when an alias changes or + * disappears */ std::string fullName = owner->getFullName() + "." + address.toString(); - std::map >::const_iterator j = propertyNameToCellMap.find(fullName); + std::map>::const_iterator j = + propertyNameToCellMap.find(fullName); if (j != propertyNameToCellMap.end()) { - std::set< CellAddress >::const_iterator k = j->second.begin(); + std::set::const_iterator k = j->second.begin(); while (k != j->second.end()) { setDirty(*k); @@ -719,7 +774,7 @@ void PropertySheet::setAlias(CellAddress address, const std::string &alias) std::map m; App::ObjectIdentifier key(owner, oldAlias); - App::ObjectIdentifier value(owner, alias.empty()?address.toString():alias); + App::ObjectIdentifier value(owner, alias.empty() ? address.toString() : alias); m[key] = value; @@ -729,16 +784,16 @@ void PropertySheet::setAlias(CellAddress address, const std::string &alias) signaller.tryInvoke(); } -void PropertySheet::setComputedUnit(CellAddress address, const Base::Unit &unit) +void PropertySheet::setComputedUnit(CellAddress address, const Base::Unit& unit) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setComputedUnit(unit); } void PropertySheet::setSpans(CellAddress address, int rows, int columns) { - Cell * cell = nonNullCellAt(address); + Cell* cell = nonNullCellAt(address); assert(cell); cell->setSpans(rows, columns); owner->cellSpanChanged(address); @@ -758,8 +813,9 @@ void PropertySheet::clear(CellAddress address, bool toClearAlias) { std::map::iterator i = data.find(address); - if (i == data.end()) + if (i == data.end()) { return; + } AtomicPropertyChange signaller(*this); @@ -773,8 +829,9 @@ void PropertySheet::clear(CellAddress address, bool toClearAlias) // Mark as dirty dirty.insert(i->first); - if (toClearAlias) + if (toClearAlias) { clearAlias(address); + } // Erase from internal struct data.erase(i); @@ -791,7 +848,9 @@ void PropertySheet::moveAlias(CellAddress currPos, CellAddress newPos) } } -void PropertySheet::moveCell(CellAddress currPos, CellAddress newPos, std::map & renames) +void PropertySheet::moveCell(CellAddress currPos, + CellAddress newPos, + std::map& renames) { std::map::const_iterator i = data.find(currPos); std::map::const_iterator j = data.find(newPos); @@ -804,7 +863,7 @@ void PropertySheet::moveCell(CellAddress currPos, CellAddress newPos, std::mapsecond; + Cell* cell = i->second; int rows, columns; // Get merged cell data @@ -831,7 +890,8 @@ void PropertySheet::moveCell(CellAddress currPos, CellAddress newPos, std::map renames; /* Copy all keys from cells map */ - boost::copy( data | boost::adaptors::map_keys, std::back_inserter(keys)); + boost::copy(data | boost::adaptors::map_keys, std::back_inserter(keys)); /* Sort them */ - std::sort(keys.begin(), keys.end(), std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); //NOLINT + std::sort(keys.begin(), + keys.end(), + std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2));// NOLINT MoveCellsExpressionVisitor visitor(*this, - CellAddress(row, CellAddress::MAX_COLUMNS), count, 0); + CellAddress(row, CellAddress::MAX_COLUMNS), + count, + 0); AtomicPropertyChange signaller(*this); // move all the aliases first so dependencies can be calculated correctly - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { - if (i->row() >= row) + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); + ++i) { + if (i->row() >= row) { moveAlias(*i, CellAddress(i->row() + count, i->col())); + } } - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); + ++i) { std::map::iterator j = data.find(*i); assert(j != data.end()); - Cell * cell = j->second; + Cell* cell = j->second; // Visit each cell to make changes to expressions if necessary visitor.reset(); @@ -873,35 +940,43 @@ void PropertySheet::insertRows(int row, int count) recomputeDependencies(*i); } - if (i->row() >= row) + if (i->row() >= row) { moveCell(*i, CellAddress(i->row() + count, i->col()), renames); + } } - const App::DocumentObject * docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject * obj) { return obj != docObj; }); + const App::DocumentObject* docObj = static_cast(getContainer()); + owner->getDocument()->renameObjectIdentifiers(renames, + [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } /** - * Sort function to sort two cell positions according to their row position. - * - */ + * Sort function to sort two cell positions according to their row position. + * + */ -bool PropertySheet::rowSortFunc(const CellAddress & a, const CellAddress & b) { - if (a.row() < b.row()) +bool PropertySheet::rowSortFunc(const CellAddress& a, const CellAddress& b) +{ + if (a.row() < b.row()) { return true; - else + } + else { return false; + } } std::vector PropertySheet::getRows(int row, int count) const { std::vector keys; - for (const auto &i : data) { + for (const auto& i : data) { auto key = i.first; - if (key.row() >= row && key.row() < row + count) + if (key.row() >= row && key.row() < row + count) { keys.push_back(key); + } } return keys; } @@ -915,19 +990,26 @@ void PropertySheet::removeRows(int row, int count) boost::copy(data | boost::adaptors::map_keys, std::back_inserter(keys)); /* Sort them */ - std::sort(keys.begin(), keys.end(), std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); + std::sort(keys.begin(), + keys.end(), + std::bind(&PropertySheet::rowSortFunc, this, sp::_1, sp::_2)); - MoveCellsExpressionVisitor visitor(*this, - CellAddress(row + count - 1, CellAddress::MAX_COLUMNS), -count, 0); + MoveCellsExpressionVisitor visitor( + *this, + CellAddress(row + count - 1, CellAddress::MAX_COLUMNS), + -count, + 0); AtomicPropertyChange signaller(*this); // move all the aliases first so dependencies can be calculated correctly for (const auto& key : keys) { - if (key.row() >= row && key.row() < row + count) + if (key.row() >= row && key.row() < row + count) { clearAlias(key); - else if (key.row() >= row + count) + } + else if (key.row() >= row + count) { moveAlias(key, CellAddress(key.row() - count, key.col())); + } } int spanRows, spanCols; @@ -936,7 +1018,7 @@ void PropertySheet::removeRows(int row, int count) assert(j != data.end()); - Cell * cell = j->second; + Cell* cell = j->second; // Visit each cell to make changes to expressions if necessary visitor.reset(); @@ -946,21 +1028,29 @@ void PropertySheet::removeRows(int row, int count) recomputeDependencies(key); } - if (key.row() >= row && key.row() < row + count) - clear(key, false); // aliases were cleared earlier - else if (key.row() >= row + count) + if (key.row() >= row && key.row() < row + count) { + clear(key, false);// aliases were cleared earlier + } + else if (key.row() >= row + count) { moveCell(key, CellAddress(key.row() - count, key.col()), renames); + } else if (cell->getSpans(spanRows, spanCols) && key.row() + spanRows >= row) { - if (key.row() + spanRows >= row + count) + if (key.row() + spanRows >= row + count) { spanRows -= count; - else + } + else { spanRows = key.row() - row; - mergeCells(j->first, CellAddress(j->first.row()+spanRows-1, j->first.col()+spanCols-1)); + } + mergeCells(j->first, + CellAddress(j->first.row() + spanRows - 1, j->first.col() + spanCols - 1)); } } - const App::DocumentObject * docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject * obj) { return obj != docObj; }); + const App::DocumentObject* docObj = static_cast(getContainer()); + owner->getDocument()->renameObjectIdentifiers(renames, + [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } @@ -976,22 +1066,27 @@ void PropertySheet::insertColumns(int col, int count) std::sort(keys.begin(), keys.end()); MoveCellsExpressionVisitor visitor(*this, - CellAddress(CellAddress::MAX_ROWS, col), 0, count); + CellAddress(CellAddress::MAX_ROWS, col), + 0, + count); AtomicPropertyChange signaller(*this); // move all the aliases first so dependencies can be calculated correctly - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { - if (i->col() >= col) + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); + ++i) { + if (i->col() >= col) { moveAlias(*i, CellAddress(i->row(), i->col() + count)); + } } - for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); ++i) { + for (std::vector::const_reverse_iterator i = keys.rbegin(); i != keys.rend(); + ++i) { std::map::iterator j = data.find(*i); assert(j != data.end()); - Cell * cell = j->second; + Cell* cell = j->second; // Visit each cell to make changes to expressions if necessary visitor.reset(); @@ -1001,35 +1096,43 @@ void PropertySheet::insertColumns(int col, int count) recomputeDependencies(*i); } - if (i->col() >= col) + if (i->col() >= col) { moveCell(*i, CellAddress(i->row(), i->col() + count), renames); + } } - const App::DocumentObject * docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject * obj) { return obj != docObj; }); + const App::DocumentObject* docObj = static_cast(getContainer()); + owner->getDocument()->renameObjectIdentifiers(renames, + [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } /** - * Sort function to sort two cell positions according to their column position. - * - */ + * Sort function to sort two cell positions according to their column position. + * + */ -bool PropertySheet::colSortFunc(const CellAddress & a, const CellAddress & b) { - if (a.col() < b.col()) +bool PropertySheet::colSortFunc(const CellAddress& a, const CellAddress& b) +{ + if (a.col() < b.col()) { return true; - else + } + else { return false; + } } std::vector PropertySheet::getColumns(int column, int count) const { std::vector keys; - for (const auto &i : data) { + for (const auto& i : data) { auto key = i.first; - if (key.col() >= column && key.col() < column + count) + if (key.col() >= column && key.col() < column + count) { keys.push_back(key); + } } return keys; } @@ -1043,19 +1146,26 @@ void PropertySheet::removeColumns(int col, int count) boost::copy(data | boost::adaptors::map_keys, std::back_inserter(keys)); /* Sort them */ - std::sort(keys.begin(), keys.end(), std::bind(&PropertySheet::colSortFunc, this, sp::_1, sp::_2)); //NOLINT + std::sort(keys.begin(), + keys.end(), + std::bind(&PropertySheet::colSortFunc, this, sp::_1, sp::_2));// NOLINT - MoveCellsExpressionVisitor visitor(*this, - CellAddress(CellAddress::MAX_ROWS, col + count - 1), 0, -count); + MoveCellsExpressionVisitor visitor( + *this, + CellAddress(CellAddress::MAX_ROWS, col + count - 1), + 0, + -count); AtomicPropertyChange signaller(*this); // move all the aliases first so dependencies can be calculated correctly for (const auto& key : keys) { - if (key.col() >= col && key.col() < col + count) + if (key.col() >= col && key.col() < col + count) { clearAlias(key); - else if (key.col() >= col + count) + } + else if (key.col() >= col + count) { moveAlias(key, CellAddress(key.row(), key.col() - count)); + } } int spanRows, spanCols; @@ -1064,7 +1174,7 @@ void PropertySheet::removeColumns(int col, int count) assert(j != data.end()); - Cell * cell = j->second; + Cell* cell = j->second; // Visit each cell to make changes to expressions if necessary visitor.reset(); @@ -1074,21 +1184,29 @@ void PropertySheet::removeColumns(int col, int count) recomputeDependencies(key); } - if (key.col() >= col && key.col() < col + count) - clear(key, false); // aliases were cleared earlier - else if (key.col() >= col + count) + if (key.col() >= col && key.col() < col + count) { + clear(key, false);// aliases were cleared earlier + } + else if (key.col() >= col + count) { moveCell(key, CellAddress(key.row(), key.col() - count), renames); + } else if (cell->getSpans(spanRows, spanCols) && key.col() + spanCols >= col) { - if (key.col() + spanCols >= col + count) + if (key.col() + spanCols >= col + count) { spanCols -= count; - else + } + else { spanCols = key.col() - col; - mergeCells(j->first, CellAddress(j->first.row()+spanRows-1, j->first.col()+spanCols-1)); + } + mergeCells(j->first, + CellAddress(j->first.row() + spanRows - 1, j->first.col() + spanCols - 1)); } } - const App::DocumentObject * docObj = static_cast(getContainer()); - owner->getDocument()->renameObjectIdentifiers(renames, [docObj](const App::DocumentObject * obj) { return obj != docObj; } ); + const App::DocumentObject* docObj = static_cast(getContainer()); + owner->getDocument()->renameObjectIdentifiers(renames, + [docObj](const App::DocumentObject* obj) { + return obj != docObj; + }); signaller.tryInvoke(); } @@ -1109,9 +1227,9 @@ bool PropertySheet::mergeCells(CellAddress from, CellAddress to) if (it != mergedCells.end()) { int rows, cols; cellAt(it->second)->getSpans(rows, cols); - if (to.row() - from.row() + 1 == rows - && to.col() - from.col() + 1 == cols) + if (to.row() - from.row() + 1 == rows && to.col() - from.col() + 1 == cols) { return false; + } } AtomicPropertyChange signaller(*this); @@ -1126,8 +1244,9 @@ bool PropertySheet::mergeCells(CellAddress from, CellAddress to) // Clear cells that will be hidden by the merge for (int r = from.row(); r <= to.row(); ++r) { for (int c = from.col(); c <= to.col(); ++c) { - if ( !(r == from.row() && c == from.col()) ) + if (!(r == from.row() && c == from.col())) { clear(CellAddress(r, c)); + } } } @@ -1151,8 +1270,9 @@ void PropertySheet::splitCell(CellAddress address) int rows, cols; std::map::const_iterator i = mergedCells.find(address); - if (i == mergedCells.end()) + if (i == mergedCells.end()) { return; + } CellAddress anchor = i->second; AtomicPropertyChange signaller(*this); @@ -1170,17 +1290,19 @@ void PropertySheet::splitCell(CellAddress address) signaller.tryInvoke(); } -void PropertySheet::getSpans(CellAddress address, int & rows, int & cols) const +void PropertySheet::getSpans(CellAddress address, int& rows, int& cols) const { std::map::const_iterator i = mergedCells.find(address); if (i != mergedCells.end()) { CellAddress anchor = i->second; - if (anchor == address) + if (anchor == address) { cellAt(anchor)->getSpans(rows, cols); - else + } + else { rows = cols = 1; + } } else { rows = cols = 1; @@ -1189,10 +1311,12 @@ void PropertySheet::getSpans(CellAddress address, int & rows, int & cols) const App::CellAddress Spreadsheet::PropertySheet::getAnchor(App::CellAddress address) const { - if (auto anchor = mergedCells.find(address); anchor != mergedCells.end()) + if (auto anchor = mergedCells.find(address); anchor != mergedCells.end()) { return anchor->second; - else + } + else { return address; + } } bool PropertySheet::isMergedCell(CellAddress address) const @@ -1208,30 +1332,32 @@ bool PropertySheet::isHidden(CellAddress address) const } /** - * Update dependencies of \a expression for cell at \a key. - * - * @param expression Expression to extract dependencies from - * @param key Address of cell containing the expression. - */ + * Update dependencies of \a expression for cell at \a key. + * + * @param expression Expression to extract dependencies from + * @param key Address of cell containing the expression. + */ void PropertySheet::addDependencies(CellAddress key) { - Cell * cell = getValue(key); + Cell* cell = getValue(key); - if (!cell) + if (!cell) { return; + } cell->clearResolveException(); - const Expression * expression = cell->getExpression(); + const Expression* expression = cell->getExpression(); - if (!expression) + if (!expression) { return; + } - for(auto &var : expression->getIdentifiers()) { - for(auto &dep : var.first.getDep(true)) { - App::DocumentObject *docObj = dep.first; - App::Document *doc = docObj->getDocument(); + for (auto& var : expression->getIdentifiers()) { + for (auto& dep : var.first.getDep(true)) { + App::DocumentObject* docObj = dep.first; + App::Document* doc = docObj->getDocument(); std::string docObjName = docObj->getFullName(); @@ -1241,7 +1367,7 @@ void PropertySheet::addDependencies(CellAddress key) cellToDocumentObjectMap[key].insert(docObjName); ++updateCount; - for(auto &name : dep.second) { + for (auto& name : dep.second) { std::string propName = docObjName + "." + name; FC_LOG("dep " << key.toString() << " -> " << name); @@ -1269,28 +1395,30 @@ void PropertySheet::addDependencies(CellAddress key) } /** - * Remove dependencies given by \a expression for cell at \a key. - * - * @param expression Expression to extract dependencies from - * @param key Address of cell containing the expression - * - */ + * Remove dependencies given by \a expression for cell at \a key. + * + * @param expression Expression to extract dependencies from + * @param key Address of cell containing the expression + * + */ void PropertySheet::removeDependencies(CellAddress key) { /* Remove from Property <-> Key maps */ - std::map >::iterator i1 = cellToPropertyNameMap.find(key); + std::map>::iterator i1 = cellToPropertyNameMap.find(key); if (i1 != cellToPropertyNameMap.end()) { - std::set< std::string >::const_iterator j = i1->second.begin(); + std::set::const_iterator j = i1->second.begin(); while (j != i1->second.end()) { - std::map >::iterator k = propertyNameToCellMap.find(*j); + std::map>::iterator k = + propertyNameToCellMap.find(*j); - //assert(k != propertyNameToCellMap.end()); - if (k != propertyNameToCellMap.end()) + // assert(k != propertyNameToCellMap.end()); + if (k != propertyNameToCellMap.end()) { k->second.erase(key); + } ++j; } @@ -1299,20 +1427,22 @@ void PropertySheet::removeDependencies(CellAddress key) /* Remove from DocumentObject <-> Key maps */ - std::map >::iterator i2 = cellToDocumentObjectMap.find(key); + std::map>::iterator i2 = cellToDocumentObjectMap.find(key); if (i2 != cellToDocumentObjectMap.end()) { - std::set< std::string >::const_iterator j = i2->second.begin(); + std::set::const_iterator j = i2->second.begin(); while (j != i2->second.end()) { - std::map >::iterator k = documentObjectToCellMap.find(*j); + std::map>::iterator k = + documentObjectToCellMap.find(*j); - //assert(k != documentObjectToCellMap.end()); + // assert(k != documentObjectToCellMap.end()); if (k != documentObjectToCellMap.end()) { k->second.erase(key); - if (k->second.empty()) + if (k->second.empty()) { documentObjectToCellMap.erase(*j); + } } ++j; @@ -1324,21 +1454,22 @@ void PropertySheet::removeDependencies(CellAddress key) } /** - * Recompute any cells that depend on \a prop. - * - */ + * Recompute any cells that depend on \a prop. + * + */ -void PropertySheet::recomputeDependants(const App::DocumentObject *owner, const char *propName) +void PropertySheet::recomputeDependants(const App::DocumentObject* owner, const char* propName) { auto itD = _Deps.find(const_cast(owner)); - if(itD!=_Deps.end() && itD->second) { + if (itD != _Deps.end() && itD->second) { // Check for hidden reference. Because a hidden reference is not // protected by cyclic dependency checking, we need to take special // care to prevent it from misbehave. - Sheet *sheet = Base::freecad_dynamic_cast(getContainer()); - if(!sheet || sheet->testStatus(App::ObjectStatus::Recompute2) - || !owner || owner->testStatus(App::ObjectStatus::Recompute2)) + Sheet* sheet = Base::freecad_dynamic_cast(getContainer()); + if (!sheet || sheet->testStatus(App::ObjectStatus::Recompute2) || !owner + || owner->testStatus(App::ObjectStatus::Recompute2)) { return; + } } // First, search without actual property name for sub-object/link @@ -1349,91 +1480,102 @@ void PropertySheet::recomputeDependants(const App::DocumentObject *owner, const std::string fullName = owner->getFullName() + "."; auto it = propertyNameToCellMap.find(fullName); if (it != propertyNameToCellMap.end()) { - for(auto &cell : it->second) + for (auto& cell : it->second) { setDirty(cell); + } } if (propName && *propName) { // Now, we check for direct property references it = propertyNameToCellMap.find(fullName + propName); if (it != propertyNameToCellMap.end()) { - for(auto &cell : it->second) + for (auto& cell : it->second) { setDirty(cell); + } } } } -void PropertySheet::breakLink(App::DocumentObject *obj, bool clear) { - AtomicPropertyChange signaller(*this,false); - PropertyExpressionContainer::breakLink(obj,clear); +void PropertySheet::breakLink(App::DocumentObject* obj, bool clear) +{ + AtomicPropertyChange signaller(*this, false); + PropertyExpressionContainer::breakLink(obj, clear); } -void PropertySheet::onBreakLink(App::DocumentObject *obj) { +void PropertySheet::onBreakLink(App::DocumentObject* obj) +{ invalidateDependants(obj); } -void PropertySheet::hasSetChildValue(App::Property &prop) { +void PropertySheet::hasSetChildValue(App::Property& prop) +{ ++updateCount; PropertyExpressionContainer::hasSetChildValue(prop); } -void PropertySheet::invalidateDependants(const App::DocumentObject *docObj) +void PropertySheet::invalidateDependants(const App::DocumentObject* docObj) { depConnections.erase(docObj); // Recompute cells that depend on this cell auto iter = documentObjectToCellMap.find(docObj->getFullName()); - if (iter == documentObjectToCellMap.end()) + if (iter == documentObjectToCellMap.end()) { return; + } // Touch to force recompute touch(); AtomicPropertyChange signaller(*this); - for(const auto &address : iter->second) { - Cell * cell = getValue(address); + for (const auto& address : iter->second) { + Cell* cell = getValue(address); cell->setResolveException("Unresolved dependency"); setDirty(address); } } -void PropertySheet::slotChangedObject(const App::DocumentObject &obj, const App::Property &prop) +void PropertySheet::slotChangedObject(const App::DocumentObject& obj, const App::Property& prop) { if (&obj == getContainer()) { - if (&prop == this || !prop.getName() || revAliasProp.count(prop.getName())) + if (&prop == this || !prop.getName() || revAliasProp.count(prop.getName())) { return; - if (stringToAddress(prop.getName(), true).isValid()) + } + if (stringToAddress(prop.getName(), true).isValid()) { return; + } } recomputeDependants(&obj, prop.getName()); } -void PropertySheet::onAddDep(App::DocumentObject *obj) { - //NOLINTBEGIN - depConnections[obj] = obj->signalChanged.connect(std::bind( - &PropertySheet::slotChangedObject, this, sp::_1, sp::_2)); - //NOLINTEND +void PropertySheet::onAddDep(App::DocumentObject* obj) +{ + // NOLINTBEGIN + depConnections[obj] = obj->signalChanged.connect( + std::bind(&PropertySheet::slotChangedObject, this, sp::_1, sp::_2)); + // NOLINTEND } -void PropertySheet::onRemoveDep(App::DocumentObject *obj) { +void PropertySheet::onRemoveDep(App::DocumentObject* obj) +{ depConnections.erase(obj); } -void PropertySheet::renamedDocumentObject(const App::DocumentObject * docObj) +void PropertySheet::renamedDocumentObject(const App::DocumentObject* docObj) { #if 1 (void)docObj; #else - if (documentObjectName.find(docObj) == documentObjectName.end()) + if (documentObjectName.find(docObj) == documentObjectName.end()) { return; + } - std::map::iterator i = data.begin(); + std::map::iterator i = data.begin(); while (i != data.end()) { RelabelDocumentObjectExpressionVisitor v(*this, docObj); i->second->visit(v); - if(v.changed()) { + if (v.changed()) { v.reset(); recomputeDependencies(i->first); setDirty(i->first); @@ -1443,19 +1585,21 @@ void PropertySheet::renamedDocumentObject(const App::DocumentObject * docObj) #endif } -void PropertySheet::onRelabeledDocument(const App::Document &doc) +void PropertySheet::onRelabeledDocument(const App::Document& doc) { RelabelDocumentExpressionVisitor v(doc); - for(auto &c : data) + for (auto& c : data) { c.second->visit(v); + } } -void PropertySheet::renameObjectIdentifiers(const std::map &paths) +void PropertySheet::renameObjectIdentifiers( + const std::map& paths) { RenameObjectIdentifierExpressionVisitor v {*this, paths, *this}; - for(auto &c : data) { + for (auto& c : data) { c.second->visit(v); - if(v.changed()) { + if (v.changed()) { v.reset(); recomputeDependencies(c.first); setDirty(c.first); @@ -1463,14 +1607,15 @@ void PropertySheet::renameObjectIdentifiers(const std::map(docObj))) { - // const App::DocumentObject * docObj = dynamic_cast(getContainer()); - // if(docObj && docObj->getDocument()!=docObj->getDocument()) { + // const App::DocumentObject * docObj = dynamic_cast(getContainer()); if(docObj && + // docObj->getDocument()!=docObj->getDocument()) { // for(auto it=xlinks.begin();it!=xlinks.end();++it) { // if(it->getValue() == docObj) { // xlinks.erase(it); @@ -1482,29 +1627,34 @@ void PropertySheet::deletedDocumentObject(const App::DocumentObject *docObj) } void PropertySheet::documentSet() -{ -} +{} -const std::set &PropertySheet::getDeps(const std::string &name) const +const std::set& PropertySheet::getDeps(const std::string& name) const { static std::set empty; - std::map >::const_iterator i = propertyNameToCellMap.find(name); + std::map>::const_iterator i = + propertyNameToCellMap.find(name); - if (i != propertyNameToCellMap.end()) + if (i != propertyNameToCellMap.end()) { return i->second; - else + } + else { return empty; + } } -const std::set &PropertySheet::getDeps(CellAddress pos) const +const std::set& PropertySheet::getDeps(CellAddress pos) const { static std::set empty; - std::map >::const_iterator i = cellToPropertyNameMap.find(pos); + std::map>::const_iterator i = + cellToPropertyNameMap.find(pos); - if (i != cellToPropertyNameMap.end()) + if (i != cellToPropertyNameMap.end()) { return i->second; - else + } + else { return empty; + } } void PropertySheet::recomputeDependencies(CellAddress key) @@ -1518,27 +1668,25 @@ void PropertySheet::recomputeDependencies(CellAddress key) void PropertySheet::hasSetValue() { - if(updateCount == 0 || - !owner || !owner->getNameInDocument() || owner->isRestoring() || - this!=&owner->cells || - testFlag(LinkDetached)) - { + if (updateCount == 0 || !owner || !owner->getNameInDocument() || owner->isRestoring() + || this != &owner->cells || testFlag(LinkDetached)) { PropertyExpressionContainer::hasSetValue(); return; } updateCount = 0; - std::map deps; + std::map deps; std::vector labels; unregisterElementReference(); UpdateElementReferenceExpressionVisitor v(*this); - for(auto &d : data) { + for (auto& d : data) { auto expr = d.second->expression.get(); - if(expr) { - expr->getDepObjects(deps,&labels); - if(!restoring) + if (expr) { + expr->getDepObjects(deps, &labels); + if (!restoring) { expr->visit(v); + } } } registerLabelReferences(std::move(labels)); @@ -1548,50 +1696,57 @@ void PropertySheet::hasSetValue() PropertyExpressionContainer::hasSetValue(); } -PyObject *PropertySheet::getPyObject() +PyObject* PropertySheet::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new PropertySheetPy(this),true); + PythonObject = Py::Object(new PropertySheetPy(this), true); } return Py::new_reference_to(PythonObject); } -void PropertySheet::setPyObject(PyObject *obj) { - if(!obj || !PyObject_TypeCheck(obj, &PropertySheetPy::Type)) +void PropertySheet::setPyObject(PyObject* obj) +{ + if (!obj || !PyObject_TypeCheck(obj, &PropertySheetPy::Type)) { throw Base::TypeError("Invalid type"); - if(obj != PythonObject.ptr()) + } + if (obj != PythonObject.ptr()) { Paste(*static_cast(obj)->getPropertySheetPtr()); + } } -PyObject *PropertySheet::getPyValue(PyObject *key) { +PyObject* PropertySheet::getPyValue(PyObject* key) +{ assert(key); - PY_TRY { + PY_TRY + { std::string addr = Py::Object(key).as_string(); - CellAddress caddr = getCellAddress(addr.c_str(),true); - if(caddr.isValid()) { + CellAddress caddr = getCellAddress(addr.c_str(), true); + if (caddr.isValid()) { auto prop = owner->getPropertyByName(caddr.toString().c_str()); - if(prop) + if (prop) { return prop->getPyObject(); + } Py_Return; } Range range = getRange(Py::Object(key).as_string().c_str(), false); - if(!range.from().isValid() || !range.to().isValid()) + if (!range.from().isValid() || !range.to().isValid()) { return Py::new_reference_to(Py::Tuple()); + } Py::Tuple res(range.size()); int i = 0; do { addr = range.address(); auto prop = owner->getPropertyByName(addr.c_str()); - res.setItem(i++,prop?Py::asObject(prop->getPyObject()):Py::Object()); - } while(range.next()); + res.setItem(i++, prop ? Py::asObject(prop->getPyObject()) : Py::Object()); + } while (range.next()); return Py::new_reference_to(res); - - } PY_CATCH + } + PY_CATCH } void PropertySheet::afterRestore() @@ -1602,54 +1757,63 @@ void PropertySheet::afterRestore() PropertyExpressionContainer::afterRestore(); { ObjectIdentifier::DocumentMapper mapper(this->_DocMap); - for(auto &d : data) + for (auto& d : data) { d.second->afterRestore(); + } } - for(auto &v : _XLinks) { - auto &xlink = *v.second; - if(!xlink.checkRestore()) + for (auto& v : _XLinks) { + auto& xlink = *v.second; + if (!xlink.checkRestore()) { continue; + } auto iter = documentObjectToCellMap.find(xlink.getValue()->getFullName()); - if(iter == documentObjectToCellMap.end()) + if (iter == documentObjectToCellMap.end()) { continue; + } touch(); - for(const auto &address : iter->second) + for (const auto& address : iter->second) { setDirty(address); + } } signaller.tryInvoke(); } -void PropertySheet::onContainerRestored() { +void PropertySheet::onContainerRestored() +{ Base::FlagToggler flag(restoring); unregisterElementReference(); UpdateElementReferenceExpressionVisitor v(*this); - for(auto &d : data) { + for (auto& d : data) { auto expr = d.second->expression.get(); - if(expr) + if (expr) { expr->visit(v); + } } } -bool PropertySheet::adjustLink(const std::set &inList) { - AtomicPropertyChange signaller(*this,false); +bool PropertySheet::adjustLink(const std::set& inList) +{ + AtomicPropertyChange signaller(*this, false); bool changed = false; - for(auto &d : data) { + for (auto& d : data) { auto expr = d.second->expression.get(); - if(!expr) + if (!expr) { continue; + } try { bool need_adjust = false; - for(auto &v : expr->getDepObjects()) { + for (auto& v : expr->getDepObjects()) { auto docObj = v.first; - if (v.second && docObj && docObj!=owner && inList.count(docObj)) { + if (v.second && docObj && docObj != owner && inList.count(docObj)) { need_adjust = true; break; } } - if(!need_adjust) + if (!need_adjust) { continue; + } signaller.aboutToChange(); changed = true; @@ -1657,297 +1821,342 @@ bool PropertySheet::adjustLink(const std::set &inList) { removeDependencies(d.first); expr->adjustLinks(inList); addDependencies(d.first); - - }catch(Base::Exception &e) { + } + catch (Base::Exception& e) { addDependencies(d.first); std::ostringstream ss; ss << "Failed to adjust link for " << owner->getFullName() << " in expression " - << expr->toString() << ": " << e.what(); + << expr->toString() << ": " << e.what(); throw Base::RuntimeError(ss.str()); } } return changed; } -void PropertySheet::updateElementReference(DocumentObject *feature,bool reverse,bool notify) +void PropertySheet::updateElementReference(DocumentObject* feature, bool reverse, bool notify) { (void)notify; - if(!feature) + if (!feature) { unregisterElementReference(); - UpdateElementReferenceExpressionVisitor visitor(*this,feature,reverse); - for(auto &d : data) { + } + UpdateElementReferenceExpressionVisitor visitor(*this, feature, reverse); + for (auto& d : data) { auto expr = d.second->expression.get(); - if(!expr) + if (!expr) { continue; + } expr->visit(visitor); } - if(feature && visitor.changed()) { + if (feature && visitor.changed()) { auto owner = dynamic_cast(getContainer()); - if(owner) + if (owner) { owner->onUpdateElementReference(this); + } } } -bool PropertySheet::referenceChanged() const { +bool PropertySheet::referenceChanged() const +{ return false; } -Property *PropertySheet::CopyOnImportExternal( - const std::map &nameMap) const +Property* +PropertySheet::CopyOnImportExternal(const std::map& nameMap) const { - std::map > changed; - for(auto &d : data) { + std::map> changed; + for (auto& d : data) { auto e = d.second->expression.get(); - if(!e) continue; + if (!e) { + continue; + } auto expr = e->importSubNames(nameMap); - if(!expr) + if (!expr) { continue; + } changed[d.first] = std::move(expr); } - if(changed.empty()) + if (changed.empty()) { return nullptr; + } std::unique_ptr copy(new PropertySheet(*this)); - for(auto &change : changed) + for (auto& change : changed) { copy->data[change.first]->setExpression(std::move(change.second)); + } return copy.release(); } -Property *PropertySheet::CopyOnLabelChange(App::DocumentObject *obj, - const std::string &ref, const char *newLabel) const +Property* PropertySheet::CopyOnLabelChange(App::DocumentObject* obj, + const std::string& ref, + const char* newLabel) const { - std::map > changed; - for(auto &d : data) { + std::map> changed; + for (auto& d : data) { auto e = d.second->expression.get(); - if(!e) continue; - auto expr = e->updateLabelReference(obj,ref,newLabel); - if(!expr) + if (!e) { continue; + } + auto expr = e->updateLabelReference(obj, ref, newLabel); + if (!expr) { + continue; + } changed[d.first] = std::move(expr); } - if(changed.empty()) + if (changed.empty()) { return nullptr; + } std::unique_ptr copy(new PropertySheet(*this)); - for(auto &change : changed) + for (auto& change : changed) { copy->data[change.first]->setExpression(std::move(change.second)); + } return copy.release(); } -Property *PropertySheet::CopyOnLinkReplace(const App::DocumentObject *parent, - App::DocumentObject *oldObj, App::DocumentObject *newObj) const +Property* PropertySheet::CopyOnLinkReplace(const App::DocumentObject* parent, + App::DocumentObject* oldObj, + App::DocumentObject* newObj) const { - std::map > changed; - for(auto &d : data) { + std::map> changed; + for (auto& d : data) { auto e = d.second->expression.get(); - if(!e) continue; - auto expr = e->replaceObject(parent,oldObj,newObj); - if(!expr) + if (!e) { continue; + } + auto expr = e->replaceObject(parent, oldObj, newObj); + if (!expr) { + continue; + } changed[d.first] = std::move(expr); } - if(changed.empty()) + if (changed.empty()) { return nullptr; + } std::unique_ptr copy(new PropertySheet(*this)); - for(auto &change : changed) + for (auto& change : changed) { copy->data[change.first]->setExpression(std::move(change.second)); + } return copy.release(); } -std::map PropertySheet::getExpressions() const { +std::map PropertySheet::getExpressions() const +{ std::map res; - for(auto &d : data) { - if(d.second->expression) { - res[ObjectIdentifier(owner,d.first.toString())] = d.second->getExpression(true); + for (auto& d : data) { + if (d.second->expression) { + res[ObjectIdentifier(owner, d.first.toString())] = d.second->getExpression(true); } } return res; } -void PropertySheet::setExpressions( - std::map &&exprs) +void PropertySheet::setExpressions(std::map&& exprs) { AtomicPropertyChange signaller(*this); - for(auto &v : exprs) { + for (auto& v : exprs) { CellAddress addr(v.first.getPropertyName().c_str()); - auto &cell = data[addr]; - if(!cell) { - if(!v.second) + auto& cell = data[addr]; + if (!cell) { + if (!v.second) { continue; - cell = new Cell(addr,this); + } + cell = new Cell(addr, this); } - if(!v.second) + if (!v.second) { clear(addr); - else + } + else { cell->setExpression(std::move(v.second)); + } } signaller.tryInvoke(); } -App::CellAddress PropertySheet::getCellAddress(const char *addr, bool silent) const { +App::CellAddress PropertySheet::getCellAddress(const char* addr, bool silent) const +{ assert(addr); CellAddress caddr; - const Cell * cell = getValueFromAlias(addr); - if(cell) + const Cell* cell = getValueFromAlias(addr); + if (cell) { return cell->getAddress(); - else - return stringToAddress(addr,silent); + } + else { + return stringToAddress(addr, silent); + } } -App::Range PropertySheet::getRange(const char *range, bool silent) const { +App::Range PropertySheet::getRange(const char* range, bool silent) const +{ assert(range); - const char *sep = strchr(range,':'); - CellAddress from,to; - if(!sep) - from = to = getCellAddress(range,silent); + const char* sep = strchr(range, ':'); + CellAddress from, to; + if (!sep) { + from = to = getCellAddress(range, silent); + } else { - std::string addr(range,sep); + std::string addr(range, sep); auto findCell = [this, &addr](CellAddress caddr, int r, int c) -> CellAddress { - if(!getValue(caddr)) + if (!getValue(caddr)) { return CellAddress(); - if(addr == "-") - r = 0; - else - c = 0; - for(;;) { - caddr.setRow(caddr.row()+r); - caddr.setCol(caddr.col()+c); - if(!caddr.isValid() || !getValue(caddr)) - break; } - caddr.setRow(caddr.row()-r); - caddr.setCol(caddr.col()-c); + if (addr == "-") { + r = 0; + } + else { + c = 0; + } + for (;;) { + caddr.setRow(caddr.row() + r); + caddr.setCol(caddr.col() + c); + if (!caddr.isValid() || !getValue(caddr)) { + break; + } + } + caddr.setRow(caddr.row() - r); + caddr.setCol(caddr.col() - c); return caddr; }; - if(addr == "-" || addr == "|") { - to = getCellAddress(sep+1,silent); - return Range(findCell(to,-1,-1), from); - } else { - from = getCellAddress(addr.c_str(),silent); - addr = sep+1; - if(addr == "-" || addr == "|") - return Range(from, findCell(from,1,1)); - to = getCellAddress(addr.c_str(),silent); + if (addr == "-" || addr == "|") { + to = getCellAddress(sep + 1, silent); + return Range(findCell(to, -1, -1), from); + } + else { + from = getCellAddress(addr.c_str(), silent); + addr = sep + 1; + if (addr == "-" || addr == "|") { + return Range(from, findCell(from, 1, 1)); + } + to = getCellAddress(addr.c_str(), silent); } } - if(!from.isValid() || !to.isValid()) - return App::Range(App::CellAddress(),App::CellAddress()); - return App::Range(from,to); + if (!from.isValid() || !to.isValid()) { + return App::Range(App::CellAddress(), App::CellAddress()); + } + return App::Range(from, to); } -bool PropertySheet::isBindingPath(const ObjectIdentifier &path, - CellAddress *from, CellAddress *to, bool *href) const +bool PropertySheet::isBindingPath(const ObjectIdentifier& path, + CellAddress* from, + CellAddress* to, + bool* href) const { - const auto &comps = path.getComponents(); - if (comps.size()!=4 - || !comps[2].isSimple() - || !comps[3].isSimple() - || (comps[1].getName()!="Bind" - && comps[1].getName()!="BindHREF" - && comps[1].getName()!="BindHiddenRef") - || path.getProperty() != this) - { + const auto& comps = path.getComponents(); + if (comps.size() != 4 || !comps[2].isSimple() || !comps[3].isSimple() + || (comps[1].getName() != "Bind" && comps[1].getName() != "BindHREF" + && comps[1].getName() != "BindHiddenRef") + || path.getProperty() != this) { return false; } - if(href) - *href = (comps[1].getName()=="BindHREF" || comps[1].getName()=="BindHiddenRef"); - if(from) + if (href) { + *href = (comps[1].getName() == "BindHREF" || comps[1].getName() == "BindHiddenRef"); + } + if (from) { *from = CellAddress(comps[2].getName()); - if(to) + } + if (to) { *to = CellAddress(comps[3].getName()); + } return true; } -PropertySheet::BindingType -PropertySheet::getBinding(const Range &range, - ExpressionPtr *pStart, - ExpressionPtr *pEnd, - App::ObjectIdentifier *pTarget) const +PropertySheet::BindingType PropertySheet::getBinding(const Range& range, + ExpressionPtr* pStart, + ExpressionPtr* pEnd, + App::ObjectIdentifier* pTarget) const { - if(!owner) + if (!owner) { return BindingNone; + } - for(int href=0;href<2;++href) { + for (int href = 0; href < 2; ++href) { ObjectIdentifier path(*this); - path << ObjectIdentifier::SimpleComponent(href?"BindHiddenRef":"Bind"); + path << ObjectIdentifier::SimpleComponent(href ? "BindHiddenRef" : "Bind"); path << ObjectIdentifier::SimpleComponent(range.from().toString().c_str()); path << ObjectIdentifier::SimpleComponent(range.to().toString().c_str()); auto res = owner->getExpression(path); - if(res.expression && res.expression->isDerivedFrom(FunctionExpression::getClassTypeId())) - { + if (res.expression && res.expression->isDerivedFrom(FunctionExpression::getClassTypeId())) { auto expr = static_cast(res.expression.get()); - if(href) { - if((expr->getFunction()!=FunctionExpression::HIDDENREF - && expr->getFunction()!=FunctionExpression::HREF) - || expr->getArgs().size()!=1 - || !expr->getArgs().front()->isDerivedFrom(FunctionExpression::getClassTypeId())) + if (href) { + if ((expr->getFunction() != FunctionExpression::HIDDENREF + && expr->getFunction() != FunctionExpression::HREF) + || expr->getArgs().size() != 1 + || !expr->getArgs().front()->isDerivedFrom( + FunctionExpression::getClassTypeId())) { continue; + } expr = static_cast(expr->getArgs().front()); } - if(expr->getFunction() == FunctionExpression::TUPLE && expr->getArgs().size()==3) { + if (expr->getFunction() == FunctionExpression::TUPLE && expr->getArgs().size() == 3) { if (pTarget) { - if (auto e = Base::freecad_dynamic_cast(expr->getArgs()[0])) + if (auto e = + Base::freecad_dynamic_cast(expr->getArgs()[0])) { *pTarget = e->getPath(); + } } - if(pStart) + if (pStart) { pStart->reset(expr->getArgs()[1]->copy()); - if(pEnd) + } + if (pEnd) { pEnd->reset(expr->getArgs()[2]->copy()); - return href?BindingHiddenRef:BindingNormal; + } + return href ? BindingHiddenRef : BindingNormal; } } } return BindingNone; } -void PropertySheet::setPathValue(const ObjectIdentifier &path, const boost::any &value) +void PropertySheet::setPathValue(const ObjectIdentifier& path, const boost::any& value) { - if(!owner) + if (!owner) { FC_THROWM(Base::RuntimeError, "Invalid state"); + } bool href = false; - CellAddress from,to; - if(!isBindingPath(path,&from,&to,&href)) { - FC_THROWM(Base::IndexError, "Invalid binding of '" << path.toString() - << "' in " << getFullName()); + CellAddress from, to; + if (!isBindingPath(path, &from, &to, &href)) { + FC_THROWM(Base::IndexError, + "Invalid binding of '" << path.toString() << "' in " << getFullName()); } Base::PyGILStateLocker lock; Py::Object pyValue = pyObjectFromAny(value); - if(pyValue.isSequence()) { + if (pyValue.isSequence()) { Py::Sequence seq(pyValue); - if(seq.size()==3 - && PyObject_TypeCheck(seq[0].ptr(),&PropertySheetPy::Type) - && Py::Object(seq[1].ptr()).isString() - && Py::Object(seq[2].ptr()).isString()) - { - AtomicPropertyChange signaller(*this,false); + if (seq.size() == 3 && PyObject_TypeCheck(seq[0].ptr(), &PropertySheetPy::Type) + && Py::Object(seq[1].ptr()).isString() && Py::Object(seq[2].ptr()).isString()) { + AtomicPropertyChange signaller(*this, false); auto other = static_cast(seq[0].ptr())->getPropertySheetPtr(); - auto otherOwner = Base::freecad_dynamic_cast(other->getContainer()); - if(!otherOwner) - FC_THROWM(Base::RuntimeError, "Invalid binding of '" << other->getFullName() - << " in " << getFullName()); + auto otherOwner = + Base::freecad_dynamic_cast(other->getContainer()); + if (!otherOwner) { + FC_THROWM(Base::RuntimeError, + "Invalid binding of '" << other->getFullName() << " in " + << getFullName()); + } - App::CellAddress targetFrom = other->getCellAddress( - Py::Object(seq[1].ptr()).as_string().c_str(), false); + App::CellAddress targetFrom = + other->getCellAddress(Py::Object(seq[1].ptr()).as_string().c_str(), false); - App::CellAddress targetTo = other->getCellAddress( - Py::Object(seq[2].ptr()).as_string().c_str(), false); + App::CellAddress targetTo = + other->getCellAddress(Py::Object(seq[2].ptr()).as_string().c_str(), false); - std::string expr(href?"hiddenref(":""); - if(other != this) { - if(otherOwner->getDocument() == owner->getDocument()) + std::string expr(href ? "hiddenref(" : ""); + if (other != this) { + if (otherOwner->getDocument() == owner->getDocument()) { expr += otherOwner->getNameInDocument(); - else + } + else { expr += otherOwner->getFullName(); + } } expr += "."; std::size_t exprSize = expr.size(); - auto normalize = [](CellAddress &from, CellAddress &to) { + auto normalize = [](CellAddress& from, CellAddress& to) { if (from.row() > to.row()) { int tmp = from.row(); from.setRow(to.row()); @@ -1965,92 +2174,97 @@ void PropertySheet::setPathValue(const ObjectIdentifier &path, const boost::any App::Range totalRange(from, to); std::set touched; - while(from.row() <= to.row() - && from.col() <= to.col() - && targetFrom.row() <= targetTo.row() - && targetFrom.col() <= targetTo.col()) - { + while (from.row() <= to.row() && from.col() <= to.col() + && targetFrom.row() <= targetTo.row() && targetFrom.col() <= targetTo.col()) { App::Range range(from, to); App::Range rangeTarget(targetFrom, targetTo); int rowCount = std::min(range.rowCount(), rangeTarget.rowCount()); int colCount = std::min(range.colCount(), rangeTarget.colCount()); - if (rowCount == range.rowCount()) + if (rowCount == range.rowCount()) { from.setCol(from.col() + colCount); - else if (colCount == range.colCount()) + } + else if (colCount == range.colCount()) { from.setRow(from.row() + rowCount); - if (rowCount == rangeTarget.rowCount()) + } + if (rowCount == rangeTarget.rowCount()) { targetFrom.setCol(targetFrom.col() + colCount); - else if (colCount == rangeTarget.colCount()) + } + else if (colCount == rangeTarget.colCount()) { targetFrom.setRow(targetFrom.row() + rowCount); + } range = App::Range(range.from().row(), range.from().col(), - range.from().row()+rowCount-1, - range.from().col()+colCount-1); + range.from().row() + rowCount - 1, + range.from().col() + colCount - 1); rangeTarget = App::Range(rangeTarget.from().row(), rangeTarget.from().col(), - rangeTarget.from().row()+rowCount-1, - rangeTarget.from().col()+colCount-1); + rangeTarget.from().row() + rowCount - 1, + rangeTarget.from().col() + colCount - 1); do { CellAddress target(*rangeTarget); CellAddress source(*range); - if(other == this && source.row() >= rangeTarget.from().row() - && source.row() <= rangeTarget.to().row() - && source.col() >= rangeTarget.from().col() - && source.col() <= rangeTarget.to().col()) + if (other == this && source.row() >= rangeTarget.from().row() + && source.row() <= rangeTarget.to().row() + && source.col() >= rangeTarget.from().col() + && source.col() <= rangeTarget.to().col()) { continue; + } - Cell *dst = other->getValue(target); - Cell *src = getValue(source); - if(!dst || !dst->getExpression()) + Cell* dst = other->getValue(target); + Cell* src = getValue(source); + if (!dst || !dst->getExpression()) { continue; + } touched.insert(source); - if(!src) { + if (!src) { signaller.aboutToChange(); src = createCell(source); } std::string alias; - if(this!=other && dst->getAlias(alias)) { - auto *oldCell = getValueFromAlias(alias); - if(oldCell && oldCell!=dst) { + if (this != other && dst->getAlias(alias)) { + auto* oldCell = getValueFromAlias(alias); + if (oldCell && oldCell != dst) { signaller.aboutToChange(); oldCell->setAlias(""); } std::string oldAlias; - if(!src->getAlias(oldAlias) || oldAlias!=alias) { + if (!src->getAlias(oldAlias) || oldAlias != alias) { signaller.aboutToChange(); - setAlias(source,alias); + setAlias(source, alias); } } expr.resize(exprSize); expr += rangeTarget.address(); - if(href) + if (href) { expr += ")"; - auto e = App::ExpressionPtr(App::Expression::parse(owner,expr)); + } + auto e = App::ExpressionPtr(App::Expression::parse(owner, expr)); auto e2 = src->getExpression(); - if(!e2 || !e->isSame(*e2,false)) { + if (!e2 || !e->isSame(*e2, false)) { signaller.aboutToChange(); src->setExpression(std::move(e)); } - } while(range.next() && rangeTarget.next()); + } while (range.next() && rangeTarget.next()); } if (totalRange.size() != (int)touched.size()) { do { CellAddress addr(*totalRange); - if (touched.count(addr)) + if (touched.count(addr)) { continue; - Cell *src = getValue(addr); + } + Cell* src = getValue(addr); if (src && src->getExpression()) { signaller.aboutToChange(); src->setExpression(nullptr); } - } while(totalRange.next()); + } while (totalRange.next()); } owner->rangeUpdated(totalRange); @@ -2059,13 +2273,16 @@ void PropertySheet::setPathValue(const ObjectIdentifier &path, const boost::any } } - FC_THROWM(Base::TypeError, "Invalid path value '" - << "' for " << getFullName()); + FC_THROWM(Base::TypeError, + "Invalid path value '" + << "' for " << getFullName()); } -const boost::any PropertySheet::getPathValue(const App::ObjectIdentifier & path) const { - if(isBindingPath(path)) +const boost::any PropertySheet::getPathValue(const App::ObjectIdentifier& path) const +{ + if (isBindingPath(path)) { return boost::any(); + } return path.getValue(); } diff --git a/src/Mod/Spreadsheet/App/PropertySheet.h b/src/Mod/Spreadsheet/App/PropertySheet.h index 21b9621b12..a72ce75d70 100644 --- a/src/Mod/Spreadsheet/App/PropertySheet.h +++ b/src/Mod/Spreadsheet/App/PropertySheet.h @@ -38,80 +38,86 @@ class Sheet; class PropertySheet; class SheetObserver; -class SpreadsheetExport PropertySheet : public App::PropertyExpressionContainer - , private App::AtomicPropertyChangeInterface { +class SpreadsheetExport PropertySheet: public App::PropertyExpressionContainer, + private App::AtomicPropertyChangeInterface +{ TYPESYSTEM_HEADER_WITH_OVERRIDE(); -public: - explicit PropertySheet(Sheet * _owner = nullptr); +public: + explicit PropertySheet(Sheet* _owner = nullptr); ~PropertySheet() override; std::map getExpressions() const override; - void setExpressions(std::map &&exprs) override; - void onRelabeledDocument(const App::Document &doc) override; + void setExpressions(std::map&& exprs) override; + void onRelabeledDocument(const App::Document& doc) override; - void updateElementReference( - App::DocumentObject *feature,bool reverse=false,bool notify=false) override; + void updateElementReference(App::DocumentObject* feature, + bool reverse = false, + bool notify = false) override; 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; - Property *CopyOnLinkReplace(const App::DocumentObject *parent, - App::DocumentObject *oldObj, App::DocumentObject *newObj) const override; - void breakLink(App::DocumentObject *obj, bool clear) 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; + Property* CopyOnLinkReplace(const App::DocumentObject* parent, + App::DocumentObject* oldObj, + App::DocumentObject* newObj) const override; + void breakLink(App::DocumentObject* obj, bool clear) override; void afterRestore() override; void onContainerRestored() override; - Property *Copy() const override; + Property* Copy() const override; - void Paste(const Property &from) override; + void Paste(const Property& from) override; - void Save (Base::Writer & writer) const override; + void Save(Base::Writer& writer) const override; - void Restore(Base::XMLReader & reader) override; + void Restore(Base::XMLReader& reader) override; - void copyCells(Base::Writer &writer, const std::vector &ranges) const; + void copyCells(Base::Writer& writer, const std::vector& ranges) const; - void pasteCells(Base::XMLReader &reader, App::Range dstRange); + void pasteCells(Base::XMLReader& reader, App::Range dstRange); - Cell *createCell(App::CellAddress address); + Cell* createCell(App::CellAddress address); - void setValue() { } + void setValue() + {} - void setContent(App::CellAddress address, const char * value); + void setContent(App::CellAddress address, const char* value); void setAlignment(App::CellAddress address, int _alignment); - void setStyle(App::CellAddress address, const std::set & _style); + void setStyle(App::CellAddress address, const std::set& _style); - void setForeground(App::CellAddress address, const App::Color &color); + void setForeground(App::CellAddress address, const App::Color& color); - void setBackground(App::CellAddress address, const App::Color &color); + void setBackground(App::CellAddress address, const App::Color& color); - void setDisplayUnit(App::CellAddress address, const std::string & unit); + void setDisplayUnit(App::CellAddress address, const std::string& unit); - void setAlias(App::CellAddress address, const std::string &alias); + void setAlias(App::CellAddress address, const std::string& alias); - void setComputedUnit(App::CellAddress address, const Base::Unit & unit); + void setComputedUnit(App::CellAddress address, const Base::Unit& unit); void setSpans(App::CellAddress address, int rows, int columns); - void clear(App::CellAddress address, bool toClearAlias=true); + void clear(App::CellAddress address, bool toClearAlias = true); void clear(); - Cell * getValue(App::CellAddress key); + Cell* getValue(App::CellAddress key); - const Cell * getValue(App::CellAddress key) const; + const Cell* getValue(App::CellAddress key) const; - Cell * getValueFromAlias(const std::string &alias); + Cell* getValueFromAlias(const std::string& alias); - const Cell * getValueFromAlias(const std::string &alias) const; + const Cell* getValueFromAlias(const std::string& alias) const; - bool isValidAlias(const std::string &candidate); + bool isValidAlias(const std::string& candidate); std::vector getUsedCells() const; @@ -121,21 +127,38 @@ public: std::tuple getNonEmptyRange() const; - Sheet * sheet() const { return owner; } + Sheet* sheet() const + { + return owner; + } - const std::set & getDirty() { return dirty; } + const std::set& getDirty() + { + return dirty; + } void setDirty(App::CellAddress address); void setDirty(); - void clearDirty(App::CellAddress key) { dirty.erase(key); } + void clearDirty(App::CellAddress key) + { + dirty.erase(key); + } - void clearDirty() { dirty.clear(); purgeTouched(); } + void clearDirty() + { + dirty.clear(); + purgeTouched(); + } - bool isDirty() const { return dirty.size() > 0; } + bool isDirty() const + { + return dirty.size() > 0; + } - void pasteCells(const std::map &cells, int rowOffset, int colOffset); + void + pasteCells(const std::map& cells, int rowOffset, int colOffset); void insertRows(int row, int count); @@ -149,13 +172,13 @@ public: void removeColumns(int col, int count); - unsigned int getMemSize () const override; + unsigned int getMemSize() const override; bool mergeCells(App::CellAddress from, App::CellAddress to); void splitCell(App::CellAddress address); - void getSpans(App::CellAddress address, int &rows, int &cols) const; + void getSpans(App::CellAddress address, int& rows, int& cols) const; bool hasSpan() const; @@ -165,62 +188,65 @@ public: bool isHidden(App::CellAddress address) const; - const std::set< App::CellAddress > & getDeps(const std::string & name) const; + const std::set& getDeps(const std::string& name) const; - const std::set &getDeps(App::CellAddress pos) const; + const std::set& getDeps(App::CellAddress pos) const; void recomputeDependencies(App::CellAddress key); - PyObject *getPyObject() override; - void setPyObject(PyObject *) override; + PyObject* getPyObject() override; + void setPyObject(PyObject*) override; - PyObject *getPyValue(PyObject *key); + PyObject* getPyValue(PyObject* key); - void invalidateDependants(const App::DocumentObject *docObj); + void invalidateDependants(const App::DocumentObject* docObj); - void renamedDocumentObject(const App::DocumentObject *docObj); - void renameObjectIdentifiers(const std::map &paths); + void renamedDocumentObject(const App::DocumentObject* docObj); + void + renameObjectIdentifiers(const std::map& paths); - void deletedDocumentObject(const App::DocumentObject *docObj); + void deletedDocumentObject(const App::DocumentObject* docObj); void documentSet(); - App::CellAddress getCellAddress(const char *addr, bool silent=false) const; - App::Range getRange(const char *range, bool silent=false) const; + App::CellAddress getCellAddress(const char* addr, bool silent = false) const; + App::Range getRange(const char* range, bool silent = false) const; - std::string getRow(int offset=0) const; + std::string getRow(int offset = 0) const; - std::string getColumn(int offset=0) const; + std::string getColumn(int offset = 0) const; - void setPathValue(const App::ObjectIdentifier & path, const boost::any & value) override; - 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; - bool isBindingPath(const App::ObjectIdentifier &path, - App::CellAddress *from=nullptr, App::CellAddress *to=nullptr, bool *href=nullptr) const; + bool isBindingPath(const App::ObjectIdentifier& path, + App::CellAddress* from = nullptr, + App::CellAddress* to = nullptr, + bool* href = nullptr) const; - enum BindingType { + enum BindingType + { BindingNone, BindingNormal, BindingHiddenRef, }; - BindingType getBinding(const App::Range &range, - App::ExpressionPtr *pStart=nullptr, - App::ExpressionPtr *pEnd=nullptr, - App::ObjectIdentifier *pTarget=nullptr) const; + BindingType getBinding(const App::Range& range, + App::ExpressionPtr* pStart = nullptr, + App::ExpressionPtr* pEnd = nullptr, + App::ObjectIdentifier* pTarget = nullptr) const; protected: 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; + 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: - - PropertySheet(const PropertySheet & other); - PropertySheet& operator= (const PropertySheet&); + PropertySheet(const PropertySheet& other); + PropertySheet& operator=(const PropertySheet&); /* friends */ @@ -232,15 +258,15 @@ private: friend class Sheet; - Cell *cellAt(App::CellAddress address); + Cell* cellAt(App::CellAddress address); - Cell *nonNullCellAt(App::CellAddress address); + Cell* nonNullCellAt(App::CellAddress address); - const Cell *cellAt(App::CellAddress address) const; + const Cell* cellAt(App::CellAddress address) const; - bool colSortFunc(const App::CellAddress &a, const App::CellAddress &b); + bool colSortFunc(const App::CellAddress& a, const App::CellAddress& b); - bool rowSortFunc(const App::CellAddress &a, const App::CellAddress &b); + bool rowSortFunc(const App::CellAddress& a, const App::CellAddress& b); /*! Set of cells that have been marked dirty */ std::set dirty; @@ -252,13 +278,15 @@ private: std::map mergedCells; /*! Owner of this property */ - Sheet * owner; + Sheet* owner; void clearAlias(App::CellAddress address); void moveAlias(App::CellAddress currPos, App::CellAddress newPos); - void moveCell(App::CellAddress currPos, App::CellAddress newPos, std::map &renames); + void moveCell(App::CellAddress currPos, + App::CellAddress newPos, + std::map& renames); /* * Cell dependency tracking @@ -268,24 +296,24 @@ private: void removeDependencies(App::CellAddress key); - void slotChangedObject(const App::DocumentObject &obj, const App::Property &prop); - void recomputeDependants(const App::DocumentObject *obj, const char *propName); + void slotChangedObject(const App::DocumentObject& obj, const App::Property& prop); + void recomputeDependants(const App::DocumentObject* obj, const char* propName); /*! Cell dependencies, i.e when a change occurs to property given in key, the set of addresses needs to be recomputed. */ - std::map > propertyNameToCellMap; + std::map> propertyNameToCellMap; /*! Properties this cell depends on */ - std::map > cellToPropertyNameMap; + std::map> cellToPropertyNameMap; /*! Cell dependencies, i.e when a change occurs to documentObject given in key, the set of addresses needs to be recomputed. */ - std::map > documentObjectToCellMap; + std::map> documentObjectToCellMap; /*! DocumentObject this cell depends on */ - std::map > cellToDocumentObjectMap; + std::map> cellToDocumentObjectMap; /*! Mapping of cell position to alias property */ std::map aliasProp; @@ -302,5 +330,5 @@ private: bool restoring = false; }; -} -#endif // PROPERTYSHEET_H +}// namespace Spreadsheet +#endif// PROPERTYSHEET_H diff --git a/src/Mod/Spreadsheet/App/PropertySheetPy.xml b/src/Mod/Spreadsheet/App/PropertySheetPy.xml index 4ee484140d..c739b3353e 100644 --- a/src/Mod/Spreadsheet/App/PropertySheetPy.xml +++ b/src/Mod/Spreadsheet/App/PropertySheetPy.xml @@ -10,7 +10,6 @@ FatherInclude="Base/PersistencePy.h" FatherNamespace="Base" Constructor="true"> - Internal spreadsheet object diff --git a/src/Mod/Spreadsheet/App/PropertySheetPyImp.cpp b/src/Mod/Spreadsheet/App/PropertySheetPyImp.cpp index c0bf240ed2..36dcedf106 100644 --- a/src/Mod/Spreadsheet/App/PropertySheetPyImp.cpp +++ b/src/Mod/Spreadsheet/App/PropertySheetPyImp.cpp @@ -24,8 +24,10 @@ #include "PropertySheet.h" // inclusion of the generated files (generated out of PropertySheetPy.xml) +// clang-format off #include "PropertySheetPy.h" #include "PropertySheetPy.cpp" +// clang-format on using namespace Spreadsheet; @@ -36,7 +38,7 @@ std::string PropertySheetPy::representation() const return {""}; } -PyObject *PropertySheetPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* PropertySheetPy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of PropertySheetPy and the Twin object return new PropertySheetPy(new PropertySheet); @@ -48,12 +50,12 @@ int PropertySheetPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) return 0; } -PyObject * PropertySheetPy::mapping_subscript(PyObject * o, PyObject *key) +PyObject* PropertySheetPy::mapping_subscript(PyObject* o, PyObject* key) { return static_cast(o)->getPropertySheetPtr()->getPyValue(key); } -PyObject *PropertySheetPy::getCustomAttributes(const char* /*attr*/) const +PyObject* PropertySheetPy::getCustomAttributes(const char* /*attr*/) const { return nullptr; } diff --git a/src/Mod/Spreadsheet/App/Sheet.cpp b/src/Mod/Spreadsheet/App/Sheet.cpp index c4b2c6940f..c5e28d65e6 100644 --- a/src/Mod/Spreadsheet/App/Sheet.cpp +++ b/src/Mod/Spreadsheet/App/Sheet.cpp @@ -23,10 +23,10 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include -# include -# include -# include +#include +#include +#include +#include #endif #include @@ -53,22 +53,22 @@ using namespace Spreadsheet; PROPERTY_SOURCE(Spreadsheet::Sheet, App::DocumentObject) -using DependencyList = boost::adjacency_list < -boost::vecS, // class OutEdgeListS : a Sequence or an AssociativeContainer -boost::vecS, // class VertexListS : a Sequence or a RandomAccessContainer -boost::directedS, // class DirectedS : This is a directed graph -boost::no_property, // class VertexProperty: -boost::no_property, // class EdgeProperty: -boost::no_property, // class GraphProperty: -boost::listS // class EdgeListS: ->; +using DependencyList = + boost::adjacency_list; using Traits = boost::graph_traits; using Vertex = Traits::vertex_descriptor; using Edge = Traits::edge_descriptor; /** - * Construct a new Sheet object. - */ + * Construct a new Sheet object. + */ Sheet::Sheet() : DocumentObject() @@ -76,10 +76,22 @@ Sheet::Sheet() , cells(this) { ADD_PROPERTY_TYPE(cells, (), "Spreadsheet", (PropertyType)(Prop_Hidden), "Cell contents"); - ADD_PROPERTY_TYPE(columnWidths, (), "Spreadsheet", (PropertyType)(Prop_ReadOnly|Prop_Hidden|Prop_Output), "Column widths"); - ADD_PROPERTY_TYPE(rowHeights, (), "Spreadsheet", (PropertyType)(Prop_ReadOnly|Prop_Hidden|Prop_Output), "Row heights"); - ADD_PROPERTY_TYPE(rowHeights, (), "Spreadsheet", (PropertyType)(Prop_ReadOnly|Prop_Hidden), "Row heights"); - ExpressionEngine.expressionChanged.connect([this](const App::ObjectIdentifier &) { + ADD_PROPERTY_TYPE(columnWidths, + (), + "Spreadsheet", + (PropertyType)(Prop_ReadOnly | Prop_Hidden | Prop_Output), + "Column widths"); + ADD_PROPERTY_TYPE(rowHeights, + (), + "Spreadsheet", + (PropertyType)(Prop_ReadOnly | Prop_Hidden | Prop_Output), + "Row heights"); + ADD_PROPERTY_TYPE(rowHeights, + (), + "Spreadsheet", + (PropertyType)(Prop_ReadOnly | Prop_Hidden), + "Row heights"); + ExpressionEngine.expressionChanged.connect([this](const App::ObjectIdentifier&) { this->updateBindings(); }); } @@ -97,8 +109,8 @@ Sheet::~Sheet() } /** - * Clear all cells in the sheet. - */ + * Clear all cells in the sheet. + */ void Sheet::clearAll() { @@ -106,7 +118,7 @@ void Sheet::clearAll() std::vector propNames = props.getDynamicPropertyNames(); - for (const auto & propName : propNames) { + for (const auto& propName : propNames) { this->removeDynamicProperty(propName.c_str()); } @@ -115,44 +127,55 @@ void Sheet::clearAll() columnWidths.clear(); rowHeights.clear(); - for (auto & observer : observers) { + for (auto& observer : observers) { delete observer.second; } observers.clear(); } -//validate import/export parameters -bool Sheet::getCharsFromPrefs(char &delim, char "e, char &escape, std::string &errMsg){ +// validate import/export parameters +bool Sheet::getCharsFromPrefs(char& delim, char& quote, char& escape, std::string& errMsg) +{ bool isValid = true; - ParameterGrp::handle group = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Spreadsheet"); - QString delimiter = QString::fromStdString(group->GetASCII("ImportExportDelimiter","tab")); - QString quoteChar = QString::fromStdString(group->GetASCII("ImportExportQuoteCharacter","\"")); - QString escapeChar = QString::fromStdString(group->GetASCII("ImportExportEscapeCharacter","\\")); + ParameterGrp::handle group = App::GetApplication().GetParameterGroupByPath( + "User parameter:BaseApp/Preferences/Mod/Spreadsheet"); + QString delimiter = QString::fromStdString(group->GetASCII("ImportExportDelimiter", "tab")); + QString quoteChar = QString::fromStdString(group->GetASCII("ImportExportQuoteCharacter", "\"")); + QString escapeChar = + QString::fromStdString(group->GetASCII("ImportExportEscapeCharacter", "\\")); delim = delimiter.size() == 1 ? delimiter[0].toLatin1() : '\0'; - if (delimiter.compare(QLatin1String("tab"), Qt::CaseInsensitive) == 0 || delimiter.compare(QLatin1String("\\t"),Qt::CaseInsensitive) == 0){ + if (delimiter.compare(QLatin1String("tab"), Qt::CaseInsensitive) == 0 + || delimiter.compare(QLatin1String("\\t"), Qt::CaseInsensitive) == 0) { delim = '\t'; - } else if (delimiter.compare(QLatin1String("comma"), Qt::CaseInsensitive) == 0){ + } + else if (delimiter.compare(QLatin1String("comma"), Qt::CaseInsensitive) == 0) { delim = ','; - } else if (delimiter.compare(QLatin1String("semicolon"), Qt::CaseInsensitive) == 0){ + } + else if (delimiter.compare(QLatin1String("semicolon"), Qt::CaseInsensitive) == 0) { delim = ';'; } - if(delim != '\0' && quoteChar.size() == 1 && escapeChar.size() == 1){ + if (delim != '\0' && quoteChar.size() == 1 && escapeChar.size() == 1) { quote = quoteChar[0].toLatin1(); escape = escapeChar[0].toLatin1(); - } else { + } + else { isValid = false; std::string importExport = errMsg; std::stringstream errStream; errStream << "Invalid spreadsheet Import/Export parameter.\n"; if (delim == '\0') { - errStream << "Unrecognized delimiter: " << delimiter.toStdString() << " (recognized tokens: \\t, tab, semicolon, comma, or any single character)\n"; + errStream + << "Unrecognized delimiter: " << delimiter.toStdString() + << " (recognized tokens: \\t, tab, semicolon, comma, or any single character)\n"; } - if (quoteChar.size() != 1){ - errStream << "Invalid quote character: " << quoteChar.toStdString() << " (quote character must be one single character)\n"; + if (quoteChar.size() != 1) { + errStream << "Invalid quote character: " << quoteChar.toStdString() + << " (quote character must be one single character)\n"; } - if (escapeChar.size() != 1){ - errStream << "Invalid escape character: " << escapeChar.toStdString() << " (escape character must be one single character)\n"; + if (escapeChar.size() != 1) { + errStream << "Invalid escape character: " << escapeChar.toStdString() + << " (escape character must be one single character)\n"; } errStream << importExport << " not done.\n"; errMsg = errStream.str(); @@ -162,17 +185,20 @@ bool Sheet::getCharsFromPrefs(char &delim, char "e, char &escape, std::strin /** - * Import a file into the spreadsheet object. - * - * @param filename Name of file to import - * @param delimiter The field delimiter character used. - * @param quoteChar Quote character, if any (set to '\0' to disable). - * @param escapeChar The escape character used, if any (set to '0' to disable). - * - * @returns True if successful, false if something failed. - */ + * Import a file into the spreadsheet object. + * + * @param filename Name of file to import + * @param delimiter The field delimiter character used. + * @param quoteChar Quote character, if any (set to '\0' to disable). + * @param escapeChar The escape character used, if any (set to '0' to disable). + * + * @returns True if successful, false if something failed. + */ -bool Sheet::importFromFile(const std::string &filename, char delimiter, char quoteChar, char escapeChar) +bool Sheet::importFromFile(const std::string& filename, + char delimiter, + char quoteChar, + char escapeChar) { Base::FileInfo fi(filename); Base::ifstream file(fi, std::ios::in); @@ -192,16 +218,21 @@ bool Sheet::importFromFile(const std::string &filename, char delimiter, char quo escaped_list_separator e; int col = 0; - if (quoteChar) + if (quoteChar) { e = escaped_list_separator(escapeChar, delimiter, quoteChar); - else + } + else { e = escaped_list_separator('\0', delimiter, '\0'); + } - tokenizer > tok(line, e); + tokenizer> tok(line, e); - for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) { - if (!i->empty()) + for (tokenizer>::iterator i = tok.begin(); + i != tok.end(); + ++i) { + if (!i->empty()) { setCell(CellAddress(row, col), (*i).c_str()); + } col++; } } @@ -216,46 +247,52 @@ bool Sheet::importFromFile(const std::string &filename, char delimiter, char quo signaller.tryInvoke(); return true; } - else - return false; -} - -/** - * Write an escaped version of the string \a s to the stream \a out. - * - * @param s The string to write. - * @param quoteChar The quote character. - * @param escapeChar The escape character. - * @param stream The stream to output the escaped string to. - * - */ - -static void writeEscaped(std::string const& s, char quoteChar, char escapeChar, std::ostream & out) { - out << quoteChar; - for (unsigned char c : s) { - if (c != quoteChar) - out << c; else { - out << escapeChar; - out << c; + return false; } - } - out << quoteChar; } /** - * Export spreadsheet data to file. - * - * @param filename Filename to store data to. - * @param delimiter Field delimiter - * @param quoteChar Quote character ('\0' to disable) - * @param escapeChar Escape character ('\0' to disable) - * - * @returns True if store is successful, false if something failed. - * - */ + * Write an escaped version of the string \a s to the stream \a out. + * + * @param s The string to write. + * @param quoteChar The quote character. + * @param escapeChar The escape character. + * @param stream The stream to output the escaped string to. + * + */ -bool Sheet::exportToFile(const std::string &filename, char delimiter, char quoteChar, char escapeChar) const +static void writeEscaped(std::string const& s, char quoteChar, char escapeChar, std::ostream& out) +{ + out << quoteChar; + for (unsigned char c : s) { + if (c != quoteChar) { + out << c; + } + else { + out << escapeChar; + out << c; + } + } + out << quoteChar; +} + +/** + * Export spreadsheet data to file. + * + * @param filename Filename to store data to. + * @param delimiter Field delimiter + * @param quoteChar Quote character ('\0' to disable) + * @param escapeChar Escape character ('\0' to disable) + * + * @returns True if store is successful, false if something failed. + * + */ + +bool Sheet::exportToFile(const std::string& filename, + char delimiter, + char quoteChar, + char escapeChar) const { Base::ofstream file; int prevRow = -1, prevCol = -1; @@ -263,44 +300,54 @@ bool Sheet::exportToFile(const std::string &filename, char delimiter, char quote Base::FileInfo fi(filename); file.open(fi, std::ios::out | std::ios::ate | std::ios::binary); - if (!file.is_open()) + if (!file.is_open()) { return false; + } auto usedCells = cells.getNonEmptyCells(); auto i = usedCells.begin(); while (i != usedCells.end()) { - Property * prop = getProperty(*i); + Property* prop = getProperty(*i); if (prevRow != -1 && prevRow != i->row()) { - for (int j = prevRow; j < i->row(); ++j) + for (int j = prevRow; j < i->row(); ++j) { file << std::endl; + } prevCol = usedCells.begin()->col(); } if (prevCol != -1 && i->col() != prevCol) { - for (int j = prevCol; j < i->col(); ++j) + for (int j = prevCol; j < i->col(); ++j) { file << delimiter; + } } std::stringstream field; - if (prop->isDerivedFrom((PropertyQuantity::getClassTypeId()))) + if (prop->isDerivedFrom((PropertyQuantity::getClassTypeId()))) { field << static_cast(prop)->getValue(); - else if (prop->isDerivedFrom((PropertyFloat::getClassTypeId()))) + } + else if (prop->isDerivedFrom((PropertyFloat::getClassTypeId()))) { field << static_cast(prop)->getValue(); - else if (prop->isDerivedFrom((PropertyInteger::getClassTypeId()))) + } + else if (prop->isDerivedFrom((PropertyInteger::getClassTypeId()))) { field << static_cast(prop)->getValue(); - else if (prop->isDerivedFrom((PropertyString::getClassTypeId()))) + } + else if (prop->isDerivedFrom((PropertyString::getClassTypeId()))) { field << static_cast(prop)->getValue(); - else + } + else { assert(0); + } std::string str = field.str(); - if (quoteChar && str.find(quoteChar) != std::string::npos) + if (quoteChar && str.find(quoteChar) != std::string::npos) { writeEscaped(str, quoteChar, escapeChar, file); - else + } + else { file << str; + } prevRow = i->row(); prevCol = i->col(); @@ -313,26 +360,26 @@ bool Sheet::exportToFile(const std::string &filename, char delimiter, char quote } /** - * Merge a rectangle specified by \a range into one logical cell. - * Data in all but the upper right cell are cleared when the cells are merged. - * - * @param range Range to merge. - * @returns True if the cells were merged, false if the merge was unsuccessful. - * - */ + * Merge a rectangle specified by \a range into one logical cell. + * Data in all but the upper right cell are cleared when the cells are merged. + * + * @param range Range to merge. + * @returns True if the cells were merged, false if the merge was unsuccessful. + * + */ -bool Sheet::mergeCells(const Range & range) +bool Sheet::mergeCells(const Range& range) { return cells.mergeCells(range.from(), range.to()); } /** - * Split a previously merged cell specified by \a address into its individual cells. - * The address can point to any of the cells that make up the merged cell. - * - * @param address Address of cell to split - * - */ + * Split a previously merged cell specified by \a address into its individual cells. + * The address can point to any of the cells that make up the merged cell. + * + * @param address Address of cell to split + * + */ void Sheet::splitCell(CellAddress address) { @@ -340,41 +387,42 @@ void Sheet::splitCell(CellAddress address) } /** - * Get contents of the cell specified by \a address, or 0 if it is not defined - * - * @returns A CellContent object or 0. - */ + * Get contents of the cell specified by \a address, or 0 if it is not defined + * + * @returns A CellContent object or 0. + */ -Cell *Sheet::getCell(CellAddress address) +Cell* Sheet::getCell(CellAddress address) { return cells.getValue(address); } /** - * Get cell contents specified by \a address. - * - * @param address - */ + * Get cell contents specified by \a address. + * + * @param address + */ -Cell *Sheet::getNewCell(CellAddress address) +Cell* Sheet::getNewCell(CellAddress address) { - Cell * cell = getCell(address); + Cell* cell = getCell(address); - if (!cell) + if (!cell) { cell = cells.createCell(address); + } return cell; } /** - * Set cell given by \a address to \a contents. - * - * @param address Address of cell to set. - * @param contents New contents of given cell. - * - */ + * Set cell given by \a address to \a contents. + * + * @param address Address of cell to set. + * @param contents New contents of given cell. + * + */ -void Sheet::setCell(const char * address, const char * contents) +void Sheet::setCell(const char* address, const char* contents) { assert(address && contents); @@ -382,15 +430,15 @@ void Sheet::setCell(const char * address, const char * contents) } /** - * Set cell at \a address to \a value. If a merged cell is specified, the upper right corner of the - * merged cell must be specified. - * - * @param address Row position of cell. - * @param value String value of expression. - * - */ + * Set cell at \a address to \a value. If a merged cell is specified, the upper right corner of the + * merged cell must be specified. + * + * @param address Row position of cell. + * @param value String value of expression. + * + */ -void Sheet::setCell(CellAddress address, const char * value) +void Sheet::setCell(CellAddress address, const char* value) { assert(value); @@ -404,28 +452,28 @@ void Sheet::setCell(CellAddress address, const char * value) } /** - * Get the Python object for the Sheet. - * - * @returns The Python object. - */ + * Get the Python object for the Sheet. + * + * @returns The Python object. + */ -PyObject *Sheet::getPyObject() +PyObject* Sheet::getPyObject() { - if (PythonObject.is(Py::_None())){ + if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new SheetPy(this),true); + PythonObject = Py::Object(new SheetPy(this), true); } return Py::new_reference_to(PythonObject); } /** - * Get the Cell Property for the cell at \a key. - * - * @returns The Property object. - * - */ + * Get the Cell Property for the cell at \a key. + * + * @returns The Property object. + * + */ -Property * Sheet::getProperty(CellAddress key) const +Property* Sheet::getProperty(CellAddress key) const { return props.getDynamicPropertyByName(key.toString(CellAddress::Cell::ShowRowColumn).c_str()); } @@ -436,20 +484,20 @@ Property * Sheet::getProperty(CellAddress key) const * @return Pointer to property, or 0 if it does not exist. */ -Property * Sheet::getProperty(const char * addr) const +Property* Sheet::getProperty(const char* addr) const { return props.getDynamicPropertyByName(addr); } /** - * Get the address as \a address of the Property \a prop. This function - * throws an exception if the property is not found. - * - */ + * Get the address as \a address of the Property \a prop. This function + * throws an exception if the property is not found. + * + */ -bool Sheet::getCellAddress(const Property *prop, CellAddress & address) +bool Sheet::getCellAddress(const Property* prop, CellAddress& address) { - std::map::const_iterator i = propAddress.find(prop); + std::map::const_iterator i = propAddress.find(prop); if (i != propAddress.end()) { address = i->second; @@ -458,12 +506,14 @@ bool Sheet::getCellAddress(const Property *prop, CellAddress & address) return false; } -App::CellAddress Sheet::getCellAddress(const char *name, bool silent) const { - return cells.getCellAddress(name,silent); +App::CellAddress Sheet::getCellAddress(const char* name, bool silent) const +{ + return cells.getCellAddress(name, silent); } -App::Range Sheet::getRange(const char *name, bool silent) const { - return cells.getRange(name,silent); +App::Range Sheet::getRange(const char* name, bool silent) const +{ + return cells.getRange(name, silent); } /** @@ -497,29 +547,36 @@ void Sheet::onSettingDocument() } /** - * Set the property for cell \p key to a PropertyFloat with the value \a value. - * If the Property exists, but of wrong type, the previous Property is destroyed and recreated as the correct type. - * - * @param key The address of the cell we want to create a Property for - * @param value The value we want to assign to the Property. - * - */ + * Set the property for cell \p key to a PropertyFloat with the value \a value. + * If the Property exists, but of wrong type, the previous Property is destroyed and recreated as + * the correct type. + * + * @param key The address of the cell we want to create a Property for + * @param value The value we want to assign to the Property. + * + */ -Property * Sheet::setFloatProperty(CellAddress key, double value) +Property* Sheet::setFloatProperty(CellAddress key, double value) { std::string name = key.toString(CellAddress::Cell::ShowRowColumn); - Property * prop = props.getDynamicPropertyByName(name.c_str()); - PropertyFloat * floatProp; + Property* prop = props.getDynamicPropertyByName(name.c_str()); + PropertyFloat* floatProp; if (!prop || prop->getTypeId() != PropertyFloat::getClassTypeId()) { if (prop) { this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - floatProp = freecad_dynamic_cast(addDynamicProperty("App::PropertyFloat", name.c_str(), nullptr, nullptr, Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + floatProp = freecad_dynamic_cast( + addDynamicProperty("App::PropertyFloat", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); } - else + else { floatProp = static_cast(prop); + } propAddress[floatProp] = key; floatProp->setValue(value); @@ -527,23 +584,27 @@ Property * Sheet::setFloatProperty(CellAddress key, double value) return floatProp; } -Property * Sheet::setIntegerProperty(CellAddress key, long value) +Property* Sheet::setIntegerProperty(CellAddress key, long value) { std::string name = key.toString(CellAddress::Cell::ShowRowColumn); - Property * prop = props.getDynamicPropertyByName(name.c_str()); - PropertyInteger * intProp; + Property* prop = props.getDynamicPropertyByName(name.c_str()); + PropertyInteger* intProp; if (!prop || prop->getTypeId() != PropertyInteger::getClassTypeId()) { if (prop) { this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - intProp = freecad_dynamic_cast(addDynamicProperty( - "App::PropertyInteger", name.c_str(), nullptr, nullptr, - Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + intProp = freecad_dynamic_cast( + addDynamicProperty("App::PropertyInteger", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); } - else + else { intProp = static_cast(prop); + } propAddress[intProp] = key; intProp->setValue(value); @@ -553,31 +614,37 @@ Property * Sheet::setIntegerProperty(CellAddress key, long value) /** - * Set the property for cell \p key to a PropertyQuantity with \a value and \a unit. - * If the Property exists, but of wrong type, the previous Property is destroyed and recreated as the correct type. - * - * @param key The address of the cell we want to create a Property for - * @param value The value we want to assign to the Property. - * @param unit The associated unit for \a value. - * - */ + * Set the property for cell \p key to a PropertyQuantity with \a value and \a unit. + * If the Property exists, but of wrong type, the previous Property is destroyed and recreated as + * the correct type. + * + * @param key The address of the cell we want to create a Property for + * @param value The value we want to assign to the Property. + * @param unit The associated unit for \a value. + * + */ -Property * Sheet::setQuantityProperty(CellAddress key, double value, const Base::Unit & unit) +Property* Sheet::setQuantityProperty(CellAddress key, double value, const Base::Unit& unit) { std::string name = key.toString(CellAddress::Cell::ShowRowColumn); - Property * prop = props.getDynamicPropertyByName(name.c_str()); - PropertySpreadsheetQuantity * quantityProp; + Property* prop = props.getDynamicPropertyByName(name.c_str()); + PropertySpreadsheetQuantity* quantityProp; if (!prop || prop->getTypeId() != PropertySpreadsheetQuantity::getClassTypeId()) { if (prop) { this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - Property * p = addDynamicProperty("Spreadsheet::PropertySpreadsheetQuantity", name.c_str(), nullptr, nullptr, Prop_ReadOnly | Prop_Hidden | Prop_NoPersist); + Property* p = addDynamicProperty("Spreadsheet::PropertySpreadsheetQuantity", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist); quantityProp = freecad_dynamic_cast(p); } - else - quantityProp = static_cast(prop); + else { + quantityProp = static_cast(prop); + } propAddress[quantityProp] = key; quantityProp->setValue(value); @@ -589,26 +656,32 @@ Property * Sheet::setQuantityProperty(CellAddress key, double value, const Base: } /** - * Set the property for cell \p key to a PropertyString with \a value. - * If the Property exists, but of wrong type, the previous Property is destroyed and recreated as the correct type. - * - * @param key The address of the cell we want to create a Property for - * @param value The value we want to assign to the Property. - * - */ + * Set the property for cell \p key to a PropertyString with \a value. + * If the Property exists, but of wrong type, the previous Property is destroyed and recreated as + * the correct type. + * + * @param key The address of the cell we want to create a Property for + * @param value The value we want to assign to the Property. + * + */ -Property * Sheet::setStringProperty(CellAddress key, const std::string & value) +Property* Sheet::setStringProperty(CellAddress key, const std::string& value) { std::string name = key.toString(CellAddress::Cell::ShowRowColumn); - Property * prop = props.getDynamicPropertyByName(name.c_str()); - PropertyString * stringProp = freecad_dynamic_cast(prop); + Property* prop = props.getDynamicPropertyByName(name.c_str()); + PropertyString* stringProp = freecad_dynamic_cast(prop); if (!stringProp) { if (prop) { this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - stringProp = freecad_dynamic_cast(addDynamicProperty("App::PropertyString", name.c_str(), nullptr, nullptr, Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + stringProp = freecad_dynamic_cast( + addDynamicProperty("App::PropertyString", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); } propAddress[stringProp] = key; @@ -617,18 +690,23 @@ Property * Sheet::setStringProperty(CellAddress key, const std::string & value) return stringProp; } -Property * Sheet::setObjectProperty(CellAddress key, Py::Object object) +Property* Sheet::setObjectProperty(CellAddress key, Py::Object object) { std::string name = key.toString(CellAddress::Cell::ShowRowColumn); - Property * prop = props.getDynamicPropertyByName(name.c_str()); - PropertyPythonObject * pyProp = freecad_dynamic_cast(prop); + Property* prop = props.getDynamicPropertyByName(name.c_str()); + PropertyPythonObject* pyProp = freecad_dynamic_cast(prop); if (!pyProp) { if (prop) { this->removeDynamicProperty(name.c_str()); propAddress.erase(prop); } - pyProp = freecad_dynamic_cast(addDynamicProperty("App::PropertyPythonObject", name.c_str(), nullptr, nullptr, Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); + pyProp = freecad_dynamic_cast( + addDynamicProperty("App::PropertyPythonObject", + name.c_str(), + nullptr, + nullptr, + Prop_ReadOnly | Prop_Hidden | Prop_NoPersist)); } propAddress[pyProp] = key; @@ -637,46 +715,51 @@ Property * Sheet::setObjectProperty(CellAddress key, Py::Object object) return pyProp; } -struct CurrentAddressLock { - CurrentAddressLock(int &r, int &c, const CellAddress &addr) - :row(r),col(c) +struct CurrentAddressLock +{ + CurrentAddressLock(int& r, int& c, const CellAddress& addr) + : row(r) + , col(c) { row = addr.row(); col = addr.col(); } - ~CurrentAddressLock() { + ~CurrentAddressLock() + { row = -1; col = -1; } - int &row; - int &col; + int& row; + int& col; }; /** - * Update the Property given by \a key. This will also eventually trigger recomputations of cells depending on \a key. - * - * @param key The address of the cell we want to recompute. - * - */ + * Update the Property given by \a key. This will also eventually trigger recomputations of cells + * depending on \a key. + * + * @param key The address of the cell we want to recompute. + * + */ void Sheet::updateProperty(CellAddress key) { - Cell * cell = getCell(key); + Cell* cell = getCell(key); if (cell) { std::unique_ptr output; - const Expression * input = cell->getExpression(); + const Expression* input = cell->getExpression(); if (input) { - CurrentAddressLock lock(currentRow,currentCol,key); + CurrentAddressLock lock(currentRow, currentCol, key); output.reset(input->eval()); } else { std::string s; - if (cell->getStringContent(s) && !s.empty()) + if (cell->getStringContent(s) && !s.empty()) { output = std::make_unique(this, s); + } else { this->removeDynamicProperty(key.toString().c_str()); return; @@ -686,90 +769,110 @@ void Sheet::updateProperty(CellAddress key) /* Eval returns either NumberExpression or StringExpression, or * PyObjectExpression objects */ auto number = freecad_dynamic_cast(output.get()); - if(number) { + if (number) { long l; auto constant = freecad_dynamic_cast(output.get()); - if(constant && !constant->isNumber()) { + if (constant && !constant->isNumber()) { Base::PyGILStateLocker lock; setObjectProperty(key, constant->getPyValue()); - } else if (!number->getUnit().isEmpty()) + } + else if (!number->getUnit().isEmpty()) { setQuantityProperty(key, number->getValue(), number->getUnit()); - else if(number->isInteger(&l)) - setIntegerProperty(key,l); - else + } + else if (number->isInteger(&l)) { + setIntegerProperty(key, l); + } + else { setFloatProperty(key, number->getValue()); - }else{ + } + } + else { auto str_expr = freecad_dynamic_cast(output.get()); - if(str_expr) + if (str_expr) { setStringProperty(key, str_expr->getText().c_str()); + } else { Base::PyGILStateLocker lock; auto py_expr = freecad_dynamic_cast(output.get()); - if(py_expr) + if (py_expr) { setObjectProperty(key, py_expr->getPyValue()); - else + } + else { setObjectProperty(key, Py::Object()); + } } } } - else + else { clear(key); + } cellUpdated(key); } /** - * Retrieve a specific Property given by \a name. - * This function might throw an exception if something fails, but might also - * return 0 in case the property is not found. - * - * @returns The property, or 0 if not found. - * - */ + * Retrieve a specific Property given by \a name. + * This function might throw an exception if something fails, but might also + * return 0 in case the property is not found. + * + * @returns The property, or 0 if not found. + * + */ -Property *Sheet::getPropertyByName(const char* name) const +Property* Sheet::getPropertyByName(const char* name) const { - CellAddress addr = getCellAddress(name,true); - Property *prop = nullptr; - if(addr.isValid()) + CellAddress addr = getCellAddress(name, true); + Property* prop = nullptr; + if (addr.isValid()) { prop = getProperty(addr); - if (prop) + } + if (prop) { return prop; - else + } + else { return DocumentObject::getPropertyByName(name); -} - -Property *Sheet::getDynamicPropertyByName(const char* name) const { - CellAddress addr = getCellAddress(name,true); - Property *prop = nullptr; - if(addr.isValid()) - prop = getProperty(addr); - if (prop) - return prop; - else - return DocumentObject::getDynamicPropertyByName(name); -} - -void Sheet::getPropertyNamedList(std::vector > &List) const { - DocumentObject::getPropertyNamedList(List); - List.reserve(List.size()+cells.aliasProp.size()); - for(auto &v : cells.aliasProp) { - auto prop = getProperty(v.first); - if(prop) - List.emplace_back(v.second.c_str(),prop); } } -void Sheet::touchCells(Range range) { - do { - cells.setDirty(*range); - }while(range.next()); +Property* Sheet::getDynamicPropertyByName(const char* name) const +{ + CellAddress addr = getCellAddress(name, true); + Property* prop = nullptr; + if (addr.isValid()) { + prop = getProperty(addr); + } + if (prop) { + return prop; + } + else { + return DocumentObject::getDynamicPropertyByName(name); + } } -void Sheet::recomputeCells(Range range) { +void Sheet::getPropertyNamedList(std::vector>& List) const +{ + DocumentObject::getPropertyNamedList(List); + List.reserve(List.size() + cells.aliasProp.size()); + for (auto& v : cells.aliasProp) { + auto prop = getProperty(v.first); + if (prop) { + List.emplace_back(v.second.c_str(), prop); + } + } +} + +void Sheet::touchCells(Range range) +{ + do { + cells.setDirty(*range); + } while (range.next()); +} + +void Sheet::recomputeCells(Range range) +{ do { recomputeCell(*range); - }while(range.next()); + } while (range.next()); } /** @@ -779,7 +882,7 @@ void Sheet::recomputeCells(Range range) { void Sheet::recomputeCell(CellAddress p) { - Cell * cell = cells.getValue(p); + Cell* cell = cells.getValue(p); try { if (cell && cell->hasException()) { @@ -790,87 +893,91 @@ void Sheet::recomputeCell(CellAddress p) updateProperty(p); - if(!cell || !cell->hasException()) { + if (!cell || !cell->hasException()) { cells.clearDirty(p); cellErrors.erase(p); } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { QString msg = QString::fromUtf8("ERR: %1").arg(QString::fromUtf8(e.what())); setStringProperty(p, Base::Tools::toStdString(msg)); - if (cell) + if (cell) { cell->setException(e.what()); - else + } + else { e.ReportException(); + } // Mark as erroneous cellErrors.insert(p); cellUpdated(p); - if(e.isDerivedFrom(Base::AbortException::getClassTypeId())) + if (e.isDerivedFrom(Base::AbortException::getClassTypeId())) { throw; + } } } -PropertySheet::BindingType -Sheet::getCellBinding(Range &range, - ExpressionPtr *pStart, - ExpressionPtr *pEnd, - App::ObjectIdentifier *pTarget) const +PropertySheet::BindingType Sheet::getCellBinding(Range& range, + ExpressionPtr* pStart, + ExpressionPtr* pEnd, + App::ObjectIdentifier* pTarget) const { range.normalize(); do { CellAddress addr = *range; - for(const auto &r : boundRanges) { - if(addr.row()>=r.from().row() - && addr.row()<=r.to().row() - && addr.col()>=r.from().col() - && addr.col()<=r.to().col()) - { - auto res = cells.getBinding(r,pStart,pEnd,pTarget); - if(res != PropertySheet::BindingNone) { + for (const auto& r : boundRanges) { + if (addr.row() >= r.from().row() && addr.row() <= r.to().row() + && addr.col() >= r.from().col() && addr.col() <= r.to().col()) { + auto res = cells.getBinding(r, pStart, pEnd, pTarget); + if (res != PropertySheet::BindingNone) { range = r; return res; } } } - } while(range.next()); + } while (range.next()); return PropertySheet::BindingNone; } -static inline unsigned _getBorder(const Sheet *sheet, - const std::vector &ranges, - const App::CellAddress &address) +static inline unsigned _getBorder(const Sheet* sheet, + const std::vector& ranges, + const App::CellAddress& address) { unsigned flags = 0; int rows, cols; sheet->getSpans(address, rows, cols); --rows; --cols; - for(auto &range : ranges) { + for (auto& range : ranges) { auto from = range.from(); auto to = range.to(); - if(address.row() < from.row() - || address.row() + rows > to.row() - || address.col() < from.col() - || address.col() + cols > to.col()) + if (address.row() < from.row() || address.row() + rows > to.row() + || address.col() < from.col() || address.col() + cols > to.col()) { continue; - if(address.row() == from.row()) + } + if (address.row() == from.row()) { flags |= Sheet::BorderTop; - if(address.row() == to.row() || address.row() + rows == to.row()) + } + if (address.row() == to.row() || address.row() + rows == to.row()) { flags |= Sheet::BorderBottom; - if(address.col() == from.col()) + } + if (address.col() == from.col()) { flags |= Sheet::BorderLeft; - if(address.col() == to.col() || address.col() + cols == to.col()) + } + if (address.col() == to.col() || address.col() + cols == to.col()) { flags |= Sheet::BorderRight; - if(flags == Sheet::BorderAll) + } + if (flags == Sheet::BorderAll) { break; + } } return flags; } -unsigned Sheet::getCellBindingBorder(App::CellAddress address) const { +unsigned Sheet::getCellBindingBorder(App::CellAddress address) const +{ return _getBorder(this, boundRanges, address); } @@ -880,29 +987,33 @@ void Sheet::updateBindings() std::set newRangeSet; std::set rangeSet; boundRanges.clear(); - for(const auto &v : ExpressionEngine.getExpressions()) { - CellAddress from,to; - if(!cells.isBindingPath(v.first,&from,&to)) + for (const auto& v : ExpressionEngine.getExpressions()) { + CellAddress from, to; + if (!cells.isBindingPath(v.first, &from, &to)) { continue; - App::Range range(from,to,true); - if(!oldRangeSet.erase(range)) + } + App::Range range(from, to, true); + if (!oldRangeSet.erase(range)) { newRangeSet.insert(range); + } rangeSet.insert(range); } boundRanges.reserve(rangeSet.size()); - boundRanges.insert(boundRanges.end(),rangeSet.begin(),rangeSet.end()); - for(const auto &range : oldRangeSet) + boundRanges.insert(boundRanges.end(), rangeSet.begin(), rangeSet.end()); + for (const auto& range : oldRangeSet) { rangeUpdated(range); - for(const auto &range : newRangeSet) + } + for (const auto& range : newRangeSet) { rangeUpdated(range); + } } /** - * Update the document properties. - * - */ + * Update the document properties. + * + */ -DocumentObjectExecReturn *Sheet::execute() +DocumentObjectExecReturn* Sheet::execute() { updateBindings(); @@ -911,33 +1022,34 @@ DocumentObjectExecReturn *Sheet::execute() // Always recompute cells that have failed for (auto cellError : cellErrors) { - cells.recomputeDependencies(cellError); - dirtyCells.insert(cellError); + cells.recomputeDependencies(cellError); + dirtyCells.insert(cellError); } DependencyList graph; std::map VertexList; std::map VertexIndexList; - std::deque workQueue(dirtyCells.begin(),dirtyCells.end()); - while(!workQueue.empty()) { + std::deque workQueue(dirtyCells.begin(), dirtyCells.end()); + while (!workQueue.empty()) { CellAddress currPos = workQueue.front(); workQueue.pop_front(); // Insert into map of CellPos -> Index, if it doesn't exist already - auto res = VertexList.emplace(currPos,Vertex()); - if(res.second) { + auto res = VertexList.emplace(currPos, Vertex()); + if (res.second) { res.first->second = add_vertex(graph); VertexIndexList[res.first->second] = currPos; } // Process cells that depend on the current cell - for(auto &dep : providesTo(currPos)) { - auto resDep = VertexList.emplace(dep,Vertex()); - if(resDep.second) { + for (auto& dep : providesTo(currPos)) { + auto resDep = VertexList.emplace(dep, Vertex()); + if (resDep.second) { resDep.first->second = add_vertex(graph); VertexIndexList[resDep.first->second] = dep; - if(dirtyCells.insert(dep).second) + if (dirtyCells.insert(dep).second) { workQueue.push_back(dep); + } } // Add edge to graph to signal dependency add_edge(res.first->second, resDep.first->second, graph); @@ -950,24 +1062,25 @@ DocumentObjectExecReturn *Sheet::execute() boost::topological_sort(graph, std::front_inserter(make_order)); // Recompute cells FC_LOG("recomputing " << getFullName()); - for(auto &pos : make_order) { - const auto &addr = VertexIndexList[pos]; + for (auto& pos : make_order) { + const auto& addr = VertexIndexList[pos]; FC_TRACE(addr.toString()); recomputeCell(addr); } - } catch (std::exception &) { - for(auto &v : VertexList) { - Cell * cell = cells.getValue(v.first); + } + catch (std::exception&) { + for (auto& v : VertexList) { + Cell* cell = cells.getValue(v.first); // Mark as erroneous - if(cell) { + if (cell) { cellErrors.insert(v.first); - cell->setException("Pending computation due to cyclic dependency",true); + cell->setException("Pending computation due to cyclic dependency", true); cellUpdated(v.first); } } // Try to be more user friendly by finding individual loops - while(!dirtyCells.empty()) { + while (!dirtyCells.empty()) { std::deque workQueue; DependencyList graph; @@ -983,16 +1096,16 @@ DocumentObjectExecReturn *Sheet::execute() workQueue.pop_front(); // Insert into map of CellPos -> Index, if it doesn't exist already - auto res = VertexList.emplace(currPos,Vertex()); - if(res.second) { + auto res = VertexList.emplace(currPos, Vertex()); + if (res.second) { res.first->second = add_vertex(graph); VertexIndexList[res.first->second] = currPos; } // Process cells that depend on the current cell - for(auto &dep : providesTo(currPos)) { - auto resDep = VertexList.emplace(dep,Vertex()); - if(resDep.second) { + for (auto& dep : providesTo(currPos)) { + auto resDep = VertexList.emplace(dep, Vertex()); + if (resDep.second) { resDep.first->second = add_vertex(graph); VertexIndexList[resDep.first->second] = dep; workQueue.push_back(dep); @@ -1006,24 +1119,28 @@ DocumentObjectExecReturn *Sheet::execute() std::list make_order; try { boost::topological_sort(graph, std::front_inserter(make_order)); - } catch (std::exception&) { //TODO: evaluate using a more specific exception (not_a_dag) + } + catch (std::exception&) {// TODO: evaluate using a more specific exception (not_a_dag) // Cycle detected; flag all with errors - Base::Console().Error("Cyclic dependency detected in spreadsheet : %s\n", *pcNameInDocument); + Base::Console().Error("Cyclic dependency detected in spreadsheet : %s\n", + *pcNameInDocument); std::ostringstream ss; ss << "Cyclic dependency"; int count = 0; - for(auto &v : VertexList) { - if(count++%20 == 0) + for (auto& v : VertexList) { + if (count++ % 20 == 0) { ss << std::endl; - else + } + else { ss << ", "; + } ss << v.first.toString(); } std::string msg = ss.str(); - for(auto &v : VertexList) { - Cell * cell = cells.getValue(v.first); + for (auto& v : VertexList) { + Cell* cell = cells.getValue(v.first); if (cell) { - cell->setException(msg.c_str(),true); + cell->setException(msg.c_str(), true); cellUpdated(v.first); } } @@ -1032,59 +1149,63 @@ DocumentObjectExecReturn *Sheet::execute() } // Signal update of column widths - const std::set & dirtyColumns = columnWidths.getDirty(); + const std::set& dirtyColumns = columnWidths.getDirty(); for (int dirtyColumn : dirtyColumns) { columnWidthChanged(dirtyColumn, columnWidths.getValue(dirtyColumn)); } // Signal update of row heights - const std::set & dirtyRows = rowHeights.getDirty(); + const std::set& dirtyRows = rowHeights.getDirty(); - for (int dirtyRow : dirtyRows) + for (int dirtyRow : dirtyRows) { rowHeightChanged(dirtyRow, rowHeights.getValue(dirtyRow)); + } - //cells.clearDirty(); + // cells.clearDirty(); rowHeights.clearDirty(); columnWidths.clearDirty(); - if (cellErrors.empty()) + if (cellErrors.empty()) { return DocumentObject::StdReturn; - else + } + else { return new DocumentObjectExecReturn("One or more cells failed contains errors.", this); + } } /** - * Determine whether this object needs to be executed to update internal structures. - * - */ + * Determine whether this object needs to be executed to update internal structures. + * + */ short Sheet::mustExecute() const { - if (!cellErrors.empty() || cells.isDirty()) + if (!cellErrors.empty() || cells.isDirty()) { return 1; + } return DocumentObject::mustExecute(); } - /** - * Clear the cell at \a address. If \a all is false, only the text or expression - * contents are cleared. If \a all is true everything in the cell - * is cleared, including color, style, etc. - * - * @param address Address of cell to clear - * @param all Whether we should clear all or not. - * - */ + * Clear the cell at \a address. If \a all is false, only the text or expression + * contents are cleared. If \a all is true everything in the cell + * is cleared, including color, style, etc. + * + * @param address Address of cell to clear + * @param all Whether we should clear all or not. + * + */ void Sheet::clear(CellAddress address, bool /*all*/) { if (auto cell = getCell(address)) { // Remove alias, if defined std::string aliasStr; - if (cell->getAlias(aliasStr)) + if (cell->getAlias(aliasStr)) { this->removeDynamicProperty(aliasStr.c_str()); + } cells.clear(address); } @@ -1096,27 +1217,27 @@ void Sheet::clear(CellAddress address, bool /*all*/) } /** - * Get row an column span for the cell at (row, col). - * - * @param address Address of cell - * @param rows The number of unit cells this cell spans - * @param cols The number of unit rows this cell spans - * - */ + * Get row an column span for the cell at (row, col). + * + * @param address Address of cell + * @param rows The number of unit cells this cell spans + * @param cols The number of unit rows this cell spans + * + */ -void Sheet::getSpans(CellAddress address, int &rows, int &cols) const +void Sheet::getSpans(CellAddress address, int& rows, int& cols) const { return cells.getSpans(address, rows, cols); } /** - * Determine whether this cell is merged with another or not. - * - * @param address - * - * @returns True if cell is merged, false if not. - * - */ + * Determine whether this cell is merged with another or not. + * + * @param address + * + * @returns True if cell is merged, false if not. + * + */ bool Sheet::isMergedCell(CellAddress address) const { @@ -1173,115 +1294,122 @@ int Sheet::getRowHeight(int row) const } /** - * Get a vector of strings with addresses of all used cells. - * - * @returns vector of strings. - * - */ + * Get a vector of strings with addresses of all used cells. + * + * @returns vector of strings. + * + */ std::vector Sheet::getUsedCells() const { std::vector usedCells; - for (const auto &addr : cells.getUsedCells()) + for (const auto& addr : cells.getUsedCells()) { usedCells.push_back(addr.toString()); + } return usedCells; } -void Sheet::updateColumnsOrRows(bool horizontal, int section, int count) +void Sheet::updateColumnsOrRows(bool horizontal, int section, int count) { - const auto &sizes = horizontal?columnWidths.getValues():rowHeights.getValues(); + const auto& sizes = horizontal ? columnWidths.getValues() : rowHeights.getValues(); auto iter = sizes.lower_bound(section); - if(iter!=sizes.end()) { - std::map newsizes(sizes.begin(),iter); - if(count>0) { - for(;iter!=sizes.end();++iter) + if (iter != sizes.end()) { + std::map newsizes(sizes.begin(), iter); + if (count > 0) { + for (; iter != sizes.end(); ++iter) { newsizes.emplace(iter->first + count, iter->second); - } else { - iter = sizes.lower_bound(section-count); - if(iter!=sizes.end()) { - for(;iter!=sizes.end();++iter) - newsizes.emplace(iter->first+count, iter->second); } } - if(horizontal) { + else { + iter = sizes.lower_bound(section - count); + if (iter != sizes.end()) { + for (; iter != sizes.end(); ++iter) { + newsizes.emplace(iter->first + count, iter->second); + } + } + } + if (horizontal) { columnWidths.setValues(newsizes); - } else { + } + else { rowHeights.setValues(newsizes); } } } /** - * Insert \a count columns at before column \a col in the spreadsheet. - * - * @param col Address of column where the columns are inserted. - * @param count Number of columns to insert - * - */ + * Insert \a count columns at before column \a col in the spreadsheet. + * + * @param col Address of column where the columns are inserted. + * @param count Number of columns to insert + * + */ void Sheet::insertColumns(int col, int count) { cells.insertColumns(col, count); - updateColumnsOrRows(true,col,count); + updateColumnsOrRows(true, col, count); } /** - * Remove \a count columns at column \a col. - * - * @param col Address of first column to remove. - * @param count Number of columns to remove. - * - */ + * Remove \a count columns at column \a col. + * + * @param col Address of first column to remove. + * @param count Number of columns to remove. + * + */ void Sheet::removeColumns(int col, int count) { // Remove aliases, if defined - for (const auto &address : cells.getColumns(col, count)) { + for (const auto& address : cells.getColumns(col, count)) { auto cell = getCell(address); std::string aliasStr; - if (cell && cell->getAlias(aliasStr)) + if (cell && cell->getAlias(aliasStr)) { removeDynamicProperty(aliasStr.c_str()); + } } cells.removeColumns(col, count); - updateColumnsOrRows(true,col,-count); + updateColumnsOrRows(true, col, -count); } /** - * Insert \a count rows at row \a row. - * - * @param row Address of row where the rows are inserted. - * @param count Number of rows to insert. - * - */ + * Insert \a count rows at row \a row. + * + * @param row Address of row where the rows are inserted. + * @param count Number of rows to insert. + * + */ void Sheet::insertRows(int row, int count) { cells.insertRows(row, count); - updateColumnsOrRows(false,row,count); + updateColumnsOrRows(false, row, count); } /** - * Remove \a count rows starting at \a row from the spreadsheet. - * - * @param row Address of first row to remove. - * @param count Number of rows to remove. - * - */ + * Remove \a count rows starting at \a row from the spreadsheet. + * + * @param row Address of first row to remove. + * @param count Number of rows to remove. + * + */ void Sheet::removeRows(int row, int count) { // Remove aliases, if defined - for (const auto &address : cells.getRows(row, count)) { + for (const auto& address : cells.getRows(row, count)) { auto cell = getCell(address); std::string aliasStr; - if (cell && cell->getAlias(aliasStr)) + if (cell && cell->getAlias(aliasStr)) { removeDynamicProperty(aliasStr.c_str()); + } } cells.removeRows(row, count); - updateColumnsOrRows(false,row,-count); + updateColumnsOrRows(false, row, -count); } /** @@ -1290,7 +1418,7 @@ void Sheet::removeRows(int row, int count) * @param value New value */ -void Sheet::setContent(CellAddress address, const char *value) +void Sheet::setContent(CellAddress address, const char* value) { cells.setContent(address, value); } @@ -1312,7 +1440,7 @@ void Sheet::setAlignment(CellAddress address, int alignment) * @param style New style */ -void Sheet::setStyle(CellAddress address, const std::set &style) +void Sheet::setStyle(CellAddress address, const std::set& style) { cells.setStyle(address, style); } @@ -1323,7 +1451,7 @@ void Sheet::setStyle(CellAddress address, const std::set &style) * @param color New color */ -void Sheet::setForeground(CellAddress address, const Color &color) +void Sheet::setForeground(CellAddress address, const Color& color) { cells.setForeground(address, color); } @@ -1334,7 +1462,7 @@ void Sheet::setForeground(CellAddress address, const Color &color) * @param color New color */ -void Sheet::setBackground(CellAddress address, const Color &color) +void Sheet::setBackground(CellAddress address, const Color& color) { cells.setBackground(address, color); } @@ -1345,7 +1473,7 @@ void Sheet::setBackground(CellAddress address, const Color &color) * @param unit New unit */ -void Sheet::setDisplayUnit(CellAddress address, const std::string &unit) +void Sheet::setDisplayUnit(CellAddress address, const std::string& unit) { cells.setDisplayUnit(address, unit); } @@ -1356,7 +1484,7 @@ void Sheet::setDisplayUnit(CellAddress address, const std::string &unit) * @param unit New unit. */ -void Sheet::setComputedUnit(CellAddress address, const Base::Unit &unit) +void Sheet::setComputedUnit(CellAddress address, const Base::Unit& unit) { cells.setComputedUnit(address, unit); } @@ -1368,22 +1496,27 @@ void Sheet::setComputedUnit(CellAddress address, const Base::Unit &unit) * @param alias New alias. */ -void Sheet::setAlias(CellAddress address, const std::string &alias) +void Sheet::setAlias(CellAddress address, const std::string& alias) { std::string existingAlias = getAddressFromAlias(alias); if (!existingAlias.empty()) { - if (existingAlias == address.toString()) // Same as old? + if (existingAlias == address.toString()) {// Same as old? return; - else + } + else { throw Base::ValueError("Alias already defined"); + } } - else if (alias.empty()) // Empty? + else if (alias.empty()) {// Empty? cells.setAlias(address, ""); - else if (isValidAlias(alias)) // Valid? + } + else if (isValidAlias(alias)) {// Valid? cells.setAlias(address, alias); - else + } + else { throw Base::ValueError("Invalid alias"); + } } /** @@ -1393,12 +1526,13 @@ void Sheet::setAlias(CellAddress address, const std::string &alias) * @returns Name of cell, or empty string if not defined */ -std::string Sheet::getAddressFromAlias(const std::string &alias) const +std::string Sheet::getAddressFromAlias(const std::string& alias) const { - const Cell * cell = cells.getValueFromAlias(alias); + const Cell* cell = cells.getValueFromAlias(alias); - if (cell) + if (cell) { return cell->getAddress().toString(); + } return {}; } @@ -1410,21 +1544,25 @@ std::string Sheet::getAddressFromAlias(const std::string &alias) const * */ -bool Sheet::isValidAlias(const std::string & candidate) +bool Sheet::isValidAlias(const std::string& candidate) { // Valid syntactically? - if (!cells.isValidAlias(candidate)) + if (!cells.isValidAlias(candidate)) { return false; + } // Existing alias? Then it's ok - if (!getAddressFromAlias(candidate).empty() ) + if (!getAddressFromAlias(candidate).empty()) { return true; + } // Check to see that is does not crash with any other property in the Sheet object. - if (getPropertyByName(candidate.c_str())) + if (getPropertyByName(candidate.c_str())) { return false; - else + } + else { return true; + } } /** @@ -1456,7 +1594,7 @@ std::set Sheet::dependsOn(CellAddress address) const * @param result Set of links. */ -void Sheet::providesTo(CellAddress address, std::set & result) const +void Sheet::providesTo(CellAddress address, std::set& result) const { std::string fullName = getFullName() + "."; std::set tmpResult = cells.getDeps(fullName + address.toString()); @@ -1472,15 +1610,15 @@ void Sheet::providesTo(CellAddress address, std::set & result) cons * @param result Set of links. */ -std::set Sheet::providesTo(CellAddress address) const +std::set Sheet::providesTo(CellAddress address) const { - return cells.getDeps(getFullName()+"."+address.toString()); + return cells.getDeps(getFullName() + "." + address.toString()); } void Sheet::onDocumentRestored() { auto ret = execute(); - if(ret!=DocumentObject::StdReturn) { + if (ret != DocumentObject::StdReturn) { FC_ERR("Failed to restore " << getFullName() << ": " << ret->Why); delete ret; } @@ -1491,7 +1629,7 @@ void Sheet::onDocumentRestored() * @param document document to observer. */ -void Sheet::observeDocument(Document * document) +void Sheet::observeDocument(Document* document) { // observer is no longer required as PropertySheet is now derived from // PropertyLinkBase and will handle all the link related behavior @@ -1506,44 +1644,52 @@ void Sheet::observeDocument(Document * document) } else { // Create a new observer - SheetObserver * observer = new SheetObserver(document, &cells); + SheetObserver* observer = new SheetObserver(document, &cells); observers[document->getName()] = observer; } #endif } -void Sheet::renameObjectIdentifiers(const std::map &paths) +void Sheet::renameObjectIdentifiers(const std::map& paths) { DocumentObject::renameObjectIdentifiers(paths); cells.renameObjectIdentifiers(paths); } -bool Sheet::hasCell(const std::vector &ranges) const { - for(auto range : ranges) { +bool Sheet::hasCell(const std::vector& ranges) const +{ + for (auto range : ranges) { do { - if(cells.getValue(*range)) + if (cells.getValue(*range)) { return true; - }while(range.next()); + } + } while (range.next()); } return false; } -std::string Sheet::getRow(int offset) const { - if(currentRow < 0) +std::string Sheet::getRow(int offset) const +{ + if (currentRow < 0) { throw Base::RuntimeError("No current row"); + } int row = currentRow + offset; - if(row<0 || row>CellAddress::MAX_ROWS) + if (row < 0 || row > CellAddress::MAX_ROWS) { throw Base::ValueError("Out of range"); - return std::to_string(row+1); + } + return std::to_string(row + 1); } -std::string Sheet::getColumn(int offset) const { - if(currentCol < 0) +std::string Sheet::getColumn(int offset) const +{ + if (currentCol < 0) { throw Base::RuntimeError("No current column"); + } int col = currentCol + offset; - if(col<0 || col>CellAddress::MAX_COLUMNS) + if (col < 0 || col > CellAddress::MAX_COLUMNS) { throw Base::ValueError("Out of range"); + } if (col < 26) { char txt[2]; txt[0] = (char)('A' + col); @@ -1559,40 +1705,46 @@ std::string Sheet::getColumn(int offset) const { return txt; } -void Sheet::onChanged(const App::Property *prop) { - if(prop == &cells) { +void Sheet::onChanged(const App::Property* prop) +{ + if (prop == &cells) { decltype(copyCutRanges) tmp; tmp.swap(copyCutRanges); - for(auto &range : tmp) + for (auto& range : tmp) { rangeUpdated(range); + } } - else + else { cells.slotChangedObject(*this, *prop); + } App::DocumentObject::onChanged(prop); } -void Sheet::setCopyOrCutRanges(const std::vector &ranges, bool copy) +void Sheet::setCopyOrCutRanges(const std::vector& ranges, bool copy) { std::set rangeSet(copyCutRanges.begin(), copyCutRanges.end()); copyCutRanges = ranges; rangeSet.insert(copyCutRanges.begin(), copyCutRanges.end()); - for(const auto &range : rangeSet) + for (const auto& range : rangeSet) { rangeUpdated(range); + } hasCopyRange = copy; } -const std::vector &Sheet::getCopyOrCutRange(bool copy) const +const std::vector& Sheet::getCopyOrCutRange(bool copy) const { static const std::vector nullRange; - if(hasCopyRange != copy) + if (hasCopyRange != copy) { return nullRange; + } return copyCutRanges; } unsigned Sheet::getCopyOrCutBorder(CellAddress address, bool copy) const { - if(hasCopyRange != copy) + if (hasCopyRange != copy) { return 0; + } return _getBorder(this, copyCutRanges, address); } @@ -1600,9 +1752,9 @@ unsigned Sheet::getCopyOrCutBorder(CellAddress address, bool copy) const TYPESYSTEM_SOURCE(Spreadsheet::PropertySpreadsheetQuantity, App::PropertyQuantity) -Property *PropertySpreadsheetQuantity::Copy() const +Property* PropertySpreadsheetQuantity::Copy() const { - PropertySpreadsheetQuantity * obj = new PropertySpreadsheetQuantity(); + PropertySpreadsheetQuantity* obj = new PropertySpreadsheetQuantity(); obj->_dValue = _dValue; obj->_Unit = _Unit; @@ -1610,9 +1762,9 @@ Property *PropertySpreadsheetQuantity::Copy() const return obj; } -void PropertySpreadsheetQuantity::Paste(const Property &from) +void PropertySpreadsheetQuantity::Paste(const Property& from) { - const auto &src = dynamic_cast(from); + const auto& src = dynamic_cast(from); aboutToSetValue(); _dValue = src._dValue; _Unit = src._Unit; @@ -1621,16 +1773,21 @@ void PropertySpreadsheetQuantity::Paste(const Property &from) // Python sheet feature --------------------------------------------------------- -namespace App { +namespace App +{ /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Spreadsheet::SheetPython, Spreadsheet::Sheet) -template<> const char* Spreadsheet::SheetPython::getViewProviderName() const { +template<> +const char* Spreadsheet::SheetPython::getViewProviderName() const +{ return "SpreadsheetGui::ViewProviderSheet"; } -template<> PyObject* Spreadsheet::SheetPython::getPyObject() { +template<> +PyObject* Spreadsheet::SheetPython::getPyObject() +{ if (PythonObject.is(Py::_None())) { // ref counter is set to 1 - PythonObject = Py::Object(new FeaturePythonPyT(this),true); + PythonObject = Py::Object(new FeaturePythonPyT(this), true); } return Py::new_reference_to(PythonObject); } @@ -1638,4 +1795,4 @@ template<> PyObject* Spreadsheet::SheetPython::getPyObject() { // explicit template instantiation template class SpreadsheetExport FeaturePythonT; -} +}// namespace App diff --git a/src/Mod/Spreadsheet/App/Sheet.h b/src/Mod/Spreadsheet/App/Sheet.h index 8c7388d169..d49016575d 100644 --- a/src/Mod/Spreadsheet/App/Sheet.h +++ b/src/Mod/Spreadsheet/App/Sheet.h @@ -24,8 +24,8 @@ #define Spreadsheet_Spreadsheet_H #ifdef signals -# undef signals -# define signals signals +#undef signals +#define signals signals #endif #include @@ -54,47 +54,55 @@ class SheetObserver; * Copy() and Paste() methods. It is used by the spreadsheet to * create aliases in a generic way. */ -class SpreadsheetExport PropertySpreadsheetQuantity : public App::PropertyQuantity +class SpreadsheetExport PropertySpreadsheetQuantity: public App::PropertyQuantity { TYPESYSTEM_HEADER_WITH_OVERRIDE(); + public: PropertySpreadsheetQuantity() = default; ~PropertySpreadsheetQuantity() override = default; - Property *Copy() const override; - void Paste(const Property &from) override; + Property* Copy() const override; + void Paste(const Property& from) override; }; -class SpreadsheetExport Sheet : public App::DocumentObject +class SpreadsheetExport Sheet: public App::DocumentObject { PROPERTY_HEADER_WITH_OVERRIDE(Spreadsheet::Sheet); public: - /// Constructor Sheet(); ~Sheet() override; /// returns the type name of the ViewProvider - const char* getViewProviderName() const override { + const char* getViewProviderName() const override + { return "SpreadsheetGui::ViewProviderSheet"; } - bool importFromFile(const std::string & filename, char delimiter = '\t', char quoteChar = '\0', char escapeChar = '\\'); + bool importFromFile(const std::string& filename, + char delimiter = '\t', + char quoteChar = '\0', + char escapeChar = '\\'); - bool getCharsFromPrefs(char &delimiter, char "e, char &escape, std::string &errMsg); + bool getCharsFromPrefs(char& delimiter, char& quote, char& escape, std::string& errMsg); - bool exportToFile(const std::string & filename, char delimiter = '\t', char quoteChar = '\0', char escapeChar = '\\') const; + bool exportToFile(const std::string& filename, + char delimiter = '\t', + char quoteChar = '\0', + char escapeChar = '\\') const; - bool mergeCells(const App::Range &range); + bool mergeCells(const App::Range& range); void splitCell(App::CellAddress address); - Cell * getCell(App::CellAddress address); + Cell* getCell(App::CellAddress address); - Cell *getNewCell(App::CellAddress address); + Cell* getNewCell(App::CellAddress address); - enum Border { + enum Border + { BorderTop = 1, BorderLeft = 2, BorderBottom = 4, @@ -103,20 +111,20 @@ public: }; unsigned getCellBindingBorder(App::CellAddress address) const; - PropertySheet::BindingType getCellBinding(App::Range &range, - App::ExpressionPtr *pStart=nullptr, - App::ExpressionPtr *pEnd=nullptr, - App::ObjectIdentifier *pTarget=nullptr) const; + PropertySheet::BindingType getCellBinding(App::Range& range, + App::ExpressionPtr* pStart = nullptr, + App::ExpressionPtr* pEnd = nullptr, + App::ObjectIdentifier* pTarget = nullptr) const; - void setCell(const char *address, const char *value); + void setCell(const char* address, const char* value); - void setCell(App::CellAddress address, const char *value); + void setCell(App::CellAddress address, const char* value); void clearAll(); void clear(App::CellAddress address, bool all = true); - void getSpans(App::CellAddress address, int & rows, int & cols) const; + void getSpans(App::CellAddress address, int& rows, int& cols) const; bool isMergedCell(App::CellAddress address) const; @@ -140,60 +148,64 @@ public: void removeRows(int row, int count); - void setContent(App::CellAddress address, const char * value); + void setContent(App::CellAddress address, const char* value); void setAlignment(App::CellAddress address, int alignment); - void setStyle(App::CellAddress address, const std::set & style); + void setStyle(App::CellAddress address, const std::set& style); - void setForeground(App::CellAddress address, const App::Color &color); + void setForeground(App::CellAddress address, const App::Color& color); - void setBackground(App::CellAddress address, const App::Color &color); + void setBackground(App::CellAddress address, const App::Color& color); - void setDisplayUnit(App::CellAddress address, const std::string & unit); + void setDisplayUnit(App::CellAddress address, const std::string& unit); - void setComputedUnit(App::CellAddress address, const Base::Unit & unit); + void setComputedUnit(App::CellAddress address, const Base::Unit& unit); - void setAlias(App::CellAddress address, const std::string & alias); + void setAlias(App::CellAddress address, const std::string& alias); - std::string getAddressFromAlias(const std::string & alias) const; + std::string getAddressFromAlias(const std::string& alias) const; - bool isValidAlias(const std::string &candidate); + bool isValidAlias(const std::string& candidate); void setSpans(App::CellAddress address, int rows, int columns); std::set dependsOn(App::CellAddress address) const; - void providesTo(App::CellAddress address, std::set & result) const; + void providesTo(App::CellAddress address, std::set& result) const; - bool hasCell(const std::vector &ranges) const; - PyObject *getPyObject() override; + bool hasCell(const std::vector& ranges) const; + PyObject* getPyObject() override; - PropertySheet *getCells() { return &cells; } + PropertySheet* getCells() + { + return &cells; + } - App::Property *getPropertyByName(const char *name) const override; + App::Property* getPropertyByName(const char* name) const override; - App::Property *getDynamicPropertyByName(const char* name) const override; + App::Property* getDynamicPropertyByName(const char* name) const override; - void getPropertyNamedList(std::vector > &List) const override; + void + getPropertyNamedList(std::vector>& List) const override; short mustExecute() const override; - App::DocumentObjectExecReturn *execute() override; + App::DocumentObjectExecReturn* execute() override; - bool getCellAddress(const App::Property *prop, App::CellAddress &address); + bool getCellAddress(const App::Property* prop, App::CellAddress& address); - App::CellAddress getCellAddress(const char *name, bool silent=false) const; + App::CellAddress getCellAddress(const char* name, bool silent = false) const; - App::Range getRange(const char *name, bool silent=false) const; + App::Range getRange(const char* name, bool silent = false) const; std::map getColumnWidths() const; std::map getRowHeights() const; - std::string getRow(int offset=0) const; + std::string getRow(int offset = 0) const; - std::string getColumn(int offset=0) const; + std::string getColumn(int offset = 0) const; void touchCells(App::Range range); @@ -201,29 +213,29 @@ public: // Signals - boost::signals2::signal cellUpdated; + boost::signals2::signal cellUpdated; - boost::signals2::signal rangeUpdated; + boost::signals2::signal rangeUpdated; - boost::signals2::signal cellSpanChanged; + boost::signals2::signal cellSpanChanged; - boost::signals2::signal columnWidthChanged; + boost::signals2::signal columnWidthChanged; - boost::signals2::signal rowHeightChanged; + boost::signals2::signal rowHeightChanged; - void observeDocument(App::Document *document); + void observeDocument(App::Document* document); - void renameObjectIdentifiers(const std::map & paths) override; + void renameObjectIdentifiers( + const std::map& paths) override; - void setCopyOrCutRanges(const std::vector &ranges, bool copy=true); - const std::vector &getCopyOrCutRange(bool copy=true) const; - unsigned getCopyOrCutBorder(App::CellAddress address, bool copy=true) const; + void setCopyOrCutRanges(const std::vector& ranges, bool copy = true); + const std::vector& getCopyOrCutRange(bool copy = true) const; + unsigned getCopyOrCutBorder(App::CellAddress address, bool copy = true) const; protected: + void onChanged(const App::Property* prop) override; - void onChanged(const App::Property *prop) override; - - void updateColumnsOrRows(bool horizontal, int section, int count) ; + void updateColumnsOrRows(bool horizontal, int section, int count); std::set providesTo(App::CellAddress address) const; @@ -231,31 +243,31 @@ protected: void recomputeCell(App::CellAddress p); - App::Property *getProperty(App::CellAddress key) const; + App::Property* getProperty(App::CellAddress key) const; - App::Property *getProperty(const char * addr) const; + App::Property* getProperty(const char* addr) const; void updateProperty(App::CellAddress key); - App::Property *setStringProperty(App::CellAddress key, const std::string & value) ; + App::Property* setStringProperty(App::CellAddress key, const std::string& value); - App::Property *setObjectProperty(App::CellAddress key, Py::Object obj) ; + App::Property* setObjectProperty(App::CellAddress key, Py::Object obj); - App::Property *setFloatProperty(App::CellAddress key, double value); + App::Property* setFloatProperty(App::CellAddress key, double value); - App::Property *setIntegerProperty(App::CellAddress key, long value); + App::Property* setIntegerProperty(App::CellAddress key, long value); - App::Property *setQuantityProperty(App::CellAddress key, double value, const Base::Unit &unit); + App::Property* setQuantityProperty(App::CellAddress key, double value, const Base::Unit& unit); void onSettingDocument() override; void updateBindings(); /* Properties for used cells */ - App::DynamicProperty &props; + App::DynamicProperty& props; /* Mapping of properties to cell position */ - std::map propAddress; + std::map propAddress; /* Set of cells with errors */ std::set cellErrors; @@ -272,7 +284,7 @@ protected: PropertyRowHeights rowHeights; /* Document observers to track changes to external properties */ - using ObserverMap = std::map; + using ObserverMap = std::map; ObserverMap observers; int currentRow = -1; @@ -290,7 +302,7 @@ protected: using SheetPython = App::FeaturePythonT; -} //namespace Spreadsheet +}// namespace Spreadsheet -#endif // Spreadsheet_Spreadsheet_H +#endif// Spreadsheet_Spreadsheet_H diff --git a/src/Mod/Spreadsheet/App/SheetObserver.cpp b/src/Mod/Spreadsheet/App/SheetObserver.cpp index 169481a8bd..a3e84b7fb9 100644 --- a/src/Mod/Spreadsheet/App/SheetObserver.cpp +++ b/src/Mod/Spreadsheet/App/SheetObserver.cpp @@ -22,76 +22,78 @@ #include "PreCompiled.h" -#include "SheetObserver.h" #include "PropertySheet.h" +#include "SheetObserver.h" using namespace Spreadsheet; using namespace App; /** - * The SheetObserver constructor. - * - * @param document The Document we are observing - * @param _sheet The sheet owning this observer. - * - */ + * The SheetObserver constructor. + * + * @param document The Document we are observing + * @param _sheet The sheet owning this observer. + * + */ -SheetObserver::SheetObserver(App::Document * document, PropertySheet *_sheet) +SheetObserver::SheetObserver(App::Document* document, PropertySheet* _sheet) : DocumentObserver(document) , sheet(_sheet) -{ -} +{} /** - * Invalidate cells that depend on this document object. - * - */ + * Invalidate cells that depend on this document object. + * + */ -void SheetObserver::slotCreatedObject(const DocumentObject &Obj) +void SheetObserver::slotCreatedObject(const DocumentObject& Obj) { sheet->invalidateDependants(&Obj); } /** - * Invalidate cells that depend on this document object. - * - */ + * Invalidate cells that depend on this document object. + * + */ -void SheetObserver::slotDeletedObject(const DocumentObject &Obj) +void SheetObserver::slotDeletedObject(const DocumentObject& Obj) { sheet->invalidateDependants(&Obj); sheet->deletedDocumentObject(&Obj); } /** - * Invoke the sheets recomputeDependants when a change to a Property occurs. - * - */ + * Invoke the sheets recomputeDependants when a change to a Property occurs. + * + */ -void SheetObserver::slotChangedObject(const DocumentObject &Obj, const Property &Prop) +void SheetObserver::slotChangedObject(const DocumentObject& Obj, const Property& Prop) { - if (&Prop == &Obj.Label) + if (&Prop == &Obj.Label) { sheet->renamedDocumentObject(&Obj); + } else { - const char * name = Obj.getPropertyName(&Prop); + const char* name = Obj.getPropertyName(&Prop); - if (!name) + if (!name) { return; + } - if (isUpdating.find(name) != isUpdating.end()) + if (isUpdating.find(name) != isUpdating.end()) { return; + } isUpdating.insert(name); - sheet->recomputeDependants(&Obj,Prop.getName()); + sheet->recomputeDependants(&Obj, Prop.getName()); isUpdating.erase(name); } } /** - * Increase reference count. - * - */ + * Increase reference count. + * + */ void SheetObserver::ref() { @@ -99,13 +101,12 @@ void SheetObserver::ref() } /** - * Decrease reference count. - * - */ + * Decrease reference count. + * + */ bool SheetObserver::unref() { refCount--; return refCount; } - diff --git a/src/Mod/Spreadsheet/App/SheetObserver.h b/src/Mod/Spreadsheet/App/SheetObserver.h index ade38fe829..ecf6b243b4 100644 --- a/src/Mod/Spreadsheet/App/SheetObserver.h +++ b/src/Mod/Spreadsheet/App/SheetObserver.h @@ -25,27 +25,33 @@ #include -namespace Spreadsheet { +namespace Spreadsheet +{ class PropertySheet; // SheetObserver is obsolete as PropertySheet is now derived from PropertyLinkBase -class SheetObserver : public App::DocumentObserver { +class SheetObserver: public App::DocumentObserver +{ public: - SheetObserver(App::Document* document, PropertySheet *_sheet); + SheetObserver(App::Document* document, PropertySheet* _sheet); ~SheetObserver() override = default; 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(); } + App::Document* getDocument() const + { + return App::DocumentObserver::getDocument(); + } + private: std::set isUpdating; - unsigned int refCount{1}; - PropertySheet * sheet; + unsigned int refCount {1}; + PropertySheet* sheet; }; -} +}// namespace Spreadsheet -#endif // SHEETOBSERVER_H +#endif// SHEETOBSERVER_H diff --git a/src/Mod/Spreadsheet/App/SheetPy.xml b/src/Mod/Spreadsheet/App/SheetPy.xml index ede5106970..6e31e8eec4 100644 --- a/src/Mod/Spreadsheet/App/SheetPy.xml +++ b/src/Mod/Spreadsheet/App/SheetPy.xml @@ -10,7 +10,6 @@ FatherInclude="App/DocumentObjectPy.h" FatherNamespace="App" Constructor="true"> - With this object you can manipulate spreadsheets @@ -180,7 +179,7 @@ following dependency order. - + @@ -191,7 +190,7 @@ or may not have a non-empty string content. - + @@ -201,7 +200,7 @@ Get a list of the names of all cells with data in them. - + @@ -214,7 +213,7 @@ of the block are not necessarily used. - + @@ -227,6 +226,6 @@ of the block do not necessarily contain anything. - + diff --git a/src/Mod/Spreadsheet/App/SheetPyImp.cpp b/src/Mod/Spreadsheet/App/SheetPyImp.cpp index 65c22eeb2c..a275e17016 100644 --- a/src/Mod/Spreadsheet/App/SheetPyImp.cpp +++ b/src/Mod/Spreadsheet/App/SheetPyImp.cpp @@ -30,8 +30,10 @@ #include "Sheet.h" // inclusion of the generated files (generated out of SheetPy.xml) +// clang-format off #include "SheetPy.h" #include "SheetPy.cpp" +// clang-format on using namespace Spreadsheet; @@ -43,7 +45,7 @@ std::string SheetPy::representation() const return {""}; } -PyObject *SheetPy::PyMake(struct _typeobject *, PyObject *, PyObject *) // Python wrapper +PyObject* SheetPy::PyMake(struct _typeobject*, PyObject*, PyObject*)// Python wrapper { // create a new instance of SheetPy and the Twin object return new SheetPy(new Sheet()); @@ -57,22 +59,24 @@ int SheetPy::PyInit(PyObject* /*args*/, PyObject* /*kwd*/) // +++ methods implementer ++++++++++++++++++++++++++++++++++++++++++++++++ -PyObject* SheetPy::set(PyObject *args) +PyObject* SheetPy::set(PyObject* args) { - char *address; - char *contents; + char* address; + char* contents; - if (!PyArg_ParseTuple(args, "ss:set", &address, &contents)) + if (!PyArg_ParseTuple(args, "ss:set", &address, &contents)) { return nullptr; + } try { - Sheet * sheet = getSheetPtr(); + Sheet* sheet = getSheetPtr(); std::string cellAddress = sheet->getAddressFromAlias(address).c_str(); /* Check to see if address is really an alias first */ - if (!cellAddress.empty()) + if (!cellAddress.empty()) { sheet->setCell(cellAddress.c_str(), contents); + } else { Range rangeIter(address); @@ -81,7 +85,7 @@ PyObject* SheetPy::set(PyObject *args) } while (rangeIter.next()); } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } @@ -89,88 +93,102 @@ PyObject* SheetPy::set(PyObject *args) Py_Return; } -PyObject* SheetPy::get(PyObject *args) +PyObject* SheetPy::get(PyObject* args) { - const char *address; - const char *address2=nullptr; + const char* address; + const char* address2 = nullptr; - if (!PyArg_ParseTuple(args, "s|s:get", &address, &address2)) + if (!PyArg_ParseTuple(args, "s|s:get", &address, &address2)) { return nullptr; + } - PY_TRY { - if(address2) { + PY_TRY + { + if (address2) { auto a1 = getSheetPtr()->getAddressFromAlias(address); - if(a1.empty()) + if (a1.empty()) { a1 = address; + } auto a2 = getSheetPtr()->getAddressFromAlias(address2); - if(a2.empty()) + if (a2.empty()) { a2 = address2; - Range range(a1.c_str(),a2.c_str()); + } + Range range(a1.c_str(), a2.c_str()); Py::Tuple tuple(range.size()); - int i=0; + int i = 0; do { - App::Property *prop = getSheetPtr()->getPropertyByName(range.address().c_str()); - if(!prop) { - PyErr_Format(PyExc_ValueError, "Invalid address '%s' in range %s:%s", - range.address().c_str(), address, address2); + App::Property* prop = getSheetPtr()->getPropertyByName(range.address().c_str()); + if (!prop) { + PyErr_Format(PyExc_ValueError, + "Invalid address '%s' in range %s:%s", + range.address().c_str(), + address, + address2); return nullptr; } - tuple.setItem(i++,Py::Object(prop->getPyObject(),true)); - }while(range.next()); + tuple.setItem(i++, Py::Object(prop->getPyObject(), true)); + } while (range.next()); return Py::new_reference_to(tuple); } - }PY_CATCH; + } + PY_CATCH; - App::Property * prop = this->getSheetPtr()->getPropertyByName(address); + App::Property* prop = this->getSheetPtr()->getPropertyByName(address); if (!prop) { - PyErr_Format(PyExc_ValueError, - "Invalid cell address or property: %s",address); + PyErr_Format(PyExc_ValueError, "Invalid cell address or property: %s", address); return nullptr; } return prop->getPyObject(); } -PyObject* SheetPy::getContents(PyObject *args) +PyObject* SheetPy::getContents(PyObject* args) { - char *strAddress; + char* strAddress; CellAddress address; - if (!PyArg_ParseTuple(args, "s:getContents", &strAddress)) + if (!PyArg_ParseTuple(args, "s:getContents", &strAddress)) { return nullptr; + } - PY_TRY { - try { - Sheet * sheet = getSheetPtr(); + PY_TRY + { + try { + Sheet* sheet = getSheetPtr(); std::string addr = sheet->getAddressFromAlias(strAddress); - if (addr.empty()) + if (addr.empty()) { address = stringToAddress(strAddress); - else + } + else { address = stringToAddress(addr.c_str()); + } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } std::string contents; - const Cell * cell = this->getSheetPtr()->getCell(address); + const Cell* cell = this->getSheetPtr()->getCell(address); - if (cell) - cell->getStringContent( contents ); + if (cell) { + cell->getStringContent(contents); + } - return Py::new_reference_to( Py::String( contents ) ); - } PY_CATCH + return Py::new_reference_to(Py::String(contents)); + } + PY_CATCH } -PyObject* SheetPy::clear(PyObject *args) +PyObject* SheetPy::clear(PyObject* args) { - const char * strAddress; + const char* strAddress; int all = 1; - if (!PyArg_ParseTuple(args, "s|p:clear", &strAddress, &all)) + if (!PyArg_ParseTuple(args, "s|p:clear", &strAddress, &all)) { return nullptr; + } try { Range rangeIter(strAddress); @@ -178,7 +196,7 @@ PyObject* SheetPy::clear(PyObject *args) this->getSheetPtr()->clear(*rangeIter, all); } while (rangeIter.next()); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } @@ -186,70 +204,89 @@ PyObject* SheetPy::clear(PyObject *args) Py_Return; } -PyObject* SheetPy::clearAll(PyObject *args) +PyObject* SheetPy::clearAll(PyObject* args) { - if (!PyArg_ParseTuple(args, "")) + if (!PyArg_ParseTuple(args, "")) { return nullptr; + } this->getSheetPtr()->clearAll(); Py_Return; } -PyObject* SheetPy::importFile(PyObject *args) +PyObject* SheetPy::importFile(PyObject* args) { - const char * filename; - const char * delimiter = "\t"; - const char * quoteChar = "\""; - const char * escapeChar = "\\"; + const char* filename; + const char* delimiter = "\t"; + const char* quoteChar = "\""; + const char* escapeChar = "\\"; - if (!PyArg_ParseTuple(args, "s|sss:importFile", &filename, &delimiter, "eChar, &escapeChar)) + if (!PyArg_ParseTuple(args, + "s|sss:importFile", + &filename, + &delimiter, + "eChar, + &escapeChar)) { return nullptr; + } - if (getSheetPtr()->importFromFile(filename, delimiter[0], quoteChar[0], escapeChar[0])) - return Py::new_reference_to( Py::Boolean(true) ); - else - return Py::new_reference_to( Py::Boolean(false) ); + if (getSheetPtr()->importFromFile(filename, delimiter[0], quoteChar[0], escapeChar[0])) { + return Py::new_reference_to(Py::Boolean(true)); + } + else { + return Py::new_reference_to(Py::Boolean(false)); + } } -PyObject* SheetPy::exportFile(PyObject *args) +PyObject* SheetPy::exportFile(PyObject* args) { - const char * filename; - const char * delimiter = "\t"; - const char * quoteChar = "\""; - const char * escapeChar = "\\"; + const char* filename; + const char* delimiter = "\t"; + const char* quoteChar = "\""; + const char* escapeChar = "\\"; - if (!PyArg_ParseTuple(args, "s|sss:exportFile", &filename, &delimiter, "eChar, &escapeChar)) + if (!PyArg_ParseTuple(args, + "s|sss:exportFile", + &filename, + &delimiter, + "eChar, + &escapeChar)) { return nullptr; + } - if (getSheetPtr()->exportToFile(filename, delimiter[0], quoteChar[0], escapeChar[0])) - return Py::new_reference_to( Py::Boolean(true) ); - else - return Py::new_reference_to( Py::Boolean(false) ); + if (getSheetPtr()->exportToFile(filename, delimiter[0], quoteChar[0], escapeChar[0])) { + return Py::new_reference_to(Py::Boolean(true)); + } + else { + return Py::new_reference_to(Py::Boolean(false)); + } } -PyObject* SheetPy::mergeCells(PyObject *args) +PyObject* SheetPy::mergeCells(PyObject* args) { - const char * range; + const char* range; - if (!PyArg_ParseTuple(args, "s:mergeCells", &range)) + if (!PyArg_ParseTuple(args, "s:mergeCells", &range)) { return nullptr; + } getSheetPtr()->mergeCells(Range(range)); Py_Return; } -PyObject* SheetPy::splitCell(PyObject *args) +PyObject* SheetPy::splitCell(PyObject* args) { - const char * strAddress; + const char* strAddress; - if (!PyArg_ParseTuple(args, "s:splitCell", &strAddress)) + if (!PyArg_ParseTuple(args, "s:splitCell", &strAddress)) { return nullptr; + } CellAddress address; try { address = stringToAddress(strAddress); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } @@ -258,75 +295,82 @@ PyObject* SheetPy::splitCell(PyObject *args) Py_Return; } -PyObject* SheetPy::insertColumns(PyObject *args) +PyObject* SheetPy::insertColumns(PyObject* args) { - const char * column; + const char* column; int count; - if (!PyArg_ParseTuple(args, "si:insertColumns", &column, &count)) + if (!PyArg_ParseTuple(args, "si:insertColumns", &column, &count)) { return nullptr; + } getSheetPtr()->insertColumns(decodeColumn(column), count); Py_Return; } -PyObject* SheetPy::removeColumns(PyObject *args) +PyObject* SheetPy::removeColumns(PyObject* args) { - const char * column; + const char* column; int count; - if (!PyArg_ParseTuple(args, "si:removeColumns", &column, &count)) + if (!PyArg_ParseTuple(args, "si:removeColumns", &column, &count)) { return nullptr; + } getSheetPtr()->removeColumns(decodeColumn(column), count); Py_Return; } -PyObject* SheetPy::insertRows(PyObject *args) +PyObject* SheetPy::insertRows(PyObject* args) { - const char * row; + const char* row; int count; - if (!PyArg_ParseTuple(args, "si:insertRows", &row, &count)) + if (!PyArg_ParseTuple(args, "si:insertRows", &row, &count)) { return nullptr; + } getSheetPtr()->insertRows(decodeRow(std::string(row)), count); Py_Return; } -PyObject* SheetPy::removeRows(PyObject *args) +PyObject* SheetPy::removeRows(PyObject* args) { - const char * row; + const char* row; int count; - if (!PyArg_ParseTuple(args, "si:removeRows", &row, &count)) + if (!PyArg_ParseTuple(args, "si:removeRows", &row, &count)) { return nullptr; + } getSheetPtr()->removeRows(decodeRow(std::string(row)), count); Py_Return; } -PyObject* SheetPy::setStyle(PyObject *args) +PyObject* SheetPy::setStyle(PyObject* args) { - const char * cell; - PyObject * value; + const char* cell; + PyObject* value; std::set style; - const char * options = "replace"; + const char* options = "replace"; - if (!PyArg_ParseTuple(args, "sO|s:setStyle", &cell, &value, &options)) + if (!PyArg_ParseTuple(args, "sO|s:setStyle", &cell, &value, &options)) { return nullptr; + } if (PySet_Check(value)) { - PyObject * copy = PySet_New(value); + PyObject* copy = PySet_New(value); while (PySet_Size(copy) > 0) { - PyObject * item = PySet_Pop(copy); + PyObject* item = PySet_Pop(copy); // check on the key: - if (PyUnicode_Check(item)) + if (PyUnicode_Check(item)) { style.insert(PyUnicode_AsUTF8(item)); + } else { - std::string error = std::string("type of the set need to be a string, not ") + item->ob_type->tp_name; + std::string error = std::string("type of the set need to be a string, not ") + + item->ob_type->tp_name; PyErr_SetString(PyExc_TypeError, error.c_str()); Py_DECREF(copy); return nullptr; @@ -339,13 +383,16 @@ PyObject* SheetPy::setStyle(PyObject *args) escaped_list_separator e('\0', '|', '\0'); std::string line = PyUnicode_AsUTF8(value); - tokenizer > tok(line, e); + tokenizer> tok(line, e); - for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); + ++i) { style.insert(*i); + } } else { - std::string error = std::string("style must be either set or string, not ") + value->ob_type->tp_name; + std::string error = + std::string("style must be either set or string, not ") + value->ob_type->tp_name; PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } @@ -361,13 +408,14 @@ PyObject* SheetPy::setStyle(PyObject *args) do { std::set oldStyle; - const Cell * cell = getSheetPtr()->getCell(*rangeIter); + const Cell* cell = getSheetPtr()->getCell(*rangeIter); // Get old styles first - if (cell) + if (cell) { cell->getStyle(oldStyle); + } - for (const auto & it : oldStyle) { + for (const auto& it : oldStyle) { style.insert(it); } @@ -380,13 +428,14 @@ PyObject* SheetPy::setStyle(PyObject *args) do { std::set oldStyle; - const Cell * cell = getSheetPtr()->getCell(*rangeIter); + const Cell* cell = getSheetPtr()->getCell(*rangeIter); // Get old styles first - if (cell) + if (cell) { cell->getStyle(oldStyle); + } - for (const auto & it : style) { + for (const auto& it : style) { oldStyle.erase(it); } @@ -400,7 +449,7 @@ PyObject* SheetPy::setStyle(PyObject *args) do { std::set oldStyle; std::set newStyle; - const Cell * cell = getSheetPtr()->getCell(*rangeIter); + const Cell* cell = getSheetPtr()->getCell(*rangeIter); // Get old styles first if (cell) { @@ -408,7 +457,7 @@ PyObject* SheetPy::setStyle(PyObject *args) newStyle = oldStyle; } - for (const auto & i : style) { + for (const auto& i : style) { if (oldStyle.find(i) == oldStyle.end()) { // Not found in oldstyle; add it to newStyle newStyle.insert(i); @@ -424,36 +473,39 @@ PyObject* SheetPy::setStyle(PyObject *args) } while (rangeIter.next()); } else { - PyErr_SetString(PyExc_ValueError, "Optional parameter must be either 'replace', 'add', 'remove', or 'invert'"); + PyErr_SetString( + PyExc_ValueError, + "Optional parameter must be either 'replace', 'add', 'remove', or 'invert'"); return nullptr; } Py_Return; } -PyObject* SheetPy::getStyle(PyObject *args) +PyObject* SheetPy::getStyle(PyObject* args) { - const char * strAddress; + const char* strAddress; CellAddress address; - if (!PyArg_ParseTuple(args, "s:getStyle", &strAddress)) + if (!PyArg_ParseTuple(args, "s:getStyle", &strAddress)) { return nullptr; + } try { address = stringToAddress(strAddress); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } std::set style; - const Cell * cell = getSheetPtr()->getCell(address); + const Cell* cell = getSheetPtr()->getCell(address); if (cell && cell->getStyle(style)) { - PyObject * s = PySet_New(nullptr); + PyObject* s = PySet_New(nullptr); - for (const auto & i : style) { + for (const auto& i : style) { PySet_Add(s, PyUnicode_FromString(i.c_str())); } @@ -465,13 +517,14 @@ PyObject* SheetPy::getStyle(PyObject *args) } } -PyObject* SheetPy::setDisplayUnit(PyObject *args) +PyObject* SheetPy::setDisplayUnit(PyObject* args) { - const char * cell; - const char * value; + const char* cell; + const char* value; - if (!PyArg_ParseTuple(args, "ss:setDisplayUnit", &cell, &value)) + if (!PyArg_ParseTuple(args, "ss:setDisplayUnit", &cell, &value)) { return nullptr; + } try { Range rangeIter(cell); @@ -480,7 +533,7 @@ PyObject* SheetPy::setDisplayUnit(PyObject *args) getSheetPtr()->setDisplayUnit(*rangeIter, value); } while (rangeIter.next()); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } @@ -488,14 +541,15 @@ PyObject* SheetPy::setDisplayUnit(PyObject *args) Py_Return; } -PyObject* SheetPy::setAlias(PyObject *args) +PyObject* SheetPy::setAlias(PyObject* args) { CellAddress address; - const char * strAddress; - PyObject * value; + const char* strAddress; + PyObject* value; - if (!PyArg_ParseTuple(args, "sO:setAlias", &strAddress, &value)) + if (!PyArg_ParseTuple(args, "sO:setAlias", &strAddress, &value)) { return nullptr; + } try { address = stringToAddress(strAddress); @@ -503,104 +557,116 @@ PyObject* SheetPy::setAlias(PyObject *args) getSheetPtr()->setAlias(address, value ? PyUnicode_AsUTF8(value) : ""); Py_Return; } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getAlias(PyObject *args) +PyObject* SheetPy::getAlias(PyObject* args) { - const char * strAddress; + const char* strAddress; - if (!PyArg_ParseTuple(args, "s:getAlias", &strAddress)) + if (!PyArg_ParseTuple(args, "s:getAlias", &strAddress)) { return nullptr; + } try { CellAddress address(strAddress); - const Cell * cell = getSheetPtr()->getCell(address); + const Cell* cell = getSheetPtr()->getCell(address); std::string alias; - if (cell && cell->getAlias(alias)) - return Py::new_reference_to( Py::String( alias ) ); - else + if (cell && cell->getAlias(alias)) { + return Py::new_reference_to(Py::String(alias)); + } + else { Py_Return; + } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getCellFromAlias(PyObject *args) +PyObject* SheetPy::getCellFromAlias(PyObject* args) { - const char * alias; + const char* alias; - if (!PyArg_ParseTuple(args, "s:getAlias", &alias)) + if (!PyArg_ParseTuple(args, "s:getAlias", &alias)) { return nullptr; + } try { std::string address = getSheetPtr()->getAddressFromAlias(alias); - if (!address.empty()) - return Py::new_reference_to( Py::String( address ) ); - else + if (!address.empty()) { + return Py::new_reference_to(Py::String(address)); + } + else { Py_Return; + } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getDisplayUnit(PyObject *args) +PyObject* SheetPy::getDisplayUnit(PyObject* args) { - const char * strAddress; + const char* strAddress; CellAddress address; - if (!PyArg_ParseTuple(args, "s:getDisplayUnit", &strAddress)) + if (!PyArg_ParseTuple(args, "s:getDisplayUnit", &strAddress)) { return nullptr; + } try { address = stringToAddress(strAddress); Spreadsheet::DisplayUnit unit; - const Cell * cell = getSheetPtr()->getCell(address); + const Cell* cell = getSheetPtr()->getCell(address); - if ( cell && cell->getDisplayUnit(unit) ) - return Py::new_reference_to( Py::String( unit.stringRep ) ); - else + if (cell && cell->getDisplayUnit(unit)) { + return Py::new_reference_to(Py::String(unit.stringRep)); + } + else { Py_Return; + } } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::setAlignment(PyObject *args) +PyObject* SheetPy::setAlignment(PyObject* args) { - const char * cell; - PyObject * value; + const char* cell; + PyObject* value; int alignment = 0; - const char * options = "replace"; + const char* options = "replace"; - if (!PyArg_ParseTuple(args, "sO|s:setAlignment", &cell, &value, &options)) + if (!PyArg_ParseTuple(args, "sO|s:setAlignment", &cell, &value, &options)) { return nullptr; + } if (PySet_Check(value)) { // Argument is a set of strings - PyObject * copy = PySet_New(value); + PyObject* copy = PySet_New(value); int n = PySet_Size(copy); while (n-- > 0) { - PyObject * item = PySet_Pop(copy); + PyObject* item = PySet_Pop(copy); - if (PyUnicode_Check(item)) + if (PyUnicode_Check(item)) { alignment = Cell::decodeAlignment(PyUnicode_AsUTF8(item), alignment); + } else { - std::string error = std::string("type of the key need to be a string, not") + item->ob_type->tp_name; + std::string error = std::string("type of the key need to be a string, not") + + item->ob_type->tp_name; PyErr_SetString(PyExc_TypeError, error.c_str()); Py_DECREF(copy); return nullptr; @@ -615,15 +681,18 @@ PyObject* SheetPy::setAlignment(PyObject *args) escaped_list_separator e('\0', '|', '\0'); std::string line = PyUnicode_AsUTF8(value); - tokenizer > tok(line, e); + tokenizer> tok(line, e); - for(tokenizer >::iterator i = tok.begin(); i != tok.end();++i) { - if(!i->empty()) + for (tokenizer>::iterator i = tok.begin(); i != tok.end(); + ++i) { + if (!i->empty()) { alignment = Cell::decodeAlignment(*i, alignment); + } } } else { - std::string error = std::string("style must be either set or string, not ") + value->ob_type->tp_name; + std::string error = + std::string("style must be either set or string, not ") + value->ob_type->tp_name; PyErr_SetString(PyExc_TypeError, error.c_str()); return nullptr; } @@ -641,15 +710,18 @@ PyObject* SheetPy::setAlignment(PyObject *args) do { int oldAlignment = 0; - const Cell * cell = getSheetPtr()->getCell(*rangeIter); + const Cell* cell = getSheetPtr()->getCell(*rangeIter); - if (cell) + if (cell) { cell->getAlignment(oldAlignment); + } - if (alignment & Cell::ALIGNMENT_VERTICAL) + if (alignment & Cell::ALIGNMENT_VERTICAL) { oldAlignment &= ~Cell::ALIGNMENT_VERTICAL; - if (alignment & Cell::ALIGNMENT_HORIZONTAL) + } + if (alignment & Cell::ALIGNMENT_HORIZONTAL) { oldAlignment &= ~Cell::ALIGNMENT_HORIZONTAL; + } getSheetPtr()->setAlignment(*rangeIter, alignment | oldAlignment); } while (rangeIter.next()); @@ -661,40 +733,47 @@ PyObject* SheetPy::setAlignment(PyObject *args) Py_Return; } -PyObject* SheetPy::getAlignment(PyObject *args) +PyObject* SheetPy::getAlignment(PyObject* args) { - const char * strAddress; + const char* strAddress; CellAddress address; - if (!PyArg_ParseTuple(args, "s:getAlignment", &strAddress)) + if (!PyArg_ParseTuple(args, "s:getAlignment", &strAddress)) { return nullptr; + } try { address = stringToAddress(strAddress); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } int alignment; - const Cell * cell = getSheetPtr()->getCell(address); + const Cell* cell = getSheetPtr()->getCell(address); if (cell && cell->getAlignment(alignment)) { - PyObject * s = PySet_New(nullptr); + PyObject* s = PySet_New(nullptr); - if (alignment & Cell::ALIGNMENT_LEFT) + if (alignment & Cell::ALIGNMENT_LEFT) { PySet_Add(s, PyUnicode_FromString("left")); - if (alignment & Cell::ALIGNMENT_HCENTER) + } + if (alignment & Cell::ALIGNMENT_HCENTER) { PySet_Add(s, PyUnicode_FromString("center")); - if (alignment & Cell::ALIGNMENT_RIGHT) + } + if (alignment & Cell::ALIGNMENT_RIGHT) { PySet_Add(s, PyUnicode_FromString("right")); - if (alignment & Cell::ALIGNMENT_TOP) + } + if (alignment & Cell::ALIGNMENT_TOP) { PySet_Add(s, PyUnicode_FromString("top")); - if (alignment & Cell::ALIGNMENT_VCENTER) + } + if (alignment & Cell::ALIGNMENT_VCENTER) { PySet_Add(s, PyUnicode_FromString("vcenter")); - if (alignment & Cell::ALIGNMENT_BOTTOM) + } + if (alignment & Cell::ALIGNMENT_BOTTOM) { PySet_Add(s, PyUnicode_FromString("bottom")); + } return s; } @@ -704,20 +783,23 @@ PyObject* SheetPy::getAlignment(PyObject *args) } } -static float decodeFloat(const PyObject * obj) +static float decodeFloat(const PyObject* obj) { - if (PyFloat_Check(obj)) - return PyFloat_AsDouble((PyObject *)obj); - else if (PyLong_Check(obj)) - return PyLong_AsLong((PyObject *)obj); + if (PyFloat_Check(obj)) { + return PyFloat_AsDouble((PyObject*)obj); + } + else if (PyLong_Check(obj)) { + return PyLong_AsLong((PyObject*)obj); + } throw Base::TypeError("Float or integer expected"); } -static void decodeColor(PyObject * value, Color & c) +static void decodeColor(PyObject* value, Color& c) { if (PyTuple_Check(value)) { - if (PyTuple_Size(value) < 3 || PyTuple_Size(value) > 4) + if (PyTuple_Size(value) < 3 || PyTuple_Size(value) > 4) { throw Base::TypeError("Tuple must be either of 3 or 4 floats/ints."); + } c.r = decodeFloat(PyTuple_GetItem(value, 0)); c.g = decodeFloat(PyTuple_GetItem(value, 1)); @@ -726,22 +808,25 @@ static void decodeColor(PyObject * value, Color & c) c.a = decodeFloat(PyTuple_GetItem(value, 3)); return; } - else + else { c.a = 1.0; + } } - else + else { throw Base::TypeError("Tuple required."); + } } -PyObject* SheetPy::setForeground(PyObject *args) +PyObject* SheetPy::setForeground(PyObject* args) { try { - const char * range; - PyObject * value; + const char* range; + PyObject* value; Color c; - if (!PyArg_ParseTuple(args, "sO:setForeground", &range, &value)) + if (!PyArg_ParseTuple(args, "sO:setForeground", &range, &value)) { return nullptr; + } decodeColor(value, c); @@ -751,41 +836,42 @@ PyObject* SheetPy::setForeground(PyObject *args) } while (rangeIter.next()); Py_Return; } - catch (const Base::TypeError & e) { + catch (const Base::TypeError& e) { PyErr_SetString(PyExc_TypeError, e.what()); return nullptr; } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getForeground(PyObject *args) +PyObject* SheetPy::getForeground(PyObject* args) { - const char * strAddress; + const char* strAddress; CellAddress address; - if (!PyArg_ParseTuple(args, "s:getForeground", &strAddress)) + if (!PyArg_ParseTuple(args, "s:getForeground", &strAddress)) { return nullptr; + } try { address = stringToAddress(strAddress); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } Color c; - const Cell * cell = getSheetPtr()->getCell(address); + const Cell* cell = getSheetPtr()->getCell(address); if (cell && cell->getForeground(c)) { - PyObject * t = PyTuple_New(4); + PyObject* t = PyTuple_New(4); - PyTuple_SetItem(t, 0, Py::new_reference_to( Py::Float(c.r) )); - PyTuple_SetItem(t, 1, Py::new_reference_to( Py::Float(c.g) )); - PyTuple_SetItem(t, 2, Py::new_reference_to( Py::Float(c.b) )); - PyTuple_SetItem(t, 3, Py::new_reference_to( Py::Float(c.a) )); + PyTuple_SetItem(t, 0, Py::new_reference_to(Py::Float(c.r))); + PyTuple_SetItem(t, 1, Py::new_reference_to(Py::Float(c.g))); + PyTuple_SetItem(t, 2, Py::new_reference_to(Py::Float(c.b))); + PyTuple_SetItem(t, 3, Py::new_reference_to(Py::Float(c.a))); return t; } @@ -795,15 +881,16 @@ PyObject* SheetPy::getForeground(PyObject *args) } } -PyObject* SheetPy::setBackground(PyObject *args) +PyObject* SheetPy::setBackground(PyObject* args) { try { - const char * strAddress; - PyObject * value; + const char* strAddress; + PyObject* value; Color c; - if (!PyArg_ParseTuple(args, "sO:setBackground", &strAddress, &value)) + if (!PyArg_ParseTuple(args, "sO:setBackground", &strAddress, &value)) { return nullptr; + } decodeColor(value, c); Range rangeIter(strAddress); @@ -813,41 +900,42 @@ PyObject* SheetPy::setBackground(PyObject *args) } while (rangeIter.next()); Py_Return; } - catch (const Base::TypeError & e) { + catch (const Base::TypeError& e) { PyErr_SetString(PyExc_TypeError, e.what()); return nullptr; } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getBackground(PyObject *args) +PyObject* SheetPy::getBackground(PyObject* args) { - const char * strAddress; + const char* strAddress; CellAddress address; - if (!PyArg_ParseTuple(args, "s:setStyle", &strAddress)) + if (!PyArg_ParseTuple(args, "s:setStyle", &strAddress)) { return nullptr; + } try { address = stringToAddress(strAddress); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } Color c; - const Cell * cell = getSheetPtr()->getCell(address); + const Cell* cell = getSheetPtr()->getCell(address); if (cell && cell->getBackground(c)) { - PyObject * t = PyTuple_New(4); + PyObject* t = PyTuple_New(4); - PyTuple_SetItem(t, 0, Py::new_reference_to( Py::Float(c.r) )); - PyTuple_SetItem(t, 1, Py::new_reference_to( Py::Float(c.g) )); - PyTuple_SetItem(t, 2, Py::new_reference_to( Py::Float(c.b) )); - PyTuple_SetItem(t, 3, Py::new_reference_to( Py::Float(c.a) )); + PyTuple_SetItem(t, 0, Py::new_reference_to(Py::Float(c.r))); + PyTuple_SetItem(t, 1, Py::new_reference_to(Py::Float(c.g))); + PyTuple_SetItem(t, 2, Py::new_reference_to(Py::Float(c.b))); + PyTuple_SetItem(t, 3, Py::new_reference_to(Py::Float(c.a))); return t; } @@ -857,14 +945,15 @@ PyObject* SheetPy::getBackground(PyObject *args) } } -PyObject* SheetPy::setColumnWidth(PyObject *args) +PyObject* SheetPy::setColumnWidth(PyObject* args) { - const char * columnStr; + const char* columnStr; int width; CellAddress address; - if (!PyArg_ParseTuple(args, "si:setColumnWidth", &columnStr, &width)) + if (!PyArg_ParseTuple(args, "si:setColumnWidth", &columnStr, &width)) { return nullptr; + } try { std::string cellAddr = std::string(columnStr) + "1"; @@ -873,37 +962,39 @@ PyObject* SheetPy::setColumnWidth(PyObject *args) getSheetPtr()->setColumnWidth(address.col(), width); Py_Return; } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getColumnWidth(PyObject *args) +PyObject* SheetPy::getColumnWidth(PyObject* args) { - const char * columnStr; + const char* columnStr; - if (!PyArg_ParseTuple(args, "s:getColumnWidth", &columnStr)) + if (!PyArg_ParseTuple(args, "s:getColumnWidth", &columnStr)) { return nullptr; + } try { CellAddress address(std::string(columnStr) + "1"); - return Py::new_reference_to( Py::Long( getSheetPtr()->getColumnWidth(address.col()) ) ); + return Py::new_reference_to(Py::Long(getSheetPtr()->getColumnWidth(address.col()))); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::setRowHeight(PyObject *args) +PyObject* SheetPy::setRowHeight(PyObject* args) { - const char * rowStr; + const char* rowStr; int height; - if (!PyArg_ParseTuple(args, "si:setRowHeight", &rowStr, &height)) + if (!PyArg_ParseTuple(args, "si:setRowHeight", &rowStr, &height)) { return nullptr; + } try { CellAddress address("A" + std::string(rowStr)); @@ -911,94 +1002,109 @@ PyObject* SheetPy::setRowHeight(PyObject *args) getSheetPtr()->setRowHeight(address.row(), height); Py_Return; } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject* SheetPy::getRowHeight(PyObject *args) +PyObject* SheetPy::getRowHeight(PyObject* args) { - const char * rowStr; + const char* rowStr; - if (!PyArg_ParseTuple(args, "s:getRowHeight", &rowStr)) + if (!PyArg_ParseTuple(args, "s:getRowHeight", &rowStr)) { return nullptr; + } try { CellAddress address("A" + std::string(rowStr)); - return Py::new_reference_to( Py::Long( getSheetPtr()->getRowHeight(address.row()) ) ); + return Py::new_reference_to(Py::Long(getSheetPtr()->getRowHeight(address.row()))); } - catch (const Base::Exception & e) { + catch (const Base::Exception& e) { PyErr_SetString(PyExc_ValueError, e.what()); return nullptr; } } -PyObject *SheetPy::touchCells(PyObject *args) { - const char *address; - const char *address2=nullptr; +PyObject* SheetPy::touchCells(PyObject* args) +{ + const char* address; + const char* address2 = nullptr; - if (!PyArg_ParseTuple(args, "s|s:touchCells", &address, &address2)) + if (!PyArg_ParseTuple(args, "s|s:touchCells", &address, &address2)) { return nullptr; + } - PY_TRY { + PY_TRY + { std::string a1 = getSheetPtr()->getAddressFromAlias(address); - if(a1.empty()) + if (a1.empty()) { a1 = address; + } std::string a2; - if(!address2) { + if (!address2) { a2 = a1; - } else { - a2 = getSheetPtr()->getAddressFromAlias(address2); - if(a2.empty()) - a2 = address2; } - getSheetPtr()->touchCells(Range(a1.c_str(),a2.c_str())); + else { + a2 = getSheetPtr()->getAddressFromAlias(address2); + if (a2.empty()) { + a2 = address2; + } + } + getSheetPtr()->touchCells(Range(a1.c_str(), a2.c_str())); Py_Return; - }PY_CATCH; + } + PY_CATCH; } -PyObject *SheetPy::recomputeCells(PyObject *args) { - const char *address; - const char *address2=nullptr; +PyObject* SheetPy::recomputeCells(PyObject* args) +{ + const char* address; + const char* address2 = nullptr; - if (!PyArg_ParseTuple(args, "s|s:touchCells", &address, &address2)) + if (!PyArg_ParseTuple(args, "s|s:touchCells", &address, &address2)) { return nullptr; + } - PY_TRY { + PY_TRY + { std::string a1 = getSheetPtr()->getAddressFromAlias(address); - if(a1.empty()) + if (a1.empty()) { a1 = address; + } std::string a2; - if(!address2) { + if (!address2) { a2 = a1; - } else { - a2 = getSheetPtr()->getAddressFromAlias(address2); - if(a2.empty()) - a2 = address2; } - getSheetPtr()->recomputeCells(Range(a1.c_str(),a2.c_str())); + else { + a2 = getSheetPtr()->getAddressFromAlias(address2); + if (a2.empty()) { + a2 = address2; + } + } + getSheetPtr()->recomputeCells(Range(a1.c_str(), a2.c_str())); Py_Return; - }PY_CATCH; + } + PY_CATCH; } -PyObject *SheetPy::getUsedCells(PyObject *args) +PyObject* SheetPy::getUsedCells(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; } auto usedCells = getSheetPtr()->getCells()->getUsedCells(); Py::List pyCellList; - for (const auto &cell : usedCells) { + for (const auto& cell : usedCells) { pyCellList.append(Py::String(cell.toString())); } return Py::new_reference_to(pyCellList); } -PyObject *SheetPy::getUsedRange(PyObject *args) +PyObject* SheetPy::getUsedRange(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1010,20 +1116,20 @@ PyObject *SheetPy::getUsedRange(PyObject *args) return Py::new_reference_to(pyTuple); } -PyObject *SheetPy::getNonEmptyCells(PyObject *args) +PyObject* SheetPy::getNonEmptyCells(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; } auto nonEmptyCells = getSheetPtr()->getCells()->getNonEmptyCells(); Py::List pyCellList; - for (const auto &cell : nonEmptyCells) { - pyCellList.append(Py::String(cell.toString())); + for (const auto& cell : nonEmptyCells) { + pyCellList.append(Py::String(cell.toString())); } return Py::new_reference_to(pyCellList); } -PyObject *SheetPy::getNonEmptyRange(PyObject *args) +PyObject* SheetPy::getNonEmptyRange(PyObject* args) { if (!PyArg_ParseTuple(args, "")) { return nullptr; @@ -1038,12 +1144,12 @@ PyObject *SheetPy::getNonEmptyRange(PyObject *args) // +++ custom attributes implementer ++++++++++++++++++++++++++++++++++++++++ -PyObject *SheetPy::getCustomAttributes(const char*) const +PyObject* SheetPy::getCustomAttributes(const char*) const { return nullptr; } -int SheetPy::setCustomAttributes(const char* , PyObject* ) +int SheetPy::setCustomAttributes(const char*, PyObject*) { return 0; } diff --git a/src/Mod/Spreadsheet/App/Utils.cpp b/src/Mod/Spreadsheet/App/Utils.cpp index 8e2f6783c9..e31d4a8962 100644 --- a/src/Mod/Spreadsheet/App/Utils.cpp +++ b/src/Mod/Spreadsheet/App/Utils.cpp @@ -23,42 +23,45 @@ #include "PreCompiled.h" #ifndef _PreComp_ -# include +#include #endif -#include "Utils.h" #include "Sheet.h" +#include "Utils.h" /** - * Encode \a col as a string. - * - * @param col Column given as a 0-based column position. - * - * @returns String with column position, with "A" being the first column, "B" being the second and so on. - * - */ + * Encode \a col as a string. + * + * @param col Column given as a 0-based column position. + * + * @returns String with column position, with "A" being the first column, "B" being the second and + * so on. + * + */ std::string Spreadsheet::columnName(int col) { std::stringstream s; - if (col < 26) + if (col < 26) { s << ((char)('A' + col)); - else - s << ((char)('A' + (col - 26) / 26 )) << ((char)('A' + (col - 26) % 26)); + } + else { + s << ((char)('A' + (col - 26) / 26)) << ((char)('A' + (col - 26) % 26)); + } return s.str(); } /** - * Encode \a row as a string. - * - * @param row Row given as a 0-based row position. - * - * @returns String with row position, with "1" being the first row. - * - */ + * Encode \a row as a string. + * + * @param row Row given as a 0-based row position. + * + * @returns String with row position, with "1" being the first row. + * + */ std::string Spreadsheet::rowName(int row) { @@ -70,7 +73,8 @@ std::string Spreadsheet::rowName(int row) } -void Spreadsheet::createRectangles(std::set > & cells, std::map, std::pair > & rectangles) +void Spreadsheet::createRectangles(std::set>& cells, + std::map, std::pair>& rectangles) { while (!cells.empty()) { int row, col; @@ -82,8 +86,9 @@ void Spreadsheet::createRectangles(std::set > & cells, std:: col = (*cells.begin()).second; // Expand right first - while (cells.find(std::make_pair(row, col + cols)) != cells.end()) + while (cells.find(std::make_pair(row, col + cols)) != cells.end()) { ++cols; + } // Expand left while (cells.find(std::make_pair(row, col + cols)) != cells.end()) { @@ -91,11 +96,12 @@ void Spreadsheet::createRectangles(std::set > & cells, std:: ++cols; } - // Try to expand cell up (the complete row above from [col,col + cols> needs to be in the cells variable) + // Try to expand cell up (the complete row above from [col,col + cols> needs to be in the + // cells variable) bool ok = true; while (ok) { for (int i = col; i < col + cols; ++i) { - if ( cells.find(std::make_pair(row - 1, i)) == cells.end()) { + if (cells.find(std::make_pair(row - 1, i)) == cells.end()) { ok = false; break; } @@ -105,17 +111,19 @@ void Spreadsheet::createRectangles(std::set > & cells, std:: row--; rows++; } - else + else { break; + } } - // Try to expand down (the complete row below from [col,col + cols> needs to be in the cells variable) + // Try to expand down (the complete row below from [col,col + cols> needs to be in the cells + // variable) ok = true; while (ok) { for (int i = col; i < col + cols; ++i) { - if ( cells.find(std::make_pair(orgRow + 1, i)) == cells.end()) { - ok = false; - break; + if (cells.find(std::make_pair(orgRow + 1, i)) == cells.end()) { + ok = false; + break; } } if (ok) { @@ -123,21 +131,24 @@ void Spreadsheet::createRectangles(std::set > & cells, std:: orgRow++; rows++; } - else + else { break; + } } // Remove entries from cell set for this rectangle - for (int r = row; r < row + rows; ++r) - for (int c = col; c < col + cols; ++c) + for (int r = row; r < row + rows; ++r) { + for (int c = col; c < col + cols; ++c) { cells.erase(std::make_pair(r, c)); + } + } // Insert into output variable rectangles[std::make_pair(row, col)] = std::make_pair(rows, cols); } } -std::string Spreadsheet::quote(const std::string &input) +std::string Spreadsheet::quote(const std::string& input) { std::stringstream output; @@ -147,29 +158,29 @@ std::string Spreadsheet::quote(const std::string &input) output << "<<"; while (cur != end) { switch (*cur) { - case '\t': - output << "\\t"; - break; - case '\n': - output << "\\n"; - break; - case '\r': - output << "\\r"; - break; - case '\\': - output << "\\\\"; - break; - case '\'': - output << "\\'"; - break; - case '"': - output << "\\\""; - break; - case '>': - output << "\\>"; - break; - default: - output << *cur; + case '\t': + output << "\\t"; + break; + case '\n': + output << "\\n"; + break; + case '\r': + output << "\\r"; + break; + case '\\': + output << "\\\\"; + break; + case '\'': + output << "\\'"; + break; + case '"': + output << "\\\""; + break; + case '>': + output << "\\>"; + break; + default: + output << *cur; } ++cur; } @@ -178,7 +189,7 @@ std::string Spreadsheet::quote(const std::string &input) return output.str(); } -std::string Spreadsheet::unquote(const std::string & input) +std::string Spreadsheet::unquote(const std::string& input) { assert(input.size() >= 4); @@ -192,32 +203,34 @@ std::string Spreadsheet::unquote(const std::string & input) while (cur != end) { if (escaped) { switch (*cur) { - case 't': - output += '\t'; - break; - case 'n': - output += '\n'; - break; - case 'r': - output += '\r'; - break; - case '\\': - output += '\\'; - break; - case '\'': - output += '\''; - break; - case '"': - output += '"'; - break; + case 't': + output += '\t'; + break; + case 'n': + output += '\n'; + break; + case 'r': + output += '\r'; + break; + case '\\': + output += '\\'; + break; + case '\'': + output += '\''; + break; + case '"': + output += '"'; + break; } escaped = false; } else { - if (*cur == '\\') + if (*cur == '\\') { escaped = true; - else + } + else { output += *cur; + } } ++cur; } diff --git a/src/Mod/Spreadsheet/App/Utils.h b/src/Mod/Spreadsheet/App/Utils.h index c75830270b..b124d055ed 100644 --- a/src/Mod/Spreadsheet/App/Utils.h +++ b/src/Mod/Spreadsheet/App/Utils.h @@ -31,15 +31,18 @@ #include -namespace Spreadsheet { +namespace Spreadsheet +{ SpreadsheetExport std::string columnName(int col); SpreadsheetExport std::string rowName(int row); -SpreadsheetExport void createRectangles(std::set > & cells, std::map, std::pair > & rectangles); -SpreadsheetExport std::string quote(const std::string &input); -SpreadsheetExport std::string unquote(const std::string & input); +SpreadsheetExport void +createRectangles(std::set>& cells, + std::map, std::pair>& rectangles); +SpreadsheetExport std::string quote(const std::string& input); +SpreadsheetExport std::string unquote(const std::string& input); -} +}// namespace Spreadsheet -#endif // UTILS_H +#endif// UTILS_H