### Build pyrevit Installers Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/CLAUDE.md Creates Inno Setup installers for the pyrevit project. Run from the repository root. ```bash pipenv run pyrevit build installers ``` -------------------------------- ### Basic pyRevit Unit Test Setup Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt This snippet shows the basic setup for a pyRevit unit test using unittest.TestCase. It includes placeholder methods for setUp, tearDown, and doCleanups. ```python from unittest import TestCase class TestWithIndependentOutput(TestCase): def setUp(self): pass def tearDown(self): pass def doCleanups(self): pass ``` -------------------------------- ### Define Preflight Test Setup Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Implement the `setUp` method to prepare the test environment before execution. This hook is called before `startTest`. ```python def setUp(self, doc, output): """Hook method for setting up the test before exercising it.""" pass ``` -------------------------------- ### Setup pyrevit Environment Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/CLAUDE.md Installs project dependencies using pipenv. Run this command from the repository root. ```bash pipenv install ``` -------------------------------- ### Build MSI Installer Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/release/README.md Use msbuild to compile the WiX project and create the MSI installer. ```bash msbuild .\release\pyrevit-cli.wixproj ``` -------------------------------- ### install Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Installs an extension package into a specified directory, with an option to install dependencies. ```APIDOC ## install(extpkg, install_dir, install_dependencies=True) ### Description Install the extension in the given parent directory. This method uses the `.installed_dir` property of the extension object as the installation directory name for this extension. It also handles the installation of extension dependencies. ### Parameters #### Path Parameters - **extpkg** (ExtensionPackage) - Required - Extension package to be installed. - **install_dir** (str) - Required - Parent directory to install extension in. #### Query Parameters - **install_dependencies** (bool) - Optional - Install the dependencies as well. Defaults to `True`. ### Raises - **PyRevitException**: on install error with error message. ``` -------------------------------- ### Call .NET Dependencies in Installer Initialization Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/adding-revit-version.md Edit `release/pyrevit.iss` and add calls to the newly defined .NET dependency procedures within the `InitializeSetup` function to ensure the required runtimes are installed. ```pascal function InitializeSetup: Boolean; begin // .NET 8 for Revit 2025-2026 Dependency_AddDotNet80; Dependency_AddDotNet80Desktop; // .NET 10 for Revit 2027+ Dependency_AddDotNet100; Dependency_AddDotNet100Desktop; // .NET XX for Revit 20YY+ (add new dependencies here) Result := True; end; ``` -------------------------------- ### Install PyRevit MSI Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/release/README.md Install the PyRevit CLI using the generated MSI package. Logs are written to dist\log.txt. ```bash msiexec /i "dist\pyRevit_CLI_*_signed.msi" /l*v "dist\log.txt" ``` -------------------------------- ### Example pyRevit Clone Command Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt An example of cloning the pyRevit repository using the pyRevit CLI with specific parameters for name, source, destination, and branch. ```bash pyrevit clone dev --source https:/gitlab.com/sanzoghenzo/pyrevit.git --dest c:\pyrevit --branch=develop ``` -------------------------------- ### Setup Telemetry System Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Call this function to set up the telemetry system on pyRevit startup. ```python setup_telemetry() ``` -------------------------------- ### Setup Telemetry Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Initializes the telemetry system. This function is typically called on pyRevit startup. ```APIDOC ## setup_telemetry() ### Description Initializes the telemetry system. ### Method Python Function Call ### Parameters None ### Request Example ```python setup_telemetry() ``` ### Response None ``` -------------------------------- ### Initialize PyRevitPluginAlreadyInstalledException Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Exception raised when an extension is already installed. Initializes with the extension package object. ```python def __init__(self, extpkg): super(PyRevitPluginAlreadyInstalledException, self).__init__() self.extpkg = extpkg PyRevitException(self) ``` -------------------------------- ### Prefer Explaining Intent: Python Example Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/CLAUDE.md This example shows the preferred way to comment, focusing on the purpose and intent of the code block rather than its implementation details. This helps future developers understand the 'why' behind the code. ```python # Collect all installed extensions visible to the current user before building the UI. extensions = get_all_extensions() ``` -------------------------------- ### Get Description Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the description of the 3D server. ```python def GetDescription(self): return self.description ``` -------------------------------- ### setup_resources Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets up WPF resources for pyRevit forms, including color and brush definitions. ```APIDOC ## `setup_resources(wpf_ctrl)` ### Description Sets the WPF resources for a given WPF control. ### Parameters * `wpf_ctrl` (any) - The WPF control to set resources for. ``` -------------------------------- ### Get Revit Failure Definition by GUID Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves a Revit failure definition using its unique GUID. Requires the failure_guid as a string. ```python def get_failure_by_guid(failure_guid): fdr = HOST_APP.app.GetFailureDefinitionRegistry() fgid = framework.Guid(failure_guid) fid = DB.FailureDefinitionId(fgid) return fdr.FindFailureDefinition(fid) ``` -------------------------------- ### Get Installed Library Extensions Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Returns a list of all installed and active Library extensions from a specified directory. This function is useful for accessing library extensions without full parsing. ```python def get_installed_lib_extensions(root_dir): """Returns all the installed and active Library extensions (not parsed). Args: root_dir (str): Extensions directory address Returns: (list[LibraryExtension]): list of components.LibraryExtension objects """ lib_ext_list = \ [lib_ext for lib_ext in parse_dir_for_ext_type(root_dir, LibraryExtension)] return _remove_disabled_extensions(lib_ext_list) ``` -------------------------------- ### Setup Local Build Environment Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/build/README.md Sets up a local build environment for C# contributors, including cloning, submodule updates, and local build execution. ```powershell git clone cd pyRevit git checkout develop git submodule update --init --recursive cd build && dotnet run -c Release -- ci && cd .. pyrevit clones add dev . pyrevit attach dev default --installed # after git pull: pyrevit clones update dev --skip-bin ``` -------------------------------- ### Get Server ID Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the unique server ID (GUID) of the 3D server. ```python def GetServerId(self): return self.guid ``` -------------------------------- ### setup_resources Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets predefined WPF resources for a given control. ```APIDOC ## setup_resources(wpf_ctrl) ### Description Sets the WPF resources. ### Parameters #### Path Parameters - **wpf_ctrl** (object) - Required - The WPF control to set resources for. ``` -------------------------------- ### setup_telemetry Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Initializes the telemetry system with default configuration and environment values. ```APIDOC ## setup_telemetry(session_id=None) ### Description Sets up the telemetry default configuration and environment values, including session ID, global toggle, and file logging. ### Parameters - **session_id** (str, optional) - The session identifier. If not provided, a default session UUID will be used. ### Returns - None ``` -------------------------------- ### Get Third-Party Extension Repositories Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves a list of Git repositories for all installed third-party extensions. It discovers Git repositories within extension directories and filters for valid ones. ```python def get_thirdparty_ext_repos(): """Return a list of repos for installed third-party extensions.""" processed_paths = set() valid_exts = [] ext_repos = [] logger.debug('Finding installed repos...') ext_info_list = extensionmgr.get_thirdparty_extension_data() for ext_info in ext_info_list: repo_path = libgit.libgit.Repository.Discover(ext_info.directory) if repo_path: repo_info = libgit.get_repo(repo_path) if repo_info: valid_exts.append(ext_info) if repo_info.directory not in processed_paths: processed_paths.add(repo_info.directory) ext_repos.append(repo_info) logger.debug('Valid third-party extensions for update: %s', valid_exts) return ext_repos ``` -------------------------------- ### Get All Third-Party Extension Data Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves all installed and active UI and Library extensions without parsing them. This function iterates through user-defined root directories to collect extension data. ```python def get_thirdparty_extension_data(): """Returns all installed and active UI and Library extensions (not parsed). Returns: (list): list of components.Extension or components.LibraryExtension """ # FIXME: reorganzie this code to use one single method to collect # extension data for both lib and ui ext_data_list = [] for root_dir in user_config.get_thirdparty_ext_root_dirs(): ext_data_list.extend( [ui_ext for ui_ext in parse_dir_for_ext_type(root_dir, Extension)]) ext_data_list.extend( [lib_ext for lib_ext in parse_dir_for_ext_type(root_dir, LibraryExtension)]) return _remove_disabled_extensions(ext_data_list) ``` -------------------------------- ### Get Installed UI Extensions Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves all UI extensions, including processing library extensions and updating their paths in syspath. This function is used to load and manage extensions for the pyRevit user interface. ```python def get_installed_ui_extensions(): """Returns all UI extensions (fully parsed) under the given directory. This will also process the Library extensions and will add their path to the syspath of the UI extensions. Returns: (list[Extension]): list of components.Extension objects """ ui_ext_list = [] lib_ext_list = [] # get a list of all directories that could include extensions ext_search_dirs = user_config.get_ext_root_dirs() mlogger.debug('Extension Directories: %s', ext_search_dirs) # collect all library extensions. Their dir paths need to be added # to sys.path for all commands for root_dir in ext_search_dirs: lib_ext_list.extend(get_installed_lib_extensions(root_dir)) # Get a list of all installed extensions in this directory # _parser.parse_dir_for_ext_type() returns a list of extensions # in given directory for root_dir in ext_search_dirs: for ext_info in parse_dir_for_ext_type(root_dir, Extension): # test if cache is valid for this ui_extension # it might seem unusual to create a ui_extension and then # re-load it from cache but minimum information about the # ui_extension needs to be passed to the cache module for proper # hash calculation and ui_extension recovery. at this point # `ui_extension` does not include any sub-components # (e.g, tabs, panels, etc) ui_extension object is very small and # its creation doesn't add much overhead. if _is_extension_enabled(ext_info): ui_extension = _parse_or_cache(ext_info) ui_ext_list.append(ui_extension) else: mlogger.debug('Skipping disabled ui extension: %s', ext_info.name) # update extension master syspaths with standard pyrevit lib paths and # lib address of other lib extensions (to support extensions that provide # library only to be used by other extensions) # all other lib paths internal to the extension and tool bundles have # already been set inside the extension bundles and will take precedence # over paths added by this method (they're the first paths added to the # search paths list, and these paths will follow) for ui_extension in ui_ext_list: _update_extension_search_paths( ui_extension, lib_ext_list, [MAIN_LIB_DIR, MISC_LIB_DIR] ) return ui_ext_list ``` -------------------------------- ### Get All Preflight Checks Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Discovers and collects all preflight checks available in installed pyRevit extensions. It iterates through extensions, finds check scripts, loads them, and wraps discovered check types into PreflightCheck objects. ```python def get_all_preflight_checks(): """Find all the preflight checks in installed extensions.""" preflight_checks = [] # get all installed ui extensions for ext in extensionmgr.get_installed_ui_extensions(): # find the checks in the extension for check_script in ext.get_checks(): # load the check source file so all the checks can be extracted check_mod = \ imp.load_source(_get_check_name(check_script), check_script) # extract the checks and wrap for check_type in _grab_test_types(check_mod): preflight_checks.append( PreflightCheck(ext, check_type, check_script) ) return preflight_checks ``` -------------------------------- ### setup_resources Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the WPF resources for the form, including colors and brushes. ```APIDOC ## setup_resources(wpf_ctrl) ### Description Sets the WPF resources for the form. ### Parameters #### Path Parameters - **wpf_ctrl** (any) - Required - The WPF control to set resources on. ### Code Example ```python @staticmethod def setup_resources(wpf_ctrl): """Sets the WPF resources.""" #2c3e50 wpf_ctrl.Resources['pyRevitDarkColor'] = \ Media.Color.FromArgb(0xFF, 0x2c, 0x3e, 0x50) #23303d wpf_ctrl.Resources['pyRevitDarkerDarkColor'] = \ Media.Color.FromArgb(0xFF, 0x23, 0x30, 0x3d) #ffffff wpf_ctrl.Resources['pyRevitButtonColor'] = \ Media.Color.FromArgb(0xFF, 0xff, 0xff, 0xff) #f39c12 wpf_ctrl.Resources['pyRevitAccentColor'] = \ Media.Color.FromArgb(0xFF, 0xf3, 0x9c, 0x12) wpf_ctrl.Resources['pyRevitDarkBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitDarkColor']) wpf_ctrl.Resources['pyRevitAccentBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitAccentColor']) wpf_ctrl.Resources['pyRevitDarkerDarkBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitDarkerDarkColor']) wpf_ctrl.Resources['pyRevitButtonForgroundBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitButtonColor']) wpf_ctrl.Resources['pyRevitRecognizesAccessKey'] = \ DEFAULT_RECOGNIZE_ACCESS_KEY ``` ``` -------------------------------- ### setup_resources(wpf_ctrl) Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets up WPF resources for a given control. This includes defining brushes and colors that can be used throughout the UI for consistent styling. ```APIDOC ## setup_resources(wpf_ctrl) ### Description Sets the WPF resources. ### Parameters #### Path Parameters - **wpf_ctrl** (object) - Required - The WPF control to set resources for. ### Returns This method does not return a value. ``` -------------------------------- ### WarningBar.__init__ Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Initializes the user prompt window, setting up the basic structure and properties for the WarningBar. ```APIDOC ## `__init__(self, height=32, **kwargs)` ### Description Initialize user prompt window. ### Parameters - `height` (int) - The height of the warning bar. Defaults to 32. - `**kwargs` - Additional keyword arguments. ### Attributes - `user_height` (instance-attribute) - `xaml_source` (class-attribute, instance-attribute) - Defaults to 'WarningBar.xaml'. ``` -------------------------------- ### Install pyRevit Extension Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Installs an extension package into a specified directory. Handles extension dependencies and logs warnings for already installed extensions or errors during installation. ```python def install(extpkg, install_dir, install_dependencies=True): """Install the extension in the given parent directory. This method uses .installed_dir property of extension object as installation directory name for this extension. This method also handles installation of extension dependencies. Args: extpkg (ExtensionPackage): Extension package to be installed install_dir (str): Parent directory to install extension in. install_dependencies (bool): Install the dependencies as well Raises: PyRevitException: on install error with error message """ try: _install_extpkg(extpkg, install_dir, install_dependencies) except PyRevitPluginAlreadyInstalledException as already_installed_err: mlogger.warning('%s extension is already installed under %s', already_installed_err.extpkg.name, already_installed_err.extpkg.is_installed) except PyRevitPluginNoInstallLinkException: mlogger.error('Extension does not have an install link ' 'and can not be installed.') ``` -------------------------------- ### Extension Installation Status Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Checks if the extension is currently installed and returns its installation directory path. ```APIDOC ## is_installed ### Description Installation directory. ### Returns - **str**: Installed directory path or empty string if not installed. ``` -------------------------------- ### setup_icon Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the default window icon. ```APIDOC ## setup_icon() ### Description Setup default window icon. ### Code Example ```python def setup_icon(self): """Setup default window icon.""" self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png')) ``` ``` -------------------------------- ### Extract GUID from String Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Parses a string to extract a Globally Unique Identifier (GUID). Handles standard GUID formats. ```python def extract_guid(source_str): """Extract GUID number from a string.""" guid_match = re.match(".*([0-9A-Fa-f]{8}" "[-][0-9A-Fa-f]{4}" "[-][0-9A-Fa-f]{4}" "[-][0-9A-Fa-f]{4}" "[-][0-9A-Fa-f]{12}).*", source_str) if guid_match: return guid_match.groups()[0] ``` -------------------------------- ### Initialize ExtensionPackage Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Initializes the ExtensionPackage class with extension information. Requires a dictionary containing type, name, description, and url. Optional keys include website, image, author, author-url, and authusers. ```python def __init__(self, info_dict, def_file_path=None): """Initialized the extension class based on provide information. Required info (Dictionary keys): type, name, description, url Optional info: website, image, author, author-url, authusers Args: info_dict (dict): A dictionary containing the required information for initializing the extension. def_file_path (str): The file path of the extension definition file """ self.type = exts.ExtensionTypes.UI_EXTENSION self.builtin = False self.default_enabled = True self.name = None self.description = None self.url = None self.def_file_path = set() self.authusers = set() self.authgroups = set() self.rocket_mode_compatible = False self.website = None self.image = None self.author = None self.author_profile = None self.dependencies = set() self.update_info(info_dict, def_file_path=def_file_path) ``` -------------------------------- ### Check for Installed Dependents in DependencyGraph Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Checks if a given extension package name has any installed dependents within the dependency graph. Returns True if installed dependents are found, False otherwise. ```python def has_installed_dependents(self, extpkg_name): if extpkg_name in self.dep_dict: for dep_pkg in self.dep_dict[extpkg_name]: if dep_pkg.is_installed: return True else: return False ``` -------------------------------- ### Build pyrevit Documentation Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/CLAUDE.md Builds the project documentation using mkdocs. Run from the repository root. ```bash pipenv run docs ``` -------------------------------- ### setup_icon() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the default window icon using a predefined path. ```APIDOC ## setup_icon() ### Description Setup default window icon. ### Method This method does not take any parameters. ``` -------------------------------- ### Extension Installed Directory Path Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the full path to the installed directory of the extension. ```APIDOC ## installed_dir ### Description Installation directory. ### Returns - **str**: Installed directory path or empty string if not installed. ``` -------------------------------- ### Check if TransactionGroup has started Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Checks if the transaction group has already started. Returns a boolean. ```python def has_started(self): return self._rvtxn_grp.HasStarted() ``` -------------------------------- ### Register and Open Dockable Panel Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Example demonstrating how to define a custom WPF panel by inheriting from `WPFPanel`, setting `panel_id` and `panel_source`, and then registering and opening it. ```python from pyrevit import forms class MyPanel(forms.WPFPanel): panel_id = "181e05a4-28f6-4311-8a9f-d2aa528c8755" panel_source = "MyPanel.xaml" forms.register_dockable_panel(MyPanel) # then from the button that needs to open the panel forms.open_dockable_panel("181e05a4-28f6-4311-8a9f-d2aa528c8755") ``` -------------------------------- ### Install Pipenv Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/dev-guide.md Use this command to install Pipenv, a tool for managing Python environments and dependencies. ```shell pip install pipenv ``` -------------------------------- ### setup_default_handlers Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets up default event handlers for the window, such as keyboard input handling. ```APIDOC ## setup_default_handlers() ### Description Set the default handlers. ### Source Code ```python def setup_default_handlers(self): """Set the default handlers.""" self.PreviewKeyDown += self.handle_input_key #pylint: disable=E1101 ``` ``` -------------------------------- ### setup_icon() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the default window icon for the application. ```APIDOC ## `setup_icon()` ### Description Setup default window icon. ### Method This is a method within a class, likely related to window or form management. ### Code Example ```python def setup_icon(self): """Setup default window icon.""" self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png')) ``` ``` -------------------------------- ### Run Release Pack, Sign, and Publish Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/build/README.md Executes the full release pipeline including packing installers, signing, and publishing. ```powershell dotnet run -c Release -- release pack sign publish ``` -------------------------------- ### Extension Installation Directory Name Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Provides the name to be used for the extension's installation directory, which is determined by the extension type. ```APIDOC ## ext_dirname ### Description Installation directory name to use. ### Returns - **str**: The name that should be used for the installation directory (based on the extension type). ``` -------------------------------- ### execute_extension_startup_script Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Executes a script using the pyRevit script executor, typically for extension startup. ```APIDOC ## execute_extension_startup_script(script_path, ext_name, sys_paths=None) ### Description Executes a script using pyRevit script executor. ### Parameters #### Path Parameters - **script_path** (str) - Required - Address of the script file - **ext_name** (str) - Required - Name of the extension - **sys_paths** (list) - Optional - additional search paths ``` -------------------------------- ### Get Revit Element Location Point Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Gets the XYZ location point of a Revit element. Requires a DB.Element as input. ```python def get_location(element): """Get element location point. Args: element (DB.Element): source element Returns: (DB.XYZ): X, Y, Z of location point element """ locp = element.Location.Point return (locp.X, locp.Y, locp.Z) ``` -------------------------------- ### setup_icon() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the default window icon for the PyRevit form. ```APIDOC ## setup_icon() ### Description Sets the default window icon for the PyRevit form. ### Method This is a method of a class, likely a window or form object. ### Endpoint N/A (Class method) ### Parameters None ``` -------------------------------- ### Start Test Execution Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Called when a test starts. It logs the test execution using a debug message and retrieves the test description. ```python def startTest(self, test): """Starts the test. Args: test (TestCase): unit test """ super(PyRevitTestResult, self).startTest(test) mlogger.debug('Running test: %s', self.getDescription(test)) ``` -------------------------------- ### extract_guid Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Extracts a Globally Unique Identifier (GUID) from a given string. This function uses regular expressions to find and return a GUID pattern. ```APIDOC ## extract_guid(source_str) ### Description Extract GUID number from a string. ### Parameters #### Path Parameters - **source_str** (str) - Required - The string from which to extract the GUID. ``` -------------------------------- ### Start and Commit Revit Transaction Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Use the Transaction context manager to automatically start and commit Revit transactions. It handles rollback on exceptions. ```python with Transaction('Move Wall'): wall.DoSomething() ``` ```python with Transaction('Move Wall', doc, clear_after_rollback=False, show_error_dialog=False, swallow_errors=False, log_errors=True, nested=False) as action: wall.DoSomething() assert action.status == ActionStatus.Started # True assert action.status == ActionStatus.Committed # True ``` -------------------------------- ### init() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Initializes routes by resetting all registered routes and shutting down any active servers. ```APIDOC ## init() ### Description Initialize routes. Reset all registered routes and shutdown servers. ### Method `init()` ### Parameters None ### Request Example ```python init() ``` ### Response None ``` -------------------------------- ### Get pyRevit Repository Information Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Returns a wrapper object containing information about the pyRevit repository. This function attempts to get the repository from the HOME_DIR. ```python def get_pyrevit_repo(): """Return pyRevit repository. Returns: (pyrevit.coreutils.git.RepoInfo): repo wrapper object """ try: return git.get_repo(HOME_DIR) except Exception as repo_err: mlogger.debug('Can not create repo from directory: %s | %s', HOME_DIR, repo_err) ``` -------------------------------- ### WarningBar.setup_owner Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the owner of the window, typically to the main application window. ```APIDOC ## `setup_owner(self)` ### Description Set the window owner. ``` -------------------------------- ### Generate GUID for Revit Element Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Generates a GUID for a Revit element using a bitwise XOR operation on parts of its UniqueId. Requires the element to have a UniqueId attribute. ```python def get_guid(element): """ Generates a GUID for a given Revit element by performing a bitwise XOR operation on parts of the element's UniqueId. Args: element: The Revit element for which the GUID is to be generated. The element must have a UniqueId attribute. Returns: str: A string representing the generated GUID. """ uid = str(element.UniqueId) last_32_bits = int(uid[28:36], 16) element_id = int(uid[37:], 16) xor = last_32_bits ^ element_id return uid[:28] + "{0:x}".format(xor) ``` -------------------------------- ### Avoid Restating Code: Python Example Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/CLAUDE.md This example demonstrates a comment that should be avoided because it simply restates what the subsequent code does. Prefer comments that explain the intent or purpose. ```python # Call get_ext_root_dirs to retrieve the list of extension paths from user config, # then pass each path to extensionmgr to scan for UI extension manifests. extensions = get_all_extensions() ``` -------------------------------- ### Execute Extension Startup Script Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Executes a script using pyRevit's script executor, allowing for custom system paths and runtime configurations. This is useful for starting extension scripts with specific environments. ```python def execute_extension_startup_script(script_path, ext_name, sys_paths=None): """Executes a script using pyRevit script executor. Args: script_path (str): Address of the script file ext_name (str): Name of the extension sys_paths (list): additional search paths """ core_syspaths = [MAIN_LIB_DIR, MISC_LIB_DIR] if sys_paths: sys_paths.extend(core_syspaths) else: sys_paths = core_syspaths script_data = runtime.types.ScriptData() script_data.ScriptPath = script_path script_data.ConfigScriptPath = None script_data.CommandUniqueId = '' script_data.CommandName = 'Starting {}'.format(ext_name) script_data.CommandBundle = '' script_data.CommandExtension = ext_name script_data.HelpSource = '' script_runtime_cfg = runtime.types.ScriptRuntimeConfigs() script_runtime_cfg.CommandData = create_tmp_commanddata() script_runtime_cfg.SelectedElements = None script_runtime_cfg.SearchPaths = framework.List[str](sys_paths or []) script_runtime_cfg.Arguments = framework.List[str]([]) script_runtime_cfg.EngineConfigs = \ runtime.create_ipyengine_configs( clean=True, full_frame=True, persistent=True, ) script_runtime_cfg.RefreshEngine = False script_runtime_cfg.ConfigMode = False script_runtime_cfg.DebugMode = False script_runtime_cfg.ExecutedFromUI = False runtime.types.ScriptExecutor.ExecuteScript( script_data, script_runtime_cfg ) ``` -------------------------------- ### Initialize SearchPrompt window Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt This is the constructor for the SearchPrompt window. It initializes the window's dimensions, sets up the search database, and prepares the UI elements for user interaction. ```python def __init__(self, search_db, width, height, **kwargs): """Initialize search prompt window.""" WPFWindow.__init__( op.join(XAML_FILES_DIR, 'SearchPrompt.xaml')) self.Width = width self.MinWidth = self.Width self.Height = height self.search_tip = kwargs.get('search_tip', '') if isinstance(search_db, list): self._search_db = None self._search_db_keys = search_db elif isinstance(search_db, dict): self._search_db = search_db self._search_db_keys = sorted(self._search_db.keys()) else: raise PyRevitException("Unknown search database type") self._search_res = None self._switches = kwargs.get('switches', []) self._setup_response() self.search_tb.Focus() self.hide_element(self.tab_icon) self.hide_element(self.return_icon) self.search_tb.Text = '' self.set_search_results() ``` -------------------------------- ### Attach pyRevit Clone to Revit Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Attach your pyRevit development clone to the default Revit installation. Ensure you are using the pyrevit CLI from a WIP installer for pyRevit 5+. ```bash pyrevit attach dev default --installed ``` -------------------------------- ### Build and Attach pyRevit CLI Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt If you need to build the pyRevit CLI from sources, use this sequence of commands. This is necessary if you don't have a WIP installer and need to attach a clone for pyRevit 5+. ```bash pipenv run pyrevit build labs copy .\release\.pyrevitargs . .\bin\pyrevit.exe attach dev default --installed ``` -------------------------------- ### Count Critical Warnings Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Counts critical warnings from a list based on a provided GUID template. Ensure warnings have a `GetFailureDefinitionId` method returning an object with a `Guid` attribute. ```python def get_critical_warnings_count(warnings, critical_warnings_template): """ Counts the number of critical warnings from a list of warnings based on a template. Args: warnings (list): A list of warning objects. Each warning object should have a method `GetFailureDefinitionId` that returns an object with a `Guid` attribute. critical_warnings_template (list): A list of string representations of GUIDs that are considered critical warnings. Returns: int: The count of critical warnings. """ warnings_guid = [warning.GetFailureDefinitionId().Guid for warning in warnings] return sum( 1 for warning_guid in warnings_guid if str(warning_guid) in critical_warnings_template ) ``` -------------------------------- ### setup_icon Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the default window icon for the pyRevit application. ```APIDOC ## `setup_icon()` ### Description Sets the default window icon using the `pyrevit_settings.png` file located in the `BIN_DIR`. ``` -------------------------------- ### Get Revit Link Status Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the status of all linked Revit models in a document. It first gets link instances, then their types, and finally queries the status of each type. ```python def get_rvt_link_status(doc=None): """ Retrieves the status of linked Revit models in the given document. Args: doc (Document, optional): The Revit document to query. If None, the current document is used. Returns: list: A list of statuses for each linked Revit model type. """ doc = doc or DOCS.doc rvtlinks_instances = get_linked_model_instances(doc) rvtlinks_types = get_linked_model_types(doc, rvtlinks_instances) return [rvtlinktype.GetLinkedFileStatus() for rvtlinktype in rvtlinks_types] ``` -------------------------------- ### Setup Telemetry Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Initializes the telemetry system by setting up default configuration and environment values. This includes managing session IDs, telemetry toggles, UTC timestamps, and file logging destinations based on user configuration. ```python def setup_telemetry(session_id=None): """Sets up the telemetry default config and environment values.""" # make sure session id is availabe if not session_id: session_id = sessioninfo.get_session_uuid() # PYREVIT TELEMETRY ------------------------------------------------------- # utc timestamp telemetry_utc_timestamp = user_config.telemetry_utc_timestamp set_telemetry_utc_timestamp(telemetry_utc_timestamp) # global telemetry toggle telemetry_state = user_config.telemetry_status set_telemetry_state(telemetry_state) # read or setup default values for file telemetry # default file path and name for telemetry telemetry_file_dir = user_config.telemetry_file_dir set_telemetry_file_dir(telemetry_file_dir) # check file telemetry config and setup destination if not telemetry_file_dir or coreutils.is_blank(telemetry_file_dir): # if no config is provided, disable output disable_telemetry_to_file() # if config exists, create new telemetry file under the same address elif telemetry_state: if op.isdir(telemetry_file_dir): telemetry_file_name = \ FILE_LOG_FILENAME_TEMPLATE.format(PYREVIT_FILE_PREFIX, session_id, FILE_LOG_EXT) # if directory is valid telemetry_fullfilepath = \ op.join(telemetry_file_dir, telemetry_file_name) set_telemetry_file_path(telemetry_fullfilepath) # setup telemetry file or disable if failed try: _setup_default_logfile(telemetry_fullfilepath) except Exception as write_err: mlogger.error('Telemetry is active but log file location ' 'is not accessible. ``` -------------------------------- ### Get All Event Hooks Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Fetches all event hooks managed by the pyRevit hooks handler. This function first retrieves the handler and then calls its method to get all registered event hooks. ```python def get_event_hooks(): """Get all the event hooks.""" hooks_handler = get_hooks_handler() return hooks_handler.GetAllEventHooks() ``` -------------------------------- ### setup_runtime_vars() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets up essential runtime environment variables with current pyRevit session information. This includes pyRevit version, host application version, IronPython engine version, and optionally, the CPython engine version and clone name. ```APIDOC ## setup_runtime_vars() ### Description Setup runtime environment variables with session information. ### Method ```python def setup_runtime_vars(): """Setup runtime environment variables with session information.""" # set pyrevit version pyrvt_ver = versionmgr.get_pyrevit_version().get_formatted() envvars.set_pyrevit_env_var(envvars.VERSION_ENVVAR, pyrvt_ver) # set app version env var if HOST_APP.is_newer_than(2017): envvars.set_pyrevit_env_var(envvars.APPVERSION_ENVVAR, HOST_APP.subversion) else: envvars.set_pyrevit_env_var(envvars.APPVERSION_ENVVAR, HOST_APP.version) # set ironpython engine version env var attachment = user_config.get_current_attachment() if attachment and attachment.Clone: envvars.set_pyrevit_env_var(envvars.CLONENAME_ENVVAR, attachment.Clone.Name) envvars.set_pyrevit_env_var(envvars.IPYVERSION_ENVVAR, str(attachment.Engine.Version)) else: mlogger.debug('Can not determine attachment.') envvars.set_pyrevit_env_var(envvars.CLONENAME_ENVVAR, "Unknown") envvars.set_pyrevit_env_var(envvars.IPYVERSION_ENVVAR, "0") # set cpython engine version env var cpyengine = user_config.get_active_cpython_engine() if cpyengine: envvars.set_pyrevit_env_var(envvars.CPYVERSION_ENVVAR, str(cpyengine.Version)) else: envvars.set_pyrevit_env_var(envvars.CPYVERSION_ENVVAR, "0") # set a list of important assemblies # this is required for dotnet script execution set_loaded_pyrevit_referenced_modules( runtime.get_references() ) ``` ``` -------------------------------- ### Get Revision Number Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Gets the revision number for a given revision object. If a sheet is provided, it returns the number as it appears on the sheet; otherwise, it returns the sequence number or revision number from the revision object. ```python def get_rev_number(revision, sheet=None): """ Get the revision number for a given revision. If a sheet is provided and it is an instance of DB.ViewSheet, the function returns the revision number as it appears on the sheet. Otherwise, it returns the sequence number of the revision or the revision number if it exists. Args: revision (DB.Revision): The revision object to get the number for. sheet (DB.ViewSheet, optional): The sheet object to get the revision number from. Defaults to None. Returns: str: The revision number as a string. """ # if sheet is provided, get number on sheet if sheet and isinstance(sheet, DB.ViewSheet): return sheet.GetRevisionNumberOnSheet(revision.Id) # otherwise get number from revision revnum = revision.SequenceNumber if hasattr(revision, "RevisionNumber"): revnum = revision.RevisionNumber return revnum ``` -------------------------------- ### Get Revit Window Rectangle Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the screen coordinates (left, top, right, bottom) of the main Revit window. This function utilizes the Windows API to get the window's bounding box. ```python def get_window_rectangle(): """Get the rectangle coordinates of the main window. Returns: (Tuple[int, int, int, int]): The left, top, right, and bottom coordinates of the window rectangle. """ return Common.User32.GetWindowRect(get_mainwindow_hwnd()) ``` -------------------------------- ### Define Preflight Test Execution Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Implement the `startTest` method to contain the core logic of the preflight test. This method is called after `setUp`. ```python def startTest(self, doc, output): """Hook method for exercising the test.""" pass ``` -------------------------------- ### Get Telemetry Status Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the overall telemetry status by attempting to get the status from configured server URLs. It prioritizes the general telemetry server URL and falls back to the application-specific telemetry server URL. ```python def get_status(): return get_status_from_url( get_telemetry_server_url() or get_apptelemetry_server_url() ) ``` -------------------------------- ### Setup Default Window Icon Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the default icon for the window by loading it from a predefined path within the application's binary directory. ```python def setup_icon(self): """Setup default window icon.""" self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png')) ``` -------------------------------- ### load_ui Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Loads a XAML file into a given window instance. If the window instance has a 'setup' method, it will be called after loading. Handles escape key and setting window owner. ```APIDOC ## load_ui(ui_instance, ui_file='ui.xaml', handle_esc=True, set_owner=True) ### Description Loads a XAML file into a given window instance. If the window instance defines a method named `setup`, it will be called after loading. ### Parameters #### Path Parameters - **ui_instance** (WPFWindow) - Required - ui form instance - **ui_file** (str) - Optional - name of ui xaml file. Defaults to 'ui.xaml' - **handle_esc** (bool) - Optional - handle escape and close window. Defaults to True - **set_owner** (bool) - Optional - set window owner to Revit window. Defaults to True ``` -------------------------------- ### Get Service ID Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the ID for the DirectContext3DService. ```python def GetServiceId(self): return ( es.ExternalServices .BuiltInExternalServices.DirectContext3DService) ``` -------------------------------- ### Setup WPF Resources Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Configures WPF resources for a control, including colors and brushes. These resources can be used for styling UI elements. ```python @staticmethod def setup_resources(wpf_ctrl): """Sets the WPF resources.""" #2c3e50 wpf_ctrl.Resources['pyRevitDarkColor'] = \ Media.Color.FromArgb(0xFF, 0x2c, 0x3e, 0x50) #23303d wpf_ctrl.Resources['pyRevitDarkerDarkColor'] = \ Media.Color.FromArgb(0xFF, 0x23, 0x30, 0x3d) #ffffff wpf_ctrl.Resources['pyRevitButtonColor'] = \ Media.Color.FromArgb(0xFF, 0xff, 0xff, 0xff) #f39c12 wpf_ctrl.Resources['pyRevitAccentColor'] = \ Media.Color.FromArgb(0xFF, 0xf3, 0x9c, 0x12) wpf_ctrl.Resources['pyRevitDarkBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitDarkColor']) wpf_ctrl.Resources['pyRevitAccentBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitAccentColor']) wpf_ctrl.Resources['pyRevitDarkerDarkBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitDarkerDarkColor']) wpf_ctrl.Resources['pyRevitButtonForgroundBrush'] = \ Media.SolidColorBrush(wpf_ctrl.Resources['pyRevitButtonColor']) wpf_ctrl.Resources['pyRevitRecognizesAccessKey'] = \ DEFAULT_RECOGNIZE_ACCESS_KEY ``` -------------------------------- ### Extension Bundle Structure Example Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/CLAUDE.md Illustrates the hierarchical structure for organizing pyRevit extensions, including configuration files, scripts, and icons. ```yaml MyExtension.extension/ MyTab.tab/ MyPanel.panel/ MyButton.pushbutton/ bundle.yaml # Button configuration script.py # Python script icon.png # Button icon ``` -------------------------------- ### Get Name Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Retrieves the name of the 3D server. ```python def GetName(self): return self.name ``` -------------------------------- ### configure() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Configures all components based on the extension's manifest. ```APIDOC ## configure() ### Description Loads the extension's manifest and configures each component with the settings from the manifest. ### Method ```python def configure(self): cfg_dict = self.get_manifest() if cfg_dict: for component in self: component.configure(cfg_dict) ``` ``` -------------------------------- ### setup_owner Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Sets the owner for the current window. ```APIDOC ## setup_owner() ### Description Set the window owner. ``` -------------------------------- ### Generate HTML Card Start Style Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Generates the starting HTML div for a card with dynamic background color based on value-to-limit ratio. Handles zero division and provides color coding for different ratio ranges (green, orange, red). ```python def card_start_style(limit, value, alt): """ Generates an HTML div element with a specific background color based on the ratio of value to limit. Args: limit (float): The limit value used to calculate the ratio. value (float): The current value to be compared against the limit. alt (str): The alt text for the div element. Returns: str: An HTML div element as a string with inline styles and the specified background color. The background color is determined by the following rules: - 'Grey' if value is 0 or if an exception occurs during ratio calculation. - 'Green' if 0 <= ratio < 0.5. - 'Orange' if 0.5 <= ratio <= 1. - 'Red' if ratio > 1. """ try: ratio = float(value) / float(limit) except ZeroDivisionError: ratio = 0 color = "#d0d3d4" if value != 0: if ratio < 0.5: color = "#D0E6A5" # green elif ratio <= 1: color = "#FFDD94" # orange else: color = "#FA897B" # red try: card_start = '
'.format( color, alt ) except Exception as e: print(e) return card_start ``` -------------------------------- ### get_current_theme() Source: https://github.com/pyrevitlabs/pyrevit/blob/develop/docs/llms-full.txt Gets the current UI theme being used by pyRevit. ```APIDOC ## get_current_theme() ### Description Get the current UI theme. ### Returns - `UITheme`: The current UI theme. ```