|
1 | | -from typing import Optional |
| 1 | +from typing import List, Optional, Tuple, Union |
| 2 | +from warnings import warn |
| 3 | + |
| 4 | +import napari.qt |
| 5 | +import tinycss2 |
| 6 | +from qtpy.QtCore import QSize |
2 | 7 |
|
3 | 8 |
|
4 | 9 | class Interval: |
@@ -34,3 +39,67 @@ def __contains__(self, val: int) -> bool: |
34 | 39 | if self.upper is not None and val > self.upper: |
35 | 40 | return False |
36 | 41 | return True |
| 42 | + |
| 43 | + |
| 44 | +def _has_id(nodes: List[tinycss2.ast.Node], id_name: str) -> bool: |
| 45 | + """ |
| 46 | + Is `id_name` in IdentTokens in the list of CSS `nodes`? |
| 47 | + """ |
| 48 | + return any( |
| 49 | + [node.type == "ident" and node.value == id_name for node in nodes] |
| 50 | + ) |
| 51 | + |
| 52 | + |
| 53 | +def _get_dimension( |
| 54 | + nodes: List[tinycss2.ast.Node], id_name: str |
| 55 | +) -> Union[int, None]: |
| 56 | + """ |
| 57 | + Get the value of the DimensionToken for the IdentToken `id_name`. |
| 58 | +
|
| 59 | + Returns |
| 60 | + ------- |
| 61 | + None if no IdentToken is found. |
| 62 | + """ |
| 63 | + cleaned_nodes = [node for node in nodes if node.type != "whitespace"] |
| 64 | + for name, _, value, _ in zip(*(iter(cleaned_nodes),) * 4): |
| 65 | + if ( |
| 66 | + name.type == "ident" |
| 67 | + and value.type == "dimension" |
| 68 | + and name.value == id_name |
| 69 | + ): |
| 70 | + return value.int_value |
| 71 | + warn(f"Unable to find DimensionToken for {id_name}", RuntimeWarning) |
| 72 | + return None |
| 73 | + |
| 74 | + |
| 75 | +def from_napari_css_get_size_of( |
| 76 | + qt_element_name: str, fallback: Tuple[int, int] |
| 77 | +) -> QSize: |
| 78 | + """ |
| 79 | + Get the size of `qt_element_name` from napari's current stylesheet. |
| 80 | +
|
| 81 | + TODO: Confirm that the napari.qt.get_current_stylesheet changes with napari |
| 82 | + theme (docs seem to indicate it should) |
| 83 | +
|
| 84 | + Returns |
| 85 | + ------- |
| 86 | + QSize of the element if it's found, the `fallback` if it's not found.. |
| 87 | + """ |
| 88 | + rules = tinycss2.parse_stylesheet( |
| 89 | + napari.qt.get_current_stylesheet(), |
| 90 | + skip_comments=True, |
| 91 | + skip_whitespace=True, |
| 92 | + ) |
| 93 | + w, h = None, None |
| 94 | + for rule in rules: |
| 95 | + if _has_id(rule.prelude, qt_element_name): |
| 96 | + w = _get_dimension(rule.content, "max-width") |
| 97 | + h = _get_dimension(rule.content, "max-height") |
| 98 | + if w and h: |
| 99 | + return QSize(w, h) |
| 100 | + warn( |
| 101 | + f"Unable to find {qt_element_name} or unable to find its size in " |
| 102 | + f"the current Napari stylesheet, falling back to {fallback}", |
| 103 | + RuntimeWarning, |
| 104 | + ) |
| 105 | + return QSize(*fallback) |
0 commit comments