code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __init__( self, *label, name=None, prefix_icon=None, suffix_icon=None, clear_icon=None, show_password_icon=None, hide_password_icon=None, **kwargs, ): """ The `*label` argument sets the text input's label. The kwargs suffixed by `_icon` each take an icon name and slot that icon into the respective slot. """ if name is None: name = concat_text(label) super().__init__(*label, name=name, **kwargs) with self: if prefix_icon: icon(prefix_icon, slot=self.prefix) if suffix_icon: icon(suffix_icon, slot=self.suffix) if clear_icon: icon(clear_icon, slot=self.clear) if show_password_icon: icon(show_password_icon, slot=self.show_password) if hide_password_icon: icon(hide_password_icon, slot=self.hide_password)
The `*label` argument sets the text input's label. The kwargs suffixed by `_icon` each take an icon name and slot that icon into the respective slot.
__init__
python
hyperdiv/hyperdiv
hyperdiv/components/text_input.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/text_input.py
Apache-2.0
def is_light(self): """ Returns `True` if the theme is in light mode, and `False` if the theme is in dark mode, regardless of whether the theme mode is set by the user or follows system. """ if self.mode == "system": return self.system_mode == "light" else: return self.mode == "light"
Returns `True` if the theme is in light mode, and `False` if the theme is in dark mode, regardless of whether the theme mode is set by the user or follows system.
is_light
python
hyperdiv/hyperdiv
hyperdiv/components/theme.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/theme.py
Apache-2.0
def __init__(self, *content, **kwargs): """ If `*content` is passed, it will be joined by `" "` and used to initialize the `content` prop. """ if content: kwargs["content"] = concat_text(content) super().__init__(**kwargs)
If `*content` is passed, it will be joined by `" "` and used to initialize the `content` prop.
__init__
python
hyperdiv/hyperdiv
hyperdiv/components/tooltip.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/tooltip.py
Apache-2.0
def __init__( self, expand_icon_name=None, collapse_icon_name=None, **kwargs, ): """ @component(icon) names can be passed in `expand_icon_name` or `collapse_icon_name` to customize the expand and collapse icons of all expandable tree nodes. The icons will automatically placed in their respective slots. The rest of `**kwargs` are passed to `Component`. """ super().__init__(**kwargs) if expand_icon_name or collapse_icon_name: with self: if expand_icon_name: icon(expand_icon_name, slot=self.expand_icon) if collapse_icon_name: icon(collapse_icon_name, slot=self.collapse_icon)
@component(icon) names can be passed in `expand_icon_name` or `collapse_icon_name` to customize the expand and collapse icons of all expandable tree nodes. The icons will automatically placed in their respective slots. The rest of `**kwargs` are passed to `Component`.
__init__
python
hyperdiv/hyperdiv
hyperdiv/components/tree.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/tree.py
Apache-2.0
def selected_items(self): """ Returns the complete list of the @component(tree_item) children that are currently selected. """ children = [] def collect_children(node): for c in node.children: if isinstance(c, tree_item): if c._key in self._selected_keys: children.append(c) collect_children(c) collect_children(self) return children
Returns the complete list of the @component(tree_item) children that are currently selected.
selected_items
python
hyperdiv/hyperdiv
hyperdiv/components/tree.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/tree.py
Apache-2.0
def __init__( self, *label, expand_icon_name=None, collapse_icon_name=None, **kwargs, ): """ @component(icon) names can be passed in `expand_icon_name` or `collapse_icon_name` to customize the expand and collapse icons of this specific three node. The icons will automatically placed in their respective slots. These icons override icons set in the parent @component(tree). `*label` and `**kwargs` are passed to @component(LabelComponent). """ super().__init__(*label, **kwargs) if expand_icon_name or collapse_icon_name: with self: if expand_icon_name: icon(expand_icon_name, slot=self.expand_icon) if collapse_icon_name: icon(collapse_icon_name, slot=self.collapse_icon)
@component(icon) names can be passed in `expand_icon_name` or `collapse_icon_name` to customize the expand and collapse icons of this specific three node. The icons will automatically placed in their respective slots. These icons override icons set in the parent @component(tree). `*label` and `**kwargs` are passed to @component(LabelComponent).
__init__
python
hyperdiv/hyperdiv
hyperdiv/components/tree_item.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/tree_item.py
Apache-2.0
def bar_chart( *datasets, labels=None, colors=None, grid_color="neutral-100", x_axis="linear", y_axis="linear", hide_legend=False, show_x_tick_labels=True, show_y_tick_labels=True, y_min=None, y_max=None, **kwargs, ): """ A @component(cartesian_chart) that renders datasets as bars. ```py hd.bar_chart( (1, 18, 4), (4, 2, 28), labels=("Jim", "Mary") ) ``` """ return cartesian_chart( "bar", *datasets, labels=labels, colors=colors, grid_color=grid_color, x_axis=x_axis, y_axis=y_axis, hide_legend=hide_legend, show_x_tick_labels=show_x_tick_labels, show_y_tick_labels=show_y_tick_labels, y_min=y_min, y_max=y_max, **kwargs, )
A @component(cartesian_chart) that renders datasets as bars. ```py hd.bar_chart( (1, 18, 4), (4, 2, 28), labels=("Jim", "Mary") ) ```
bar_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/bar_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/bar_chart.py
Apache-2.0
def bubble_chart( *datasets, labels=None, colors=None, grid_color="neutral-100", x_axis="linear", y_axis="linear", hide_legend=False, show_x_tick_labels=True, show_y_tick_labels=True, y_min=None, y_max=None, **kwargs, ): """ A @component(cartesian_chart) that renders datasets as bubble points. It works like @component(scatter_chart), but you can specify the visual size of the points by providing an extra `r` component for each point, which specifies the radius of the bubble in pixels. ```py hd.bubble_chart( ((1, 8), (8, 20), (3, 12)), ((10, 7), (5, 30), (10, 12)), labels=("Jim", "Mary") ) ``` In this dataset specification, each point is specified as `(y, r)` where `y` is the `y`-value and `r` is the size of the bubble, in pixels. The `x` is automatically inferred as `1`, `2`, `3`, ..., on the linear axis, since it is not specified. You can specify the `x` in each point, too, by passing 3-tuples, each specifying `(x, y, r)`. ```py hd.bubble_chart( ((0, 1, 8), (3, 8, 20), (7, 3, 12)), ((2, 10, 7), (8, 5, 30), (21, 10, 12)), labels=("Jim", "Mary") ) ``` Bubble points can be specified in the following ways: * A 2-tuple, specifying `(y, r)`. In this case, `x` is inferred from the `x_axis` argument, like above. * A 3-tuple, representing `(x, y, r)`. * A dict, like `dict(x=1, y=2, r=10)`. Equivalent to the above, but in dict form. See @component(cartesian_chart) for more. """ return cartesian_chart( "bubble", *datasets, labels=labels, colors=colors, grid_color=grid_color, x_axis=x_axis, y_axis=y_axis, hide_legend=hide_legend, show_x_tick_labels=show_x_tick_labels, show_y_tick_labels=show_y_tick_labels, y_min=y_min, y_max=y_max, **kwargs, )
A @component(cartesian_chart) that renders datasets as bubble points. It works like @component(scatter_chart), but you can specify the visual size of the points by providing an extra `r` component for each point, which specifies the radius of the bubble in pixels. ```py hd.bubble_chart( ((1, 8), (8, 20), (3, 12)), ((10, 7), (5, 30), (10, 12)), labels=("Jim", "Mary") ) ``` In this dataset specification, each point is specified as `(y, r)` where `y` is the `y`-value and `r` is the size of the bubble, in pixels. The `x` is automatically inferred as `1`, `2`, `3`, ..., on the linear axis, since it is not specified. You can specify the `x` in each point, too, by passing 3-tuples, each specifying `(x, y, r)`. ```py hd.bubble_chart( ((0, 1, 8), (3, 8, 20), (7, 3, 12)), ((2, 10, 7), (8, 5, 30), (21, 10, 12)), labels=("Jim", "Mary") ) ``` Bubble points can be specified in the following ways: * A 2-tuple, specifying `(y, r)`. In this case, `x` is inferred from the `x_axis` argument, like above. * A 3-tuple, representing `(x, y, r)`. * A dict, like `dict(x=1, y=2, r=10)`. Equivalent to the above, but in dict form. See @component(cartesian_chart) for more.
bubble_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/bubble_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/bubble_chart.py
Apache-2.0
def cartesian_chart( chart_type, *datasets, labels=None, colors=None, grid_color="neutral-100", x_axis="linear", y_axis="linear", hide_legend=False, show_x_tick_labels=True, show_y_tick_labels=True, y_min=None, y_max=None, **kwargs, ): """ ## Introduction `cartesian_chart` is the base chart constructor used by @component(line_chart), @component(bar_chart), @component(scatter_chart), and @component(bubble_chart). All these charts work fundamentally similarly in that they render `x`/`y` data on a grid. They only differ in how the rendered data looks visually. There is a slight exception for @component(bubble_chart), which in addition to `x` and `y`, it renders `r`-data, which is the radius of each bubble. Because they work similarly, multiple datasets of different types can be overlaid on the same chart. Parameters: * `chart_type`: One of `"bar"`, `"line"`, `"scatter"`, or `"bubble"`. * `*datasets`: The data to be rendered. * `labels`: The names of the datasets. * `colors`: The colors of the datasets. * `grid_color`: The color of the chart's grid lines. * `x_axis`: Can be a list of names, specifying that the axis is a fixed category of items. The default is `"linear"`, specifying a linear axis. It can also be `"logarithmic"`, specifying a log axis, or `"timeseries"` specifying time values. * `y_axis`: Same as above, but for the y-axis. * `hide_legend`: Hides the clickable legend at the top of the chart. This legend is rendered automatically when `labels` is specified, unless this parameter is set to `False`. * `show_x_tick_labels`: Hides the tick labels on the x-axis. Tick labels are shown by default. * `show_y_tick_labels`: As above, but for the y-axis. * `y_min`: The minimum value of the y-axis. This is overridden if a data value is less than this value. * `y_max`: As above, but for the maximum value of the y-axis. * `**kwargs`: Component style and slot props that are passed upward to @component(chart). Each of `line_chart`, `bar_chart`, `scatter_chart`, and `bubble_chart` simply invoke `cartesian_chart(chart_type, ...)` where `chart_type` is `"line"`, `"bar"`, `"scatter"`, and `"bubble"`, respectively. These functions return a @component(chart) object. ```py hd.bar_chart((1, 8, 4)) # is equivalent to hd.cartesian_chart("bar", (1, 8, 4)) ``` ## Multiple Datasets Each chart type can accept multiple datasets: ```py hd.line_chart( (1, 8, 4), (2, 6, 9), (18, 4, 12) ) ``` ## Category Axis, Dataset Names, and Colors Each axis can be set to a fixed category of items by setting the axis to a tuple containing the items in the category. Then, each point in each dataset corresponds to a category item, in order. The datasets can be given names using the `labels` argument, which are rendered as a clickable legend at the top of the chart, unless `hide_legend` is set to `True`. The datasets can also be given custom colors using the `colors` argument. ```py hd.line_chart( (1, 8, 4), (2, 6, 9), (18, 4, 12), labels=("Jim", "Mary", "Joe"), colors=("yellow", "blue", "fuchsia"), x_axis=("Oats", "Corn", "Milk") ) ``` ## Log and Time Axes The `x_axis` and `y_axis` can also be set to `"logarithmic"` for log data, or `"timeseries"` for time data. A log axis de-emphasizes large differences among data: ```py hd.line_chart( (1, 18000, 20, 240241, 17), y_axis="logarithmic", ) # Versus linear (the default): hd.line_chart( (1, 18000, 20, 240241, 17), ) ``` A timeseries axis can intelligently render time labels. You can pass millisecond Unix timestamps as time values: ```py import time now = int(time.time()*1000) day = 24 * 60 * 60 * 1000 hd.line_chart( ((now, 20), (now+(2 * day), 100), (now+(18 * day), 80)), x_axis="timeseries", ) ``` ## Scale and Ticks You can choose to show or hide the tick labels on the x- and y-axis using the `show_x_tick_labels` and `show_y_tick_labels` parameters. Tick labels are shown by default. ```py hd.bar_chart( (2, 6, 10), show_x_tick_labels=False, show_y_tick_labels=False ) ``` You can control the y-axis scale using the `y_min` and `y_max` parameters. These are overridden if the data exceeds the defined scale. ```py hd.bar_chart( (2, 6, 11), # 11 exceeds the max value y_min=-10, y_max=10 ) ``` ## Mixed Datasets Cartesian datasets of different types can be mixed on the same chart. For any dataset, we can override the default chart type by passing a dictionary that specifies `chart_type`, and includes the data points in `data`. `chart_type` can be any of `"line"`, `"bar"`, `"scatter"`, and `"bubble"`. ```py hd.line_chart( (1, 4, 5), # defaults to "line" dict( # Override the default to "bar" # for this dataset: chart_type="bar", # The point data: data=(1, 4, 5) ) ) ``` ## Dataset Specification Each dataset specifies a series of "points" to be rendered on the chart. Each point must specify the `(x, y)` values: the x-axis value, and y-axis value. ### Point Specification Each point in a `"line"`, `"bar"`, or `"scatter"` dataset can be specified in the following ways: * A single value, like `5`. This represents the `y`-value of the point, and its `x`-value is inferred from the `x_axis` argument. * A tuple, like `(1, 5)`. This represents `(x, y)`. * A dict, like `dict(x=1, y=2)`. This is equivalent to the above, but in dict form. Bubble points also take an `r` value in addition to `x` and `y`, specifying the radius of the bubble. Bubble points can be specified in the following ways: * A 2-tuple, like `(1, 10)`, specifying `(y, r)`. In this case, `x` is inferred from the `x_axis` argument, like above. * A 3-tuple, representing `(x, y, r)`. * A dict, like `(dict(x=1, y=2, r=10)`. Equivalent to the above, but in dict form. ### Dataset Options A dataset can be passed to a chart constructor either as a tuple of points (where each point is specified according to the spec above), or as a dictionary that allows further customization of the dataset. When passing the dataset as a dictionary, the dataset's tuple of points is provided in the dictionary's `data` property: ```py-nodemo dict(data=((1, 2), (3, 4))) ``` In addition to `data`, the dictionary can provide `chart_type`, `color`, and `label` properties. `chart_type` allows mixing and matching multiple chart types in the same chart. `color` and `label` allow setting the dataset's color and label. These will override whatever is specified in the `colors` and `labels` top-level arguments. ```py hd.bar_chart( dict( data=(1, 18, 10), chart_type="line", label="Trend", color="green", ), dict( data=(1, 18, 10), label="Harvest", color="yellow" ) ) ``` """ check_chart_type(chart_type) if not datasets: raise ValueError("Nothing to render in a chart.") if labels and len(labels) != len(datasets): raise ValueError("Length of `datasets` differs from length of `labels`") grid_color = Color.render(Color.parse(grid_color)) auto_color_gen = auto_color_generator() out_datasets = [] for i, dataset in enumerate(datasets): out_dataset = dict(data=[], borderWidth=1) dataset_type = chart_type auto_color = next(auto_color_gen) if isinstance(dataset, dict): if "color" in dataset: color = Color.render(Color.parse(dataset["color"])) out_dataset["borderColor"] = color out_dataset["backgroundColor"] = color if "chart_type" in dataset: check_chart_type(dataset["chart_type"]) out_dataset["type"] = dataset["chart_type"] dataset_type = out_dataset["type"] if "label" in dataset: out_dataset["label"] = dataset["label"] dataset_data = dataset["data"] else: dataset_data = dataset if "borderColor" not in out_dataset: if colors and len(colors) > i: color = Color.render(Color.parse(colors[i])) else: color = Color.render(Color.parse(auto_color)) out_dataset["borderColor"] = color out_dataset["backgroundColor"] = color if "label" not in out_dataset: if labels: out_dataset["label"] = labels[i] for j, point in enumerate(dataset_data): # `r` the radius of bubble charts, if the current dataset # is a bubble dataset. r = None if isinstance(point, dict): # If a point is a dict, it should look like # dict(x=..., y=...), or dict(x=..., y=..., r=...) in # the case of bubble charts. x = point["x"] y = point["y"] if dataset_type == "bubble": r = point["r"] elif isinstance(point, (tuple, list)): # If the point is a tuple: # # In a bubble chart, we accept # - a 2-tuple (y, r) with x being implied by the # axis, or inferred. # - a 3-tuple (x, y, r) # # In a non-bubble chart we accept # - a 2-tuple (x, y) if dataset_type == "bubble": if len(point) == 3: x, y, r = point elif len(point) == 2: y, r = point if isinstance(x_axis, (list, tuple)): x = x_axis[j] else: x = j else: x, y = point else: # If the point is a single value: # - This is an error if we're in a bubble chart, since # bubble points should specify at least `y` and `r` # - Otherwise the value is `y`, and `x` is implied by # the axis, or inferred. if dataset_type == "bubble": raise ValueError(f"{point} is not a valid bubble value.") y = point if isinstance(x_axis, (list, tuple)): x = x_axis[j] else: x = j out_point = dict(x=x, y=y) if dataset_type == "bubble": out_point["r"] = r out_dataset["data"].append(out_point) out_datasets.append(out_dataset) # Labels check has_labels = ["label" in ds for ds in out_datasets] if any(has_labels) and not all(has_labels): raise ValueError("Either all datasets or no datasets should have labels.") # Set up axes. If `x_axis` and `y_axis` are a list/tuple, the axis # type is assumed to be "category", and the list items are the # members of the category. if isinstance(x_axis, (tuple, list)): x_axis_config = dict(type="category", labels=x_axis) else: x_axis_config = dict(type=x_axis) if isinstance(y_axis, (tuple, list)): y_axis_config = dict(type="category", labels=y_axis, reverse=True) else: y_axis_config = dict(type=y_axis) x_axis_config["grid"] = dict(color=grid_color) y_axis_config["grid"] = dict(color=grid_color) x_axis_config["ticks"] = dict(display=show_x_tick_labels) y_axis_config["ticks"] = dict(display=show_y_tick_labels) y_axis_config["suggestedMin"] = y_min y_axis_config["suggestedMax"] = y_max # Hide the legend if (a) there are no dataset labels specified, or # (b) `hide_legend` is True. plugins_config = dict(colors=False) if not any(has_labels) or hide_legend: plugins_config["legend"] = dict(display=False) return chart( config=dict( type=chart_type, data=dict(datasets=out_datasets), options=dict( plugins=plugins_config, maintainAspectRatio=False, responsive=True, scales=dict( x=x_axis_config, y=y_axis_config, ), ), ), **kwargs, )
## Introduction `cartesian_chart` is the base chart constructor used by @component(line_chart), @component(bar_chart), @component(scatter_chart), and @component(bubble_chart). All these charts work fundamentally similarly in that they render `x`/`y` data on a grid. They only differ in how the rendered data looks visually. There is a slight exception for @component(bubble_chart), which in addition to `x` and `y`, it renders `r`-data, which is the radius of each bubble. Because they work similarly, multiple datasets of different types can be overlaid on the same chart. Parameters: * `chart_type`: One of `"bar"`, `"line"`, `"scatter"`, or `"bubble"`. * `*datasets`: The data to be rendered. * `labels`: The names of the datasets. * `colors`: The colors of the datasets. * `grid_color`: The color of the chart's grid lines. * `x_axis`: Can be a list of names, specifying that the axis is a fixed category of items. The default is `"linear"`, specifying a linear axis. It can also be `"logarithmic"`, specifying a log axis, or `"timeseries"` specifying time values. * `y_axis`: Same as above, but for the y-axis. * `hide_legend`: Hides the clickable legend at the top of the chart. This legend is rendered automatically when `labels` is specified, unless this parameter is set to `False`. * `show_x_tick_labels`: Hides the tick labels on the x-axis. Tick labels are shown by default. * `show_y_tick_labels`: As above, but for the y-axis. * `y_min`: The minimum value of the y-axis. This is overridden if a data value is less than this value. * `y_max`: As above, but for the maximum value of the y-axis. * `**kwargs`: Component style and slot props that are passed upward to @component(chart). Each of `line_chart`, `bar_chart`, `scatter_chart`, and `bubble_chart` simply invoke `cartesian_chart(chart_type, ...)` where `chart_type` is `"line"`, `"bar"`, `"scatter"`, and `"bubble"`, respectively. These functions return a @component(chart) object. ```py hd.bar_chart((1, 8, 4)) # is equivalent to hd.cartesian_chart("bar", (1, 8, 4)) ``` ## Multiple Datasets Each chart type can accept multiple datasets: ```py hd.line_chart( (1, 8, 4), (2, 6, 9), (18, 4, 12) ) ``` ## Category Axis, Dataset Names, and Colors Each axis can be set to a fixed category of items by setting the axis to a tuple containing the items in the category. Then, each point in each dataset corresponds to a category item, in order. The datasets can be given names using the `labels` argument, which are rendered as a clickable legend at the top of the chart, unless `hide_legend` is set to `True`. The datasets can also be given custom colors using the `colors` argument. ```py hd.line_chart( (1, 8, 4), (2, 6, 9), (18, 4, 12), labels=("Jim", "Mary", "Joe"), colors=("yellow", "blue", "fuchsia"), x_axis=("Oats", "Corn", "Milk") ) ``` ## Log and Time Axes The `x_axis` and `y_axis` can also be set to `"logarithmic"` for log data, or `"timeseries"` for time data. A log axis de-emphasizes large differences among data: ```py hd.line_chart( (1, 18000, 20, 240241, 17), y_axis="logarithmic", ) # Versus linear (the default): hd.line_chart( (1, 18000, 20, 240241, 17), ) ``` A timeseries axis can intelligently render time labels. You can pass millisecond Unix timestamps as time values: ```py import time now = int(time.time()*1000) day = 24 * 60 * 60 * 1000 hd.line_chart( ((now, 20), (now+(2 * day), 100), (now+(18 * day), 80)), x_axis="timeseries", ) ``` ## Scale and Ticks You can choose to show or hide the tick labels on the x- and y-axis using the `show_x_tick_labels` and `show_y_tick_labels` parameters. Tick labels are shown by default. ```py hd.bar_chart( (2, 6, 10), show_x_tick_labels=False, show_y_tick_labels=False ) ``` You can control the y-axis scale using the `y_min` and `y_max` parameters. These are overridden if the data exceeds the defined scale. ```py hd.bar_chart( (2, 6, 11), # 11 exceeds the max value y_min=-10, y_max=10 ) ``` ## Mixed Datasets Cartesian datasets of different types can be mixed on the same chart. For any dataset, we can override the default chart type by passing a dictionary that specifies `chart_type`, and includes the data points in `data`. `chart_type` can be any of `"line"`, `"bar"`, `"scatter"`, and `"bubble"`. ```py hd.line_chart( (1, 4, 5), # defaults to "line" dict( # Override the default to "bar" # for this dataset: chart_type="bar", # The point data: data=(1, 4, 5) ) ) ``` ## Dataset Specification Each dataset specifies a series of "points" to be rendered on the chart. Each point must specify the `(x, y)` values: the x-axis value, and y-axis value. ### Point Specification Each point in a `"line"`, `"bar"`, or `"scatter"` dataset can be specified in the following ways: * A single value, like `5`. This represents the `y`-value of the point, and its `x`-value is inferred from the `x_axis` argument. * A tuple, like `(1, 5)`. This represents `(x, y)`. * A dict, like `dict(x=1, y=2)`. This is equivalent to the above, but in dict form. Bubble points also take an `r` value in addition to `x` and `y`, specifying the radius of the bubble. Bubble points can be specified in the following ways: * A 2-tuple, like `(1, 10)`, specifying `(y, r)`. In this case, `x` is inferred from the `x_axis` argument, like above. * A 3-tuple, representing `(x, y, r)`. * A dict, like `(dict(x=1, y=2, r=10)`. Equivalent to the above, but in dict form. ### Dataset Options A dataset can be passed to a chart constructor either as a tuple of points (where each point is specified according to the spec above), or as a dictionary that allows further customization of the dataset. When passing the dataset as a dictionary, the dataset's tuple of points is provided in the dictionary's `data` property: ```py-nodemo dict(data=((1, 2), (3, 4))) ``` In addition to `data`, the dictionary can provide `chart_type`, `color`, and `label` properties. `chart_type` allows mixing and matching multiple chart types in the same chart. `color` and `label` allow setting the dataset's color and label. These will override whatever is specified in the `colors` and `labels` top-level arguments. ```py hd.bar_chart( dict( data=(1, 18, 10), chart_type="line", label="Trend", color="green", ), dict( data=(1, 18, 10), label="Harvest", color="yellow" ) ) ```
cartesian_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/cartesian_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/cartesian_chart.py
Apache-2.0
def line_chart( *datasets, labels=None, colors=None, grid_color="neutral-100", x_axis="linear", y_axis="linear", hide_legend=False, show_x_tick_labels=True, show_y_tick_labels=True, y_min=None, y_max=None, **kwargs, ): """ A @component(cartesian_chart) that renders datasets as points connected by lines. ```py hd.line_chart( (1, 18, 4), (4, 2, 28), labels=("Jim", "Mary") ) ``` """ return cartesian_chart( "line", *datasets, labels=labels, colors=colors, grid_color=grid_color, x_axis=x_axis, y_axis=y_axis, hide_legend=hide_legend, show_x_tick_labels=show_x_tick_labels, show_y_tick_labels=show_y_tick_labels, y_min=y_min, y_max=y_max, **kwargs, )
A @component(cartesian_chart) that renders datasets as points connected by lines. ```py hd.line_chart( (1, 18, 4), (4, 2, 28), labels=("Jim", "Mary") ) ```
line_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/line_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/line_chart.py
Apache-2.0
def pie_chart( dataset, labels=None, colors=None, hide_legend=False, doughnut=True, **kwargs, ): """ A good ol pie chart. `dataset` holds the numeric sizes of the slices. ```py hd.pie_chart((1, 3, 12, 8)) ``` `labels` gives names to the pie slices, order. And `colors` specifies custom colors, in the same order. When you set `labels`, the clickable legend will automatically be rendered unless you pass `show_legend=False` ```py hd.pie_chart( (1, 3, 12, 8), labels=("Oats", "Corn", "Garlic", "Onions"), colors=("yellow-300", "emerald", "fuchsia-400", "orange") ) ``` You can pass `doughnut=False` to close the doughnut hole. ```py hd.pie_chart( (1, 3, 12, 8), labels=("Oats", "Corn", "Garlic", "Onions"), colors=("yellow-300", "emerald", "fuchsia-400", "orange"), doughnut=False ) ``` """ config = get_radial_chart_config( "doughnut" if doughnut else "pie", dataset, labels, colors, hide_legend ) return chart(config=config, **kwargs)
A good ol pie chart. `dataset` holds the numeric sizes of the slices. ```py hd.pie_chart((1, 3, 12, 8)) ``` `labels` gives names to the pie slices, order. And `colors` specifies custom colors, in the same order. When you set `labels`, the clickable legend will automatically be rendered unless you pass `show_legend=False` ```py hd.pie_chart( (1, 3, 12, 8), labels=("Oats", "Corn", "Garlic", "Onions"), colors=("yellow-300", "emerald", "fuchsia-400", "orange") ) ``` You can pass `doughnut=False` to close the doughnut hole. ```py hd.pie_chart( (1, 3, 12, 8), labels=("Oats", "Corn", "Garlic", "Onions"), colors=("yellow-300", "emerald", "fuchsia-400", "orange"), doughnut=False ) ```
pie_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/pie_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/pie_chart.py
Apache-2.0
def polar_chart( dataset, labels=None, colors=None, grid_color="neutral-100", hide_legend=False, show_tick_labels=True, r_min=None, r_max=None, **kwargs, ): """ A polar chart component. This works like @component(pie_chart) but unlike a pie chart, which shows dataset differences in the *angles* of the slices, the polar chart keeps the angles identical and emphasizes difference in the slice "lengths". The `labels` argument specifies the name of each slice, and the `dataset` specifies the value of each slice. ```py hd.polar_chart( (4, 6, 4, 8, 2), labels=("Oats", "Milk", "Cheese", "Garlic", "Onions") ) ``` The slice colors can be customized using the `colors` argument, and the legend and tick labels can be hidden. ```py hd.polar_chart( (4, 6, 4, 8, 2), colors=("red-200", "orange-200", "blue-100", "green-300", "yellow"), labels=("Oats", "Milk", "Cheese", "Garlic", "Onions"), hide_legend=True, show_tick_labels=False ) ``` You can set the minimum and maximum values for the radar chart using the `r_min` and `r_max` parameters. These are overridden if the dataset values exceed the scale. ```py hd.polar_chart( (4, 6, 4, 11, 2), # 11 exceeds the r_max colors=("red-200", "orange-200", "blue-100", "green-300", "yellow"), labels=("Oats", "Milk", "Cheese", "Garlic", "Onions"), r_min=-10, r_max=10 ) ``` """ grid_color = Color.render(Color.parse(grid_color)) config = get_radial_chart_config("polarArea", dataset, labels, colors, hide_legend) config["options"]["scales"] = dict( r=dict( grid=dict(color=grid_color), suggestedMin=r_min, suggestedMax=r_max, ticks=dict( showLabelBackdrop=False, display=show_tick_labels, ), ), ) return chart(config=config, **kwargs)
A polar chart component. This works like @component(pie_chart) but unlike a pie chart, which shows dataset differences in the *angles* of the slices, the polar chart keeps the angles identical and emphasizes difference in the slice "lengths". The `labels` argument specifies the name of each slice, and the `dataset` specifies the value of each slice. ```py hd.polar_chart( (4, 6, 4, 8, 2), labels=("Oats", "Milk", "Cheese", "Garlic", "Onions") ) ``` The slice colors can be customized using the `colors` argument, and the legend and tick labels can be hidden. ```py hd.polar_chart( (4, 6, 4, 8, 2), colors=("red-200", "orange-200", "blue-100", "green-300", "yellow"), labels=("Oats", "Milk", "Cheese", "Garlic", "Onions"), hide_legend=True, show_tick_labels=False ) ``` You can set the minimum and maximum values for the radar chart using the `r_min` and `r_max` parameters. These are overridden if the dataset values exceed the scale. ```py hd.polar_chart( (4, 6, 4, 11, 2), # 11 exceeds the r_max colors=("red-200", "orange-200", "blue-100", "green-300", "yellow"), labels=("Oats", "Milk", "Cheese", "Garlic", "Onions"), r_min=-10, r_max=10 ) ```
polar_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/polar_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/polar_chart.py
Apache-2.0
def scatter_chart( *datasets, labels=None, colors=None, grid_color="neutral-100", x_axis="linear", y_axis="linear", hide_legend=False, show_x_tick_labels=True, show_y_tick_labels=True, y_min=None, y_max=None, **kwargs, ): """ A @component(cartesian_chart) that renders datasets as points. ```py hd.scatter_chart( (1, 18, 4), (4, 2, 28), labels=("Jim", "Mary") ) ``` """ return cartesian_chart( "scatter", *datasets, labels=labels, colors=colors, grid_color=grid_color, x_axis=x_axis, y_axis=y_axis, hide_legend=hide_legend, show_x_tick_labels=show_x_tick_labels, show_y_tick_labels=show_y_tick_labels, y_min=y_min, y_max=y_max, **kwargs, )
A @component(cartesian_chart) that renders datasets as points. ```py hd.scatter_chart( (1, 18, 4), (4, 2, 28), labels=("Jim", "Mary") ) ```
scatter_chart
python
hyperdiv/hyperdiv
hyperdiv/components/charts/scatter_chart.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/charts/scatter_chart.py
Apache-2.0
def __init__(self, *label, **kwargs): """ If `*label` is provided, it will be concatenated by spaces and stored as a `text` or `plaintext` component in the component's body. If `*label` is not provided, it is assumed the caller will store the label explicitly. `**kwargs` are passed up to @component(Component). """ super().__init__(**kwargs) self._label_slot = self._get_label_slot() if label: with self: if self._label_slot: text(concat_text(label), slot=self._label_slot) else: plaintext(concat_text(label))
If `*label` is provided, it will be concatenated by spaces and stored as a `text` or `plaintext` component in the component's body. If `*label` is not provided, it is assumed the caller will store the label explicitly. `**kwargs` are passed up to @component(Component).
__init__
python
hyperdiv/hyperdiv
hyperdiv/components/common/label_component.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/common/label_component.py
Apache-2.0
def label(self): """ Reads/writes the label. If the label slot has been manually populated by the user with something other than a text or plaintext component, reading this property returns `None`, and writing it does nothing. """ item = self._find_plaintext_child(self._label_slot) if item: return item.content
Reads/writes the label. If the label slot has been manually populated by the user with something other than a text or plaintext component, reading this property returns `None`, and writing it does nothing.
label
python
hyperdiv/hyperdiv
hyperdiv/components/common/label_component.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/common/label_component.py
Apache-2.0
def __init__(self, src=None, **kwargs): """ `src` is a local or remote path to an audio file. If `src` is provided, a @component(media_source) will automatically be created. """ super().__init__(**kwargs) if src: with self: media_source(src=src)
`src` is a local or remote path to an audio file. If `src` is provided, a @component(media_source) will automatically be created.
__init__
python
hyperdiv/hyperdiv
hyperdiv/components/common/media_base.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/components/common/media_base.py
Apache-2.0
def __init__( self, data, id_column_name=None, show_id_column=True, rows_per_page=10, show_pagination=True, row_actions=None, show_select_column=False, vertical_scroll=False, **kwargs, ): """ Parameters: * `data`: The data dictionary to be rendered in the table. It maps column names to the row value of each column. * `id_column_name`: Specifies a column name, from `data`, which identifies each row uniquely. You need to specify this argument if you use the `row_actions` or `show_select_column` arguments. * `show_id_column`: If `id_column_name` is specified, this controls whether the ID column is visible in the table. * `rows_per_page`: How many rows per page to show. * `show_pagination`: Whether to show or hide the pagination component when the length of each row in `data` is longer than `rows_per_page`. If you set this to `False`, you will need to implement an alternative way for users to paginate through the data. * `row_actions`: A function, taking the row's ID as a parameter, that renders row-specific Hyperdiv components. These components will be rendered as the last column in the table. * `show_select_column`: Whether to render a leading column of checkboxes, which enables users to select rows. `**kwargs` will be passed to the `box` superclass. """ # The length of the longest rendered column: num_rows = max( [ len(c) for col_name, c in data.items() if col_name != id_column_name or show_id_column ] ) # Integrity checks: if id_column_name is None: if row_actions is not None: raise Exception( "Cannot specify row_actions without specifying id_column_name." ) if show_select_column: raise Exception( "Cannot specify show_select_column=True without specifying id_column_name." ) else: unique_ids = set(data[id_column_name]) if len(unique_ids) != len(data[id_column_name]): raise Exception("The data in the ID column is not unique per row.") if len(unique_ids) != num_rows: raise Exception("The ID column does not provide IDs for all the rows.") self.state = TableState() self.selected_row_id = None self.deselected_row_id = None # If somehow we lost the unique ID column, reset the selected # state. if not id_column_name and self.state.selected_rows: self.state.selected_rows = () # If some selected rows got deleted, update the selected rows state. if self.state.selected_rows: lost_ids = set(self.state.selected_rows).difference(unique_ids) if lost_ids: self.state.selected_rows = tuple( row_id for row_id in self.state.selected_rows if row_id not in lost_ids ) self.num_pages = ceil(num_rows / rows_per_page) # If some data got deleted such that the page number points # beyond the last page, update it to point to the last page. if self.state.page > self.num_pages: self.state.page = max(self.num_pages, 1) super().__init__(vertical_scroll=vertical_scroll, **kwargs) with self: # Render a 'No Data' box if there is no data to render. if num_rows == 0: with hd.box( align="center", justify="center", padding=2, border="1px solid neutral-100", height="100%", ): hd.text("No Data", font_color="neutral-400") return # Otherwise render the data table. low = (self.state.page - 1) * rows_per_page high = min(num_rows, self.state.page * rows_per_page) with hd.box(horizontal_scroll=True): with hd.table() as self.table: self._header( data, low, high, id_column_name, show_select_column, show_id_column, row_actions, ) self._body( data, low, high, id_column_name, show_select_column, show_id_column, row_actions, ) if num_rows > rows_per_page and show_pagination: self._pagination()
Parameters: * `data`: The data dictionary to be rendered in the table. It maps column names to the row value of each column. * `id_column_name`: Specifies a column name, from `data`, which identifies each row uniquely. You need to specify this argument if you use the `row_actions` or `show_select_column` arguments. * `show_id_column`: If `id_column_name` is specified, this controls whether the ID column is visible in the table. * `rows_per_page`: How many rows per page to show. * `show_pagination`: Whether to show or hide the pagination component when the length of each row in `data` is longer than `rows_per_page`. If you set this to `False`, you will need to implement an alternative way for users to paginate through the data. * `row_actions`: A function, taking the row's ID as a parameter, that renders row-specific Hyperdiv components. These components will be rendered as the last column in the table. * `show_select_column`: Whether to render a leading column of checkboxes, which enables users to select rows. `**kwargs` will be passed to the `box` superclass.
__init__
python
hyperdiv/hyperdiv
hyperdiv/ext/data_table.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/data_table.py
Apache-2.0
def __init__( self, icon_name, name, href, responsive_threshold=650, font_size="small", font_color="neutral-700", border_radius="medium", hover_background_color="neutral-100", direction="horizontal", align="center", gap=0.5, height=2, padding=(0.5, 0.7, 0.5, 0.7), **kwargs ): """ Parameters: * `icon_name`: The icon to render in the link. * `name`: The rendered name of the link. * `href`: The linked URL or path. * `responsive_threshold`: The window width, in pixels, below which the link name is rendered in a tooltip, instead of being rendered inline. The rest of the keyword arguments are passed up to @component(link). """ w = window() show_name = w.width > responsive_threshold super().__init__( href=href, font_size=font_size, font_color=font_color, border_radius=border_radius, hover_background_color=hover_background_color, direction=direction, align=align, gap=gap, height=height, padding=padding, collect=False, **kwargs ) with self: icon(icon_name) if show_name: text(name) if show_name: self.collect() else: with tooltip(name): self.collect()
Parameters: * `icon_name`: The icon to render in the link. * `name`: The rendered name of the link. * `href`: The linked URL or path. * `responsive_threshold`: The window width, in pixels, below which the link name is rendered in a tooltip, instead of being rendered inline. The rest of the keyword arguments are passed up to @component(link).
__init__
python
hyperdiv/hyperdiv
hyperdiv/ext/icon_link.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/icon_link.py
Apache-2.0
def link_group(links, drawer=None): """ Renders a group of links. This is usually the whole menu, in flat menus, or the link group within a menu section, in hierarchical menus. If an optional `drawer` is passed, the drawer is closed when a link is clicked. """ active_route = get_active_route(links) with hd.animation(play=True, duration=200): with hd.box_list(gap=0.1, vertical_scroll=False): for link_name, settings in links.items(): href = settings["href"] icon = settings.get("icon") with hd.scope(f"{link_name}:{href}"): with hd.box_list_item(): with hd.link( href=href, direction="horizontal", align="center", gap=0.5, font_color="neutral-800", hover_background_color=( "neutral-100" if active_route == href else "neutral-50" ), background_color=( "neutral-100" if active_route == href else None ), border_radius="medium", padding=(0.2, 0.5, 0.2, 0.5), ) as link: if icon: hd.icon(icon) hd.text(link_name) if drawer and link.clicked: drawer.opened = False
Renders a group of links. This is usually the whole menu, in flat menus, or the link group within a menu section, in hierarchical menus. If an optional `drawer` is passed, the drawer is closed when a link is clicked.
link_group
python
hyperdiv/hyperdiv
hyperdiv/ext/navigation_menu.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/navigation_menu.py
Apache-2.0
def nav_section(name, links, drawer=None, expanded=False): """ Renders a collapsible section, including the section title and expand/collapse logic. """ state = hd.state(expanded=expanded) active_route = get_active_route(links) if active_route: state.expanded = True with hd.box(gap=0.5): with hd.animation(name="shake") as shake_anim: header_link = hd.button( name, variant="text", height=1.8, label_style=hd.style( padding=(0, 0.5, 0, 0), font_color="neutral-800", font_weight="bold", ), margin=0, ) with header_link: hd.icon( "chevron-down" if state.expanded else "chevron-right", slot=header_link.suffix, ) if not expanded and header_link.clicked: if active_route and state.expanded: shake_anim.play = True else: state.expanded = not state.expanded if state.expanded: link_group(links, drawer=drawer)
Renders a collapsible section, including the section title and expand/collapse logic.
nav_section
python
hyperdiv/hyperdiv
hyperdiv/ext/navigation_menu.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/navigation_menu.py
Apache-2.0
def navigation_menu(link_dict, drawer=None, expanded=False): """ Renders a navigation menu component. The menu is wrapped in a @component(nav) and uses @component(link) for each link. `link_dict` is a dictionary specifying the menu, which can be either a flat menu, or a two-level hierarchical menu. `drawer` is an optional @component(drawer). If a drawer is passed, when a link is clicked, the drawer is automatically closed. This is a niche use case for @component(template), where a navigation menu is rendered in the sidebar drawer. If `expanded` is `True`, the menu sections will render fully expanded and are not collapsible. ### Flat Menu ```py hd.navigation_menu({ "Home": {"href": "/"}, "Users": {"href": "/users"}, "Google": {"href": "https://google.com"}, }) ``` `"href"` specifies a path (or external URL) to which Hyperdiv navigates when you click the menu item. ### Icons Navigation menus support optional prefix icons by setting `"icon"` in each link to an icon name: ```py hd.navigation_menu({ "Home": {"href": "/", "icon": "house"}, "Users": {"href": "/users", "icon": "people"}, "Google": {"href": "https://google.com", "icon": "google"}, }) ``` ### Hierarchical Menu `link_dict` also supports a syntax for specifying two-level menus (Section -> Menu) with collapsible sections, by adding an extra level to the `link_dict`: ```py hd.navigation_menu({ "Application": { "Home": {"href": "/", "icon": "house"}, "Users": {"href": "/users", "icon": "people"}, }, "Resources": { "Google": {"href": "https://google.com", "icon": "google"}, "Facebook": {"href": "https://google.com", "icon": "facebook"}, } }) ``` """ current_group = None with hd.nav(gap=1, font_size="small") as menu: for key, value in link_dict.items(): if "href" in value: if not current_group: current_group = dict() current_group[key] = value else: if current_group: link_group(current_group, drawer=drawer) current_group = None with hd.scope(key): nav_section(key, value, drawer=drawer, expanded=expanded) if current_group: link_group(current_group, drawer=drawer) return menu
Renders a navigation menu component. The menu is wrapped in a @component(nav) and uses @component(link) for each link. `link_dict` is a dictionary specifying the menu, which can be either a flat menu, or a two-level hierarchical menu. `drawer` is an optional @component(drawer). If a drawer is passed, when a link is clicked, the drawer is automatically closed. This is a niche use case for @component(template), where a navigation menu is rendered in the sidebar drawer. If `expanded` is `True`, the menu sections will render fully expanded and are not collapsible. ### Flat Menu ```py hd.navigation_menu({ "Home": {"href": "/"}, "Users": {"href": "/users"}, "Google": {"href": "https://google.com"}, }) ``` `"href"` specifies a path (or external URL) to which Hyperdiv navigates when you click the menu item. ### Icons Navigation menus support optional prefix icons by setting `"icon"` in each link to an icon name: ```py hd.navigation_menu({ "Home": {"href": "/", "icon": "house"}, "Users": {"href": "/users", "icon": "people"}, "Google": {"href": "https://google.com", "icon": "google"}, }) ``` ### Hierarchical Menu `link_dict` also supports a syntax for specifying two-level menus (Section -> Menu) with collapsible sections, by adding an extra level to the `link_dict`: ```py hd.navigation_menu({ "Application": { "Home": {"href": "/", "icon": "house"}, "Users": {"href": "/users", "icon": "people"}, }, "Resources": { "Google": {"href": "https://google.com", "icon": "google"}, "Facebook": {"href": "https://google.com", "icon": "facebook"}, } }) ```
navigation_menu
python
hyperdiv/hyperdiv
hyperdiv/ext/navigation_menu.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/navigation_menu.py
Apache-2.0
def route(self, path, redirect_from=None): """The main decorator for defining routes: ```py-nodemo @router.route("/foo") def foo(): hd.text("The foo page.") ``` `redirect_from` can be a tuple of paths, such that if the user navigates to any those paths, they will be redirected to this route. In this example, if the user navigates to either "/" or "/foo", the location will change to "/foo/bar" and route `bar()` will be rendered: ```py-nodemo @router.route("/foo/bar", redirect_from=("/", "/foo")) def bar(): hd.text("The bar page.") ``` """ def _route(fn): @wraps(fn) def wrapper(*args): return fn(*args) wrapper.path = path self._add_route(path, wrapper, redirect_from=redirect_from) return wrapper return _route
The main decorator for defining routes: ```py-nodemo @router.route("/foo") def foo(): hd.text("The foo page.") ``` `redirect_from` can be a tuple of paths, such that if the user navigates to any those paths, they will be redirected to this route. In this example, if the user navigates to either "/" or "/foo", the location will change to "/foo/bar" and route `bar()` will be rendered: ```py-nodemo @router.route("/foo/bar", redirect_from=("/", "/foo")) def bar(): hd.text("The bar page.") ```
route
python
hyperdiv/hyperdiv
hyperdiv/ext/router.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/router.py
Apache-2.0
def not_found(self): """ A decorator for defining a custom "Not Found" page, to be rendered when a user navigates to an undefined path. ```py-nodemo @router.not_found def my_custom_not_found_page(): with hd.box(gap=1): hd.markdown("# Not Found") hd.text("There is nothing here.") ``` """ def _route(fn): @wraps(fn) def wrapper(): return fn() wrapper.path = None self.not_found_handler = wrapper return wrapper return _route
A decorator for defining a custom "Not Found" page, to be rendered when a user navigates to an undefined path. ```py-nodemo @router.not_found def my_custom_not_found_page(): with hd.box(gap=1): hd.markdown("# Not Found") hd.text("There is nothing here.") ```
not_found
python
hyperdiv/hyperdiv
hyperdiv/ext/router.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/router.py
Apache-2.0
def render_not_found(self): """ This method can be used to programmatically invoke the `not_found` route. ```py-nodemo @router("/users/{user_id}") def user(user_id): u = get_user(user_id) if not u: router.render_not_found() else: hd.text(u.name) ``` """ loc = hd.location() if self.not_found_handler: self.not_found_handler() else: with hd.box(gap=1.5): hd.markdown("# Not Found") hd.markdown(f"Oops, there is no content at `{loc.path}`")
This method can be used to programmatically invoke the `not_found` route. ```py-nodemo @router("/users/{user_id}") def user(user_id): u = get_user(user_id) if not u: router.render_not_found() else: hd.text(u.name) ```
render_not_found
python
hyperdiv/hyperdiv
hyperdiv/ext/router.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/router.py
Apache-2.0
def run(self): """ Calls the correct route function based on the current @component(location) path. If there is no route corresponding to the current path, it renders the `not_found` route. """ loc = hd.location() fn = self.routes.get(loc.path) if fn: with hd.scope(loc.path): return fn() for route, fn in self.routes.items(): result = parse.parse(route, loc.path) if result: args = result.named.values() has_slashes = False for arg in args: if "/" in arg: has_slashes = True break if has_slashes: continue with hd.scope(route + ":" + "#".join(str(arg) for arg in args)): return fn(*result.named.values()) if loc.path in self.redirects: loc.path = self.redirects[loc.path] return self.render_not_found()
Calls the correct route function based on the current @component(location) path. If there is no route corresponding to the current path, it renders the `not_found` route.
run
python
hyperdiv/hyperdiv
hyperdiv/ext/router.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/router.py
Apache-2.0
def __init__( self, logo=None, title=None, sidebar=True, theme_switcher=True, responsive_threshold=1000, responsive_topbar_links_threshold=600, ): """ Parameters: * `logo`: The path to a logo image, e.g. `/assets/logo.svg`. The logo will be rendered in the top-left corner of the app. * `title`: The title of the app, rendered in the top-left next to the logo. * `sidebar`: Whether to render a sidebar. * `theme_switcher`: Whether to render the theme/dark-mode switcher in the top-right. * `responsive_threshold`: The width of the window (in pixels), below which the sidebar is rendered as a togglable drawer instead of as an in-line sidebar. * `responsive_topbar_links_threshold`: The width of the window (in pixels) below which the topbar icons are rendered as icon+hover tooltip instead of icon+name. """ window = hd.window() wide = window.width > responsive_threshold self._responsive_topbar_links_threshold = responsive_topbar_links_threshold self._drawer = None self._drawer_title = None self._sidebar = None if sidebar: self._drawer = hd.drawer( width=20, background_color="neutral-50", body_style=hd.style(padding=0), panel_style=hd.style(background_color="neutral-0"), title_style=hd.style(padding=(1.5, 1, 1.5, 2)), ) if window.changed and wide: self._drawer.opened = False with hd.box(collect=False) as self._drawer_title: if title: hd.text(title, font_weight="bold") self._sidebar = hd.box( width=20, shrink=False, padding=2, gap=1, horizontal_scroll=True, collect=False, ) with hd.box(height="100vh"): with hd.box( background_color="neutral-50", shrink=False, padding=(1, 1, 1, 2), ) as self._header: with hd.hbox(justify="space-between", align="center"): with hd.hbox(gap=1, align="center"): if sidebar and not wide: if hd.icon_button("list").clicked: self._drawer.opened = not self._drawer.opened with hd.link( href="/", direction="horizontal", gap=1, align="center", font_color="neutral-900", ): if logo: hd.image(logo, height=2) with hd.box() as self._app_title: if title: hd.text(title, font_weight="bold") with hd.hbox(align="center"): self._topbar_links = hd.hbox(align="center") if theme_switcher: hyperdiv_theme_switcher() with hd.hbox(grow=True, horizontal_scroll=False): if sidebar: if wide: self._sidebar.collect() else: with self._drawer: with hd.hbox( gap=1, align="center", slot=self._drawer.label_slot ): if logo: hd.image(logo, height=2) self._drawer_title.collect() self._sidebar.collect() with hd.scope(hd.location().path): self._body = hd.box( padding=2, gap=1, grow=True, horizontal_scroll=True )
Parameters: * `logo`: The path to a logo image, e.g. `/assets/logo.svg`. The logo will be rendered in the top-left corner of the app. * `title`: The title of the app, rendered in the top-left next to the logo. * `sidebar`: Whether to render a sidebar. * `theme_switcher`: Whether to render the theme/dark-mode switcher in the top-right. * `responsive_threshold`: The width of the window (in pixels), below which the sidebar is rendered as a togglable drawer instead of as an in-line sidebar. * `responsive_topbar_links_threshold`: The width of the window (in pixels) below which the topbar icons are rendered as icon+hover tooltip instead of icon+name.
__init__
python
hyperdiv/hyperdiv
hyperdiv/ext/template.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/template.py
Apache-2.0
def add_sidebar_menu(self, link_dict, expanded=False): """ Adds a @component(navigation_menu) to the sidebar. `link_dict` is passed to @component(navigation_menu) to construct the menu and add it to the sidebar container. The template's `drawer` property is passed into the navigation menu as its `drawer` kwarg, so the drawer is auto-closed when a link is clicked. The `expanded` kwarg is passed down to @component(navigation_menu), causing the menu sections to stay expanded if `True`. If the template was constructed with `sidebar=False`, calling this function will raise an error. """ if not self._sidebar: raise Exception("There is no sidebar.") with self._sidebar: navigation_menu(link_dict, drawer=self._drawer, expanded=expanded)
Adds a @component(navigation_menu) to the sidebar. `link_dict` is passed to @component(navigation_menu) to construct the menu and add it to the sidebar container. The template's `drawer` property is passed into the navigation menu as its `drawer` kwarg, so the drawer is auto-closed when a link is clicked. The `expanded` kwarg is passed down to @component(navigation_menu), causing the menu sections to stay expanded if `True`. If the template was constructed with `sidebar=False`, calling this function will raise an error.
add_sidebar_menu
python
hyperdiv/hyperdiv
hyperdiv/ext/template.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/template.py
Apache-2.0
def add_topbar_link(self, icon, name, href): """ Adds a @component(icon_link) component to the `topbar_links` container. The `icon`, `name`, and `href` components are passed to the @component(icon_link) constructor. The app template's `responsive_topbar_links_threshold` setting is passed down as @component(icon_link)'s `responsive_threshold` parameter. """ with self._topbar_links: icon_link( icon, name, href, responsive_threshold=self._responsive_topbar_links_threshold, )
Adds a @component(icon_link) component to the `topbar_links` container. The `icon`, `name`, and `href` components are passed to the @component(icon_link) constructor. The app template's `responsive_topbar_links_threshold` setting is passed down as @component(icon_link)'s `responsive_threshold` parameter.
add_topbar_link
python
hyperdiv/hyperdiv
hyperdiv/ext/template.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/template.py
Apache-2.0
def add_topbar_links(self, link_dict): """ Adds multiple @component(icon_link) components to the `topbar_links` container in one shot. The `link_dict` syntax is the same as the `linked_dict` passed to @component(navigation_menu), but only flat menus are supported in this case. """ for link_name, settings in link_dict.items(): with hd.scope(link_name): icon = settings["icon"] href = settings["href"] self.add_topbar_link(icon, link_name, href)
Adds multiple @component(icon_link) components to the `topbar_links` container in one shot. The `link_dict` syntax is the same as the `linked_dict` passed to @component(navigation_menu), but only flat menus are supported in this case.
add_topbar_links
python
hyperdiv/hyperdiv
hyperdiv/ext/template.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/template.py
Apache-2.0
def theme_switcher(icon_font_size="medium"): """ Renders a theme switcher inline icon and dropdown menu. When the icon is clicked, the dropdown menu opens with Dark/Light/System choices. The icon is a "moon" icon in dark mode and a "sun" icon in light mode. This menu remembers the user's setting in browser local storage, so if a user chooses Light or Dark mode, that setting will stick across app visits. If they choose System, the local storage setting is forgotten, as "System" is the default. ```py hd.theme_switcher() ``` `icon_font_size` takes @prop_type(Size) values and can be used to control the size of the inline icon. ```py hd.theme_switcher(icon_font_size="x-small") hd.theme_switcher(icon_font_size=3) ``` """ theme = hd.theme() with hd.dropdown() as dropdown: b = hd.icon_button( "moon" if not theme.is_light else "sun", slot=dropdown.trigger, font_size=icon_font_size, padding=0.5, ) if b.clicked: dropdown.opened = not dropdown.opened with hd.menu() as menu: item = hd.menu_item("Light", prefix_icon="sun", item_type="checkbox") item.checked = theme.mode == "light" if menu.selected_item == item: item.checked = True theme.set_and_remember_theme_mode("light") dropdown.opened = False item = hd.menu_item("Dark", prefix_icon="moon", item_type="checkbox") item.checked = theme.mode == "dark" if menu.selected_item == item: item.checked = True theme.set_and_remember_theme_mode("dark") dropdown.opened = False hd.divider(spacing="x-small") item = hd.menu_item("System", item_type="checkbox") item.checked = theme.mode == "system" if menu.selected_item == item: item.checked = True theme.reset_and_forget_theme_mode() dropdown.opened = False
Renders a theme switcher inline icon and dropdown menu. When the icon is clicked, the dropdown menu opens with Dark/Light/System choices. The icon is a "moon" icon in dark mode and a "sun" icon in light mode. This menu remembers the user's setting in browser local storage, so if a user chooses Light or Dark mode, that setting will stick across app visits. If they choose System, the local storage setting is forgotten, as "System" is the default. ```py hd.theme_switcher() ``` `icon_font_size` takes @prop_type(Size) values and can be used to control the size of the inline icon. ```py hd.theme_switcher(icon_font_size="x-small") hd.theme_switcher(icon_font_size=3) ```
theme_switcher
python
hyperdiv/hyperdiv
hyperdiv/ext/theme_switcher.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/ext/theme_switcher.py
Apache-2.0
def render(self, value): """Specialized render function for floats. We need this because `json` will render float('inf') and float('-inf') as special constants that don't correspond to anything in JS. The strings "+Infinity" and "-Infinity" behave correctly when coerced to numbers on the JS side. """ if value == float("inf"): return "+Infinity" if value == float("-inf"): return "-Infinity" return value
Specialized render function for floats. We need this because `json` will render float('inf') and float('-inf') as special constants that don't correspond to anything in JS. The strings "+Infinity" and "-Infinity" behave correctly when coerced to numbers on the JS side.
render
python
hyperdiv/hyperdiv
hyperdiv/prop_types/float_type.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/prop_types/float_type.py
Apache-2.0
def __init__(self, typ, name=None, coercible_types=None): """ `typ` should be a Python type. `coercible_types` is a list of additional accepted types. However, the final value will be coerced to `typ`. `name` is an optional name. By default, a name will be derived from `typ`. """ self.typ = typ self.name = name or typ.__name__.capitalize() self.coercible_types = coercible_types
`typ` should be a Python type. `coercible_types` is a list of additional accepted types. However, the final value will be coerced to `typ`. `name` is an optional name. By default, a name will be derived from `typ`.
__init__
python
hyperdiv/hyperdiv
hyperdiv/prop_types/native.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/prop_types/native.py
Apache-2.0
def test_click_twice(): """ Test that an update batch containing updates to the same prop schedules those updates in different frames. """ button_key = None text_key = None def my_app(): nonlocal button_key, text_key s = state(count=0) b = button("Click Me") button_key = b._key if b.clicked: s.count += 1 t = plaintext(s.count) text_key = t._key with MockRunner(my_app) as mr: mr.process_updates( [ (button_key, "clicked", True), (button_key, "clicked", True), ] ) assert mr.get_state(text_key, "content") == "2"
Test that an update batch containing updates to the same prop schedules those updates in different frames.
test_click_twice
python
hyperdiv/hyperdiv
hyperdiv/tests/app_runner_tests.py
https://github.com/hyperdiv/hyperdiv/blob/master/hyperdiv/tests/app_runner_tests.py
Apache-2.0
def instance(cls) -> '_AutomationClient': """Singleton instance (this prevents com creation on import).""" if cls._instance is None: cls._instance = cls() return cls._instance
Singleton instance (this prevents com creation on import).
instance
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def instance(cls) -> '_DllClient': """Singleton instance (this prevents com creation on import).""" if cls._instance is None: cls._instance = cls() return cls._instance
Singleton instance (this prevents com creation on import).
instance
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetClipboardText(text: str) -> bool: """ Return bool, True if succeed otherwise False. """ if ctypes.windll.user32.OpenClipboard(0): ctypes.windll.user32.EmptyClipboard() textByteLen = (len(text) + 1) * 2 hClipboardData = ctypes.windll.kernel32.GlobalAlloc(0, textByteLen) # GMEM_FIXED=0 hDestText = ctypes.windll.kernel32.GlobalLock(ctypes.c_void_p(hClipboardData)) ctypes.cdll.msvcrt.wcsncpy(ctypes.c_wchar_p(hDestText), ctypes.c_wchar_p(text), ctypes.c_size_t(textByteLen // 2)) ctypes.windll.kernel32.GlobalUnlock(ctypes.c_void_p(hClipboardData)) # system owns hClipboardData after calling SetClipboardData, # application can not write to or free the data once ownership has been transferred to the system ctypes.windll.user32.SetClipboardData(ctypes.c_uint(13), ctypes.c_void_p(hClipboardData)) # CF_TEXT=1, CF_UNICODETEXT=13 ctypes.windll.user32.CloseClipboard() return True return False
Return bool, True if succeed otherwise False.
SetClipboardText
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetConsoleColor(color: int) -> bool: """ Change the text color on console window. color: int, a value in class `ConsoleColor`. Return bool, True if succeed otherwise False. """ global _ConsoleOutputHandle global _DefaultConsoleColor if not _DefaultConsoleColor: if not _ConsoleOutputHandle: _ConsoleOutputHandle = ctypes.c_void_p(ctypes.windll.kernel32.GetStdHandle(_StdOutputHandle)) bufferInfo = ConsoleScreenBufferInfo() ctypes.windll.kernel32.GetConsoleScreenBufferInfo(_ConsoleOutputHandle, ctypes.byref(bufferInfo)) _DefaultConsoleColor = int(bufferInfo.wAttributes & 0xFF) if sys.stdout: sys.stdout.flush() return bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, ctypes.c_ushort(color)))
Change the text color on console window. color: int, a value in class `ConsoleColor`. Return bool, True if succeed otherwise False.
SetConsoleColor
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def ResetConsoleColor() -> bool: """ Reset to the default text color on console window. Return bool, True if succeed otherwise False. """ if sys.stdout: sys.stdout.flush() return bool(ctypes.windll.kernel32.SetConsoleTextAttribute(_ConsoleOutputHandle, ctypes.c_ushort(_DefaultConsoleColor)))
Reset to the default text color on console window. Return bool, True if succeed otherwise False.
ResetConsoleColor
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetCursorPos() -> Tuple[int, int]: """ GetCursorPos from Win32. Get current mouse cursor positon. Return Tuple[int, int], two ints tuple (x, y). """ point = ctypes.wintypes.POINT(0, 0) ctypes.windll.user32.GetCursorPos(ctypes.byref(point)) return point.x, point.y
GetCursorPos from Win32. Get current mouse cursor positon. Return Tuple[int, int], two ints tuple (x, y).
GetCursorPos
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.LeftUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
Simulate mouse click at point x, y. x: int. y: int. waitTime: float.
Click
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.MiddleUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
Simulate mouse middle click at point x, y. x: int. y: int. waitTime: float.
MiddleClick
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right click at point x, y. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(0.05) mouse_event(MouseEventFlag.RightUp | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
Simulate mouse right click at point x, y. x: int. y: int. waitTime: float.
RightClick
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press left mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.LeftDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
Press left mouse. x: int. y: int. waitTime: float.
PressMouse
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def RightPressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press right mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.RightDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
Press right mouse. x: int. y: int. waitTime: float.
RightPressMouse
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def MiddlePressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Press middle mouse. x: int. y: int. waitTime: float. """ SetCursorPos(x, y) screenWidth, screenHeight = GetScreenSize() mouse_event(MouseEventFlag.MiddleDown | MouseEventFlag.Absolute, x * 65535 // screenWidth, y * 65535 // screenHeight, 0, 0) time.sleep(waitTime)
Press middle mouse. x: int. y: int. waitTime: float.
MiddlePressMouse
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse move to point x, y from current cursor. x: int. y: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ if moveSpeed <= 0: moveTime = 0 else: moveTime = MAX_MOVE_SECOND / moveSpeed curX, curY = GetCursorPos() xCount = abs(x - curX) yCount = abs(y - curY) maxPoint = max(xCount, yCount) screenWidth, screenHeight = GetScreenSize() maxSide = max(screenWidth, screenHeight) minSide = min(screenWidth, screenHeight) if maxPoint > minSide: maxPoint = minSide if maxPoint < maxSide: maxPoint = 100 + int((maxSide - 100) / maxSide * maxPoint) moveTime = moveTime * maxPoint * 1.0 / maxSide stepCount = maxPoint // 20 if stepCount > 1: xStep = (x - curX) * 1.0 / stepCount yStep = (y - curY) * 1.0 / stepCount interval = moveTime / stepCount for i in range(stepCount): cx = curX + int(xStep * i) cy = curY + int(yStep * i) # upper-left(0,0), lower-right(65536,65536) # mouse_event(MouseEventFlag.Move | MouseEventFlag.Absolute, cx*65536//screenWidth, cy*65536//screenHeight, 0, 0) SetCursorPos(cx, cy) time.sleep(interval) SetCursorPos(x, y) time.sleep(waitTime)
Simulate mouse move to point x, y from current cursor. x: int. y: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
MoveTo
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ PressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) ReleaseMouse(waitTime)
Simulate mouse left button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
DragDrop
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse right button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ RightPressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) RightReleaseMouse(waitTime)
Simulate mouse right button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
RightDragDrop
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def MiddleDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse middle button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float. """ MiddlePressMouse(x1, y1, 0.05) MoveTo(x2, y2, moveSpeed, 0.05) MiddleReleaseMouse(waitTime)
Simulate mouse middle button drag from point x1, y1 drop to point x2, y2. x1: int. y1: int. x2: int. y2: int. moveSpeed: float, 1 normal speed, < 1 move slower, > 1 move faster. waitTime: float.
MiddleDragDrop
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def WheelDown(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse wheel down. wheelTimes: int. interval: float. waitTime: float. """ for i in range(wheelTimes): mouse_event(MouseEventFlag.Wheel, 0, 0, -120, 0) #WHEEL_DELTA=120 time.sleep(interval) time.sleep(waitTime)
Simulate mouse wheel down. wheelTimes: int. interval: float. waitTime: float.
WheelDown
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float. """ for i in range(wheelTimes): mouse_event(MouseEventFlag.Wheel, 0, 0, 120, 0) #WHEEL_DELTA=120 time.sleep(interval) time.sleep(waitTime)
Simulate mouse wheel up. wheelTimes: int. interval: float. waitTime: float.
WheelUp
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetDpiAwareness(dpiAwarenessPerMonitor: bool = True) -> int: ''' Call SetThreadDpiAwarenessContext(Windows 10 version 1607+) or SetProcessDpiAwareness(Windows 8.1+). You should call this function with True if you enable DPI scaling. uiautomation calls this function when it initializes. dpiAwarenessPerMonitor: bool. Return int. ''' try: # https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setthreaddpiawarenesscontext # Windows 10 1607+ ctypes.windll.user32.SetThreadDpiAwarenessContext.restype = ctypes.c_void_p context = DpiAwarenessContext.DpiAwarenessContextPerMonitorAware if dpiAwarenessPerMonitor else DpiAwarenessContext.DpiAwarenessContextUnaware oldContext = ctypes.windll.user32.SetThreadDpiAwarenessContext(ctypes.c_void_p(context)) return oldContext except Exception as ex: try: # https://docs.microsoft.com/en-us/windows/win32/api/shellscalingapi/nf-shellscalingapi-setprocessdpiawareness # Once SetProcessDpiAwareness is set for an app, any future calls to SetProcessDpiAwareness will fail. # Windows 8.1+ if dpiAwarenessPerMonitor: return ctypes.windll.shcore.SetProcessDpiAwareness(ProcessDpiAwareness.ProcessPerMonitorDpiAware) except Exception as ex2: pass
Call SetThreadDpiAwarenessContext(Windows 10 version 1607+) or SetProcessDpiAwareness(Windows 8.1+). You should call this function with True if you enable DPI scaling. uiautomation calls this function when it initializes. dpiAwarenessPerMonitor: bool. Return int.
SetDpiAwareness
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetScreenSize(dpiAwarenessPerMonitor: bool = True) -> Tuple[int, int]: """ dpiAwarenessPerMonitor: bool. Return Tuple[int, int], two ints tuple (width, height). """ SetDpiAwareness(dpiAwarenessPerMonitor) SM_CXSCREEN = 0 SM_CYSCREEN = 1 w = ctypes.windll.user32.GetSystemMetrics(SM_CXSCREEN) h = ctypes.windll.user32.GetSystemMetrics(SM_CYSCREEN) return w, h
dpiAwarenessPerMonitor: bool. Return Tuple[int, int], two ints tuple (width, height).
GetScreenSize
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetVirtualScreenSize(dpiAwarenessPerMonitor: bool = True) -> Tuple[int, int]: """ dpiAwarenessPerMonitor: bool. Return Tuple[int, int], two ints tuple (width, height). """ SetDpiAwareness(dpiAwarenessPerMonitor) SM_CXVIRTUALSCREEN = 78 SM_CYVIRTUALSCREEN = 79 w = ctypes.windll.user32.GetSystemMetrics(SM_CXVIRTUALSCREEN) h = ctypes.windll.user32.GetSystemMetrics(SM_CYVIRTUALSCREEN) return w, h
dpiAwarenessPerMonitor: bool. Return Tuple[int, int], two ints tuple (width, height).
GetVirtualScreenSize
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetMonitorsRect(dpiAwarenessPerMonitor: bool = False) -> List[Rect]: """ Get monitors' rect. dpiAwarenessPerMonitor: bool. Return List[Rect]. """ SetDpiAwareness(dpiAwarenessPerMonitor) MonitorEnumProc = ctypes.WINFUNCTYPE(ctypes.c_int, ctypes.c_size_t, ctypes.c_size_t, ctypes.POINTER(ctypes.wintypes.RECT), ctypes.c_size_t) rects = [] def MonitorCallback(hMonitor: int, hdcMonitor: int, lprcMonitor: ctypes.POINTER(ctypes.wintypes.RECT), dwData: int): rect = Rect(lprcMonitor.contents.left, lprcMonitor.contents.top, lprcMonitor.contents.right, lprcMonitor.contents.bottom) rects.append(rect) return 1 ret = ctypes.windll.user32.EnumDisplayMonitors(ctypes.c_void_p(0), ctypes.c_void_p(0), MonitorEnumProc(MonitorCallback), 0) return rects
Get monitors' rect. dpiAwarenessPerMonitor: bool. Return List[Rect].
GetMonitorsRect
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetPixelColor(x: int, y: int, handle: int = 0) -> int: """ Get pixel color of a native window. x: int. y: int. handle: int, the handle of a native window. Return int, the bgr value of point (x,y). r = bgr & 0x0000FF g = (bgr & 0x00FF00) >> 8 b = (bgr & 0xFF0000) >> 16 If handle is 0, get pixel from Desktop window(root control). Note: Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function. For example, console window doesn't support. """ hdc = ctypes.windll.user32.GetWindowDC(ctypes.c_void_p(handle)) bgr = ctypes.windll.gdi32.GetPixel(hdc, x, y) ctypes.windll.user32.ReleaseDC(ctypes.c_void_p(handle), ctypes.c_void_p(hdc)) return bgr
Get pixel color of a native window. x: int. y: int. handle: int, the handle of a native window. Return int, the bgr value of point (x,y). r = bgr & 0x0000FF g = (bgr & 0x00FF00) >> 8 b = (bgr & 0xFF0000) >> 16 If handle is 0, get pixel from Desktop window(root control). Note: Not all devices support GetPixel. An application should call GetDeviceCaps to determine whether a specified device supports this function. For example, console window doesn't support.
GetPixelColor
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetWindowTopmost(handle: int, isTopmost: bool) -> bool: """ handle: int, the handle of a native window. isTopmost: bool Return bool, True if succeed otherwise False. """ topValue = SWP.HWND_Topmost if isTopmost else SWP.HWND_NoTopmost return bool(SetWindowPos(handle, topValue, 0, 0, 0, 0, SWP.SWP_NoSize | SWP.SWP_NoMove))
handle: int, the handle of a native window. isTopmost: bool Return bool, True if succeed otherwise False.
SetWindowTopmost
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetWindowText(handle: int) -> str: """ GetWindowText from Win32. handle: int, the handle of a native window. Return str. """ arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.user32.GetWindowTextW(ctypes.c_void_p(handle), values, ctypes.c_int(MAX_PATH)) return values.value
GetWindowText from Win32. handle: int, the handle of a native window. Return str.
GetWindowText
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetEditText(handle: int) -> str: """ Get text of a native Win32 Edit. handle: int, the handle of a native window. Return str. """ textLen = SendMessage(handle, 0x000E, 0, 0) + 1 #WM_GETTEXTLENGTH arrayType = ctypes.c_wchar * textLen values = arrayType() SendMessage(handle, 0x000D, textLen, values) #WM_GETTEXT return values.value
Get text of a native Win32 Edit. handle: int, the handle of a native window. Return str.
GetEditText
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetConsoleOriginalTitle() -> str: """ GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher. """ if IsNT6orHigher: arrayType = ctypes.c_wchar * MAX_PATH values = arrayType() ctypes.windll.kernel32.GetConsoleOriginalTitleW(values, ctypes.c_uint(MAX_PATH)) return values.value else: raise RuntimeError('GetConsoleOriginalTitle is not supported on Windows XP or lower.')
GetConsoleOriginalTitle from Win32. Return str. Only available on Windows Vista or higher.
GetConsoleOriginalTitle
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def IsDesktopLocked() -> bool: """ Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode. """ isLocked = False desk = ctypes.windll.user32.OpenDesktopW(ctypes.c_wchar_p('Default'), ctypes.c_uint(0), ctypes.c_int(0), ctypes.c_uint(0x0100)) # DESKTOP_SWITCHDESKTOP = 0x0100 if desk: isLocked = not ctypes.windll.user32.SwitchDesktop(ctypes.c_void_p(desk)) ctypes.windll.user32.CloseDesktop(ctypes.c_void_p(desk)) return isLocked
Check if desktop is locked. Return bool. Desktop is locked if press Win+L, Ctrl+Alt+Del or in remote desktop mode.
IsDesktopLocked
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def PlayWaveFile(filePath: str = r'C:\Windows\Media\notify.wav', isAsync: bool = False, isLoop: bool = False) -> bool: """ Call PlaySound from Win32. filePath: str, if emtpy, stop playing the current sound. isAsync: bool, if True, the sound is played asynchronously and returns immediately. isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True. Return bool, True if succeed otherwise False. """ if filePath: SND_ASYNC = 0x0001 SND_NODEFAULT = 0x0002 SND_LOOP = 0x0008 SND_FILENAME = 0x20000 flags = SND_NODEFAULT | SND_FILENAME if isAsync: flags |= SND_ASYNC if isLoop: flags |= SND_LOOP flags |= SND_ASYNC return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(filePath), ctypes.c_void_p(0), ctypes.c_uint(flags))) else: return bool(ctypes.windll.winmm.PlaySoundW(ctypes.c_wchar_p(0), ctypes.c_void_p(0), ctypes.c_uint(0)))
Call PlaySound from Win32. filePath: str, if emtpy, stop playing the current sound. isAsync: bool, if True, the sound is played asynchronously and returns immediately. isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True. Return bool, True if succeed otherwise False.
PlayWaveFile
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def IsProcess64Bit(processId: int) -> bool: """ Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown, maybe caused by having no acess right to the process. """ try: func = ctypes.windll.ntdll.ZwWow64ReadVirtualMemory64 #only 64 bit OS has this function except Exception as ex: return False try: IsWow64Process = ctypes.windll.kernel32.IsWow64Process except Exception as ex: return False hProcess = ctypes.windll.kernel32.OpenProcess(0x1000, 0, processId) #PROCESS_QUERY_INFORMATION=0x0400,PROCESS_QUERY_LIMITED_INFORMATION=0x1000 if hProcess: is64Bit = ctypes.c_int32() if IsWow64Process(ctypes.c_void_p(hProcess), ctypes.byref(is64Bit)): ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess)) return False if is64Bit.value else True else: ctypes.windll.kernel32.CloseHandle(ctypes.c_void_p(hProcess))
Return True if process is 64 bit. Return False if process is 32 bit. Return None if unknown, maybe caused by having no acess right to the process.
IsProcess64Bit
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def RunScriptAsAdmin(argv: List[str], workingDirectory: str = None, showFlag: int = SW.ShowNormal) -> bool: """ Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: List[str], a str list like sys.argv, argv[0] is the script file, argv[1:] are other arguments. workingDirectory: str, the working directory for the script file. showFlag: int, a value in class `SW`. Return bool, True if succeed. """ args = ' '.join('"{}"'.format(arg) for arg in argv) return ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, workingDirectory, showFlag) > 32
Run a python script as administrator. System will show a popup dialog askes you whether to elevate as administrator if UAC is enabled. argv: List[str], a str list like sys.argv, argv[0] is the script file, argv[1:] are other arguments. workingDirectory: str, the working directory for the script file. showFlag: int, a value in class `SW`. Return bool, True if succeed.
RunScriptAsAdmin
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Simulate typing a key. key: int, a value in class `Keys`. """ keybd_event(key, 0, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey, 0) keybd_event(key, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
Simulate typing a key. key: int, a value in class `Keys`.
SendKey
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def IsKeyPressed(key: int) -> bool: """ key: int, a value in class `Keys`. Return bool. """ state = ctypes.windll.user32.GetAsyncKeyState(key) return bool(state & 0x8000)
key: int, a value in class `Keys`. Return bool.
IsKeyPressed
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def _CreateInput(structure) -> INPUT: """ Create Win32 struct `INPUT` for `SendInput`. Return `INPUT`. """ if isinstance(structure, MOUSEINPUT): return INPUT(InputType.Mouse, _INPUTUnion(mi=structure)) if isinstance(structure, KEYBDINPUT): return INPUT(InputType.Keyboard, _INPUTUnion(ki=structure)) if isinstance(structure, HARDWAREINPUT): return INPUT(InputType.Hardware, _INPUTUnion(hi=structure)) raise TypeError('Cannot create INPUT structure!')
Create Win32 struct `INPUT` for `SendInput`. Return `INPUT`.
_CreateInput
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SendInput(*inputs) -> int: """ SendInput from Win32. input: `INPUT`. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread. """ cbSize = ctypes.c_int(ctypes.sizeof(INPUT)) for ip in inputs: ret = ctypes.windll.user32.SendInput(1, ctypes.byref(ip), cbSize) return ret #or one call #nInputs = len(inputs) #LPINPUT = INPUT * nInputs #pInputs = LPINPUT(*inputs) #cbSize = ctypes.c_int(ctypes.sizeof(INPUT)) #return ctypes.windll.user32.SendInput(nInputs, ctypes.byref(pInputs), cbSize)
SendInput from Win32. input: `INPUT`. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread.
SendInput
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SendUnicodeChar(char: str, charMode: bool = True) -> int: """ Type a single unicode char. char: str, len(char) must equal to 1. charMode: bool, if False, the char typied is depend on the input method if a input method is on. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread. """ if charMode: vk = 0 scan = ord(char) flag = KeyboardEventFlag.KeyUnicode else: res = ctypes.windll.user32.VkKeyScanW(ctypes.wintypes.WCHAR(char)) if (res >> 8) & 0xFF == 0: vk = res & 0xFF scan = 0 flag = 0 else: vk = 0 scan = ord(char) flag = KeyboardEventFlag.KeyUnicode return SendInput(KeyboardInput(vk, scan, flag | KeyboardEventFlag.KeyDown), KeyboardInput(vk, scan, flag | KeyboardEventFlag.KeyUp))
Type a single unicode char. char: str, len(char) must equal to 1. charMode: bool, if False, the char typied is depend on the input method if a input method is on. Return int, the number of events that it successfully inserted into the keyboard or mouse input stream. If the function returns zero, the input was already blocked by another thread.
SendUnicodeChar
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def _VKtoSC(key: int) -> int: """ This function is only for internal use in SendKeys. key: int, a value in class `Keys`. Return int. """ if key in _SCKeys: return _SCKeys[key] scanCode = ctypes.windll.user32.MapVirtualKeyA(key, 0) if not scanCode: return 0 keyList = [Keys.VK_APPS, Keys.VK_CANCEL, Keys.VK_SNAPSHOT, Keys.VK_DIVIDE, Keys.VK_NUMLOCK] if key in keyList: scanCode |= 0x0100 return scanCode
This function is only for internal use in SendKeys. key: int, a value in class `Keys`. Return int.
_VKtoSC
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, charMode: bool = True, debug: bool = False) -> None: """ Simulate typing keys on keyboard. text: str, keys to type. interval: float, seconds between keys. waitTime: float. charMode: bool, if False, the text typied is depend on the input method if a input method is on. debug: bool, if True, print the keys. Examples: {Ctrl}, {Delete} ... are special keys' name in SpecialKeyNames. SendKeys('{Ctrl}a{Delete}{Ctrl}v{Ctrl}s{Ctrl}{Shift}s{Win}e{PageDown}') #press Ctrl+a, Delete, Ctrl+v, Ctrl+s, Ctrl+Shift+s, Win+e, PageDown SendKeys('{Ctrl}(AB)({Shift}(123))') #press Ctrl+A+B, type (, press Shift+1+2+3, type ), if () follows a hold key, hold key won't release util ) SendKeys('{Ctrl}{a 3}') #press Ctrl+a at the same time, release Ctrl+a, then type a 2 times SendKeys('{a 3}{B 5}') #type a 3 times, type B 5 times SendKeys('{{}Hello{}}abc {a}{b}{c} test{} 3}{!}{a} (){(}{)}') #type: {Hello}abc abc test}}}!a ()() SendKeys('0123456789{Enter}') SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}') SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}') SendKeys('`~!@#$%^&*()-_=+{Enter}') SendKeys('[]{{}{}}\\|;:\'\",<.>/?{Enter}') """ holdKeys = ('WIN', 'LWIN', 'RWIN', 'SHIFT', 'LSHIFT', 'RSHIFT', 'CTRL', 'CONTROL', 'LCTRL', 'RCTRL', 'LCONTROL', 'LCONTROL', 'ALT', 'LALT', 'RALT') keys = [] printKeys = [] i = 0 insertIndex = 0 length = len(text) hold = False include = False lastKeyValue = None while True: if text[i] == '{': rindex = text.find('}', i) if rindex == i + 1:#{}} rindex = text.find('}', i + 2) if rindex == -1: raise ValueError('"{" or "{}" is not valid, use "{{}" for "{", use "{}}" for "}"') key = text[i + 1:rindex] key = [it for it in key.split(' ') if it] if not key: raise ValueError('"{}" is not valid, use "{{Space}}" or " " for " "'.format(text[i:rindex + 1])) if (len(key) == 2 and not key[1].isdigit()) or len(key) > 2: raise ValueError('"{}" is not valid'.format(text[i:rindex + 1])) upperKey = key[0].upper() count = 1 if len(key) > 1: count = int(key[1]) for j in range(count): if hold: if upperKey in SpecialKeyNames: keyValue = SpecialKeyNames[upperKey] if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue elif key[0] in CharacterCodes: keyValue = CharacterCodes[key[0]] if type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (key[0], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (key[0], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue else: printKeys.insert(insertIndex, (key[0], 'UnicodeChar')) keys.insert(insertIndex, (key[0], 'UnicodeChar')) lastKeyValue = key[0] if include: insertIndex += 1 else: if upperKey in holdKeys: insertIndex += 1 else: hold = False else: if upperKey in SpecialKeyNames: keyValue = SpecialKeyNames[upperKey] printKeys.append((key[0], 'KeyDown | ExtendedKey')) printKeys.append((key[0], 'KeyUp | ExtendedKey')) keys.append((keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.append((keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue if upperKey in holdKeys: hold = True insertIndex = len(keys) - 1 else: hold = False else: printKeys.append((key[0], 'UnicodeChar')) keys.append((key[0], 'UnicodeChar')) lastKeyValue = key[0] i = rindex + 1 elif text[i] == '(': if hold: include = True else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 elif text[i] == ')': if hold: include = False hold = False else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 else: if hold: if text[i] in CharacterCodes: keyValue = CharacterCodes[text[i]] if include and type(lastKeyValue) == type(keyValue) and lastKeyValue == keyValue: insertIndex += 1 printKeys.insert(insertIndex, (text[i], 'KeyDown | ExtendedKey')) printKeys.insert(insertIndex + 1, (text[i], 'KeyUp | ExtendedKey')) keys.insert(insertIndex, (keyValue, KeyboardEventFlag.KeyDown | KeyboardEventFlag.ExtendedKey)) keys.insert(insertIndex + 1, (keyValue, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey)) lastKeyValue = keyValue else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] if include: insertIndex += 1 else: hold = False else: printKeys.append((text[i], 'UnicodeChar')) keys.append((text[i], 'UnicodeChar')) lastKeyValue = text[i] i += 1 if i >= length: break hotkeyInterval = 0.01 for i, key in enumerate(keys): if key[1] == 'UnicodeChar': SendUnicodeChar(key[0], charMode) time.sleep(interval) if debug: Logger.ColorfullyWrite('<Color=DarkGreen>{}</Color>, sleep({})\n'.format(printKeys[i], interval), writeToFile=False) else: scanCode = _VKtoSC(key[0]) keybd_event(key[0], scanCode, key[1], 0) if debug: Logger.Write(printKeys[i], ConsoleColor.DarkGreen, writeToFile=False) if i + 1 == len(keys): time.sleep(interval) if debug: Logger.Write(', sleep({})\n'.format(interval), writeToFile=False) else: if key[1] & KeyboardEventFlag.KeyUp: if keys[i + 1][1] == 'UnicodeChar' or keys[i + 1][1] & KeyboardEventFlag.KeyUp == 0: time.sleep(interval) if debug: Logger.Write(', sleep({})\n'.format(interval), writeToFile=False) else: time.sleep(hotkeyInterval) #must sleep for a while, otherwise combined keys may not be caught if debug: Logger.Write(', sleep({})\n'.format(hotkeyInterval), writeToFile=False) else: #KeyboardEventFlag.KeyDown time.sleep(hotkeyInterval) if debug: Logger.Write(', sleep({})\n'.format(hotkeyInterval), writeToFile=False) #make sure hold keys are not pressed #win = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_LWIN) #ctrl = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_CONTROL) #alt = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_MENU) #shift = ctypes.windll.user32.GetAsyncKeyState(Keys.VK_SHIFT) #if win & 0x8000: #Logger.WriteLine('ERROR: WIN is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_LWIN, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if ctrl & 0x8000: #Logger.WriteLine('ERROR: CTRL is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_CONTROL, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if alt & 0x8000: #Logger.WriteLine('ERROR: ALT is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_MENU, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) #if shift & 0x8000: #Logger.WriteLine('ERROR: SHIFT is pressed, it should not be pressed!', ConsoleColor.Red) #keybd_event(Keys.VK_SHIFT, 0, KeyboardEventFlag.KeyUp | KeyboardEventFlag.ExtendedKey, 0) time.sleep(waitTime)
Simulate typing keys on keyboard. text: str, keys to type. interval: float, seconds between keys. waitTime: float. charMode: bool, if False, the text typied is depend on the input method if a input method is on. debug: bool, if True, print the keys. Examples: {Ctrl}, {Delete} ... are special keys' name in SpecialKeyNames. SendKeys('{Ctrl}a{Delete}{Ctrl}v{Ctrl}s{Ctrl}{Shift}s{Win}e{PageDown}') #press Ctrl+a, Delete, Ctrl+v, Ctrl+s, Ctrl+Shift+s, Win+e, PageDown SendKeys('{Ctrl}(AB)({Shift}(123))') #press Ctrl+A+B, type (, press Shift+1+2+3, type ), if () follows a hold key, hold key won't release util ) SendKeys('{Ctrl}{a 3}') #press Ctrl+a at the same time, release Ctrl+a, then type a 2 times SendKeys('{a 3}{B 5}') #type a 3 times, type B 5 times SendKeys('{{}Hello{}}abc {a}{b}{c} test{} 3}{!}{a} (){(}{)}') #type: {Hello}abc abc test}}}!a ()() SendKeys('0123456789{Enter}') SendKeys('ABCDEFGHIJKLMNOPQRSTUVWXYZ{Enter}') SendKeys('abcdefghijklmnopqrstuvwxyz{Enter}') SendKeys('`~!@#$%^&*()-_=+{Enter}') SendKeys('[]{{}{}}\|;:'",<.>/?{Enter}')
SendKeys
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Write(log: Any, consoleColor: int = ConsoleColor.Default, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None, printTruncateLen: int = 0) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. printTruncateLen: int, if <= 0, log is not truncated when print. """ if not isinstance(log, str): log = str(log) if printToStdout and sys.stdout: isValidColor = (consoleColor >= ConsoleColor.Black and consoleColor <= ConsoleColor.White) if isValidColor: SetConsoleColor(consoleColor) try: if printTruncateLen > 0 and len(log) > printTruncateLen: sys.stdout.write(log[:printTruncateLen] + '...') else: sys.stdout.write(log) except Exception as ex: SetConsoleColor(ConsoleColor.Red) isValidColor = True sys.stdout.write(ex.__class__.__name__ + ': can\'t print the log!') if log.endswith('\n'): sys.stdout.write('\n') if isValidColor: ResetConsoleColor() sys.stdout.flush() if not writeToFile: return fileName = logFile if logFile else Logger.FileName fout = None try: fout = open(fileName, 'a+', encoding='utf-8') fout.write(log) except Exception as ex: if sys.stdout: sys.stdout.write(ex.__class__.__name__ + ': can\'t write the log!') finally: if fout: fout.close()
log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. printTruncateLen: int, if <= 0, log is not truncated when print.
Write
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def ColorfullyWrite(log: str, consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames. """ text = [] start = 0 while True: index1 = log.find('<Color=', start) if index1 >= 0: if index1 > start: text.append((log[start:index1], consoleColor)) index2 = log.find('>', index1) colorName = log[index1+7:index2] index3 = log.find('</Color>', index2 + 1) text.append((log[index2 + 1:index3], Logger.ColorNames[colorName])) start = index3 + 8 else: if start < len(log): text.append((log[start:], consoleColor)) break for t, c in text: Logger.Write(t, c, writeToFile, printToStdout, logFile)
log: str. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyWrite('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames.
ColorfullyWrite
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Log(log: Any = '', consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path. """ frameCount = 1 while True: frame = sys._getframe(frameCount) _, scriptFileName = os.path.split(frame.f_code.co_filename) if scriptFileName != Logger._SelfFileName: break frameCount += 1 t = datetime.datetime.now() log = '{}-{:02}-{:02} {:02}:{:02}:{:02}.{:03} {}[{}] {} -> {}\n'.format(t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond // 1000, scriptFileName, frame.f_lineno, frame.f_code.co_name, log) Logger.Write(log, consoleColor, writeToFile, printToStdout, logFile)
log: any type. consoleColor: int, a value in class `ConsoleColor`, such as `ConsoleColor.DarkGreen`. writeToFile: bool. printToStdout: bool. logFile: str, log file path.
Log
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def ColorfullyLog(log: str = '', consoleColor: int = -1, writeToFile: bool = True, printToStdout: bool = True, logFile: str = None) -> None: """ log: any type. consoleColor: int, a value in class ConsoleColor, such as ConsoleColor.DarkGreen. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyLog('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames """ frameCount = 1 while True: frame = sys._getframe(frameCount) _, scriptFileName = os.path.split(frame.f_code.co_filename) if scriptFileName != Logger._SelfFileName: break frameCount += 1 t = datetime.datetime.now() log = '{}-{:02}-{:02} {:02}:{:02}:{:02}.{:03} {}[{}] {} -> {}\n'.format(t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond // 1000, scriptFileName, frame.f_lineno, frame.f_code.co_name, log) Logger.ColorfullyWrite(log, consoleColor, writeToFile, printToStdout, logFile)
log: any type. consoleColor: int, a value in class ConsoleColor, such as ConsoleColor.DarkGreen. writeToFile: bool. printToStdout: bool. logFile: str, log file path. ColorfullyLog('Hello <Color=Green>Green</Color> !!!'), color name must be in Logger.ColorNames
ColorfullyLog
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def __init__(self, width: int = 0, height: int = 0): """ Create a black bimap of size(width, height). """ self._width = width self._height = height self._bitmap = 0 if width > 0 and height > 0: self._bitmap = _DllClient.instance().dll.BitmapCreate(width, height)
Create a black bimap of size(width, height).
__init__
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def FromHandle(self, hwnd: int, left: int = 0, top: int = 0, right: int = 0, bottom: int = 0) -> bool: """ Capture a native window to Bitmap by its handle. hwnd: int, the handle of a native window. left: int. top: int. right: int. bottom: int. left, top, right and bottom are control's internal postion(from 0,0). Return bool, True if succeed otherwise False. """ self.Release() root = GetRootControl() rect = ctypes.wintypes.RECT() ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)) left, top, right, bottom = left + rect.left, top + rect.top, right + rect.left, bottom + rect.top self._bitmap = _DllClient.instance().dll.BitmapFromWindow(root.NativeWindowHandle, left, top, right, bottom) self._getsize() return self._bitmap > 0
Capture a native window to Bitmap by its handle. hwnd: int, the handle of a native window. left: int. top: int. right: int. bottom: int. left, top, right and bottom are control's internal postion(from 0,0). Return bool, True if succeed otherwise False.
FromHandle
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def FromControl(self, control: 'Control', x: int = 0, y: int = 0, width: int = 0, height: int = 0) -> bool: """ Capture a control to Bitmap. control: `Control` or its subclass. x: int. y: int. width: int. height: int. x, y: the point in control's internal position(from 0,0) width, height: image's width and height from x, y, use 0 for entire area, If width(or height) < 0, image size will be control's width(or height) - width(or height). Return bool, True if succeed otherwise False. """ rect = control.BoundingRectangle while rect.width() == 0 or rect.height() == 0: #some controls maybe visible but their BoundingRectangle are all 0, capture its parent util valid control = control.GetParentControl() if not control: return False rect = control.BoundingRectangle if width <= 0: width = rect.width() + width if height <= 0: height = rect.height() + height handle = control.NativeWindowHandle if handle: left = x top = y right = left + width bottom = top + height else: while True: control = control.GetParentControl() handle = control.NativeWindowHandle if handle: pRect = control.BoundingRectangle left = rect.left - pRect.left + x top = rect.top - pRect.top + y right = left + width bottom = top + height break return self.FromHandle(handle, left, top, right, bottom)
Capture a control to Bitmap. control: `Control` or its subclass. x: int. y: int. width: int. height: int. x, y: the point in control's internal position(from 0,0) width, height: image's width and height from x, y, use 0 for entire area, If width(or height) < 0, image size will be control's width(or height) - width(or height). Return bool, True if succeed otherwise False.
FromControl
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def FromFile(self, filePath: str) -> bool: """ Load image from a file. filePath: str. Return bool, True if succeed otherwise False. """ self.Release() self._bitmap = _DllClient.instance().dll.BitmapFromFile(ctypes.c_wchar_p(filePath)) self._getsize() return self._bitmap > 0
Load image from a file. filePath: str. Return bool, True if succeed otherwise False.
FromFile
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def ToFile(self, savePath: str) -> bool: """ Save to a file. savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff. Return bool, True if succeed otherwise False. """ name, ext = os.path.splitext(savePath) extMap = {'.bmp': 'image/bmp' , '.jpg': 'image/jpeg' , '.jpeg': 'image/jpeg' , '.gif': 'image/gif' , '.tif': 'image/tiff' , '.tiff': 'image/tiff' , '.png': 'image/png' } gdiplusImageFormat = extMap.get(ext.lower(), 'image/png') return bool(_DllClient.instance().dll.BitmapToFile(self._bitmap, ctypes.c_wchar_p(savePath), ctypes.c_wchar_p(gdiplusImageFormat)))
Save to a file. savePath: str, should end with .bmp, .jpg, .jpeg, .png, .gif, .tif, .tiff. Return bool, True if succeed otherwise False.
ToFile
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetPixelColorsHorizontally(self, x: int, y: int, count: int) -> ctypes.Array: """ x: int. y: int. count: int. Return `ctypes.Array`, an iterable array of int values in argb form point x,y horizontally. """ arrayType = ctypes.c_uint32 * count values = arrayType() _DllClient.instance().dll.BitmapGetPixelsHorizontally(ctypes.c_size_t(self._bitmap), x, y, values, count) return values
x: int. y: int. count: int. Return `ctypes.Array`, an iterable array of int values in argb form point x,y horizontally.
GetPixelColorsHorizontally
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetPixelColorsHorizontally(self, x: int, y: int, colors: Iterable[int]) -> bool: """ Set pixel colors form x,y horizontally. x: int. y: int. colors: Iterable[int], an iterable list of int color values in argb. Return bool, True if succeed otherwise False. """ count = len(colors) arrayType = ctypes.c_uint32 * count values = arrayType(*colors) return _DllClient.instance().dll.BitmapSetPixelsHorizontally(ctypes.c_size_t(self._bitmap), x, y, values, count)
Set pixel colors form x,y horizontally. x: int. y: int. colors: Iterable[int], an iterable list of int color values in argb. Return bool, True if succeed otherwise False.
SetPixelColorsHorizontally
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetPixelColorsVertically(self, x: int, y: int, count: int) -> ctypes.Array: """ x: int. y: int. count: int. Return `ctypes.Array`, an iterable array of int values in argb form point x,y vertically. """ arrayType = ctypes.c_uint32 * count values = arrayType() _DllClient.instance().dll.BitmapGetPixelsVertically(ctypes.c_size_t(self._bitmap), x, y, values, count) return values
x: int. y: int. count: int. Return `ctypes.Array`, an iterable array of int values in argb form point x,y vertically.
GetPixelColorsVertically
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetPixelColorsVertically(self, x: int, y: int, colors: Iterable[int]) -> bool: """ Set pixel colors form x,y vertically. x: int. y: int. colors: Iterable[int], an iterable list of int color values in argb. Return bool, True if succeed otherwise False. """ count = len(colors) arrayType = ctypes.c_uint32 * count values = arrayType(*colors) return _DllClient.instance().dll.BitmapSetPixelsVertically(ctypes.c_size_t(self._bitmap), x, y, values, count)
Set pixel colors form x,y vertically. x: int. y: int. colors: Iterable[int], an iterable list of int color values in argb. Return bool, True if succeed otherwise False.
SetPixelColorsVertically
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetPixelColorsOfRect(self, x: int, y: int, width: int, height: int) -> ctypes.Array: """ x: int. y: int. width: int. height: int. Return `ctypes.Array`, an iterable array of int values in argb of the input rect. """ arrayType = ctypes.c_uint32 * (width * height) values = arrayType() _DllClient.instance().dll.BitmapGetPixelsOfRect(ctypes.c_size_t(self._bitmap), x, y, width, height, values) return values
x: int. y: int. width: int. height: int. Return `ctypes.Array`, an iterable array of int values in argb of the input rect.
GetPixelColorsOfRect
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetPixelColorsOfRect(self, x: int, y: int, width: int, height: int, colors: Iterable[int]) -> bool: """ x: int. y: int. width: int. height: int. colors: Iterable[int], an iterable list of int values in argb, it's length must equal to width*height. Return bool. """ arrayType = ctypes.c_uint32 * (width * height) values = arrayType(*colors) return bool(_DllClient.instance().dll.BitmapSetPixelsOfRect(ctypes.c_size_t(self._bitmap), x, y, width, height, values))
x: int. y: int. width: int. height: int. colors: Iterable[int], an iterable list of int values in argb, it's length must equal to width*height. Return bool.
SetPixelColorsOfRect
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetPixelColorsOfRects(self, rects: List[Tuple[int, int, int, int]]) -> List[ctypes.Array]: """ rects: List[Tuple[int, int, int, int]], such as [(0,0,10,10), (10,10,20,20), (x,y,width,height)]. Return List[ctypes.Array], a list whose elements are ctypes.Array which is an iterable array of int values in argb. """ rects2 = [(x, y, x + width, y + height) for x, y, width, height in rects] left, top, right, bottom = zip(*rects2) left, top, right, bottom = min(left), min(top), max(right), max(bottom) width, height = right - left, bottom - top allColors = self.GetPixelColorsOfRect(left, top, width, height) colorsOfRects = [] for x, y, w, h in rects: x -= left y -= top colors = [] for row in range(h): colors.extend(allColors[(y + row) * width + x:(y + row) * width + x + w]) colorsOfRects.append(colors) return colorsOfRects
rects: List[Tuple[int, int, int, int]], such as [(0,0,10,10), (10,10,20,20), (x,y,width,height)]. Return List[ctypes.Array], a list whose elements are ctypes.Array which is an iterable array of int values in argb.
GetPixelColorsOfRects
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetSubBitmap(self, x: int, y: int, width: int, height: int) -> 'Bitmap': """ x: int. y: int. width: int. height: int. Return `Bitmap`, a sub bitmap of the input rect. """ colors = self.GetPixelColorsOfRect(x, y, width, height) bitmap = Bitmap(width, height) bitmap.SetPixelColorsOfRect(0, 0, width, height, colors) return bitmap
x: int. y: int. width: int. height: int. Return `Bitmap`, a sub bitmap of the input rect.
GetSubBitmap
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetPatternIdInterface(patternId: int): """ Get pattern COM interface by pattern id. patternId: int, a value in class `PatternId`. Return comtypes._cominterface_meta. """ global _PatternIdInterfaces if not _PatternIdInterfaces: _PatternIdInterfaces = { # PatternId.AnnotationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern, # PatternId.CustomNavigationPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern, PatternId.DockPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDockPattern, # PatternId.DragPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern, # PatternId.DropTargetPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern, PatternId.ExpandCollapsePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationExpandCollapsePattern, PatternId.GridItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationGridItemPattern, PatternId.GridPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationGridPattern, PatternId.InvokePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationInvokePattern, PatternId.ItemContainerPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationItemContainerPattern, PatternId.LegacyIAccessiblePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationLegacyIAccessiblePattern, PatternId.MultipleViewPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationMultipleViewPattern, # PatternId.ObjectModelPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern, PatternId.RangeValuePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationRangeValuePattern, PatternId.ScrollItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationScrollItemPattern, PatternId.ScrollPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationScrollPattern, PatternId.SelectionItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionItemPattern, PatternId.SelectionPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSelectionPattern, # PatternId.SpreadsheetItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern, # PatternId.SpreadsheetPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern, # PatternId.StylesPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern, PatternId.SynchronizedInputPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationSynchronizedInputPattern, PatternId.TableItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTableItemPattern, PatternId.TablePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTablePattern, # PatternId.TextChildPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern, # PatternId.TextEditPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern, PatternId.TextPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern, # PatternId.TextPattern2: _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2, PatternId.TogglePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTogglePattern, PatternId.TransformPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern, # PatternId.TransformPattern2: _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2, PatternId.ValuePattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationValuePattern, PatternId.VirtualizedItemPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationVirtualizedItemPattern, PatternId.WindowPattern: _AutomationClient.instance().UIAutomationCore.IUIAutomationWindowPattern, } debug = False #the following patterns doesn't exist on Windows 7 or lower try: _PatternIdInterfaces[PatternId.AnnotationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationAnnotationPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have AnnotationPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.CustomNavigationPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationCustomNavigationPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have CustomNavigationPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.DragPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDragPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have DragPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.DropTargetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationDropTargetPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have DropTargetPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.ObjectModelPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationObjectModelPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have ObjectModelPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.SpreadsheetItemPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetItemPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have SpreadsheetItemPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.SpreadsheetPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationSpreadsheetPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have SpreadsheetPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.StylesPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationStylesPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have StylesPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextChildPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextChildPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have TextChildPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextEditPattern] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextEditPattern except: if debug: Logger.WriteLine('UIAutomationCore does not have TextEditPattern.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TextPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTextPattern2 except: if debug: Logger.WriteLine('UIAutomationCore does not have TextPattern2.', ConsoleColor.Yellow) try: _PatternIdInterfaces[PatternId.TransformPattern2] = _AutomationClient.instance().UIAutomationCore.IUIAutomationTransformPattern2 except: if debug: Logger.WriteLine('UIAutomationCore does not have TransformPattern2.', ConsoleColor.Yellow) return _PatternIdInterfaces[patternId]
Get pattern COM interface by pattern id. patternId: int, a value in class `PatternId`. Return comtypes._cominterface_meta.
GetPatternIdInterface
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetDockPosition(self, dockPosition: int, waitTime: float = OPERATION_WAIT_TIME) -> int: """ Call IUIAutomationDockPattern::SetDockPosition. dockPosition: int, a value in class `DockPosition`. waitTime: float. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdockpattern-setdockposition """ ret = self.pattern.SetDockPosition(dockPosition) time.sleep(waitTime) return ret
Call IUIAutomationDockPattern::SetDockPosition. dockPosition: int, a value in class `DockPosition`. waitTime: float. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdockpattern-setdockposition
SetDockPosition
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetGrabbedItems(self) -> List['Control']: """ Call IUIAutomationDragPattern::GetCurrentGrabbedItems. Return List[Control], a list of `Control` subclasses that represent the full set of items that the user is dragging as part of a drag operation. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-getcurrentgrabbeditems """ eleArray = self.pattern.GetCurrentGrabbedItems() if eleArray: controls = [] for i in range(eleArray.Length): ele = eleArray.GetElement(i) con = Control.CreateControlFromElement(element=ele) if con: controls.append(con) return controls return []
Call IUIAutomationDragPattern::GetCurrentGrabbedItems. Return List[Control], a list of `Control` subclasses that represent the full set of items that the user is dragging as part of a drag operation. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationdragpattern-getcurrentgrabbeditems
GetGrabbedItems
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Collapse(self, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationExpandCollapsePattern::Collapse. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-collapse """ ret = self.pattern.Collapse() == S_OK time.sleep(waitTime) return ret
Call IUIAutomationExpandCollapsePattern::Collapse. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-collapse
Collapse
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Expand(self, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationExpandCollapsePattern::Expand. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-expand """ ret = self.pattern.Expand() == S_OK time.sleep(waitTime) return ret
Call IUIAutomationExpandCollapsePattern::Expand. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationexpandcollapsepattern-expand
Expand
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Invoke(self, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationInvokePattern::Invoke. Invoke the action of a control, such as a button click. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationinvokepattern-invoke """ ret = self.pattern.Invoke() == S_OK time.sleep(waitTime) return ret
Call IUIAutomationInvokePattern::Invoke. Invoke the action of a control, such as a button click. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationinvokepattern-invoke
Invoke
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def DoDefaultAction(self, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationLegacyIAccessiblePattern::DoDefaultAction. Perform the Microsoft Active Accessibility default action for the element. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-dodefaultaction """ ret = self.pattern.DoDefaultAction() == S_OK time.sleep(waitTime) return ret
Call IUIAutomationLegacyIAccessiblePattern::DoDefaultAction. Perform the Microsoft Active Accessibility default action for the element. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-dodefaultaction
DoDefaultAction
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def GetSelection(self) -> List['Control']: """ Call IUIAutomationLegacyIAccessiblePattern::GetCurrentSelection. Return List[Control], a list of `Control` subclasses, the Microsoft Active Accessibility property that identifies the selected children of this element. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-getcurrentselection """ eleArray = self.pattern.GetCurrentSelection() if eleArray: controls = [] for i in range(eleArray.Length): ele = eleArray.GetElement(i) con = Control.CreateControlFromElement(element=ele) if con: controls.append(con) return controls return []
Call IUIAutomationLegacyIAccessiblePattern::GetCurrentSelection. Return List[Control], a list of `Control` subclasses, the Microsoft Active Accessibility property that identifies the selected children of this element. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-getcurrentselection
GetSelection
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def Select(self, flagsSelect: int, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationLegacyIAccessiblePattern::Select. Perform a Microsoft Active Accessibility selection. flagsSelect: int, a value in `AccessibleSelection`. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-select """ ret = self.pattern.Select(flagsSelect) == S_OK time.sleep(waitTime) return ret
Call IUIAutomationLegacyIAccessiblePattern::Select. Perform a Microsoft Active Accessibility selection. flagsSelect: int, a value in `AccessibleSelection`. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-select
Select
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetValue(self, value: str, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationLegacyIAccessiblePattern::SetValue. Set the Microsoft Active Accessibility value property for the element. value: str. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-setvalue """ ret = self.pattern.SetValue(value) == S_OK time.sleep(waitTime) return ret
Call IUIAutomationLegacyIAccessiblePattern::SetValue. Set the Microsoft Active Accessibility value property for the element. value: str. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationlegacyiaccessiblepattern-setvalue
SetValue
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def SetValue(self, value: float, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationRangeValuePattern::SetValue. Set the value of the control. value: int. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationrangevaluepattern-setvalue """ ret = self.pattern.SetValue(value) == S_OK time.sleep(waitTime) return ret
Call IUIAutomationRangeValuePattern::SetValue. Set the value of the control. value: int. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationrangevaluepattern-setvalue
SetValue
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0
def ScrollIntoView(self, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationScrollItemPattern::ScrollIntoView. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollitempattern-scrollintoview """ ret = self.pattern.ScrollIntoView() == S_OK time.sleep(waitTime) return ret
Call IUIAutomationScrollItemPattern::ScrollIntoView. waitTime: float. Return bool, True if succeed otherwise False. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationscrollitempattern-scrollintoview
ScrollIntoView
python
cluic/wxauto
wxauto/uiautomation.py
https://github.com/cluic/wxauto/blob/master/wxauto/uiautomation.py
Apache-2.0