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