Skip to content

forms

Reusable WPF forms for pyRevit.

Examples:

from pyrevit.forms import WPFWindow

Attributes

mlogger = get_logger(__name__) module-attribute

DEFAULT_CMDSWITCHWND_WIDTH = 600 module-attribute

DEFAULT_SEARCHWND_WIDTH = 600 module-attribute

DEFAULT_SEARCHWND_HEIGHT = 100 module-attribute

DEFAULT_INPUTWINDOW_WIDTH = 500 module-attribute

DEFAULT_INPUTWINDOW_HEIGHT = 600 module-attribute

DEFAULT_RECOGNIZE_ACCESS_KEY = False module-attribute

WPF_HIDDEN = framework.Windows.Visibility.Hidden module-attribute

WPF_COLLAPSED = framework.Windows.Visibility.Collapsed module-attribute

WPF_VISIBLE = framework.Windows.Visibility.Visible module-attribute

XAML_FILES_DIR = op.dirname(__file__) module-attribute

ParamDef = namedtuple('ParamDef', ['name', 'istype', 'definition', 'isreadonly']) module-attribute

Parameter definition tuple.

Attributes:

Name Type Description
name str

parameter name

istype bool

true if type parameter, otherwise false

definition Definition

parameter definition object

isreadonly bool

true if the parameter value can't be edited

Classes

reactive(getter)

Bases: property

Decorator for WPF bound properties.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, getter):
    def newgetter(ui_control):
        try:
            return getter(ui_control)
        except AttributeError:
            return None
    super(reactive, self).__init__(newgetter)

Functions

setter(setter)

Property setter.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setter(self, setter):
    """Property setter."""
    def newsetter(ui_control, newvalue):
        oldvalue = self.fget(ui_control)
        if oldvalue != newvalue:
            setter(ui_control, newvalue)
            ui_control.OnPropertyChanged(setter.__name__)
    return property(
        fget=self.fget,
        fset=newsetter,
        fdel=self.fdel,
        doc=self.__doc__)

Reactive

Bases: INotifyPropertyChanged

WPF property updator base mixin.

Functions

add_PropertyChanged(value)

Called when a property is added to the object.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def add_PropertyChanged(self, value):
    """Called when a property is added to the object."""
    self.PropertyChanged += value
remove_PropertyChanged(value)

Called when a property is removed from the object.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def remove_PropertyChanged(self, value):
    """Called when a property is removed from the object."""
    self.PropertyChanged -= value
OnPropertyChanged(prop_name)

Called when a property is changed.

Parameters:

Name Type Description Default
prop_name str

property name

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def OnPropertyChanged(self, prop_name):
    """Called when a property is changed.

    Args:
        prop_name (str): property name
    """
    if self._propertyChangedCaller:
        args = ComponentModel.PropertyChangedEventArgs(prop_name)
        self._propertyChangedCaller(self, args)

WindowToggler(window)

Bases: object

Context manager to toggle window visibility.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, window):
    self._window = window

WPFWindow(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Bases: Window

WPF Window base class for all pyRevit forms.

Parameters:

Name Type Description Default
xaml_source str

xaml source filepath or xaml content

required
literal_string bool

xaml_source contains xaml content, not filepath

False
handle_esc bool

handle Escape button and close the window

True
set_owner bool

set the owner of window to host app window

True

Examples:

from pyrevit import forms
layout = '<Window ' \
         'xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" ' \
         'xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ' \
         'ShowInTaskbar="False" ResizeMode="NoResize" ' \
         'WindowStartupLocation="CenterScreen" ' \
         'HorizontalContentAlignment="Center">' \
         '</Window>'
w = forms.WPFWindow(layout, literal_string=True)
w.show()

Initialize WPF window and resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Initialize WPF window and resources."""
    # load xaml
    self.load_xaml(
        xaml_source,
        literal_string=literal_string,
        handle_esc=handle_esc,
        set_owner=set_owner
        )

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
handle_input_key(sender, args)

Handle keyboard input and close the window on Escape.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):    #pylint: disable=W0613
    """Handle keyboard input and close the window on Escape."""
    if args.Key == Input.Key.Escape:
        self.Close()
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show(modal=False)

Show window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show(self, modal=False):
    """Show window."""
    if modal:
        return self.ShowDialog()
    # else open non-modal
    self.Show()
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
dispatch(func, *args, **kwargs)

Runs the function in a new thread.

Parameters:

Name Type Description Default
func Callable

function to run

required
*args Any

positional arguments to pass to func

()
**kwargs Any

keyword arguments to pass to func

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
def dispatch(self, func, *args, **kwargs):
    """Runs the function in a new thread.

    Args:
        func (Callable): function to run
        *args (Any): positional arguments to pass to func
        **kwargs (Any): keyword arguments to pass to func
    """
    if framework.get_current_thread_id() == self.thread_id:
        t = threading.Thread(
            target=func,
            args=args,
            kwargs=kwargs
            )
        t.start()
    else:
        # ask ui thread to call the func with args and kwargs
        self.Dispatcher.Invoke(
            System.Action(
                lambda: func(*args, **kwargs)
                ),
            Threading.DispatcherPriority.Background
            )
conceal()

Conceal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def conceal(self):
    """Conceal window."""
    return WindowToggler(self)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_COLLAPSED
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_VISIBLE
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    for wpfel in wpf_elements:
        if wpfel.Visibility == WPF_VISIBLE:
            WPFWindow.hide_element(wpfel)
        elif wpfel.Visibility == WPF_COLLAPSED:
            WPFWindow.show_element(wpfel)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = False
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = True
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)

WPFPanel()

Bases: Page

WPF panel base class for all pyRevit dockable panels.

panel_id (str) must be set on the type to dockable panel uuid panel_source (str): xaml source filepath

Examples:

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")

Initialize WPF panel and resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self):
    """Initialize WPF panel and resources."""
    if not self.panel_id:
        raise PyRevitException("\"panel_id\" property is not set")
    if not self.panel_source:
        raise PyRevitException("\"panel_source\" property is not set")

    if not op.exists(self.panel_source):
        wpf.LoadComponent(self,
                          os.path.join(EXEC_PARAMS.command_path,
                          self.panel_source))
    else:
        wpf.LoadComponent(self, self.panel_source)

    # set properties
    self.thread_id = framework.get_current_thread_id()
    WPFWindow.setup_resources(self)

Attributes

panel_id = None class-attribute instance-attribute
panel_source = None class-attribute instance-attribute
thread_id = framework.get_current_thread_id() instance-attribute

Functions

set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    WPFPanel.hide_element(*wpf_elements)
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    WPFPanel.show_element(*wpf_elements)
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    WPFPanel.toggle_element(*wpf_elements)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    WPFPanel.disable_element(*wpf_elements)
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list): WPF framework elements to be enabled
    """
    WPFPanel.enable_element(*wpf_elements)
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)

TemplateUserInputWindow(context, title, width, height, **kwargs)

Bases: WPFWindow

Base class for pyRevit user input standard forms.

Parameters:

Name Type Description Default
context any

window context element(s)

required
title str

window title

required
width int

window width

required
height int

window height

required
**kwargs Any

other arguments to be passed to :func:_setup

{}

Initialize user input window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, context, title, width, height, **kwargs):
    """Initialize user input window."""
    WPFWindow.__init__(self,
                       op.join(XAML_FILES_DIR, self.xaml_source),
                       handle_esc=True)
    self.Title = title or 'pyRevit'
    self.Width = width
    self.Height = height

    self._context = context
    self.response = None

    # parent window?
    owner = kwargs.get('owner', None)
    if owner:
        # set wpf windows directly
        self.Owner = owner
        self.WindowStartupLocation = \
            framework.Windows.WindowStartupLocation.CenterOwner

    self._setup(**kwargs)

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

xaml_source = 'BaseWindow.xaml' class-attribute instance-attribute
Title = title or 'pyRevit' instance-attribute
Width = width instance-attribute
Height = height instance-attribute
response = None instance-attribute
Owner = owner instance-attribute
WindowStartupLocation = framework.Windows.WindowStartupLocation.CenterOwner instance-attribute

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
handle_input_key(sender, args)

Handle keyboard input and close the window on Escape.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):    #pylint: disable=W0613
    """Handle keyboard input and close the window on Escape."""
    if args.Key == Input.Key.Escape:
        self.Close()
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
dispatch(func, *args, **kwargs)

Runs the function in a new thread.

Parameters:

Name Type Description Default
func Callable

function to run

required
*args Any

positional arguments to pass to func

()
**kwargs Any

keyword arguments to pass to func

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
def dispatch(self, func, *args, **kwargs):
    """Runs the function in a new thread.

    Args:
        func (Callable): function to run
        *args (Any): positional arguments to pass to func
        **kwargs (Any): keyword arguments to pass to func
    """
    if framework.get_current_thread_id() == self.thread_id:
        t = threading.Thread(
            target=func,
            args=args,
            kwargs=kwargs
            )
        t.start()
    else:
        # ask ui thread to call the func with args and kwargs
        self.Dispatcher.Invoke(
            System.Action(
                lambda: func(*args, **kwargs)
                ),
            Threading.DispatcherPriority.Background
            )
conceal()

Conceal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def conceal(self):
    """Conceal window."""
    return WindowToggler(self)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_COLLAPSED
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_VISIBLE
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    for wpfel in wpf_elements:
        if wpfel.Visibility == WPF_VISIBLE:
            WPFWindow.hide_element(wpfel)
        elif wpfel.Visibility == WPF_COLLAPSED:
            WPFWindow.show_element(wpfel)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = False
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = True
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)
show(context, title='User Input', width=DEFAULT_INPUTWINDOW_WIDTH, height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs) classmethod

Show user input window.

Parameters:

Name Type Description Default
context any

window context element(s)

required
title str

window title

'User Input'
width int

window width

DEFAULT_INPUTWINDOW_WIDTH
height int

window height

DEFAULT_INPUTWINDOW_HEIGHT
**kwargs any

other arguments to be passed to window

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
@classmethod
def show(cls, context,  #pylint: disable=W0221
         title='User Input',
         width=DEFAULT_INPUTWINDOW_WIDTH,
         height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs):
    """Show user input window.

    Args:
        context (any): window context element(s)
        title (str): window title
        width (int): window width
        height (int): window height
        **kwargs (any): other arguments to be passed to window
    """
    dlg = cls(context, title, width, height, **kwargs)
    dlg.ShowDialog()
    return dlg.response

TemplateListItem(orig_item, checked=False, checkable=True, name_attr=None)

Bases: Reactive

Base class for checkbox option wrapping another object.

Initialize the checkbox option and wrap given obj.

Parameters:

Name Type Description Default
orig_item any

Object to wrap (must have name property or be convertable to string with str()

required
checked bool

Initial state. Defaults to False

False
checkable bool

Use checkbox for items

True
name_attr str

Get this attribute of wrapped object as name

None
Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, orig_item,
             checked=False, checkable=True, name_attr=None):
    """Initialize the checkbox option and wrap given obj.

    Args:
        orig_item (any): Object to wrap (must have name property
                         or be convertable to string with str()
        checked (bool): Initial state. Defaults to False
        checkable (bool): Use checkbox for items
        name_attr (str): Get this attribute of wrapped object as name
    """
    super(TemplateListItem, self).__init__()
    self.item = orig_item
    self.state = checked
    self._nameattr = name_attr
    self._checkable = checkable

Attributes

item = orig_item instance-attribute
state = checked instance-attribute
name property

Name property.

checkable property writable

List Item CheckBox Visibility.

Functions

add_PropertyChanged(value)

Called when a property is added to the object.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def add_PropertyChanged(self, value):
    """Called when a property is added to the object."""
    self.PropertyChanged += value
remove_PropertyChanged(value)

Called when a property is removed from the object.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def remove_PropertyChanged(self, value):
    """Called when a property is removed from the object."""
    self.PropertyChanged -= value
OnPropertyChanged(prop_name)

Called when a property is changed.

Parameters:

Name Type Description Default
prop_name str

property name

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def OnPropertyChanged(self, prop_name):
    """Called when a property is changed.

    Args:
        prop_name (str): property name
    """
    if self._propertyChangedCaller:
        args = ComponentModel.PropertyChangedEventArgs(prop_name)
        self._propertyChangedCaller(self, args)
unwrap()

Unwrap and return wrapped object.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def unwrap(self):
    """Unwrap and return wrapped object."""
    return self.item
checked(value)
Source code in pyrevitlib/pyrevit/forms/__init__.py
@checked.setter
def checked(self, value):
    self.state = value

SelectFromList(context, title, width, height, **kwargs)

Bases: TemplateUserInputWindow

Standard form to select from a list of items.

Any object can be passed in a list to the context argument. This class wraps the objects passed to context, in TemplateListItem. This class provides the necessary mechanism to make this form work both for selecting items from a list, and from a list of checkboxes. See the list of arguments below for additional options and features.

Parameters:

Name Type Description Default
context list[str] or dict[list[str]]

list of items to be selected from OR dict of list of items to be selected from. use dict when input items need to be grouped e.g. List of sheets grouped by sheet set.

required
title str

window title. see super class for defaults.

required
width int

window width. see super class for defaults.

required
height int

window height. see super class for defaults.

required

Other Parameters:

Name Type Description
button_name str

name of select button. defaults to 'Select'

name_attr str

object attribute that should be read as item name.

multiselect bool

allow multi-selection (uses check boxes). defaults to False

info_panel bool

show information panel and fill with .description property of item

return_all bool

return all items. This is handly when some input items have states and the script needs to check the state changes on all items. This options works in multiselect mode only. defaults to False

filterfunc function

filter function to be applied to context items.

resetfunc function

reset function to be called when user clicks on Reset button

group_selector_title str

title for list group selector. defaults to 'List Group'

default_group str

name of defautl group to be selected

sort_groups str

Determines the sorting type applied to the list groups. This attribute can take one of the following values: 'sorted': This will sort the groups in standard alphabetical order 'natural': This will sort the groups in a manner that is more intuitive for human perception, especially when there are numbers involved. 'unsorted': The groups will maintain the original order in which they were provided, without any reordering. Defaults to 'sorted'.

Examples:

from pyrevit import forms
items = ['item1', 'item2', 'item3']
forms.SelectFromList.show(items, button_name='Select Item')
['item1']
from pyrevit import forms
ops = [viewsheet1, viewsheet2, viewsheet3]
res = forms.SelectFromList.show(ops,
                                multiselect=False,
                                name_attr='Name',
                                button_name='Select Sheet')

from pyrevit import forms
ops = {'Sheet Set A': [viewsheet1, viewsheet2, viewsheet3],
       'Sheet Set B': [viewsheet4, viewsheet5, viewsheet6]}
res = forms.SelectFromList.show(ops,
                                multiselect=True,
                                name_attr='Name',
                                group_selector_title='Sheet Sets',
                                button_name='Select Sheets',
                                sort_groups='sorted')

This module also provides a wrapper base class :obj:TemplateListItem for when the checkbox option is wrapping another element, e.g. a Revit ViewSheet. Derive from this base class and define the name property to customize how the checkbox is named on the dialog.

from pyrevit import forms
class MyOption(forms.TemplateListItem):
   @property
   def name(self):
       return '{} - {}{}'.format(self.item.SheetNumber,
                                 self.item.SheetNumber)
ops = [MyOption('op1'), MyOption('op2', True), MyOption('op3')]
res = forms.SelectFromList.show(ops,
                                multiselect=True,
                                button_name='Select Item')
[bool(x) for x in res]  # or [x.state for x in res]
[True, False, True]

Initialize user input window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, context, title, width, height, **kwargs):
    """Initialize user input window."""
    WPFWindow.__init__(self,
                       op.join(XAML_FILES_DIR, self.xaml_source),
                       handle_esc=True)
    self.Title = title or 'pyRevit'
    self.Width = width
    self.Height = height

    self._context = context
    self.response = None

    # parent window?
    owner = kwargs.get('owner', None)
    if owner:
        # set wpf windows directly
        self.Owner = owner
        self.WindowStartupLocation = \
            framework.Windows.WindowStartupLocation.CenterOwner

    self._setup(**kwargs)

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

Title = title or 'pyRevit' instance-attribute
Width = width instance-attribute
Height = height instance-attribute
response = None instance-attribute
Owner = owner instance-attribute
WindowStartupLocation = framework.Windows.WindowStartupLocation.CenterOwner instance-attribute
in_check = False class-attribute instance-attribute
in_uncheck = False class-attribute instance-attribute
xaml_source = 'SelectFromList.xaml' class-attribute instance-attribute
use_regex property

Is using regex?

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
handle_input_key(sender, args)

Handle keyboard input and close the window on Escape.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):    #pylint: disable=W0613
    """Handle keyboard input and close the window on Escape."""
    if args.Key == Input.Key.Escape:
        self.Close()
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show(context, title='User Input', width=DEFAULT_INPUTWINDOW_WIDTH, height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs) classmethod

Show user input window.

Parameters:

Name Type Description Default
context any

window context element(s)

required
title str

window title

'User Input'
width int

window width

DEFAULT_INPUTWINDOW_WIDTH
height int

window height

DEFAULT_INPUTWINDOW_HEIGHT
**kwargs any

other arguments to be passed to window

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
@classmethod
def show(cls, context,  #pylint: disable=W0221
         title='User Input',
         width=DEFAULT_INPUTWINDOW_WIDTH,
         height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs):
    """Show user input window.

    Args:
        context (any): window context element(s)
        title (str): window title
        width (int): window width
        height (int): window height
        **kwargs (any): other arguments to be passed to window
    """
    dlg = cls(context, title, width, height, **kwargs)
    dlg.ShowDialog()
    return dlg.response
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
dispatch(func, *args, **kwargs)

Runs the function in a new thread.

Parameters:

Name Type Description Default
func Callable

function to run

required
*args Any

positional arguments to pass to func

()
**kwargs Any

keyword arguments to pass to func

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
def dispatch(self, func, *args, **kwargs):
    """Runs the function in a new thread.

    Args:
        func (Callable): function to run
        *args (Any): positional arguments to pass to func
        **kwargs (Any): keyword arguments to pass to func
    """
    if framework.get_current_thread_id() == self.thread_id:
        t = threading.Thread(
            target=func,
            args=args,
            kwargs=kwargs
            )
        t.start()
    else:
        # ask ui thread to call the func with args and kwargs
        self.Dispatcher.Invoke(
            System.Action(
                lambda: func(*args, **kwargs)
                ),
            Threading.DispatcherPriority.Background
            )
conceal()

Conceal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def conceal(self):
    """Conceal window."""
    return WindowToggler(self)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_COLLAPSED
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_VISIBLE
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    for wpfel in wpf_elements:
        if wpfel.Visibility == WPF_VISIBLE:
            WPFWindow.hide_element(wpfel)
        elif wpfel.Visibility == WPF_COLLAPSED:
            WPFWindow.show_element(wpfel)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = False
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = True
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)
toggle_all(sender, args)

Handle toggle all button to toggle state of all check boxes.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def toggle_all(self, sender, args):    #pylint: disable=W0613
    """Handle toggle all button to toggle state of all check boxes."""
    self._set_states(flip=True)
check_all(sender, args)

Handle check all button to mark all check boxes as checked.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def check_all(self, sender, args):    #pylint: disable=W0613
    """Handle check all button to mark all check boxes as checked."""
    self._set_states(state=True)
uncheck_all(sender, args)

Handle uncheck all button to mark all check boxes as un-checked.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def uncheck_all(self, sender, args):    #pylint: disable=W0613
    """Handle uncheck all button to mark all check boxes as un-checked."""
    self._set_states(state=False)
check_selected(sender, args)

Mark selected checkboxes as checked.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def check_selected(self, sender, args):    #pylint: disable=W0613
    """Mark selected checkboxes as checked."""
    if not self.in_check:
        try:
            self.in_check = True
            self._set_states(state=True, selected=True)
        finally:
            self.in_check = False
uncheck_selected(sender, args)

Mark selected checkboxes as unchecked.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def uncheck_selected(self, sender, args):    #pylint: disable=W0613
    """Mark selected checkboxes as unchecked."""
    if not self.in_uncheck:
        try:
            self.in_uncheck = True
            self._set_states(state=False, selected=True)
        finally:
            self.in_uncheck = False
button_reset(sender, args)

Handle reset button click.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def button_reset(self, sender, args):#pylint: disable=W0613
    """Handle reset button click."""
    if self.reset_func:
        all_items = self.list_lb.ItemsSource
        self.reset_func(all_items)
button_select(sender, args)

Handle select button click.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def button_select(self, sender, args):    #pylint: disable=W0613
    """Handle select button click."""
    self.response = self._get_options()
    self.Close()
search_txt_changed(sender, args)

Handle text change in search box.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def search_txt_changed(self, sender, args):    #pylint: disable=W0613
    """Handle text change in search box."""
    if self.info_panel:
        self._toggle_info_panel(state=False)

    if self.search_tb.Text == '':
        self.hide_element(self.clrsearch_b)
    else:
        self.show_element(self.clrsearch_b)

    self._list_options(option_filter=self.search_tb.Text)
selection_changed(sender, args)

Handle selection change.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def selection_changed(self, sender, args):
    """Handle selection change."""
    if self.info_panel:
        self._toggle_info_panel(state=False)

    self._list_options(option_filter=self.search_tb.Text)
selected_item_changed(sender, args)

Handle selected item change.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def selected_item_changed(self, sender, args):
    """Handle selected item change."""
    if self.info_panel and self.list_lb.SelectedItem is not None:
        self._toggle_info_panel(state=True)
        self.infoData.Text = \
            getattr(self.list_lb.SelectedItem, 'description', '')
toggle_regex(sender, args)

Activate regex in search.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def toggle_regex(self, sender, args):
    """Activate regex in search."""
    self.regexToggle_b.Content = \
        self.Resources['regexIcon'] if self.use_regex \
            else self.Resources['filterIcon']
    self.search_txt_changed(sender, args)
    self.search_tb.Focus()

Clear search box.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def clear_search(self, sender, args):    #pylint: disable=W0613
    """Clear search box."""
    self.search_tb.Text = ' '
    self.search_tb.Clear()
    self.search_tb.Focus()

CommandSwitchWindow(context, title, width, height, **kwargs)

Bases: TemplateUserInputWindow

Standard form to select from a list of command options.

Other Parameters:

Name Type Description
context list[str]

list of command options to choose from

switches list[str]

list of on/off switches

message str

window title message

config dict

dictionary of config dicts for options or switches

recognize_access_key bool

recognize '_' as mark of access key

Returns:

Type Description
str | tuple[str, dict]

name of selected option. if switches option is used, returns a tuple of selection option name and dict of switches

Examples:

This is an example with series of command options:

from pyrevit import forms
ops = ['option1', 'option2', 'option3', 'option4']
forms.CommandSwitchWindow.show(ops, message='Select Option')
'option2'

A more advanced example of combining command options, on/off switches, and option or switch configuration options:

from pyrevit import forms
ops = ['option1', 'option2', 'option3', 'option4']
switches = ['switch1', 'switch2']
cfgs = {'option1': { 'background': '0xFF55FF'}}
rops, rswitches = forms.CommandSwitchWindow.show(
    ops,
    switches=switches
    message='Select Option',
    config=cfgs,
    recognize_access_key=False
    )
rops
'option2'
rswitches
{'switch1': False, 'switch2': True}

Initialize user input window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, context, title, width, height, **kwargs):
    """Initialize user input window."""
    WPFWindow.__init__(self,
                       op.join(XAML_FILES_DIR, self.xaml_source),
                       handle_esc=True)
    self.Title = title or 'pyRevit'
    self.Width = width
    self.Height = height

    self._context = context
    self.response = None

    # parent window?
    owner = kwargs.get('owner', None)
    if owner:
        # set wpf windows directly
        self.Owner = owner
        self.WindowStartupLocation = \
            framework.Windows.WindowStartupLocation.CenterOwner

    self._setup(**kwargs)

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

Title = title or 'pyRevit' instance-attribute
Width = width instance-attribute
Height = height instance-attribute
response = None instance-attribute
Owner = owner instance-attribute
WindowStartupLocation = framework.Windows.WindowStartupLocation.CenterOwner instance-attribute
xaml_source = 'CommandSwitchWindow.xaml' class-attribute instance-attribute

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show(context, title='User Input', width=DEFAULT_INPUTWINDOW_WIDTH, height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs) classmethod

Show user input window.

Parameters:

Name Type Description Default
context any

window context element(s)

required
title str

window title

'User Input'
width int

window width

DEFAULT_INPUTWINDOW_WIDTH
height int

window height

DEFAULT_INPUTWINDOW_HEIGHT
**kwargs any

other arguments to be passed to window

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
@classmethod
def show(cls, context,  #pylint: disable=W0221
         title='User Input',
         width=DEFAULT_INPUTWINDOW_WIDTH,
         height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs):
    """Show user input window.

    Args:
        context (any): window context element(s)
        title (str): window title
        width (int): window width
        height (int): window height
        **kwargs (any): other arguments to be passed to window
    """
    dlg = cls(context, title, width, height, **kwargs)
    dlg.ShowDialog()
    return dlg.response
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
dispatch(func, *args, **kwargs)

Runs the function in a new thread.

Parameters:

Name Type Description Default
func Callable

function to run

required
*args Any

positional arguments to pass to func

()
**kwargs Any

keyword arguments to pass to func

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
def dispatch(self, func, *args, **kwargs):
    """Runs the function in a new thread.

    Args:
        func (Callable): function to run
        *args (Any): positional arguments to pass to func
        **kwargs (Any): keyword arguments to pass to func
    """
    if framework.get_current_thread_id() == self.thread_id:
        t = threading.Thread(
            target=func,
            args=args,
            kwargs=kwargs
            )
        t.start()
    else:
        # ask ui thread to call the func with args and kwargs
        self.Dispatcher.Invoke(
            System.Action(
                lambda: func(*args, **kwargs)
                ),
            Threading.DispatcherPriority.Background
            )
conceal()

Conceal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def conceal(self):
    """Conceal window."""
    return WindowToggler(self)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_COLLAPSED
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_VISIBLE
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    for wpfel in wpf_elements:
        if wpfel.Visibility == WPF_VISIBLE:
            WPFWindow.hide_element(wpfel)
        elif wpfel.Visibility == WPF_COLLAPSED:
            WPFWindow.show_element(wpfel)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = False
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = True
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)
handle_click(sender, args)

Handle mouse click.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_click(self, sender, args):    #pylint: disable=W0613
    """Handle mouse click."""
    self.Close()
handle_input_key(sender, args)

Handle keyboard inputs.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):
    """Handle keyboard inputs."""
    if args.Key == Input.Key.Escape:
        if self.search_tb.Text:
            self.search_tb.Text = ''
        else:
            self.Close()
    elif args.Key == Input.Key.Enter:
        active_button = self._get_active_button()
        if active_button:
            if isinstance(active_button,
                          framework.Controls.Primitives.ToggleButton):
                return
            self.process_option(active_button, None)
            args.Handled = True
    elif args.Key != Input.Key.Tab \
            and args.Key != Input.Key.Space\
            and args.Key != Input.Key.LeftShift\
            and args.Key != Input.Key.RightShift:
        self.search_tb.Focus()
search_txt_changed(sender, args)

Handle text change in search box.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def search_txt_changed(self, sender, args):    #pylint: disable=W0613
    """Handle text change in search box."""
    self._filter_options(option_filter=self.search_tb.Text)
process_option(sender, args)

Handle click on command option button.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def process_option(self, sender, args):    #pylint: disable=W0613
    """Handle click on command option button."""
    self.Close()
    if sender:
        self._setup_response(response=sender.Content)

GetValueWindow(context, title, width, height, **kwargs)

Bases: TemplateUserInputWindow

Standard form to get simple values from user.

Examples:

from pyrevit import forms
items = ['item1', 'item2', 'item3']
forms.SelectFromList.show(items, button_name='Select Item')
['item1']

Initialize user input window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, context, title, width, height, **kwargs):
    """Initialize user input window."""
    WPFWindow.__init__(self,
                       op.join(XAML_FILES_DIR, self.xaml_source),
                       handle_esc=True)
    self.Title = title or 'pyRevit'
    self.Width = width
    self.Height = height

    self._context = context
    self.response = None

    # parent window?
    owner = kwargs.get('owner', None)
    if owner:
        # set wpf windows directly
        self.Owner = owner
        self.WindowStartupLocation = \
            framework.Windows.WindowStartupLocation.CenterOwner

    self._setup(**kwargs)

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

Title = title or 'pyRevit' instance-attribute
Width = width instance-attribute
Height = height instance-attribute
response = None instance-attribute
Owner = owner instance-attribute
WindowStartupLocation = framework.Windows.WindowStartupLocation.CenterOwner instance-attribute
xaml_source = 'GetValueWindow.xaml' class-attribute instance-attribute

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
handle_input_key(sender, args)

Handle keyboard input and close the window on Escape.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):    #pylint: disable=W0613
    """Handle keyboard input and close the window on Escape."""
    if args.Key == Input.Key.Escape:
        self.Close()
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show(context, title='User Input', width=DEFAULT_INPUTWINDOW_WIDTH, height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs) classmethod

Show user input window.

Parameters:

Name Type Description Default
context any

window context element(s)

required
title str

window title

'User Input'
width int

window width

DEFAULT_INPUTWINDOW_WIDTH
height int

window height

DEFAULT_INPUTWINDOW_HEIGHT
**kwargs any

other arguments to be passed to window

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
@classmethod
def show(cls, context,  #pylint: disable=W0221
         title='User Input',
         width=DEFAULT_INPUTWINDOW_WIDTH,
         height=DEFAULT_INPUTWINDOW_HEIGHT, **kwargs):
    """Show user input window.

    Args:
        context (any): window context element(s)
        title (str): window title
        width (int): window width
        height (int): window height
        **kwargs (any): other arguments to be passed to window
    """
    dlg = cls(context, title, width, height, **kwargs)
    dlg.ShowDialog()
    return dlg.response
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
dispatch(func, *args, **kwargs)

Runs the function in a new thread.

Parameters:

Name Type Description Default
func Callable

function to run

required
*args Any

positional arguments to pass to func

()
**kwargs Any

keyword arguments to pass to func

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
def dispatch(self, func, *args, **kwargs):
    """Runs the function in a new thread.

    Args:
        func (Callable): function to run
        *args (Any): positional arguments to pass to func
        **kwargs (Any): keyword arguments to pass to func
    """
    if framework.get_current_thread_id() == self.thread_id:
        t = threading.Thread(
            target=func,
            args=args,
            kwargs=kwargs
            )
        t.start()
    else:
        # ask ui thread to call the func with args and kwargs
        self.Dispatcher.Invoke(
            System.Action(
                lambda: func(*args, **kwargs)
                ),
            Threading.DispatcherPriority.Background
            )
conceal()

Conceal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def conceal(self):
    """Conceal window."""
    return WindowToggler(self)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_COLLAPSED
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_VISIBLE
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    for wpfel in wpf_elements:
        if wpfel.Visibility == WPF_VISIBLE:
            WPFWindow.hide_element(wpfel)
        elif wpfel.Visibility == WPF_COLLAPSED:
            WPFWindow.show_element(wpfel)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = False
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = True
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)
string_value_changed(sender, args)

Handle string vlaue update event.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def string_value_changed(self, sender, args): #pylint: disable=unused-argument
    """Handle string vlaue update event."""
    filtered_rvalues = \
        sorted([x for x in self.reserved_values
                if self.stringValue_tb.Text == str(x)])
    similar_rvalues = \
        sorted([x for x in self.reserved_values
                if self.stringValue_tb.Text in str(x)],
               reverse=True)
    filtered_rvalues.extend(similar_rvalues)
    if filtered_rvalues:
        self.reservedValuesList.ItemsSource = filtered_rvalues
        self.show_element(self.reservedValuesListPanel)
        self.okayButton.IsEnabled = \
            self.stringValue_tb.Text not in filtered_rvalues
    else:
        self.reservedValuesList.ItemsSource = []
        self.hide_element(self.reservedValuesListPanel)
        self.okayButton.IsEnabled = True
select(sender, args)

Process input data and set the response.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def select(self, sender, args):    #pylint: disable=W0613
    """Process input data and set the response."""
    self.Close()
    if self.value_type == 'string':
        self.response = self.stringValue_tb.Text
    elif self.value_type == 'dropdown':
        self.response = self.dropdown_cb.SelectedItem
    elif self.value_type == 'date':
        if self.datePicker.SelectedDate:
            datestr = self.datePicker.SelectedDate.ToString("MM/dd/yyyy")
            self.response = datetime.datetime.strptime(datestr, r'%m/%d/%Y')
        else:
            self.response = None
    elif self.value_type == 'slider':
        self.response = self.numberPicker.Value

TemplatePromptBar(height=32, **kwargs)

Bases: WPFWindow

Template context-manager class for creating prompt bars.

Prompt bars are show at the top of the active Revit window and are designed for better prompt visibility.

Parameters:

Name Type Description Default
height int

window height

32
**kwargs Any

other arguments to be passed to :func:_setup

{}

Initialize user prompt window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, height=32, **kwargs):
    """Initialize user prompt window."""
    WPFWindow.__init__(self,
                       op.join(XAML_FILES_DIR, self.xaml_source))

    self.user_height = height
    self.update_window()
    self._setup(**kwargs)

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

xaml_source = 'TemplatePromptBar.xaml' class-attribute instance-attribute
user_height = height instance-attribute

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
handle_input_key(sender, args)

Handle keyboard input and close the window on Escape.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):    #pylint: disable=W0613
    """Handle keyboard input and close the window on Escape."""
    if args.Key == Input.Key.Escape:
        self.Close()
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show(modal=False)

Show window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show(self, modal=False):
    """Show window."""
    if modal:
        return self.ShowDialog()
    # else open non-modal
    self.Show()
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self, wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    WPFWindow.set_image_source_file(wpf_element, image_file)
dispatch(func, *args, **kwargs)

Runs the function in a new thread.

Parameters:

Name Type Description Default
func Callable

function to run

required
*args Any

positional arguments to pass to func

()
**kwargs Any

keyword arguments to pass to func

{}
Source code in pyrevitlib/pyrevit/forms/__init__.py
def dispatch(self, func, *args, **kwargs):
    """Runs the function in a new thread.

    Args:
        func (Callable): function to run
        *args (Any): positional arguments to pass to func
        **kwargs (Any): keyword arguments to pass to func
    """
    if framework.get_current_thread_id() == self.thread_id:
        t = threading.Thread(
            target=func,
            args=args,
            kwargs=kwargs
            )
        t.start()
    else:
        # ask ui thread to call the func with args and kwargs
        self.Dispatcher.Invoke(
            System.Action(
                lambda: func(*args, **kwargs)
                ),
            Threading.DispatcherPriority.Background
            )
conceal()

Conceal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def conceal(self):
    """Conceal window."""
    return WindowToggler(self)
hide_element(*wpf_elements) staticmethod

Collapse elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be collaped

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def hide_element(*wpf_elements):
    """Collapse elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be collaped
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_COLLAPSED
show_element(*wpf_elements) staticmethod

Show collapsed elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be set to visible.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def show_element(*wpf_elements):
    """Show collapsed elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be set to visible.
    """
    for wpfel in wpf_elements:
        wpfel.Visibility = WPF_VISIBLE
toggle_element(*wpf_elements) staticmethod

Toggle visibility of elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be toggled.

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def toggle_element(*wpf_elements):
    """Toggle visibility of elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be toggled.
    """
    for wpfel in wpf_elements:
        if wpfel.Visibility == WPF_VISIBLE:
            WPFWindow.hide_element(wpfel)
        elif wpfel.Visibility == WPF_COLLAPSED:
            WPFWindow.show_element(wpfel)
disable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def disable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = False
enable_element(*wpf_elements) staticmethod

Enable elements.

Parameters:

Name Type Description Default
*wpf_elements list[UIElement]

WPF framework elements to be enabled

()
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def enable_element(*wpf_elements):
    """Enable elements.

    Args:
        *wpf_elements (list[UIElement]): WPF framework elements to be enabled
    """
    for wpfel in wpf_elements:
        wpfel.IsEnabled = True
handle_url_click(sender, args)

Callback for handling click on package website url.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_url_click(self, sender, args): #pylint: disable=unused-argument
    """Callback for handling click on package website url."""
    return webbrowser.open_new_tab(sender.NavigateUri.AbsoluteUri)
update_window()

Update the prompt bar to match Revit window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def update_window(self):
    """Update the prompt bar to match Revit window."""
    screen_area = HOST_APP.proc_screen_workarea
    scale_factor = 1.0 / HOST_APP.proc_screen_scalefactor
    top = left = width = height = 0

    window_rect = revit.ui.get_window_rectangle()

    # set width and height
    width = window_rect.Right - window_rect.Left
    height = self.user_height

    top = window_rect.Top
    # in maximized window, the top might be off the active screen
    # due to windows thicker window frames
    # lets cut the height and re-adjust the top
    top_diff = abs(screen_area.Top - top)
    if 10 > top_diff > 0 and top_diff < height:
        height -= top_diff
        top = screen_area.Top

    left = window_rect.Left
    # in maximized window, Left also might be off the active screen
    # due to windows thicker window frames
    # let's fix the width to accomodate the extra pixels as well
    left_diff = abs(screen_area.Left - left)
    if 10 > left_diff > 0 and left_diff < width:
        # deduct two times the left negative offset since this extra
        # offset happens on both left and right side
        width -= left_diff * 2
        left = screen_area.Left

    self.Top = top * scale_factor
    self.Left = left * scale_factor
    self.Width = width * scale_factor
    self.Height = height

WarningBar(height=32, **kwargs)

Bases: TemplatePromptBar

Show warning bar at the top of Revit window.

Other Parameters:

Name Type Description
title string

warning bar text

Examples:

with WarningBar(title='my warning'):
   # do stuff

Initialize user prompt window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def __init__(self, height=32, **kwargs):
    """Initialize user prompt window."""
    WPFWindow.__init__(self,
                       op.join(XAML_FILES_DIR, self.xaml_source))

    self.user_height = height
    self.update_window()
    self._setup(**kwargs)

Attributes

pyrevit_version property

Active pyRevit formatted version e.g. '4.9-beta'.

user_height = height instance-attribute
xaml_source = 'WarningBar.xaml' class-attribute instance-attribute

Functions

load_xaml(xaml_source, literal_string=False, handle_esc=True, set_owner=True)

Load the window XAML file.

Parameters:

Name Type Description Default
xaml_source str

The XAML content or file path to load.

required
literal_string bool

True if xaml_source is content, False if it is a path. Defaults to False.

False
handle_esc bool

Whether the ESC key should be handled. Defaults to True.

True
set_owner bool

Whether to se the window owner. Defaults to True.

True
Source code in pyrevitlib/pyrevit/forms/__init__.py
def load_xaml(self, xaml_source, literal_string=False, handle_esc=True, set_owner=True):
    """Load the window XAML file.

    Args:
        xaml_source (str): The XAML content or file path to load.
        literal_string (bool, optional): True if `xaml_source` is content,
            False if it is a path. Defaults to False.
        handle_esc (bool, optional): Whether the ESC key should be handled.
            Defaults to True.
        set_owner (bool, optional): Whether to se the window owner.
            Defaults to True.
    """
    # create new id for this window
    self.window_id = coreutils.new_uuid()

    if not literal_string:
        wpf.LoadComponent(self, self._determine_xaml(xaml_source))
    else:
        wpf.LoadComponent(self, framework.StringReader(xaml_source))

    # set properties
    self.thread_id = framework.get_current_thread_id()
    if set_owner:
        self.setup_owner()
    self.setup_icon()
    WPFWindow.setup_resources(self)
    if handle_esc:
        self.setup_default_handlers()
merge_resource_dict(xaml_source)

Merge a ResourceDictionary xaml file with this window.

Parameters:

Name Type Description Default
xaml_source str

xaml file with the resource dictionary

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def merge_resource_dict(self, xaml_source):
    """Merge a ResourceDictionary xaml file with this window.

    Args:
        xaml_source (str): xaml file with the resource dictionary
    """
    lang_dictionary = ResourceDictionary()
    lang_dictionary.Source = Uri(xaml_source, UriKind.Absolute)
    self.Resources.MergedDictionaries.Add(lang_dictionary)
get_locale_string(string_name)

Get localized string.

Parameters:

Name Type Description Default
string_name str

string name

required

Returns:

Type Description
str

localized string

Source code in pyrevitlib/pyrevit/forms/__init__.py
def get_locale_string(self, string_name):
    """Get localized string.

    Args:
        string_name (str): string name

    Returns:
        (str): localized string
    """
    return self.FindResource(string_name)
setup_owner()

Set the window owner.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_owner(self):
    """Set the window owner."""
    wih = Interop.WindowInteropHelper(self)
    wih.Owner = AdWindows.ComponentManager.ApplicationWindow
setup_resources(wpf_ctrl) staticmethod

Sets the WPF resources.

Source code in pyrevitlib/pyrevit/forms/__init__.py
@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_default_handlers()

Set the default handlers.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_default_handlers(self):
    """Set the default handlers."""
    self.PreviewKeyDown += self.handle_input_key    #pylint: disable=E1101
handle_input_key(sender, args)

Handle keyboard input and close the window on Escape.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def handle_input_key(self, sender, args):    #pylint: disable=W0613
    """Handle keyboard input and close the window on Escape."""
    if args.Key == Input.Key.Escape:
        self.Close()
set_icon(icon_path)

Set window icon to given icon path.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_icon(self, icon_path):
    """Set window icon to given icon path."""
    self.Icon = utils.bitmap_from_file(icon_path)
setup_icon()

Setup default window icon.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def setup_icon(self):
    """Setup default window icon."""
    self.set_icon(op.join(BIN_DIR, 'pyrevit_settings.png'))
hide()

Hide window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def hide(self):
    """Hide window."""
    self.Hide()
show(modal=False)

Show window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show(self, modal=False):
    """Show window."""
    if modal:
        return self.ShowDialog()
    # else open non-modal
    self.Show()
show_dialog()

Show modal window.

Source code in pyrevitlib/pyrevit/forms/__init__.py
def show_dialog(self):
    """Show modal window."""
    return self.ShowDialog()
set_image_source_file(wpf_element, image_file) staticmethod

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
@staticmethod
def set_image_source_file(wpf_element, image_file):
    """Set source file for image element.

    Args:
        wpf_element (System.Windows.Controls.Image): xaml image element
        image_file (str): image file path
    """
    if not op.exists(image_file):
        wpf_element.Source = \
            utils.bitmap_from_file(
                os.path.join(EXEC_PARAMS.command_path,
                             image_file)
                )
    else:
        wpf_element.Source = utils.bitmap_from_file(image_file)
set_image_source(wpf_element, image_file)

Set source file for image element.

Parameters:

Name Type Description Default
wpf_element Image

xaml image element

required
image_file str

image file path

required
Source code in pyrevitlib/pyrevit/forms/__init__.py
def set_image_source(self,