#!/usr/bin/env python # -*- coding: utf-8 -*- # ======================================================================== # Macro Sketch Constraint From Spreadsheet # file name : Sketch_Constraint_From_Spreadsheet.FCMacro # ======================================================================== # == == # == Adds a length constraint to a line, circle, points ... == # == using a spreadsheet cell alias or name (ex. C2). == # == Future changes to the spreadsheet will update the constraint. == # == if necessary, the macro help you to create alias == # == USE: == # == 1) Select 1 line, 2 points or a constraint in the sketch == # == 2) Select a cell in a spreadsheet (1 and 2 in any order) == # == 3) Launch the macro, from the spreadsheet or from the sketch == # == (from the sketch, the cell selected in the last active == # == spreadsheet is used, see the report view) == # == if the cell has an alias, the length property will be something == # == like 'Spreadsheet.alias'. == # == if not, just something like 'Spreadsheet.C2' == # == You can select lines, points line, points, circle... == # == You can select external objects == # ======================================================================== # ======================================================================== __Name__ = "Sketch Constraint From Spreadsheet" # Addon Manager reads metadata line by line : keep each value on a single line __Comment__ = "Macro Sketch Constraint From Spreadsheet: Quickly add a fully dynamic length constraint to a sketch element, using a spreadsheet cell alias or address, or link spreadsheet values to object properties. The macro can also create aliases automatically." # noqa: E501 __Author__ = "2cv001" __Title__ = "Macro Sketch Constraint From Spreadsheet" __Date__ = "2026/11/23 08:50" # YYYY/MM/DD __Version__ = __Date__ __Icon__ = "https://wiki.freecad.org/images/6/60/Sketch_Constraint_From_Spreadsheet.png" # __Icon__ = "https://raw.githubusercontent.com/2cv001/FreeCAD-macros/master/Spreadsheet/Sketch_Constraint_From_Spreadsheet.png" __Wiki__ = "https://wiki.freecad.org/Macro_sketchConstraintFromSpreadsheet" __License__ = "Apache-2.0" from PySide import QtGui from PySide import QtCore from PySide.QtGui import QIcon from PySide.QtGui import QGuiApplication try: from PySide.QtCore import QRegularExpression as fcRegExp from PySide.QtGui import QRegularExpressionValidator as fcRegExpValidator except ImportError: # Qt5 : no QRegularExpressionValidator from PySide.QtCore import QRegExp as fcRegExp from PySide.QtGui import QRegExpValidator as fcRegExpValidator from datetime import datetime from collections import namedtuple import configparser import os import FreeCAD as App import Sketcher import re import itertools import locale import FreeCADGui as Gui # ini file (settings saved between executions), in the macro directory INI_FILE = os.path.join(App.getUserMacroDir(True), "sketchConstraintFromSpreadsheet.ini") # -------------------------------------------------------------------------------------------------------- # Just after one of these word, you can have a formula for Alias # if your alias is 'radius_f__mul_2_plu_1' the expression will be something like # <>.radius_f__mul_2_plu_1*2+1' # -------------------------------------------------------------------------------------------------------- formulaSeparator = '_f_' dicoFormula = { '_div_': '/', '_mul_': '*', '_plu_': '+', '_mor_': '+', '_les_': '-', '_moi_': '-', '_pg_': '(', '_lp_': '(', '_pd_': ')', '_rp_': ')', } def recomputeAll(): for obj in App.ActiveDocument.Objects: obj.touch() App.ActiveDocument.recompute() def getLanguage(): # Dictionary of common languages common_languages = { "en": "English", "fr": "French", } lang = App.ParamGet("User parameter:BaseApp/Preferences/General").GetString( "Language" ) if not lang: # if App.ParamGet found nothing try: system_locale = locale.getlocale() if system_locale and system_locale[0]: system_language = system_locale[0][:2] if system_language in common_languages: lang = common_languages[system_language] else: # Fallback if locale returns None or empty lang = "English" except (TypeError, IndexError): # Handle any exceptions by defaulting to English lang = "English" if lang not in common_languages.values(): lang = "English" return lang language = getLanguage() # use : messages[language]["Values"] messages = { "French": { "DialogCheckbox1Document": "Document", "DialogToolTip": "Si coché, l'alias sera automatiquement créé lors de l'éxécution de la macro. " + "\nLes Alias seront créés à droite des cellules avec texte. Les cellules avec texte sont celle ci et en dessous : ", "DialogCheckboxAlias": "Cellule de départ pour les textes des alias :", "DialogCheckboxSpreadsheet": "Spreadsheets", "DialogTextboxSpreadsheetNameTolLip": "Nom pour les spreadsheet", "DialogCheckboxTextDocument": "Text document", "DialogTextboxTextdocumentNameToolTip": "Nom pour les Text Document", "DialogcheckboxBody": "Body", "DialogTextboxBodyNameToolTip": "Nom pour les body", "DialogcheckboxSketch": "Sketch", "DialogTextboxSketchNameTolLip": "Nom pour les sketch", "TITLE": "TITRE", "Textsforalias": "Libellé des alias", "andAlias": " et alias", "Values": "Valeurs", "OkOui": "&Oui", "NoPasDe": "Pas de", "foundTrouve": "trouvé", "foundCreateOne": "trouvé, en créer un ?", "Cancel": "Aban&don", "Warning": "Attention", "XYPlane": "Plan XY", "XZPlane": "Plan XZ", "YZPlane": "Plan YZ", "referenceNoName": "La contrainte que vous avez sélectionnée est une contrainte de type référence." + "\n Elle n'a pas de nom. \nVoulez-vous que la macro lui en donne " + "\n et voulez-vous que la cellule contienne la valeur de la contrainte ?" + "\n ATTENTION, vérifiez que vous n'allez pas créer une référence circulaire." + "\n\nIl se peut que PENDING apparaisse dans la cellule. Pour l'instant, " + "je ne recommande pas son utilisation car FreeCad manage mal les href. " + "\n Pour retirer le pending lancer un recalcul sur le spreadsheet ou sur la cellule ou " + "tapez Gui.ActiveDocument.ActiveView.getSheet().recompute(True) dans la console python", "referenceWithName": "La contrainte que vous avez sélectionnée est une contrainte de type référence." + "\n\nVoulez-vous que la cellule contienne la valeur de la contrainte ?" + "\n ATTENTION, vérifiez que vous n'allez pas créer une référence circulaire." + "\n\nIl se peut que PENDING apparaisse dans la cellule. " + "\n Pour retirer le pending lancer un recalcul sur le spreadsheet ou sur la cellule ou " + "tapez Gui.ActiveDocument.ActiveView.getSheet().recompute(True) dans la console python. " + "je ne recommande pas son utilisation car FreeCad manage mal les href.", "ClickOnACellBefore": "Cliquez dans une cellule avec une valeur numérique avant de lancer la macro.", "SelectHelp": "Sélectionnez 1 ligne, 2 points ou une contrainte dans un sketch, " + "et une cellule dans un tableur.", "SelectNothing": "Aucune sélection valide.\n" + "Sélectionnez 1 ligne, 2 points ou une contrainte dans un sketch en mode édition, " + "et une cellule dans un tableur.", "SelectTooMany": "Trop d'objets sélectionnés.", "SelectSingleNotSupported": "Cet objet seul n'est pas pris en charge.\n" + "Sélectionnez 1 ligne, 1 cercle, 2 points ou une contrainte dans un sketch, " + "et une cellule dans un tableur.", "SelectTwoNotPoints": "2 objets sont sélectionnés, mais ce ne sont pas 2 points.", "ActivateWindowTitle": "Activation de la fenêtre", "NoActiveDocument": "Pas de document actif.", "No3DView": "Pas de vue 3D ouverte pour le document actif.", "NoSketchInEdit": "Aucune vue 3D n'a de sketch en mode édition pour le document actif.", "NoObjectSelected": "Vous n'avez pas sélectionné d'objets dans le sketch actif." + "\nCela veut il dire que vous souhaitez créer automatiquement des alias à droite des cellules sélectionnées" + "en utilisant le texte de ces cellules sélectionnées." + "\n\nA moins que vous souhaitiez modofier directement une propriété dans l'arbre. " + " \n En ce cas sortez du mode d'édition du Sketch.", "NoActiveSpreadsheet": "Aucun tableur ouvert." + "\nOuvrez un tableur et sélectionnez la cellule contenant la valeur.", "ConstarintConflicDetected": "Détection de conflit dans les contraintes. Annulation de la création de la conrainte ?", "getConstraintTypeAliasToolTip": "Si coché, l'alias sera automatiquement créé lors de l'éxécution de la macro." + "\nLes Alias seront créés à droite des cellules avec texte. Les cellules avec texte sont celle ci et en dessous : ", "getConstraintTypeOption1ButtonSetText": "Contrainte &horizontale ", "getConstraintTypeOption2ButtonSetText": "Contrainte &verticale", "getConstraintTypeOption3ButtonSetText": "Contrainte &alignée", "getConstraintTypeOption1ButtonSetTextToolTip": "Contrainte horizontale", "getConstraintTypeOption2ButtonSetTextToolTip": "Contrainte verticale", "getConstraintTypeOption3ButtonSetTextToolTip": "Contrainte alignée", "getConstraintTypeCheckboxConflic": "Détecttion des conflits", "getConstraintTypeCheckboxConflicToolTip": "Avertissement en cas de conflit de contraintes." + "\nDonne la possibilité d'annuler la contrainte ", "getConstraintTypeWindowTitle": "Choix du type de contrainte", "getConstraintTypeCheckboxAlias": "Textes pour alias automatiques dans cette cellule et en dessous :", "getConstraintTypeRadioGroupTitle": "Diamètre dans tableur donne un rayon dans le sketch (valeur divisée par 2)", "getConstraintTypeRadioGroupTooltip": "À utiliser, par exemple, lorsque vous connaissez la valeur du diamètre, " + "\nmais que le sketch nécessite une contrainte sur le rayon. Utile notamment pour les fonctions de révolution.", "getConstraintTypeRadioRadius": "Oui (/ 2)", "getConstraintTypeRadioDiameter": "Non (inchangé)", "PropNoneSelected": "Aucune propriété de {obj} n'est sélectionnée dans la fenêtre des propriétés." + "\n\nCliquez sur la propriété à lier (ex : Length, ou Placement > Position > x), " + "puis relancez la macro.", "PropHasSubItems": "{path} contient plusieurs valeurs." + "\n\nDépliez-la et sélectionnez une seule valeur (ex : x, y ou z).", "PropNotEditable": "{path} n'est pas modifiable dans ce contexte (propriété grisée)." + "\n\nRendez-la modifiable avant de lancer la macro." + "\n(ex : pour un sketch attaché, utilisez Attachment Offset au lieu de Placement)", "PropLinkFailed": "Impossible de lier {path} à {expr} :\n\n{error}", "PropAlreadyLinked": "{path} est déjà liée par l'expression :\n\n {old}\n\nQue voulez-vous faire ?", "PropAlreadyLinkedNoSheet": "{path} est liée par l'expression :\n\n {old}" + "\n\nAucun tableur n'est ouvert : la macro peut seulement supprimer ce lien." + "\n\nPour lier la propriété à une autre cellule, ou pour les autres " + "fonctions de la macro, ouvrez un tableur, sélectionnez une cellule " + "et relancez la macro.", "PropReplaceLink": "&Remplacer par la cellule sélectionnée", "PropRecomputeError": "FreeCAD a détecté une erreur après la liaison de {path} à {expr} :" + "\n\n{errors}" + "\n\nRevenir en arrière (remettre {old}) ?", "PropRestoreFailed": "Impossible de remettre l'ancienne valeur de {path} :\n\n{error}" + "\n\nUtilisez Édition > Annuler (Ctrl+Z).", "CellEmpty": "La cellule {cell} est vide ou contient une erreur." + "\n\nMettez-y une valeur avant de la lier à {path}.", "CellTextForNumber": "La cellule {cell} contient du texte ({value}), mais {path} attend un nombre." + "\n\nLiaison refusée.", "CellUnitMismatch": "L'unité de la cellule {cell} ({cellUnit}) ne correspond pas " + "à celle de {path} ({propertyUnit})." + "\n\nLiaison refusée.", "CellTextForBool": "La cellule {cell} contient du texte ({value}), mais {path} est une case à cocher : " + "elle attend 0 (décochée) ou 1 (cochée)." + "\n\nLiaison refusée.", "CellEnumText": "La cellule {cell} contient « {value} », qui n'est pas un choix possible pour {path}." + "\n\nChoix possibles (numéro : texte) :\n{choices}" + "\n\nLiaison refusée.", "CellEnumIndex": "La cellule {cell} contient {value}, qui n'est pas un numéro de choix " + "pour {path} (de 0 à {last})." + "\n\nChoix possibles (numéro : texte) :\n{choices}" + "\n\nLiaison refusée.", "PropRemoveLink": "&Supprimer le lien", "PropBoolEnumWarning": "{path} est une case à cocher ou une liste de choix." + "\n\nLa lier à une cellule est FORTEMENT DÉCONSEILLÉ :" + "\n - une fois liée, la case ou la liste de la fenêtre des propriétés n'a plus " + "aucun effet, et ne permet pas de retirer le lien ;" + "\n - si la cellule est effacée ou déplacée, la propriété reste bloquée ;" + "\n - pour une liste, la cellule donne le numéro du choix (0 = premier), " + "numéro qui peut changer avec une autre version de FreeCAD." + "\n\nPour retirer le lien plus tard :" + "\n - relancez la macro en sélectionnant cette propriété : " + "elle proposera de supprimer le lien ;" + "\n - ou tapez dans la console Python :\n {cmd}" + "\n\nLier quand même ?", }, "English": { "DialogCheckbox1Document": "Document", "DialogToolTip": "If checked, alias will automatically be created during each macro execution. " + "\nAlias will be created at the right of cells with text. Cells with text is this one and cells and under : ", "DialogCheckboxAlias": "Starting cell for alias texts :", "DialogCheckboxSpreadsheet": "Spreadsheets", "DialogTextboxSpreadsheetNameTolLip": "Name for the spreadsheet", "DialogCheckboxTextDocument": "Text document", "DialogTextboxTextdocumentNameToolTip": "Name for the Text Document", "DialogcheckboxBody": "Body", "DialogTextboxBodyNameToolTip": "Name for the body", "DialogcheckboxSketch": "Sketch", "DialogTextboxSketchNameTolLip": "Name for the sketch", "TITLE": "TITLE", "Textsforalias": "Texts for alias", "andAlias": " and alias", "Values": "Values", "OkOui": "&OK", "NoPasDe": "No", "foundTrouve": "found", "foundCreateOne": "found, create one?", "Cancel": "&Cancel", "Warning": "Warning", "XYPlane": "XY Plane", "XZPlane": "XZ Plane", "YZPlane": "YZ Plane", "referenceNoName": "The constraint you have selected is a reference type constraint." + "\n It does not have a name. \nDo you want the macro to give it one " + "\n and do you want the cell to contain the value of the constraint?" + "\n WARNING, check that you are not going to create a circular reference." + "\n\nPENDING may appear in the cell. This will appear too often. \nFor now, " + "I do not recommend its use.." + "\n To remove the pending status, trigger a recalculation on the spreadsheet or on the cell or " + "type Gui.ActiveDocument.ActiveView.getSheet().recompute(True) in the python console.", "referenceWithName": "The constraint you have selected is a reference type constraint." + "\n\nDo you want the cell to contain the value of the constraint?" + "\n WARNING, check that you are not going to create a circular reference." + "\n\nPENDING may appear in the cell. " + "\n To remove the pending status, trigger a recalculation on the spreadsheet or on the cell or " + "type Gui.ActiveDocument.ActiveView.getSheet().recompute(True) in the python console.", "ClickOnACellBefore": "Click on a cell with a numeric value before running the macro.", "SelectHelp": "Select 1 line, 2 points or a constraint in a sketch, " + "and a cell in a spreadsheet.", "SelectNothing": "Nothing valid is selected.\n" + "Select 1 line, 2 points or a constraint in a sketch in edit mode, " + "and a cell in a spreadsheet.", "SelectTooMany": "Too many objects selected.", "SelectSingleNotSupported": "This single object is not supported.\n" + "Select 1 line, 1 circle, 2 points or a constraint in a sketch, " + "and a cell in a spreadsheet.", "SelectTwoNotPoints": "2 objects are selected, but they are not 2 points.", "ActivateWindowTitle": "Activate window", "NoActiveDocument": "No active document.", "No3DView": "No 3D view opened for the active document.", "NoSketchInEdit": "No 3D view has a sketch in edit mode for the active document.", "NoObjectSelected": "You have not selected any objects in the active sketch." + "\nDoes this mean you want to automatically create aliases to the right of the selected cells" + "using the text of these selected cells?" + "\n\nUnless you wish to directly modify a property in the tree." + "\nIn that case, exit the Sketch editing mode.", "NoActiveSpreadsheet": "No spreadsheet open." + "\nOpen a spreadsheet and select the cell containing the value.", "ConstarintConflicDetected": "Constraints conflic detected. Cancel constraint creation?", "getConstraintTypeAliasToolTip": "If checked, alias will automatically be created during each macro execution." + "\nAlias will be built for the right cells from the text in this cell and under.", "getConstraintTypeOption1ButtonSetText": "Constrain &Horzontal Dist", "getConstraintTypeOption2ButtonSetText": "Constrain &Vertical Dist", "getConstraintTypeOption3ButtonSetText": "Constrain &Distance", "getConstraintTypeOption1ButtonSetTextToolTip": "Constrain Horzontal Distance", "getConstraintTypeOption2ButtonSetTextToolTip": "Constrain Vertical Distance", "getConstraintTypeOption3ButtonSetTextToolTip": "Constrain Distance", "getConstraintTypeCheckboxConflic": "Conflict detection", "getConstraintTypeCheckboxConflicToolTip": "Warning in case of constraint conflict. Gives the possibility to cancel the constraint.", "getConstraintTypeWindowTitle": "Choose a constraint type", "getConstraintTypeCheckboxAlias": "Texts for Automatic alias labels for this cell, and under :", "getConstraintTypeRadioGroupTitle": "Diameter in spreadsheet results in radius in sketch (value divided by 2)", "getConstraintTypeRadioGroupTooltip": "This option is useful when the known value is a diameter, but the sketch requires a " + "\nradius constraint—particularly relevant for revolved geometries.", "getConstraintTypeRadioRadius": "Yes (/ 2)", "getConstraintTypeRadioDiameter": "No (unchanged)", "PropNoneSelected": "No property of {obj} is selected in the property view." + "\n\nClick the property to link (ex: Length, or Placement > Position > x), " + "then run the macro again.", "PropHasSubItems": "{path} contains several values." + "\n\nExpand it and select a single value (ex: x, y or z).", "PropNotEditable": "{path} is not editable in this context (greyed property)." + "\n\nMake it editable before running the macro." + "\n(ex: for an attached sketch, use Attachment Offset instead of Placement)", "PropLinkFailed": "Unable to link {path} to {expr}:\n\n{error}", "PropAlreadyLinked": "{path} is already linked by the expression:\n\n {old}\n\nWhat do you want to do?", "PropAlreadyLinkedNoSheet": "{path} is linked by the expression:\n\n {old}" + "\n\nNo spreadsheet is open: the macro can only remove this link." + "\n\nTo link the property to another cell, or for the other features " + "of the macro, open a spreadsheet, select a cell " + "and run the macro again.", "PropReplaceLink": "&Replace by the selected cell", "PropRecomputeError": "FreeCAD detected an error after linking {path} to {expr}:" + "\n\n{errors}" + "\n\nGo back (put back {old})?", "PropRestoreFailed": "Unable to put back the previous value of {path}:\n\n{error}" + "\n\nUse Edit > Undo (Ctrl+Z).", "CellEmpty": "The cell {cell} is empty or contains an error." + "\n\nPut a value in it before linking it to {path}.", "CellTextForNumber": "The cell {cell} contains text ({value}), but {path} expects a number." + "\n\nLink refused.", "CellUnitMismatch": "The unit of the cell {cell} ({cellUnit}) does not match " + "the unit of {path} ({propertyUnit})." + "\n\nLink refused.", "CellTextForBool": "The cell {cell} contains text ({value}), but {path} is a check box: " + "it expects 0 (unchecked) or 1 (checked)." + "\n\nLink refused.", "CellEnumText": "The cell {cell} contains \"{value}\", which is not a possible choice for {path}." + "\n\nPossible choices (number : text):\n{choices}" + "\n\nLink refused.", "CellEnumIndex": "The cell {cell} contains {value}, which is not a choice number " + "for {path} (0 to {last})." + "\n\nPossible choices (number : text):\n{choices}" + "\n\nLink refused.", "PropRemoveLink": "Re&move the link", "PropBoolEnumWarning": "{path} is a check box or a list of choices." + "\n\nLinking it to a cell is STRONGLY DISCOURAGED:" + "\n - once linked, the check box or list in the property view has no effect " + "anymore, and gives no way to remove the link;" + "\n - if the cell is cleared or moved, the property stays locked;" + "\n - for a list, the cell gives the number of the choice (0 = first), " + "a number that may change with another FreeCAD version." + "\n\nTo remove the link later:" + "\n - run the macro again with this property selected: " + "it will offer to remove the link;" + "\n - or type in the Python console:\n {cmd}" + "\n\nLink anyway?", }, } # =============================================================================== # ini file : the only place where the ini file is read or written # sections : SettingNames, SettingsAlias, Conflict_detection # =============================================================================== def _iniRead(): config = configparser.ConfigParser() config.read(INI_FILE) # no error if the file does not exist yet return config def iniGet(section, key, default): return _iniRead().get(section, key, fallback=default) def iniGetBool(section, key, default): try: return _iniRead().getboolean(section, key, fallback=default) except ValueError: # value in the file is not a boolean return default def iniSet(values): # values : {section: {key: value, ...}, ...} Other settings in the file are kept. config = _iniRead() for section, items in values.items(): if not config.has_section(section): config.add_section(section) for key, value in items.items(): config.set(section, key, str(value)) with open(INI_FILE, "w") as configfile: config.write(configfile) # Read name given by user for object choiceObject (Spreadsheet, Body...) def getIniName(choiceObject): return iniGet("SettingNames", choiceObject, choiceObject) # Read starting cell for alias texts def getIniCellForAlias(): return iniGet("SettingsAlias", "textboxAlias", "A3") or "A3" # Read "automatic alias" checkbox state def getIniCheckboxStateForAlias(): return iniGetBool("SettingsAlias", "checkboxAlias", True) # Save starting cell for alias texts and "automatic alias" checkbox state def save_settings_Alias(cell, checked): iniSet({"SettingsAlias": {"textboxAlias": cell.upper(), "checkboxAlias": checked}}) def isSketchActif(): try: s = ActiveSketch return True except NameError: # ActiveSketch exists only when a sketch is in edit mode return False # To know if an freecad expression is valid # -------------------------------------------- def validate_expression(expression): try: result = eval(expression) return True # The expression is valid except Exception as e: return False # The expression is invalid # =============================================================================== # Property selected in the property view (ex : Placement > Position > x of a Pad) # selectedPropertyInPropertyView() and getPropertyValue() are shared with # SpreadsheetDependencyInspector.FCMacro : keep them identical in both macros. # # How it works (the property view has no Python API) : # - the rows of the property view are read with Qt (tree named "propertyEditorData") # - top rows are groups (Base, Attachment...), their children are the properties, # and below come the sub-items (Position, x...) # - the internal name of the property is read in its tooltip ("Name: Placement"), # because the displayed name is translated ("Axe de rotation" in French) # - sub-items have no tooltip : their displayed label is compared with the English # label translated by FreeCAD, so it works whatever the FreeCAD language # - the path found is checked on the object before being returned # =============================================================================== SelectedProperty = namedtuple( "SelectedProperty", "obj path name typeId value editable hasSubItems" ) # obj : object owning the property (Pad, Sketch...) # path : path for obj.setExpression(), same format as obj.ExpressionEngine # without the leading '.' (ex 'Placement.Rotation.Axis.x') # name : internal name of the property (ex 'Placement') # typeId : type of the property (ex 'App::PropertyPlacement') # value : current value, read on the object with the path # editable : the value is editable and not greyed in the property view # hasSubItems : the selected row has sub-items (ex Placement, Position) : link one of them # Sub-items whose internal path differs from the label shown by FreeCAD. # key : property type without 'App::Property' ; value : {English label : internal path} # Sub-items not listed (x, y, z, named constraints...) use their displayed label. PROPERTY_SUB_ITEMS = { "Placement": {"Position": "Base", "Axis": "Rotation.Axis", "Angle": "Rotation.Angle"}, "Rotation": {"Axis": "Axis", "Angle": "Angle"}, } def getPropertyValue(obj, path): # path : as in obj.ExpressionEngine, ex 'Length', '.Placement.Base.x', # 'Constraints[3]' or 'Constraints.myName' (a sketch constraint object is returned) # raise an exception (AttributeError, IndexError...) if the path does not exist value = obj for part in path.lstrip(".").split("."): match = re.fullmatch(r"(\w+)\[(\d+)\]", part) if match: # ex Constraints[3] value = getattr(value, match.group(1))[int(match.group(2))] elif isinstance(value, (list, tuple)): # ex Constraints.myName value = next(v for v in value if getattr(v, "Name", None) == part) else: value = getattr(value, part) return value def setPropertyValue(obj, path, value): # path : as for getPropertyValue, without constraints (ex 'Length', 'Placement.Base.x') # In Python, sub-values (obj.Placement, .Base...) are copies : the chain of copies is # modified from the end, then assigned back up to the object. parts = path.lstrip(".").split(".") chain = [obj] for part in parts[:-1]: chain.append(getattr(chain[-1], part)) setattr(chain[-1], parts[-1], value) for i in range(len(parts) - 1, 0, -1): setattr(chain[i - 1], parts[i - 1], chain[i]) def selectedPropertyInPropertyView(obj=None): # obj : object owning the property (default : the single object selected in the tree) # return a SelectedProperty, or None if no property of obj is selected def translated(label): # label as displayed by FreeCAD in the current language return QtGui.QApplication.translate("App::Property", label) def displayedName(name): # 'MapMode' -> 'Map Mode', as FreeCAD displays it return translated(re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", name)) def pathExists(path): try: getPropertyValue(obj, path) return True except Exception: # on purpose : AttributeError, IndexError, StopIteration... return False if obj is None: selection = Gui.Selection.getSelection() if len(selection) != 1: return None obj = selection[0] tree = Gui.getMainWindow().findChild(QtGui.QTreeView, "propertyEditorData") if tree is None: return None selected = [i for i in tree.selectedIndexes() if i.column() == 0] index = selected[0] if selected else tree.currentIndex().siblingAtColumn(0) rows = [] # from the top (group) down to the clicked row while index.isValid(): rows.insert(0, index) index = index.parent() if len(rows) < 2: # nothing or a group is selected return None propertyRow, subRows, clicked = rows[1], rows[2:], rows[-1] # internal name of the property : in the tooltip ("Type: ...\nName: Placement\n...") match = re.search(r"^Name: (\S+)$", propertyRow.data(QtCore.Qt.ToolTipRole) or "", re.M) name = match.group(1) if match else None if name not in obj.PropertiesList: # no name in the tooltip (older FreeCAD) : compare displayed names shown = propertyRow.data(QtCore.Qt.DisplayRole) or "" name = next((p for p in obj.PropertiesList if shown in (p, displayedName(p)) or shown.replace(" ", "") == p), None) if name is None: return None typeId = obj.getTypeIdOfProperty(name) # sub-items : English label translated by FreeCAD, else the displayed label path = name subLabels = PROPERTY_SUB_ITEMS.get(typeId.split("::Property")[-1], {}) for level, row in enumerate(subRows): shown = row.data(QtCore.Qt.DisplayRole) or "" candidates = [internal for label, internal in subLabels.items() if level == 0 and shown in (label, translated(label))] candidates += [shown, shown.replace(" ", "")] found = next((c for c in candidates if pathExists(path + "." + c)), None) if found is None: print("Property path not found :", obj.Name + "." + path + " > " + shown) return None path += "." + found if not pathExists(path): return None flags = clicked.siblingAtColumn(1).flags() return SelectedProperty( obj=obj, path=path, name=name, typeId=typeId, value=getPropertyValue(obj, path), editable=bool(flags & QtCore.Qt.ItemIsEditable) and bool(flags & QtCore.Qt.ItemIsEnabled), hasSubItems=tree.model().rowCount(clicked) > 0, ) ################################################################################# # part code for objects creation at the begining of the macro execution. # If there is no spreadsheet or sketch: ask for creation. ################################################################################# # =============================================================================== # dialog box class for objects creations # =============================================================================== class Dialog(QtGui.QDialog): def __init__( self, documentState, spreadsheetState, textdocumentState, bodyState, sketchState, text="", parent=None, ): super(Dialog, self).__init__(parent) ToolTip = messages[language]["DialogToolTip"] self.documentState = documentState self.textdocumentState = textdocumentState self.spreadsheetState = spreadsheetState self.bodyState = bodyState self.sketchState = sketchState self.text_widget = QtGui.QLabel(text) self.checkbox1Document = self.create_checkbox( messages[language]["DialogCheckbox1Document"], documentState ) self.checkboxTextDocument = self.create_checkbox( messages[language]["DialogCheckboxTextDocument"], textdocumentState ) self.checkboxSpreadsheet = self.create_checkbox( messages[language]["DialogCheckboxSpreadsheet"], spreadsheetState ) self.checkboxBody = self.create_checkbox( messages[language]["DialogcheckboxBody"], bodyState ) self.checkboxSketch = self.create_checkbox( messages[language]["DialogcheckboxSketch"], sketchState ) self.checkboxAlias = QtGui.QCheckBox(messages[language]["DialogCheckboxAlias"]) self.checkboxAlias.setToolTip(ToolTip) self.textboxSpreadsheetName = QtGui.QLineEdit( getIniName("Spreadsheet") ) self.textboxSpreadsheetName.setFixedWidth(200) # size self.textboxSpreadsheetName.setToolTip( messages[language]["DialogTextboxSpreadsheetNameTolLip"] ) self.textboxTextdocumentName = QtGui.QLineEdit( getIniName("Textdocument") ) self.textboxTextdocumentName.setFixedWidth(200) # size self.textboxTextdocumentName.setToolTip( messages[language]["DialogTextboxTextdocumentNameToolTip"] ) self.textboxBodyName = QtGui.QLineEdit(getIniName("Body")) self.textboxBodyName.setFixedWidth(200) # size self.textboxBodyName.setToolTip( messages[language]["DialogTextboxBodyNameToolTip"] ) self.textboxSketchName = QtGui.QLineEdit(getIniName("Sketch")) self.textboxSketchName.setMaximumWidth( 200 ) # Set the maximum width of the text box self.textboxSketchName.setFixedWidth(200) # size self.textboxSketchName.setToolTip( messages[language]["DialogTextboxSketchNameTolLip"] ) layout_checkbox1Document = QtGui.QHBoxLayout() if documentState != "no": layout_checkbox1Document.addWidget(self.checkbox1Document) layout_checkboxSpreadSheet = QtGui.QHBoxLayout() layout_checkboxSpreadSheet.addSpacing(20) if spreadsheetState != "no": layout_checkboxSpreadSheet.addWidget(self.checkboxSpreadsheet) layout_checkboxSpreadSheet.addWidget(self.textboxSpreadsheetName) layout_checkboxTextDocument = QtGui.QHBoxLayout() layout_checkboxTextDocument.addSpacing(20) if textdocumentState != "no": layout_checkboxTextDocument.addWidget(self.checkboxTextDocument) layout_checkboxTextDocument.addWidget(self.textboxTextdocumentName) layout_checkboxBody = QtGui.QHBoxLayout() layout_checkboxBody.addSpacing(20) if bodyState != "no": layout_checkboxBody.addWidget(self.checkboxBody) layout_checkboxBody.addWidget(self.textboxBodyName) layout_checkboxSketch = QtGui.QHBoxLayout() layout_checkboxSketch.addSpacing(40) if sketchState != "no": layout_checkboxSketch.addWidget(self.checkboxSketch) layout_checkboxSketch.addWidget(self.textboxSketchName) self.radiobutton1 = QtGui.QRadioButton(messages[language]["XYPlane"]) self.radiobutton2 = QtGui.QRadioButton(messages[language]["XZPlane"]) self.radiobutton3 = QtGui.QRadioButton(messages[language]["YZPlane"]) self.radiobutton1.setIcon(QIcon(":/icons/view-top")) self.radiobutton2.setIcon(QIcon(":/icons/view-front")) self.radiobutton3.setIcon(QIcon(":/icons/view-right")) # Set the XY Plane radio button to be checked by default self.radiobutton1.setChecked(True) self.textboxAlias = QtGui.QLineEdit(getIniCellForAlias()) self.textboxAlias.setMaximumWidth(50) # Set the maximum width of the text box self.textboxAlias.setMaxLength(4) # Limit the text box to 4 characters self.textboxAlias.setToolTip(ToolTip) regex = fcRegExp("^[a-zA-Z]+[0-9]+$") validator = fcRegExpValidator(regex, self) self.textboxAlias.setValidator(validator) self.textboxAlias.textChanged.connect(self.onTextChanged) # Set the checkboxes self.checkbox1Document.setChecked( documentState == "exist" or documentState == "on" ) self.checkboxTextDocument.setChecked(True) self.checkboxSpreadsheet.setChecked( spreadsheetState == "exist" or spreadsheetState == "on" ) self.checkboxBody.setChecked(bodyState == "exist" or bodyState == "on") self.checkboxSketch.setChecked(sketchState == "exist" or sketchState == "on") self.checkboxAlias.setChecked( getIniCheckboxStateForAlias() ) self.checkbox1Document.stateChanged.connect(self.update_document_checkbox) self.checkboxTextDocument.stateChanged.connect( self.update_textdocument_checkbox ) self.checkboxSpreadsheet.stateChanged.connect(self.update_spreadsheet_checkbox) self.checkboxBody.stateChanged.connect(self.update_body_checkbox) self.checkboxSketch.stateChanged.connect(self.update_sketch_checkbox) layout = QtGui.QVBoxLayout() if text != "": layout.addWidget(self.text_widget) layout.addLayout(layout_checkbox1Document) layout.addLayout(layout_checkboxSpreadSheet) layout.addLayout(layout_checkboxTextDocument) layout.addLayout(layout_checkboxBody) layout.addLayout(layout_checkboxSketch) layout_radio1 = QtGui.QHBoxLayout() layout_radio1.addSpacing(60) if sketchState != "no": layout_radio1.addWidget(self.radiobutton1) layout_radio2 = QtGui.QHBoxLayout() layout_radio2.addSpacing(60) if sketchState != "no": layout_radio2.addWidget(self.radiobutton2) layout_radio3 = QtGui.QHBoxLayout() layout_radio3.addSpacing(60) if sketchState != "no": layout_radio3.addWidget(self.radiobutton3) layout.addLayout(layout_radio1) layout.addLayout(layout_radio2) layout.addLayout(layout_radio3) layout_Alias = QtGui.QHBoxLayout() layout_Alias.addWidget(self.checkboxAlias) layout_Alias.addWidget(self.textboxAlias) layout_Alias.addItem( QtGui.QSpacerItem( 0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred ) ) layout.addLayout(layout_Alias) # Add OK and Cancel buttons self.buttons = QtGui.QDialogButtonBox( QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self, ) self.buttons.accepted.connect(self.accept) self.buttons.rejected.connect(self.reject) self.buttons.button(QtGui.QDialogButtonBox.Ok).setText( messages[language]["OkOui"] ) self.buttons.button(QtGui.QDialogButtonBox.Cancel).setText( messages[language]["Cancel"] ) layout.addWidget(self.buttons) self.setLayout(layout) self.update_document_checkbox() self.update_spreadsheet_checkbox() self.update_textdocument_checkbox() self.update_body_checkbox() self.update_sketch_checkbox() self.update_radiobuttons() def onTextChanged(self, text): # Convertir le texte en majuscules uppercase_text = text.upper() self.textboxAlias.blockSignals(True) self.textboxAlias.setText(uppercase_text) self.textboxAlias.blockSignals(False) def update_document_checkbox(self): self.checkboxTextDocument.setEnabled(self.checkbox1Document.isChecked()) if not self.checkbox1Document.isChecked(): self.checkboxTextDocument.setChecked(False) self.checkboxSpreadsheet.setEnabled(self.checkbox1Document.isChecked()) self.checkboxSpreadsheet.setChecked(self.checkbox1Document.isChecked()) self.checkboxTextDocument.setEnabled(self.checkbox1Document.isChecked()) self.checkboxTextDocument.setChecked(self.checkbox1Document.isChecked()) self.checkboxBody.setEnabled(self.checkbox1Document.isChecked()) self.checkboxBody.setChecked(self.checkbox1Document.isChecked()) self.update_textdocument_checkbox() self.update_spreadsheet_checkbox() self.update_body_checkbox() def update_textdocument_checkbox(self): if self.textdocumentState == "exist": self.checkboxTextDocument.setEnabled(False) self.checkboxTextDocument.setChecked(True) self.textboxTextdocumentName.setEnabled( self.checkboxTextDocument.isChecked() and self.checkboxTextDocument.isEnabled() ) def update_spreadsheet_checkbox(self): if self.spreadsheetState == "exist": self.checkboxSpreadsheet.setEnabled(False) self.checkboxSpreadsheet.setChecked(True) self.textboxSpreadsheetName.setEnabled( self.checkboxSpreadsheet.isChecked() and self.checkboxSpreadsheet.isEnabled() ) def update_body_checkbox(self): if self.bodyState == "exist": self.checkboxBody.setEnabled(False) self.checkboxBody.setChecked(True) self.textboxBodyName.setEnabled( self.checkboxBody.isChecked() and self.checkboxBody.isEnabled() ) self.checkboxSketch.setEnabled(self.checkboxBody.isChecked()) self.checkboxSketch.setChecked(self.checkboxBody.isChecked()) self.update_sketch_checkbox() def update_sketch_checkbox(self): if self.sketchState == "exist": self.checkboxSketch.setEnabled(False) self.checkboxSketch.setChecked(True) self.textboxSketchName.setEnabled( self.checkboxSketch.isChecked() and self.checkboxSketch.isEnabled() ) self.update_radiobuttons() def update_radiobuttons(self): enable = self.checkboxSketch.isChecked() and self.checkboxBody.isChecked() if not self.checkboxSketch.isChecked() or not self.checkboxBody.isChecked(): enable = False if not self.checkboxSketch.isChecked(): enable = False if not self.checkboxSketch.isEnabled(): enable = False self.radiobutton1.setEnabled(enable) self.radiobutton2.setEnabled(enable) self.radiobutton3.setEnabled(enable) def create_checkbox(self, text, state): # checkbox = QtGui.QCheckBox(text+' found' if state == "exist" else "No " + # text + " found, create one?") checkbox = QtGui.QCheckBox( text + " " + messages[language]["foundTrouve"] if state == "exist" else messages[language]["NoPasDe"] + " " + text + " " + messages[language]["foundCreateOne"] ) checkbox.setEnabled(state != "off") checkbox.setChecked(state != "off") if state == "exist": checkbox.setEnabled(False) checkbox.setChecked(True) return checkbox def save_settings(self): iniSet({ "SettingsAlias": { "textboxAlias": self.textboxAlias.text().upper(), "checkboxAlias": self.checkboxAlias.isChecked(), }, "SettingNames": { "Body": self.textboxBodyName.text(), "Spreadsheet": self.textboxSpreadsheetName.text(), "Textdocument": self.textboxTextdocumentName.text(), "Sketch": self.textboxSketchName.text(), }, }) # Retrieve the results after displaying the object creation dialogue box. ############################################################################### def get_user_input( documentState, spreadsheetState, textdocumentState, bodyState, sketchState, text="" ): dialog = Dialog( documentState, spreadsheetState, textdocumentState, bodyState, sketchState, text ) result = ( dialog.exec() ) # Display the dialog box and wait for the user to make their choices if result: dialog.save_settings() # Save the settings to the INI file # Return the state of the checkboxes and radio buttons, and the result of the dialog box return { "checkbox1Document": dialog.checkbox1Document.isChecked(), "checkboxSpreadsheet": dialog.checkboxSpreadsheet.isChecked(), "checkboxTextDocument": dialog.checkboxTextDocument.isChecked(), "checkboxBody": dialog.checkboxBody.isChecked(), "checkboxSketch": dialog.checkboxSketch.isChecked(), "radiobutton1": dialog.radiobutton1.isChecked(), "radiobutton2": dialog.radiobutton2.isChecked(), "radiobutton3": dialog.radiobutton3.isChecked(), "checkboxAlias": dialog.checkboxAlias.isChecked(), "textboxAlias": dialog.textboxAlias.text(), "textboxSpreadsheetName": dialog.textboxSpreadsheetName.text(), "textboxTextdocumentName": dialog.textboxTextdocumentName.text(), "textboxBodyName": dialog.textboxBodyName.text(), "textboxSketchName": dialog.textboxSketchName.text(), "result": ( "OK" if result == QtGui.QDialog.Accepted else "Cancel" if result == QtGui.QDialog.Rejected else "Closed" ), } # ========================================================= # Function that manages everything to add # necessary or desired objects. # ========================================================= def addTheObjects(): def firstObject(type, doc=App.ActiveDocument): if doc == None: return None for obj in doc.Objects: if obj.TypeId == type: return obj doc = Gui.ActiveDocument firstTextdocument = None firstSpreadsheet = None firstBody = None firstSketch = None if not doc: paramDocument = "on" paramTextdocument = "on" paramSpreadsheet = "on" paramBody = "on" paramSketch = "on" else: paramDocument = "exist" firstTextdocument = firstObject("App::TextDocument") if firstTextdocument != None: paramTextdocument = "exist" else: paramTextdocument = "off" firstSpreadsheet = firstObject("Spreadsheet::Sheet") if firstSpreadsheet != None: paramSpreadsheet = "exist" else: paramSpreadsheet = "on" firstBody = firstObject("PartDesign::Body") if firstBody != None: paramBody = "exist" else: paramBody = "on" firstSketch = firstObject("Sketcher::SketchObject") if firstSketch != None: paramSketch = "exist" else: paramSketch = "on" # The creation of the objects themselves. Return the object def createObjects(user_input): objCreate = False if user_input["checkbox1Document"] and not Gui.ActiveDocument: firstDocument = App.newDocument() objCreate = True if ( firstObject("Spreadsheet::Sheet") == None and user_input["checkboxSpreadsheet"] ): firstSpreadsheet = App.activeDocument().addObject( "Spreadsheet::Sheet", user_input["textboxSpreadsheetName"] ) # si la checkbox est cochée alors on ajoute les textes titres dans les cellules firstSpreadsheet.mergeCells("A1:B1") firstSpreadsheet.setAlignment("A1:B1", "center|vcenter|vimplied") firstSpreadsheet.setStyle("A1:B1", "bold") firstSpreadsheet.set("A1", messages[language]["TITLE"]) if getIniCellForAlias(): cellAbove, cellRight = get_adjacent_cells( getIniCellForAlias() ) if cellAbove != "" and cellAbove not in ["A1", "B1"]: firstSpreadsheet.set(cellAbove, messages[language]["Textsforalias"]) firstSpreadsheet.set(cellRight, messages[language]["Values"]) firstSpreadsheet.setStyle(cellAbove, "bold") firstSpreadsheet.setStyle(cellRight, "bold") firstSpreadsheet.recompute() Gui.ActiveDocument.getObject(firstSpreadsheet.Name).doubleClicked() objCreate = True if ( firstObject("App::TextDocument") == None and user_input["checkboxTextDocument"] ): firstTextdocument = App.activeDocument().addObject( "App::TextDocument", user_input["textboxTextdocumentName"] ) # Gui.ActiveDocument.getObject(firstTextdocument.Name).doubleClicked() objCreate = True if firstObject("PartDesign::Body") == None and user_input["checkboxBody"]: firstBody = App.activeDocument().addObject( "PartDesign::Body", user_input["textboxBodyName"] ) objCreate = True else: firstBody = firstObject("PartDesign::Body") if ( firstObject("Sketcher::SketchObject") == None and user_input["checkboxSketch"] ): if user_input["radiobutton1"]: sketchSupport = "XY_Plane" elif user_input["radiobutton2"]: sketchSupport = "XZ_Plane" elif user_input["radiobutton3"]: sketchSupport = "YZ_Plane" firstSketch = firstBody.newObject( "Sketcher::SketchObject", user_input["textboxSketchName"] ) if hasattr(firstSketch, "AttachmentSupport"): firstSketch.AttachmentSupport = ( App.ActiveDocument.getObject(sketchSupport), [""], ) else: firstSketch.Support = ( App.ActiveDocument.getObject(sketchSupport), [""], ) firstSketch.MapMode = "FlatFace" # Gui.ActiveDocument.getObject(firstSketch.Name).doubleClicked() Gui.runCommand("Std_TileWindows", 0) objCreate = True return objCreate # Use the function to display the dialog box and get the user's input if paramSpreadsheet != "exist" or paramSketch != "exist": user_input = get_user_input( paramDocument, paramSpreadsheet, paramTextdocument, paramBody, paramSketch ) if user_input["result"] == "OK": return createObjects(user_input) else: return True # To stop macro because canceled # end of def addTheObjects() ############################################################# ############################################################# # end part for objects creation at the begining. ############################################################## ############################################################## ################################################################################# # part code for alias ################################################################################# # parameters for alias creation separateur = " " # typically put " " so blanks will be replaced by nouveauCaract nouveauCaract = "" # Put for example "_" to have the separators replaced by "_". Put "" to have no separator majuscule = ( True # set to True if you want "Diametre du cercle" to be "DiametreDuCercle" ) changeTexteCellule = False # the text will only be changed if changeCellText is True. # This does not change anything for the allias itself premierCaractereEnMinuscule = False # Force the first character to be in lower case # list of characters to be replaced by an equivalent. for example an @ will be replaced by 'a' # if you add characters, please send me a private message. Il will eventually add it in my code. caracEquivalents = [ ["é", "e"], ["è", "e"], ["ê", "e"], ["à", "a"], ["@", "a"], ["&", "e"], ["ç", "c"], ["²", "2"], ["'", ""], ["?", ""], ['"', ""], ["(", ""], [")", ""], ["#", ""], [".", ""], [",", ""], [";", ""], ["$", ""], ["+", ""], ["-", ""], ["*", ""], ["/", ""], ["\\", ""], ["[", ""], ["]", ""], ] def traitementChaineSource(chaineSource, separateur, nouveauCaract, majuscule): # If separator is ' ' and nouveauCaract is '_', and majuscule is True # transforms "Diametre du cylindre" into "Diametre_Du_Cylindre def remplaceCararcDansMot(mot): def remplaceCartatParEquivalent(caractere): # replaces a character with its equivalent if it exists caracResult = caractere for couple in caracEquivalents: if couple[0] == caractere: caracResult = couple[1] break return caracResult # replaces all characters of the word with its equivalent if it exists motResult = mot for caract in mot: a = remplaceCartatParEquivalent(caract) motResult = motResult.replace(caract, a) return motResult chaineResult = "" first = True carctDeSeparation = "" for mots in chaineSource.split(separateur): mots = remplaceCararcDansMot(mots) if not (first): carctDeSeparation = nouveauCaract if majuscule: chaineResult = chaineResult + carctDeSeparation + mots[:1].upper() + mots[1:] # We use "[:1]" instead of "[0]", # for no crash in case of an empty string (which happens if the cell is empty) else: chaineResult = chaineResult + carctDeSeparation + mots first = False if premierCaractereEnMinuscule: chaineResult = chaineResult[:1].lower() + chaineResult[1:] return chaineResult def get_adjacent_cells(cell): # Use a regular expression to separate the letters and numbers match = re.match(r"([a-z]+)([0-9]+)", cell, re.I) if match: items = match.groups() else: return None, None # Retrieve the letter and number of the cell letter = items[0].upper() number = int(items[1]) # If the cell is in the first row, return an empty string if number == 1: return "", "" # Calculate the cell above above = letter + str(number - 1) # Calculate the cell above to the right right = nextCell(above) return above, right def get_column(cell): column = "".join([c for c in cell if not c.isdigit()]) return column def get_row(cell): row = "".join([c for c in cell if c.isdigit()]) if row == "": row = "1" return int(row) def nextCell(cell): colonne, ligne = re.match(r"([A-Z]+)([0-9]+)", cell).groups() num = 0 for c in colonne: num = num * 26 + ord(c) - ord("A") + 1 num += 1 colonne_suivante = "" while num > 0: num, reste = divmod(num - 1, 26) colonne_suivante = chr(65 + reste) + colonne_suivante return colonne_suivante + ligne ########################################## # Spreadsheet view to use (its sheet and its selected cells) : # - the active view if it is a spreadsheet # - else (ex : the sketch has the focus) the spreadsheet of the active document # that had the focus most recently # - None if no spreadsheet is open ########################################## def findSpreadsheetView(): doc = Gui.ActiveDocument if doc is None: return None if hasattr(doc.ActiveView, "getSheet"): # the active view is a spreadsheet return doc.ActiveView sheetViews = doc.mdiViewsOfType("SpreadsheetGui::SheetView") if len(sheetViews) <= 1: return sheetViews[0] if sheetViews else None # several spreadsheets : the one whose window had the focus most recently mdiArea = Gui.getMainWindow().centralWidget() try: order = QtGui.QMdiArea.WindowOrder.ActivationHistoryOrder # Qt6 except AttributeError: order = QtGui.QMdiArea.ActivationHistoryOrder # Qt5 for win in reversed(mdiArea.subWindowList(order)): # most recent first titleParts = [p.strip() for p in win.windowTitle().replace("[*]", "").split(" : ")] for view in sheetViews: if view.getSheet().Label in titleParts: return view return sheetViews[0] def setAlias(aliasCellsSelect, aliasAuto, sheetView=None): # sheetView : spreadsheet view to use, found by findSpreadsheetView() if not given # If the user wants to trigger the creation of alias # it is sufficient that he does not select any objects in the Sketch # but select cells containing strings in the left hand column # of where he want the alias to be created # so test if an object is selected : # result : False if macro can continue. if sheetView is None: sheetView = findSpreadsheetView() if sheetView is None: # no spreadsheet open QtGui.QMessageBox.warning( Gui.getMainWindow(), messages[language]["Warning"], messages[language]["NoActiveSpreadsheet"], ) return True mySpreadsheet = sheetView.getSheet() # To get list of all selected cells sel_items = sheetView.selectedCells() # sel_items est un tableau sous la forme ['C4', 'C5', 'C6', 'C7', 'D6', 'D7', 'E4', 'E5', 'E6', 'E7'] tabCells = [] if aliasAuto: sellStart = getIniCellForAlias() columnTextAlias = get_column(sellStart) rowStartAlias = get_row(sellStart) try: # only non-empty cells of the alias column, from the starting row tabCells = sorted( (c for c in mySpreadsheet.getNonEmptyCells() if get_column(c) == columnTextAlias and get_row(c) >= rowStartAlias), key=get_row, ) except AttributeError: # old FreeCAD without getNonEmptyCells() for i in range(rowStartAlias, 20000): tabCells.append(columnTextAlias + format(i)) if aliasCellsSelect: tabCells = sel_items changed = False for cell in tabCells: # The selected cells are scanned next_cell = nextCell(cell) # cell at the right activeCellContenu = mySpreadsheet.getContents(cell) # processing the character string contained in the cell activeCellContenu = traitementChaineSource( activeCellContenu, separateur, nouveauCaract, majuscule ) if ( changeTexteCellule ): # if the changeCellText parameter is set to True then we replace the text in the cell mySpreadsheet.set(cell, activeCellContenu) alias = activeCellContenu try: # Bloc try to recover errors if alias != "": mySpreadsheet.setAlias( next_cell, alias ) # The alias is assigned to the right-hand neighbouring cell changed = True except ( ValueError ): # If a "ValueError" is triggered (which happens when the alias is not valid) # The user is warned in the report App.Console.PrintWarning( "Can't set alias for cell {} : {} isn't valid\n".format( next_cell, alias ) ) return False ################################################################################# # End part code for alias ################################################################################# # ======================================================= # Dialog box # Ask user which sort of constraint is required # ======================================================= class getConstraintType(QtGui.QDialog): def __init__(self, widgetToFocus=None): super(getConstraintType, self).__init__() self.widgetToFocus = widgetToFocus self.initUI() def initUI(self): ToolTip = messages[language]["getConstraintTypeAliasToolTip"] # main layout layout = QtGui.QVBoxLayout(self) self.setWindowIcon(QtGui.QIcon("dialog_icon.png")) option1Button = QtGui.QPushButton( QtGui.QIcon(":/icons/constraints/Constraint_HorizontalDistance.svg"), "" ) option2Button = QtGui.QPushButton( QtGui.QIcon(":/icons/constraints/Constraint_VerticalDistance.svg"), "" ) option3Button = QtGui.QPushButton( QtGui.QIcon(":/icons/constraints/Constraint_Length.svg"), "" ) option1Button.setText( messages[language]["getConstraintTypeOption1ButtonSetText"] ) option2Button.setText( messages[language]["getConstraintTypeOption2ButtonSetText"] ) option3Button.setText( messages[language]["getConstraintTypeOption3ButtonSetText"] ) option1Button.setToolTip( messages[language]["getConstraintTypeOption1ButtonSetTextToolTip"] ) option2Button.setToolTip( messages[language]["getConstraintTypeOption2ButtonSetTextToolTip"] ) option3Button.setToolTip( messages[language]["getConstraintTypeOption3ButtonSetTextToolTip"] ) option1Button.clicked.connect(self.onOption1) option2Button.clicked.connect(self.onOption2) option3Button.clicked.connect(self.onOption3) option4Button = QtGui.QPushButton( QtGui.QIcon(":/icons/application-exit.svg"), messages[language]["Cancel"] ) option4Button.clicked.connect(self.onOption4) constraintsLayoutBox = QtGui.QGroupBox( messages[language]["getConstraintTypeWindowTitle"] ) constraintsLayout = QtGui.QGridLayout() constraintsLayout.addWidget(option1Button, 0, 0) constraintsLayout.addWidget(option2Button, 0, 1) constraintsLayout.addWidget(option3Button, 1, 0) constraintsLayout.addWidget(option4Button, 1, 1) constraintsLayoutBox.setLayout(constraintsLayout) layout.addWidget(constraintsLayoutBox) self.textboxAlias = QtGui.QLineEdit(getIniCellForAlias()) self.textboxAlias.setMaximumWidth(50) # Set the maximum width of the text box self.textboxAlias.setMaxLength(4) # Limit the text box to 4 characters self.textboxAlias.setToolTip(ToolTip) self.setGeometry(250, 250, 0, 50) self.setWindowTitle(messages[language]["getConstraintTypeWindowTitle"]) self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) self.choiceConstraint = "" option1Button.setFocusPolicy(QtCore.Qt.NoFocus) option2Button.setFocusPolicy(QtCore.Qt.NoFocus) option3Button.setFocusPolicy(QtCore.Qt.NoFocus) option4Button.setFocusPolicy(QtCore.Qt.NoFocus) # set focus to specified widget if self.widgetToFocus == "DistanceX": option1Button.setFocus() elif self.widgetToFocus == "DistanceY": option2Button.setFocus() elif self.widgetToFocus == "Distance": option3Button.setFocus() # Add checkbox self.checkboxConflic = QtGui.QCheckBox( messages[language]["getConstraintTypeCheckboxConflic"] ) self.checkboxConflic.setToolTip( messages[language]["getConstraintTypeCheckboxConflicToolTip"] ) self.checkboxConflic.setChecked(True) self.checkboxConflic.clicked.connect(self.onOptionCheckBox) self.checkboxAlias = QtGui.QCheckBox( messages[language]["getConstraintTypeCheckboxAlias"] ) self.checkboxAlias.setToolTip(ToolTip) # Only letter in textboxAlias regex = fcRegExp("^[a-zA-Z]+[0-9]+$") validator = fcRegExpValidator(regex, self) self.textboxAlias.setValidator(validator) self.textboxAlias.textChanged.connect(self.onTextChanged) self.checkboxAlias.setChecked(getIniCheckboxStateForAlias()) restOfLayoutGroupBox = QtGui.QGroupBox( messages[language]["getConstraintTypeCheckboxConflic"] + messages[language]["andAlias"] ) restOfLayout = QtGui.QGridLayout() restOfLayout.addWidget(self.checkboxConflic, 0, 0) restOfLayout.addWidget(self.checkboxAlias, 1, 0) restOfLayout.addWidget(self.textboxAlias, 1, 1) restOfLayoutGroupBox.setLayout(restOfLayout) layout.addWidget(restOfLayoutGroupBox) # Groupe de sélection Rayon / Diamètre self.radioGroupBox = QtGui.QGroupBox(messages[language]["getConstraintTypeRadioGroupTitle"]) self.radioGroupBox.setToolTip(messages[language]["getConstraintTypeRadioGroupTooltip"]) self.radioButtonRadius = QtGui.QRadioButton(messages[language]["getConstraintTypeRadioRadius"]) self.radioButtonDiameter = QtGui.QRadioButton(messages[language]["getConstraintTypeRadioDiameter"]) # Valeur par défaut : Diameter self.radioButtonDiameter.setChecked(True) # Layout horizontal pour les boutons radio radioLayout = QtGui.QHBoxLayout() radioLayout.addWidget(self.radioButtonRadius) radioLayout.addWidget(self.radioButtonDiameter) self.radioGroupBox.setLayout(radioLayout) layout.addWidget(self.radioGroupBox) # read ini file to know last time state self.checkboxConflic.setChecked( iniGetBool("Conflict_detection", "save_checkbox_state", True) ) # window positioning centerPoint = QGuiApplication.screens()[0].geometry().center() self.move(centerPoint - self.frameGeometry().center()) def onTextChanged(self, text): # Convertir le texte en majuscules uppercase_text = text.upper() self.textboxAlias.blockSignals(True) self.textboxAlias.setText(uppercase_text) self.textboxAlias.blockSignals(False) def onOption1(self): self.choiceConstraint = "DistanceX" self.save_settings() self.close() def onOption2(self): self.choiceConstraint = "DistanceY" self.save_settings() self.close() def onOption3(self): self.choiceConstraint = "Distance" self.save_settings() self.close() def onOption4(self): self.choiceConstraint = "Cancel" self.close() def onOptionCheckBox(self): # Save checkbox state to file iniSet({"Conflict_detection": {"save_checkbox_state": int(self.getCheckBoxState())}}) def save_settings(self): save_settings_Alias(self.textboxAlias.text(), self.checkboxAlias.isChecked()) def getCheckBoxState(self): return self.checkboxConflic.isChecked() def getRadiusOrDiameter(self): return "Radius" if self.radioButtonRadius.isChecked() else "Diameter" # ======================================================= # Give the focus to editing Sketch window # no parameter # use : activateSketchEditingWindow() # ======================================================= def activateSketchEditingWindow(): def searchForNode(tree, childName, maxLevel=0): return recursiveSearchForNode(tree, childName, maxLevel, 1) def recursiveSearchForNode(tree, childName, maxLevel, currentLevel): try: if tree.getByName(childName): return True elif maxLevel > 0 and currentLevel >= maxLevel: return False else: for child in tree.getChildren(): if recursiveSearchForNode( child, childName, maxLevel, currentLevel + 1 ): return True except Exception: # on purpose : best effort on any kind of scene graph node pass return False # Gui.activateWorkbench("SketcherWorkbench")#################################### doc = Gui.ActiveDocument if not doc: QtGui.QMessageBox.information( Gui.getMainWindow(), messages[language]["ActivateWindowTitle"], messages[language]["NoActiveDocument"], ) return views = Gui.ActiveDocument.mdiViewsOfType("Gui::View3DInventor") if not views: QtGui.QMessageBox.information( Gui.getMainWindow(), messages[language]["ActivateWindowTitle"], messages[language]["No3DView"], ) return editView = None for view in views: if searchForNode(view.getSceneGraph(), "Sketch_EditRoot", 3): editView = view break if not editView: QtGui.QMessageBox.information( Gui.getMainWindow(), messages[language]["ActivateWindowTitle"], messages[language]["NoSketchInEdit"], ) return for win in Gui.getMainWindow().centralWidget().subWindowList(): if editView.graphicsView() in win.findChildren(QtGui.QGraphicsView): Gui.getMainWindow().centralWidget().setActiveSubWindow(win) break ###################################################################################### # Helpers for featuresObjSelected ###################################################################################### CIRCLE_TYPES = ("Part::GeomCircle", "Part::GeomArcOfCircle") # 'Edge12' -> ('Edge', 12) 'ExternalEdge3' -> ('ExternalEdge', 3) def splitName(name): letters, digits = ["".join(c) for _, c in itertools.groupby(name, str.isalpha)] return letters, int(digits) # Geometry of the active sketch (geoIndex >= 0) # or external geometry from another sketch (geoIndex <= -3, Sketcher convention) def geometryOf(mySketch, geoIndex, tabExternalGeometry): if geoIndex >= 0: return mySketch.Geometry[geoIndex] externalSketchName, externalGeometryName = tabExternalGeometry[-geoIndex - 3] numExtGeometry = splitName(externalGeometryName)[1] return App.ActiveDocument.getObject(externalSketchName).Geometry[numExtGeometry - 1] # Coordinates of the start (1), end (2) or center (3) of a geometry. # A point has only one position. (0, 0) if the geometry has no such position. def pointOf(geo, pos): if geo.TypeId == "Part::GeomPoint": return geo.X, geo.Y attribute = {1: "StartPoint", 2: "EndPoint", 3: "Center"}.get(pos) if attribute and hasattr(geo, attribute): point = getattr(geo, attribute) return point.x, point.y return 0, 0 ###################################################################################### # to get necessary values for the constraint # Parameters : # sel : selection of objects (a line, 2 points..). # numOrdreObjSelected if we want the first object selected or the second. # indexExtremite if we want the start point (1) or the end point (2), if exist, of the sel # return features of a point # - typeIdGeometry : Part::GeomLineSegment .... # - typeInSubElementName : Edge, vertex ... # - indexObjectHavingPoint index of the object having the point (line...) # - indexExtremiteLine index of the ends (points) of the line (= start point or end point) # - x, y : coordinates of the point # - isInternalObject : True if the object is on the active sketch ##################################################################################### def featuresObjSelected(mySketch, sel, numOrdreObjSelected, indexExtremite): nbSelected = len(sel.SubElementNames) itemName = sel.SubElementNames[numOrdreObjSelected] # ex Edge5 ( line) # to get something like # [('Sketch', 'Edge2'), ('Sketch001', 'Edge2'), ('Sketch001', 'Edge1'), ('Sketch', 'Edge1')] tabExternalGeometry = [ (item[0].Name, objName) for item in mySketch.ExternalGeometry for objName in item[1] ] if itemName in ["V_Axis", "H_Axis", "RootPoint"]: # Axes and origin are all handled as the origin point (-1, 1): # a DistanceX from the origin is the same as a distance from V_Axis, # a DistanceY from the origin is the same as a distance from H_Axis. return "Part::GeomPoint", itemName, -1, 1, 0, 0, True typeInSubElementName, numInName = splitName(itemName) typeIdGeometry = None indexObjectHavingPoint = -10 indexExtremiteLine = 1 x, y = 0, 0 isInternalObject = True if typeInSubElementName == "Edge": # line, circle... of the active sketch geoIndex = numInName - 1 geo = mySketch.Geometry[geoIndex] typeIdGeometry = geo.TypeId if nbSelected == 1: # the whole line (or circle) indexObjectHavingPoint = geoIndex indexExtremiteLine = indexExtremite if typeIdGeometry == "Part::GeomLineSegment": x, y = pointOf(geo, indexExtremite) elif typeIdGeometry in CIRCLE_TYPES: # circle + point : the center of the circle indexObjectHavingPoint = geoIndex indexExtremiteLine = 3 # 3 for center x, y = pointOf(geo, 3) elif typeInSubElementName == "ExternalEdge": # line, circle... of another sketch isInternalObject = False indexObjectHavingPoint = -numInName - 2 indexExtremiteLine = indexExtremite geo = geometryOf(mySketch, indexObjectHavingPoint, tabExternalGeometry) typeIdGeometry = geo.TypeId if typeIdGeometry in CIRCLE_TYPES: indexExtremiteLine = 3 # 3 for center x, y = pointOf(geo, 3) elif typeIdGeometry == "Part::GeomLineSegment" and nbSelected == 1: x, y = pointOf(geo, indexExtremite) elif typeInSubElementName == "Vertex": # a point, internal or external indexObjectHavingPoint, indexExtremiteLine = sel.Object.getGeoVertexIndex( numInName - 1 ) isInternalObject = indexObjectHavingPoint >= 0 geo = geometryOf(mySketch, indexObjectHavingPoint, tabExternalGeometry) typeIdGeometry = geo.TypeId x, y = pointOf(geo, indexExtremiteLine) elif typeInSubElementName == "Constraint" and nbSelected == 1: indexObjectHavingPoint = numInName - 1 # index of the constraint typeIdGeometry = "Constraint" return ( typeIdGeometry, typeInSubElementName, indexObjectHavingPoint, indexExtremiteLine, x, y, isInternalObject, ) # Features of a selected point, same order as the result of featuresObjSelected Feature = namedtuple( "Feature", ["typeIdGeometry", "typeName", "index", "extremite", "x", "y", "isInternal"] ) POINT_NAMES = ("Vertex", "V_Axis", "H_Axis", "RootPoint", "ExternalEdge") ###################################################################################### # Analyse the selection in the sketch in edit mode # Valid selections : 1 line, 1 circle (or its center), 1 constraint, # 2 points, 1 circle + 1 point # return (p1, p2, indexConstraint, error) # - p1, p2 : Feature of the 2 points (p2 is None for a circle or a constraint) # for a line : its start point and its end point # - indexConstraint : index of the selected constraint, -1 if none # - error : message to show if the selection is not valid, else None ###################################################################################### def analyse_selection(mySketch, sels): msg = messages[language] if len(sels) == 0 or len(sels[0].SubElementNames) == 0: return None, None, -1, msg["SelectNothing"] sel = sels[0] nbSelected = len(sel.SubElementNames) if nbSelected > 2: return None, None, -1, msg["SelectTooMany"] + "\n" + msg["SelectHelp"] p1 = Feature(*featuresObjSelected(mySketch, sel, 0, 1)) p2 = None indexConstraint = -1 if nbSelected == 1: if p1.typeName == "Constraint": indexConstraint = p1.index elif p1.typeIdGeometry == "Part::GeomLineSegment" and p1.typeName in ("Edge", "ExternalEdge"): # a whole line (a single vertex of a line is not enough) : p2 = end point p2 = Feature(*featuresObjSelected(mySketch, sel, 0, 2)) elif p1.typeIdGeometry not in CIRCLE_TYPES: # a single vertex (of a line, of an ellipse...), axis, ellipse... : no constraint possible # (a circle, or only its center, is accepted on purpose: it gives a Diameter/Radius constraint) return p1, None, -1, msg["SelectSingleNotSupported"] else: p2 = Feature(*featuresObjSelected(mySketch, sel, 1, 1)) circleAndPoint = p1.typeIdGeometry in CIRCLE_TYPES and p1.typeName == "Edge" if (p1.typeName not in POINT_NAMES or p2.typeName not in POINT_NAMES) and not circleAndPoint: return p1, p2, -1, msg["SelectTwoNotPoints"] + "\n" + msg["SelectHelp"] return p1, p2, indexConstraint, None # Button having the focus in the dialog box : # DistanceX if the two points are more horizontal than vertical def defaultConstraintButton(p1, p2): return "DistanceX" if abs(p1.x - p2.x) > abs(p1.y - p2.y) else "DistanceY" # With an axis, no choice : DistanceX from V_Axis, DistanceY from H_Axis. None otherwise def forcedConstraint(p1, p2): if "V_Axis" in (p1.typeName, p2.typeName): return "DistanceX" if "H_Axis" in (p1.typeName, p2.typeName): return "DistanceY" return None # For DistanceX (DistanceY), the first point must be the one on the left (bottom) def orderPoints(myConstraint, p1, p2): if (myConstraint == "DistanceX" and p1.x > p2.x) or ( myConstraint == "DistanceY" and p1.y > p2.y): return p2, p1 return p1, p2 ########################################## # function returning selected objects at GUI level # = Sketch, SpreadSheet .... # parameter : # '' = no filter # 'Spreadsheet::Sheet' for spreadsheets only # 'Sketcher::SketchObject' for sketches etc... # output: an array of sketch objects, spreadsheets etc. ########################################## def getGuiObjsSelect(type=""): tabGObjSelect = [] selections = Gui.Selection.getCompleteSelection() for sel in selections: if hasattr(sel, "Object"): # depend freecad version if type == "" or sel.Object.TypeId == type: tabGObjSelect.append(sel.Object) else: obj = App.ActiveDocument.getObject(sel.Name) if type == "" or obj.TypeId == type: tabGObjSelect.append(obj) return tabGObjSelect ########################################## # Build the expression linking a constraint or a property to a cell # Parameters : # - spreadsheetLabel : label of the spreadsheet (ex 'datas') # - cellCode : address of the cell (ex 'C2') # - cellAlias : alias of the cell, or None # - divideBy2 : True for the option "diameter in spreadsheet gives a radius in sketch" # return : # - cellExpression : ex '<>.C2', '<>.longueur', '<>.L_f__mul_2*2' # - isRadius : True if the alias starts with 'radius' or 'rayon' # (a circle then gets a Radius constraint instead of a Diameter constraint) ########################################## def build_expression(spreadsheetLabel, cellCode, cellAlias, divideBy2): isRadius = False if cellAlias is None: cellExpression = "<<" + spreadsheetLabel + ">>." + cellCode else: cellExpression = "<<" + spreadsheetLabel + ">>." + cellAlias if formulaSeparator in cellAlias: # formula after the separator, with key words of dicoFormula # ex : alias 'radius_f__mul_2_plu_1' gives '<>.radius_f__mul_2_plu_1*2+1' formula = cellAlias.split(formulaSeparator, 1)[1].lower() for word, remplacement in dicoFormula.items(): formula = formula.replace(word.lower(), remplacement) if validate_expression('0' + formula): cellExpression = cellExpression + formula else: print('There is an error in the formula', formula) elif any(cellAlias.lower().startswith(word) for word in ("rayon", "radius")): isRadius = True if divideBy2: cellExpression = f"({cellExpression})/2" return cellExpression, isRadius ########################################## # Property mode, step 1 : at the start of the macro, before the spreadsheet is needed, # so that an existing link can be removed even when no spreadsheet is open. # Checks the property selected in the property view, and if it is already linked, # offers to replace the link (only if a spreadsheet is open), to remove it, or to cancel. # Parameters : # - obj : object owning the property (Pad, Pocket...) # - spreadsheetOpen : a spreadsheet is open (its selected cell can be used) # return : the SelectedProperty to link, or None if the macro must stop # (property refused, link removed, or cancelled) ########################################## def prepare_property_link(obj, spreadsheetOpen): msg = messages[language] selected = selectedPropertyInPropertyView(obj) if selected is None: showWarning(msg["PropNoneSelected"].format(obj=obj.Label)) return None fullPath = obj.Label + "." + selected.path if selected.hasSubItems: showWarning(msg["PropHasSubItems"].format(path=fullPath)) return None if not selected.editable: # greyed / read only, whatever its type showWarning(msg["PropNotEditable"].format(path=fullPath)) return None oldExpression = propertyExpression(selected) if oldExpression is None: return selected if spreadsheetOpen: action = askLinkAction(msg["PropAlreadyLinked"].format(path=fullPath, old=oldExpression), allowReplace=True) else: action = askLinkAction(msg["PropAlreadyLinkedNoSheet"].format(path=fullPath, old=oldExpression), allowReplace=False) if action == "remove": obj.setExpression(selected.path, None) print("Link removed:", fullPath) return None return selected if action == "replace" else None # Expression already set on the selected property, or None def propertyExpression(selected): return next((e for p, e in selected.obj.ExpressionEngine if p.lstrip(".") == selected.path), None) ########################################## # Is the cell value compatible with the property ? # Parameters : # - selected : SelectedProperty # - cellValue : mySpreadsheet.get(cell) : number, Quantity, text, or None (empty cell / error) # - cellName : ex 'datas.C2', for the messages # return : None if compatible, else the message explaining the refusal # Only clear incompatibilities are refused. Other property types (text, links...) # are left to FreeCAD, which refuses the expression if needed. ########################################## def cellCompatibilityError(selected, cellValue, cellName): msg = messages[language] path = selected.obj.Label + "." + selected.path value = selected.value cellIsText = isinstance(cellValue, str) cellIsNumber = isinstance(cellValue, (int, float)) or hasattr(cellValue, "Unit") def unitType(quantity): # 'Length', 'Angle'... or '' if no unit unit = getattr(quantity, "Unit", None) if unit is None or unit == App.Units.Unit(): return "" return getattr(unit, "Type", "") or str(unit) if cellValue is None: return msg["CellEmpty"].format(cell=cellName, path=path) # enumeration (ex Type of a Pad) : a text among the choices, or the number of a choice if selected.typeId.startswith("App::PropertyEnumeration"): try: choices = list(selected.obj.getEnumerationsOfProperty(selected.name)) except Exception: # on purpose : old FreeCAD without getEnumerationsOfProperty return None choicesText = "\n".join(" {} : {}".format(i, c) for i, c in enumerate(choices)) if cellIsText and cellValue not in choices: return msg["CellEnumText"].format(cell=cellName, value=cellValue, path=path, choices=choicesText) if cellIsNumber: number = float(getattr(cellValue, "Value", cellValue)) if number != int(number) or not 0 <= number < len(choices): return msg["CellEnumIndex"].format(cell=cellName, value=cellValue, path=path, last=len(choices) - 1, choices=choicesText) return None # boolean : 0 (unchecked) or 1 (checked) if selected.typeId.startswith("App::PropertyBool") or isinstance(value, bool): if not cellIsNumber: return msg["CellTextForBool"].format(cell=cellName, value=cellValue, path=path) return None # number (Length, x, Angle...) : no text, and the same kind of unit if isinstance(value, (int, float)) or hasattr(value, "Unit"): if not cellIsNumber: return msg["CellTextForNumber"].format(cell=cellName, value=cellValue, path=path) cellUnit, propertyUnit = unitType(cellValue), unitType(value) if cellUnit and propertyUnit and cellUnit != propertyUnit: return msg["CellUnitMismatch"].format(cell=cellName, cellUnit=cellUnit, path=path, propertyUnit=propertyUnit) return None ########################################## # Property mode, step 2 : link the property to the cell expression. # Parameters : # - selected : result of prepare_property_link() # - cellExpression : ex '<>.longueur' # - cellValue : value of the cell (mySpreadsheet.get()), None if empty or error # - cellName : ex 'datas.C2', for the messages # return : True if the property has been linked ########################################## def apply_to_property(selected, cellExpression, cellValue, cellName): msg = messages[language] obj = selected.obj fullPath = obj.Label + "." + selected.path error = cellCompatibilityError(selected, cellValue, cellName) if error: showWarning(error) return False # Booleans and enumerations (ex Type of a Pad) : strongly discouraged. Once linked, their # check box or list in the property view has no effect and gives no way to remove the link. # (numeric properties keep an expression editor (f(x)) in which the link can be removed) # No warning if the link is replaced : the user already knows. if (propertyExpression(selected) is None and (selected.typeId.startswith(("App::PropertyBool", "App::PropertyEnumeration")) or isinstance(selected.value, bool))): unlinkCommand = "App.getDocument('{}').getObject('{}').setExpression('{}', None)".format( obj.Document.Name, obj.Name, selected.path) if not askYesNo(msg["PropBoolEnumWarning"].format(path=fullPath, cmd=unlinkCommand)): return False # link, recompute, and offer to go back if FreeCAD detects a new error doc = obj.Document oldExpression = propertyExpression(selected) invalidBefore = {o.Name for o in doc.Objects if not o.isValid()} doc.openTransaction("Link " + fullPath) # Ctrl+Z also cancels the link try: obj.setExpression(selected.path, cellExpression) except Exception as e: # on purpose : RuntimeError, ParserError, AttributeError... doc.abortTransaction() showWarning(msg["PropLinkFailed"].format(path=fullPath, expr=cellExpression, error=e)) return False doc.recompute() errors = ["{} : {}".format(o.Label, o.getStatusString()) for o in doc.Objects if not o.isValid() and o.Name not in invalidBefore] if errors: if oldExpression is not None: previous = oldExpression else: previous = getattr(selected.value, "UserString", selected.value) if askYesNo(msg["PropRecomputeError"].format(path=fullPath, expr=cellExpression, errors="\n".join(errors), old=previous), defaultYes=True): doc.abortTransaction() restoreProperty(selected, oldExpression) doc.recompute() print("Link cancelled:", fullPath) return False doc.commitTransaction() print("Property linked:", fullPath, "=", cellExpression) return True ########################################## # Put back the expression (or the value if there was no expression) of the property, # as it was before the macro linked it. # The transaction has already been aborted : this makes sure the property is restored. ########################################## def restoreProperty(selected, oldExpression): try: selected.obj.setExpression(selected.path, oldExpression) # None removes the expression if oldExpression is None: setPropertyValue(selected.obj, selected.path, selected.value) except Exception as e: # on purpose : the restore must never crash the macro showWarning(messages[language]["PropRestoreFailed"].format( path=selected.obj.Label + "." + selected.path, error=e)) # Dialog boxes used when linking the constraint (replaced by stubs in tests) def askOkCancel(message): return QtGui.QMessageBox.warning( Gui.getMainWindow(), messages[language]["Warning"], message, QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, ) == QtGui.QMessageBox.Ok def askYesNo(message, defaultYes=False): # "No" by default return QtGui.QMessageBox.question( None, "", message, QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.Yes if defaultYes else QtGui.QMessageBox.No, ) == QtGui.QMessageBox.Yes def showWarning(message): QtGui.QMessageBox.warning(Gui.getMainWindow(), messages[language]["Warning"], message) def askLinkAction(message, allowReplace=True): # property already linked : return "replace", "remove" or "cancel" ("cancel" by default) # allowReplace : show the "replace by the selected cell" button box = QtGui.QMessageBox(Gui.getMainWindow()) box.setIcon(QtGui.QMessageBox.Question) box.setWindowTitle(messages[language]["Warning"]) box.setText(message) replaceButton = None if allowReplace: replaceButton = box.addButton(messages[language]["PropReplaceLink"], QtGui.QMessageBox.AcceptRole) removeButton = box.addButton(messages[language]["PropRemoveLink"], QtGui.QMessageBox.DestructiveRole) cancelButton = box.addButton(messages[language]["Cancel"], QtGui.QMessageBox.RejectRole) box.setDefaultButton(cancelButton) box.exec() clicked = box.clickedButton() if replaceButton is not None and clicked == replaceButton: return "replace" if clicked == removeButton: return "remove" return "cancel" ########################################## # Add the constraint to the sketch # Parameters : # - nbSelected : number of selected objects (1 or 2) # - typeIdGeometry1 : type of the first selected object (circle, line, 'Constraint'...) # - point1, point2 : (indexObject, indexExtremite, isInternalObject) # - myConstraint : 'DistanceX', 'DistanceY' or 'Distance' (lines and points) # - cellContents : value of the cell # - isRadius : a circle gets a Radius constraint instead of a Diameter constraint # - indexConstraint : index of the selected constraint, if a constraint is selected # return : index of the constraint (new one, or the selected one) ########################################## def create_constraint(mySketch, nbSelected, typeIdGeometry1, point1, point2, myConstraint, cellContents, isRadius, indexConstraint): if nbSelected == 1 and typeIdGeometry1 in CIRCLE_TYPES: # internal or external circle indexConstraint = mySketch.addConstraint( Sketcher.Constraint("Radius" if isRadius else "Diameter", point1[0], cellContents) ) elif typeIdGeometry1 != "Constraint": # a line or 2 points indexConstraint = mySketch.addConstraint( Sketcher.Constraint( myConstraint, point1[0], point1[1], point2[0], point2[1], cellContents ) ) return indexConstraint # True if only external objects (from another sketch) are selected : # the constraint must then be a reference one def allSelectedAreExternal(nbSelected, point1, point2): return (nbSelected == 1 and not point1[2]) or ( nbSelected == 2 and not point1[2] and not point2[2]) ########################################## # Link the constraint and the cell # - only external objects : the constraint becomes a reference # - driving constraint : its value is the cell expression # - reference constraint : after confirmation, the cell gets the value of the # constraint (=href(Sketch.Constraints.Name)); the constraint is named if needed ########################################## def link_constraint(mySketch, indexConstraint, cellExpression, allExternal, mySpreadsheet, cellCode, confirm=askOkCancel): if allExternal: mySketch.setDriving(indexConstraint, False) elif mySketch.Constraints[indexConstraint].Driving: # set the constraint 'formula' (ex : 'spreadSheet.unAlias') mySketch.setExpression("Constraints[" + str(indexConstraint) + "]", cellExpression) else: print("The constraints is a reference one") if mySketch.Constraints[indexConstraint].Name == "": message = messages[language]["referenceNoName"] else: message = messages[language]["referenceWithName"] if confirm(message): if mySketch.Constraints[indexConstraint].Name == "": mySketch.renameConstraint( indexConstraint, mySketch.Name + "_" + str(indexConstraint) + "_" + datetime.now().strftime("%S"), ) mySpreadsheet.set( cellCode, "=href(" + mySketch.Name + ".Constraints." + mySketch.Constraints[indexConstraint].Name + ")", ) # If the sketch has a conflict, propose to delete the new constraint def remove_if_conflict(mySketch, indexConstraint, confirm=askYesNo): if "Invalid" in mySketch.State: if confirm(messages[language]["ConstarintConflicDetected"]): mySketch.delConstraint(indexConstraint) ########################################## # Main proceddure ########################################## def main(): form = None sheckBoxConstraintConflicState = False indexConstraint = -1 myConstraint = None # Property mode (no sketch in edit mode, an object selected in the tree) : # the property selected in the property view is checked first, so that an # existing link can be removed even when no spreadsheet is open sels = Gui.Selection.getSelectionEx() myPadOrPocket = None # object owner of the property selectedProperty = None if sels and not isSketchActif(): myPadOrPocket = sels[0].Object selectedProperty = prepare_property_link(myPadOrPocket, findSpreadsheetView() is not None) if selectedProperty is None: # refused, link removed or cancelled return if addTheObjects(): # Creation of missing objects if wanted return # Part of setAlias : problem to create alias ? sels = Gui.Selection.getSelectionEx() if not (len(sels) != 0 and len(sels[0].SubElementNames) != 0): if len(sels) == 0 or isSketchActif(): message = messages[language]["NoObjectSelected"] if ( QtGui.QMessageBox.warning( Gui.getMainWindow(), messages[language]["Warning"], message, QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel, ) == QtGui.QMessageBox.Cancel ): # if user don't want return True setAlias(True, False) return # spreadsheet : the active view, or the last active spreadsheet if the sketch has the focus sheetView = findSpreadsheetView() if sheetView is None: # no spreadsheet open QtGui.QMessageBox.warning( Gui.getMainWindow(), messages[language]["Warning"], messages[language]["NoActiveSpreadsheet"], ) return True mySpreadsheet = sheetView.getSheet() # Sketch in edit mode, or object (Pad, Pocket...) whose property is selected # (myPadOrPocket and selectedProperty : found at the start of main) # -------------------------------------------------------------- sels = Gui.Selection.getSelectionEx() mySketch = ActiveSketch if isSketchActif() else None # Part SpreadSheet (sheetView / mySpreadsheet : found above) # --------------------------------- sheets = getGuiObjsSelect("Spreadsheet::Sheet") for sheet in sheets: Gui.Selection.removeSelection(App.ActiveDocument.Name, sheet.Name) mySpreadSheetName = mySpreadsheet.Name mySpreadSheetLabel = mySpreadsheet.Label # retrieve the selected cell (it may have been selected a while ago if the # spreadsheet does not have the focus : show it in the report view) cellCode = sheetView.currentIndex() print("Spreadsheet cell used:", mySpreadSheetLabel + "." + cellCode) try: if sels[0].Object.TypeId not in ["Part::Part2DObjectPython"]: # ShapeString cellContents = mySpreadsheet.get(cellCode) cellContents = float(mySpreadsheet.get(cellCode)) except ValueError: # empty cell, text or formula error if isSketchActif(): QtGui.QMessageBox.information( None, messages[language]["Warning"], messages[language]["ClickOnACellBefore"], ) return # Part sketch # ---------------------------- sels = Gui.Selection.getSelectionEx() p1 = p2 = None if myPadOrPocket is None: # a sketch is in edit mode p1, p2, indexConstraint, error = analyse_selection(mySketch, sels) if error: QtGui.QMessageBox.information(None, messages[language]["Warning"], error) activateSketchEditingWindow() return # a line or 2 points : ask the user what kind of constraint he wants if (len(sels[0].SubElementNames) == 1 and p1.typeIdGeometry == "Part::GeomLineSegment") \ or len(sels[0].SubElementNames) == 2: form = getConstraintType(defaultConstraintButton(p1, p2)) sheckBoxConstraintConflicState = form.getCheckBoxState() myConstraint = forcedConstraint(p1, p2) # an axis is selected if myConstraint is None: form.exec() # open dialog box sheckBoxConstraintConflicState = form.getCheckBoxState() if form.choiceConstraint in ("Cancel", ""): activateSketchEditingWindow() return myConstraint = form.choiceConstraint # 'DistanceX', 'DistanceY' or 'Distance' p1, p2 = orderPoints(myConstraint, p1, p2) if getIniCheckboxStateForAlias(): setAlias(False, True, sheetView) # same spreadsheet as the cell # create constraint # ================================= # get value for constraint cellAlias = App.ActiveDocument.getObject(mySpreadSheetName).getAlias(cellCode) cellExpression, isRadius = build_expression( mySpreadSheetLabel, cellCode, cellAlias, # "Diameter in spreadsheet gives a radius in sketch" option (value divided by 2) # (form exists only for lines / points in a sketch) divideBy2=( form is not None and myPadOrPocket is None and form.getRadiusOrDiameter() == "Radius" ), ) if myPadOrPocket is not None: try: cellValue = mySpreadsheet.get(cellCode) except Exception: # on purpose : empty cell or cell error, depending on the FreeCAD version cellValue = None apply_to_property(selectedProperty, cellExpression, cellValue, mySpreadSheetLabel + "." + cellCode) return nbSelected = len(sels[0].SubElementNames) point1 = (p1.index, p1.extremite, p1.isInternal) point2 = (p2.index, p2.extremite, p2.isInternal) if p2 else (None, None, True) indexConstraint = create_constraint( mySketch, nbSelected, p1.typeIdGeometry, point1, point2, myConstraint, cellContents, isRadius, indexConstraint, ) link_constraint( mySketch, indexConstraint, cellExpression, allSelectedAreExternal(nbSelected, point1, point2), mySpreadsheet, cellCode, ) # put Sketch window ahead activateSketchEditingWindow() Gui.Selection.clearSelection() mySketch.recompute() if sheckBoxConstraintConflicState: remove_if_conflict(mySketch, indexConstraint) recomputeAll() activateSketchEditingWindow() return if __name__ == "__main__": main()