pythonnative 0.37.0__py3-none-any.whl → 0.38.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. pythonnative/__init__.py +9 -1
  2. pythonnative/alerts.py +6 -14
  3. pythonnative/cli/pn.py +96 -10
  4. pythonnative/components/_base.py +31 -0
  5. pythonnative/components/controls.py +19 -16
  6. pythonnative/components/layout.py +5 -8
  7. pythonnative/components/lists.py +6 -6
  8. pythonnative/gestures.py +27 -6
  9. pythonnative/native_modules/__init__.py +19 -0
  10. pythonnative/native_modules/battery.py +13 -14
  11. pythonnative/native_modules/biometrics.py +12 -14
  12. pythonnative/native_modules/camera.py +10 -6
  13. pythonnative/native_modules/clipboard.py +9 -11
  14. pythonnative/native_modules/file_system.py +81 -172
  15. pythonnative/native_modules/haptics.py +14 -10
  16. pythonnative/native_modules/linking.py +9 -8
  17. pythonnative/native_modules/location.py +10 -12
  18. pythonnative/native_modules/net_info.py +1 -4
  19. pythonnative/native_modules/notifications.py +25 -32
  20. pythonnative/native_modules/permissions.py +70 -22
  21. pythonnative/native_modules/secure_store.py +16 -20
  22. pythonnative/native_modules/share.py +5 -5
  23. pythonnative/navigation/__init__.py +2 -1
  24. pythonnative/navigation/hooks.py +46 -7
  25. pythonnative/navigation/state.py +30 -9
  26. pythonnative/project/android.py +23 -0
  27. pythonnative/project/builder.py +64 -35
  28. pythonnative/project/config.py +84 -24
  29. pythonnative/project/deps.py +703 -0
  30. pythonnative/project/doctor.py +53 -4
  31. pythonnative/project/runtime_assets.py +13 -14
  32. pythonnative/style.py +94 -44
  33. pythonnative/templates/android_template/app/build.gradle +5 -2
  34. pythonnative/templates/android_template/build.gradle +7 -4
  35. pythonnative/templates/android_template/gradle/wrapper/gradle-wrapper.properties +1 -1
  36. pythonnative/templates/android_template/pythonnative/src/main/java/com/pythonnative/runtime/modules/PermissionsModule.kt +15 -4
  37. pythonnative/templates/ios_template/PythonNativeKit/Sources/PythonNativeKit/Modules/PermissionModules.swift +25 -10
  38. pythonnative/templates/ios_template/ios_template/PythonRuntime.swift +3 -2
  39. pythonnative/templates/ios_template/ios_template.xcodeproj/project.pbxproj +35 -9
  40. pythonnative/utils.py +22 -27
  41. pythonnative/virtual_rows.py +10 -20
  42. {pythonnative-0.37.0.dist-info → pythonnative-0.38.0.dist-info}/METADATA +8 -8
  43. {pythonnative-0.37.0.dist-info → pythonnative-0.38.0.dist-info}/RECORD +47 -46
  44. {pythonnative-0.37.0.dist-info → pythonnative-0.38.0.dist-info}/WHEEL +0 -0
  45. {pythonnative-0.37.0.dist-info → pythonnative-0.38.0.dist-info}/entry_points.txt +0 -0
  46. {pythonnative-0.37.0.dist-info → pythonnative-0.38.0.dist-info}/licenses/LICENSE +0 -0
  47. {pythonnative-0.37.0.dist-info → pythonnative-0.38.0.dist-info}/top_level.txt +0 -0
pythonnative/__init__.py CHANGED
@@ -62,7 +62,7 @@ Example:
62
62
  ```
63
63
  """
64
64
 
65
- __version__ = "0.37.0"
65
+ __version__ = "0.38.0"
66
66
 
67
67
  from . import appearance, diagnostics, gestures, images, runtime, sdk
68
68
  from .alerts import Alert
@@ -190,6 +190,7 @@ from .style import (
190
190
  AutoCapitalize,
191
191
  Color,
192
192
  Dimension,
193
+ Display,
193
194
  EdgeInsets,
194
195
  FlexDirection,
195
196
  FlexWrap,
@@ -198,6 +199,7 @@ from .style import (
198
199
  KeyboardType,
199
200
  LayoutDirection,
200
201
  Overflow,
202
+ PointerEvents,
201
203
  Position,
202
204
  ReturnKeyType,
203
205
  ScaleType,
@@ -207,6 +209,8 @@ from .style import (
207
209
  StyleSheet,
208
210
  TextAlign,
209
211
  TextDecoration,
212
+ TextTransform,
213
+ Theme,
210
214
  ThemeContext,
211
215
  TransformSpec,
212
216
  default_theme,
@@ -314,6 +318,7 @@ __all__ = [
314
318
  "DEFAULT_DARK_THEME",
315
319
  "DEFAULT_LIGHT_THEME",
316
320
  "Dimension",
321
+ "Display",
317
322
  "EdgeInsets",
318
323
  "FlexDirection",
319
324
  "FlexWrap",
@@ -322,6 +327,7 @@ __all__ = [
322
327
  "KeyboardType",
323
328
  "LayoutDirection",
324
329
  "Overflow",
330
+ "PointerEvents",
325
331
  "Position",
326
332
  "ReturnKeyType",
327
333
  "ScaleType",
@@ -331,6 +337,8 @@ __all__ = [
331
337
  "StyleSheet",
332
338
  "TextAlign",
333
339
  "TextDecoration",
340
+ "TextTransform",
341
+ "Theme",
334
342
  "ThemeContext",
335
343
  "TransformSpec",
336
344
  "default_theme",
pythonnative/alerts.py CHANGED
@@ -56,12 +56,9 @@ async def _present(
56
56
  implementation records the call and answers from the queue set by
57
57
  [`Alert.set_test_response`][pythonnative.alerts.Alert.set_test_response].
58
58
  """
59
- try:
60
- result = await native_module("Alert").call_async(
61
- "present", title=title, message=message, buttons=buttons, style=style
62
- )
63
- except Exception:
64
- return -1
59
+ result = await native_module("Alert").call_async(
60
+ "present", title=title, message=message, buttons=buttons, style=style
61
+ )
65
62
  try:
66
63
  return int(result)
67
64
  except (TypeError, ValueError):
@@ -135,14 +132,9 @@ class Alert:
135
132
  [`choose`][pythonnative.alerts.Alert.choose] and ``await``
136
133
  the result.
137
134
  """
138
- try:
139
- native_module("Alert").call(
140
- "show", title=title, message=message, buttons=[{"label": button, "style": "default"}], style="alert"
141
- )
142
- except Exception:
143
- from . import diagnostics
144
-
145
- diagnostics.swallowed("alerts.Alert.show")
135
+ native_module("Alert").call(
136
+ "show", title=title, message=message, buttons=[{"label": button, "style": "default"}], style="alert"
137
+ )
146
138
 
147
139
  @staticmethod
148
140
  async def confirm(
pythonnative/cli/pn.py CHANGED
@@ -6,6 +6,9 @@ The console script `pn` (declared in `pyproject.toml`) dispatches to:
6
6
  ``app/``) into ``./name/``, or into the current directory when no name
7
7
  is given.
8
8
  - `pn doctor [platform]`: diagnose the local toolchain and config.
9
+ - `pn deps [platform]`: resolve ``[requirements].packages`` for every
10
+ device target and report which wheels would be used (or why a package
11
+ can't be installed), without building anything.
9
12
  - `pn preview [component]`: render the app in a desktop (Tkinter) window
10
13
  with Fast Refresh, the fast inner dev loop, no device required.
11
14
  - `pn devices [platform]`: list connected devices, emulators, and
@@ -41,6 +44,7 @@ from pathlib import Path
41
44
  from typing import Any, Dict, List, Optional, TextIO
42
45
 
43
46
  from ..project import builder as builder_mod
47
+ from ..project import deps as deps_mod
44
48
  from ..project import devices as devices_mod
45
49
  from ..project import doctor as doctor_mod
46
50
  from ..project.android import collect_logcat_filters
@@ -54,22 +58,29 @@ HOT_RELOAD_DEV_ROOT = "pythonnative_dev"
54
58
  # init
55
59
  # ======================================================================
56
60
 
57
- _MAIN_TEMPLATE = """import pythonnative as pn
61
+ _MAIN_TEMPLATE = """from typing import TypedDict
62
+
63
+ import pythonnative as pn
58
64
 
59
65
  Stack = pn.create_stack_navigator()
60
66
 
61
67
 
68
+ class DetailParams(TypedDict):
69
+ count: int
70
+
71
+
62
72
  @pn.component
63
73
  def HomeScreen():
64
74
  count, set_count = pn.use_state(0)
65
75
  nav = pn.use_navigation()
76
+ theme = pn.use_theme()
66
77
  return pn.ScrollView(
67
78
  pn.Column(
68
- pn.Text("Hello from PythonNative!", style={"font_size": 24, "bold": True}),
79
+ pn.Text("Hello from PythonNative!", style={"font_size": theme.font_size_title, "bold": True}),
69
80
  pn.Text(f"Tapped {count} times"),
70
81
  pn.Button("Tap me", on_press=lambda: set_count(count + 1)),
71
- pn.Button("Open detail", on_press=lambda: nav.navigate("Detail", {"count": count})),
72
- style={"spacing": 12, "padding": 16, "align_items": "stretch"},
82
+ pn.Button("Open detail", on_press=lambda: nav.navigate("Detail", count=count)),
83
+ style={"spacing": theme.spacing_large, "padding": 16, "align_items": "stretch"},
73
84
  )
74
85
  )
75
86
 
@@ -77,9 +88,9 @@ def HomeScreen():
77
88
  @pn.component
78
89
  def DetailScreen():
79
90
  nav = pn.use_navigation()
80
- params = pn.use_route()
91
+ route = pn.use_route(DetailParams)
81
92
  return pn.Column(
82
- pn.Text(f"Detail: count was {params.get('count', 0)}", style={"font_size": 20}),
93
+ pn.Text(f"Detail: count was {route.params['count']}", style={"font_size": 20}),
83
94
  pn.Button("Back", on_press=nav.go_back),
84
95
  style={"spacing": 12, "padding": 16},
85
96
  )
@@ -89,8 +100,8 @@ def DetailScreen():
89
100
  def App():
90
101
  return pn.NavigationContainer(
91
102
  Stack.Navigator(
92
- Stack.Screen("Home", component=HomeScreen, options={"title": "Home"}),
93
- Stack.Screen("Detail", component=DetailScreen, options={"title": "Detail"}),
103
+ Stack.Screen("Home", HomeScreen, title="Home"),
104
+ Stack.Screen("Detail", DetailScreen, title="Detail"),
94
105
  )
95
106
  )
96
107
  """
@@ -278,6 +289,56 @@ def app_id_command(args: argparse.Namespace) -> None:
278
289
  print(config.application_id if args.platform == "android" else config.bundle_id)
279
290
 
280
291
 
292
+ # ======================================================================
293
+ # deps
294
+ # ======================================================================
295
+
296
+
297
+ def deps_command(args: argparse.Namespace) -> None:
298
+ """Report how ``[requirements].packages`` resolve for each device target.
299
+
300
+ Runs pip in its cross-platform dry-run mode once per target (iOS
301
+ device, iOS Simulator, and one per Android ABI) and prints the
302
+ wheel each package would use, flagging binary wheels and their
303
+ source index. Exits non-zero when any target can't be satisfied,
304
+ so it doubles as a CI gate. ``--json`` emits the same data as a
305
+ machine-readable document.
306
+
307
+ Args:
308
+ args: Parsed namespace with optional ``platform``, ``json``, and
309
+ ``python`` (the interpreter to run pip with).
310
+ """
311
+ platform: Optional[str] = getattr(args, "platform", None)
312
+ as_json: bool = getattr(args, "json", False)
313
+ python: Optional[str] = getattr(args, "python", None)
314
+
315
+ config = _load_config_or_exit()
316
+ targets = deps_mod.targets_for(config, platform)
317
+ runner = builder_mod.SubprocessRunner()
318
+ if not as_json and config.requirements:
319
+ print(
320
+ f"Resolving {len(config.requirements)} requirement(s) for Python {config.python_version} "
321
+ f"across {len(targets)} target(s)...\n"
322
+ )
323
+ resolutions = deps_mod.resolve_all(config, targets, runner=runner, python=python)
324
+
325
+ if as_json:
326
+ print(
327
+ json.dumps(
328
+ {
329
+ "python_version": config.python_version,
330
+ "requirements": list(config.requirements),
331
+ "targets": [res.to_dict() for res in resolutions],
332
+ },
333
+ indent=2,
334
+ )
335
+ )
336
+ else:
337
+ print(deps_mod.format_report(resolutions, requirements=config.requirements))
338
+ if any(not res.ok for res in resolutions):
339
+ sys.exit(1)
340
+
341
+
281
342
  # ======================================================================
282
343
  # preview
283
344
  # ======================================================================
@@ -426,8 +487,18 @@ def run_project(args: argparse.Namespace) -> None:
426
487
  config = _load_config_or_exit()
427
488
  builder = builder_mod.Builder(config, log=print)
428
489
 
490
+ # Resolve third-party packages only for the destination being built
491
+ # (device wheels and Simulator wheels differ); prepare-only keeps both
492
+ # slices so the staged project builds for either in Xcode.
493
+ if prepare_only:
494
+ ios_sdks: tuple = deps_mod.IOS_SDKS
495
+ elif device is not None and device.kind == "device":
496
+ ios_sdks = ("iphoneos",)
497
+ else:
498
+ ios_sdks = ("iphonesimulator",)
499
+
429
500
  try:
430
- prepared = builder.prepare(platform)
501
+ prepared = builder.prepare(platform, ios_sdks=ios_sdks)
431
502
  except builder_mod.BuildError as exc:
432
503
  print(f"Error: {exc}")
433
504
  sys.exit(1)
@@ -593,7 +664,11 @@ def build_project(args: argparse.Namespace) -> None:
593
664
  sys.exit(1)
594
665
 
595
666
  try:
596
- prepared = builder.prepare(platform, release=not debug)
667
+ prepared = builder.prepare(
668
+ platform,
669
+ release=not debug,
670
+ ios_sdks=("iphonesimulator",) if debug else ("iphoneos",),
671
+ )
597
672
  if platform == "android":
598
673
  artifacts = builder.build_android(prepared, debug=debug)
599
674
  else:
@@ -1020,6 +1095,17 @@ def _build_parser() -> argparse.ArgumentParser:
1020
1095
  parser_doctor.add_argument("platform", nargs="?", choices=["android", "ios"], help="Restrict checks to a platform")
1021
1096
  parser_doctor.set_defaults(func=doctor_command)
1022
1097
 
1098
+ parser_deps = subparsers.add_parser(
1099
+ "deps", help="Check which wheels [requirements].packages resolve to on each device target"
1100
+ )
1101
+ parser_deps.add_argument("platform", nargs="?", choices=["android", "ios"], help="Restrict to a platform")
1102
+ parser_deps.add_argument("--json", action="store_true", help="Print a JSON report for scripting")
1103
+ parser_deps.add_argument(
1104
+ "--python",
1105
+ help="Interpreter to run pip with (default: the one running pn; any version works, pip cross-resolves)",
1106
+ )
1107
+ parser_deps.set_defaults(func=deps_command)
1108
+
1023
1109
  parser_preview = subparsers.add_parser("preview", help="Render the app in a desktop window")
1024
1110
  parser_preview.add_argument(
1025
1111
  "component",
@@ -76,6 +76,37 @@ def _make_element(
76
76
  return Element(name, out, list(children), key=key)
77
77
 
78
78
 
79
+ # ======================================================================
80
+ # RefreshControl attachment
81
+ # ======================================================================
82
+
83
+ REFRESH_CONTROL_TYPE = "RefreshControl"
84
+ """Element type produced by [`RefreshControl`][pythonnative.RefreshControl]."""
85
+
86
+
87
+ def _refresh_control_props(control: Optional[Element], *, owner: str) -> Optional[Dict[str, Any]]:
88
+ """Turn a ``RefreshControl`` element into the ``refresh_control`` wire prop.
89
+
90
+ Scroll containers hold their refresh control as a prop rather than
91
+ a child (the native side attaches a ``UIRefreshControl`` /
92
+ ``SwipeRefreshLayout`` to the scroll view itself), so the element
93
+ is unwrapped here into the flat dict the bridge and the event
94
+ extractor expect. Keeping it an element on the Python side means
95
+ users build it like every other piece of UI and get a clear error
96
+ if they pass the wrong thing.
97
+
98
+ Raises:
99
+ TypeError: If ``control`` is not a ``RefreshControl`` element.
100
+ """
101
+ if control is None:
102
+ return None
103
+ if not isinstance(control, Element) or control.type != REFRESH_CONTROL_TYPE:
104
+ raise TypeError(
105
+ f"{owner}(refresh_control=...) expects pn.RefreshControl(...), got {type(control).__name__}: {control!r}"
106
+ )
107
+ return dict(control.props)
108
+
109
+
79
110
  # ======================================================================
80
111
  # Rich text spans
81
112
  # ======================================================================
@@ -2,7 +2,7 @@
2
2
 
3
3
  ``Switch``, ``Slider``, ``ProgressBar``, ``ActivityIndicator``,
4
4
  ``Checkbox``, ``SegmentedControl``, ``DatePicker``, ``Picker``, the
5
- ``RefreshControl`` spec helper, and ``StatusBar``.
5
+ ``RefreshControl``, and ``StatusBar``.
6
6
  """
7
7
 
8
8
  from typing import Any, Callable, Dict, List, Literal, Optional
@@ -10,7 +10,7 @@ from typing import Any, Callable, Dict, List, Literal, Optional
10
10
  from ..element import Element
11
11
  from ..hooks import Ref
12
12
  from ..style import AccessibilityState, Color, StyleProp
13
- from ._base import _make_element
13
+ from ._base import REFRESH_CONTROL_TYPE, _make_element
14
14
 
15
15
 
16
16
  def Switch(
@@ -426,13 +426,17 @@ def RefreshControl(
426
426
  refreshing: bool = False,
427
427
  on_refresh: Optional[Callable[[], Any]] = None,
428
428
  tint_color: Optional[Color] = None,
429
- ) -> Dict[str, Any]:
430
- """Pull-to-refresh spec for [`ScrollView`][pythonnative.ScrollView] / [`FlatList`][pythonnative.FlatList].
429
+ ) -> Element:
430
+ """Pull-to-refresh control for [`ScrollView`][pythonnative.ScrollView] and the list components.
431
431
 
432
- Returns a plain dict that should be passed as the
433
- ``refresh_control=`` prop. Modeled as a dict (not an
434
- [`Element`][pythonnative.Element]) so the host scroll container can
435
- hold one without it appearing as a child node.
432
+ Pass the result as the ``refresh_control=`` prop of a
433
+ [`ScrollView`][pythonnative.ScrollView],
434
+ [`FlatList`][pythonnative.FlatList], or
435
+ [`SectionList`][pythonnative.SectionList]. It is a regular
436
+ [`Element`][pythonnative.Element] (type ``"RefreshControl"``) built
437
+ like every other piece of UI; the scroll container attaches it to
438
+ its native scroll view rather than rendering it as a child, and
439
+ rejects anything else with a ``TypeError``.
436
440
 
437
441
  Args:
438
442
  refreshing: Drive the spinner's visibility from a use_state
@@ -443,8 +447,7 @@ def RefreshControl(
443
447
  tint_color: Color of the spinner.
444
448
 
445
449
  Returns:
446
- Dict suitable for the ``refresh_control`` prop on a scroll
447
- container.
450
+ An [`Element`][pythonnative.Element] of type ``"RefreshControl"``.
448
451
 
449
452
  Example:
450
453
  ```python
@@ -467,12 +470,12 @@ def RefreshControl(
467
470
  )
468
471
  ```
469
472
  """
470
- spec: Dict[str, Any] = {"refreshing": bool(refreshing)}
471
- if on_refresh is not None:
472
- spec["on_refresh"] = on_refresh
473
- if tint_color is not None:
474
- spec["tint_color"] = tint_color
475
- return spec
473
+ return _make_element(
474
+ REFRESH_CONTROL_TYPE,
475
+ refreshing=bool(refreshing),
476
+ on_refresh=on_refresh,
477
+ tint_color=tint_color,
478
+ )
476
479
 
477
480
 
478
481
  def StatusBar(
@@ -12,7 +12,7 @@ from ..component import component
12
12
  from ..element import Element
13
13
  from ..hooks import Ref, use_keyboard_height, use_safe_area_insets, use_state
14
14
  from ..style import AccessibilityState, StyleProp, resolve_style
15
- from ._base import _make_element
15
+ from ._base import _make_element, _refresh_control_props
16
16
 
17
17
 
18
18
  def View(
@@ -281,7 +281,7 @@ def Spacer(
281
281
 
282
282
  def ScrollView(
283
283
  *children: Element,
284
- refresh_control: Optional[Dict[str, Any]] = None,
284
+ refresh_control: Optional[Element] = None,
285
285
  scroll_axis: Optional[Literal["vertical", "horizontal"]] = None,
286
286
  on_scroll: Optional[Callable[[Dict[str, float]], None]] = None,
287
287
  shows_scroll_indicator: bool = True,
@@ -302,11 +302,8 @@ def ScrollView(
302
302
 
303
303
  Args:
304
304
  *children: Child elements to scroll.
305
- refresh_control: Optional pull-to-refresh spec, typically
306
- constructed via
307
- [`RefreshControl`][pythonnative.RefreshControl]. The dict
308
- must have ``refreshing`` (bool) and ``on_refresh``
309
- (callable).
305
+ refresh_control: Optional [`RefreshControl`][pythonnative.RefreshControl]
306
+ element attached to the scroll view for pull-to-refresh.
310
307
  scroll_axis: ``"vertical"`` (default) or ``"horizontal"``.
311
308
  on_scroll: Callback invoked with ``{"x": …, "y": …}`` content
312
309
  offsets as the user scrolls.
@@ -333,7 +330,7 @@ def ScrollView(
333
330
  style=style,
334
331
  ref=ref,
335
332
  key=key,
336
- refresh_control=refresh_control,
333
+ refresh_control=_refresh_control_props(refresh_control, owner="ScrollView"),
337
334
  scroll_axis=scroll_axis,
338
335
  on_scroll=on_scroll,
339
336
  shows_scroll_indicator=False if shows_scroll_indicator is False else None,
@@ -124,7 +124,7 @@ def _VirtualizedList(
124
124
  header: Optional[Element] = None,
125
125
  footer: Optional[Element] = None,
126
126
  empty: Optional[Element] = None,
127
- refresh_control: Optional[Dict[str, Any]] = None,
127
+ refresh_control: Optional[Element] = None,
128
128
  on_end_reached: Optional[Callable[[], Any]] = None,
129
129
  on_end_reached_threshold: Optional[float] = None,
130
130
  on_viewable_items_changed: Optional[Callable[[List[Dict[str, Any]]], None]] = None,
@@ -464,7 +464,7 @@ def FlatList(
464
464
  get_item_height: Optional[Callable[[Any, int], float]] = None,
465
465
  estimated_item_height: Optional[float] = None,
466
466
  separator_height: float = 0,
467
- refresh_control: Optional[Dict[str, Any]] = None,
467
+ refresh_control: Optional[Element] = None,
468
468
  horizontal: bool = False,
469
469
  num_columns: int = 1,
470
470
  list_header: Optional[Element] = None,
@@ -509,8 +509,8 @@ def FlatList(
509
509
  estimated_item_height: Starting extent estimate for rows whose
510
510
  true size isn't known yet (default 44).
511
511
  separator_height: Gap below each row, in points.
512
- refresh_control: Optional pull-to-refresh spec from
513
- [`RefreshControl`][pythonnative.RefreshControl].
512
+ refresh_control: Optional [`RefreshControl`][pythonnative.RefreshControl]
513
+ element for pull-to-refresh.
514
514
  horizontal: Scroll horizontally (extents become widths).
515
515
  num_columns: Render items in a grid of this many columns.
516
516
  list_header: Element rendered once before all rows.
@@ -666,7 +666,7 @@ def SectionList(
666
666
  estimated_item_height: Optional[float] = None,
667
667
  section_header_height: Optional[float] = None,
668
668
  separator_height: float = 0,
669
- refresh_control: Optional[Dict[str, Any]] = None,
669
+ refresh_control: Optional[Element] = None,
670
670
  list_header: Optional[Element] = None,
671
671
  list_footer: Optional[Element] = None,
672
672
  list_empty: Optional[Element] = None,
@@ -699,7 +699,7 @@ def SectionList(
699
699
  estimated_item_height: Starting estimate for unmeasured rows.
700
700
  section_header_height: Header extent in points, when known.
701
701
  separator_height: Gap below each item, in points.
702
- refresh_control: Optional pull-to-refresh spec.
702
+ refresh_control: Optional [`RefreshControl`][pythonnative.RefreshControl] element.
703
703
  list_header: Element rendered once before everything.
704
704
  list_footer: Element rendered once after everything.
705
705
  list_empty: Element rendered when there are no sections.
pythonnative/gestures.py CHANGED
@@ -78,6 +78,7 @@ from __future__ import annotations
78
78
 
79
79
  import math
80
80
  from dataclasses import dataclass, field
81
+ from enum import Enum
81
82
  from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Set, Tuple
82
83
 
83
84
  __all__ = [
@@ -99,16 +100,30 @@ __all__ = [
99
100
  ]
100
101
 
101
102
 
102
- class GestureState:
103
- """States reported on [`GestureEvent.state`][pythonnative.gestures.GestureEvent]."""
103
+ class GestureState(str, Enum):
104
+ """Lifecycle states reported on [`GestureEvent.state`][pythonnative.gestures.GestureEvent].
105
+
106
+ A ``str`` enum, so members compare equal to their wire value
107
+ (``GestureState.ENDED == "ended"``) and serialize as plain strings
108
+ across the native bridge, while callers get exhaustive
109
+ ``match`` support and autocomplete.
110
+
111
+ Attributes:
112
+ BEGAN: The gesture activated (first callback).
113
+ CHANGED: A continuous gesture updated (pan, pinch, rotation).
114
+ ENDED: The gesture completed successfully.
115
+ CANCELLED: The gesture was interrupted (lost arbitration, view
116
+ unmounted, pointer left the window).
117
+ """
104
118
 
105
119
  BEGAN = "began"
106
120
  CHANGED = "changed"
107
121
  ENDED = "ended"
108
122
  CANCELLED = "cancelled"
109
123
 
124
+ def __str__(self) -> str:
125
+ return self.value
110
126
 
111
- GestureStateName = Literal["began", "changed", "ended", "cancelled"]
112
127
 
113
128
  GestureCallback = Callable[["GestureEvent"], Any]
114
129
 
@@ -141,7 +156,7 @@ class GestureEvent:
141
156
  """
142
157
 
143
158
  kind: str
144
- state: GestureStateName
159
+ state: GestureState
145
160
  x: float = 0.0
146
161
  y: float = 0.0
147
162
  translation_x: float = 0.0
@@ -153,6 +168,12 @@ class GestureEvent:
153
168
  pointer_count: int = 1
154
169
  direction: Optional[str] = None
155
170
 
171
+ def __post_init__(self) -> None:
172
+ # Payloads from the native bridge carry plain strings; coerce
173
+ # so ``event.state`` is always a ``GestureState`` member.
174
+ if not isinstance(self.state, GestureState):
175
+ object.__setattr__(self, "state", GestureState(self.state))
176
+
156
177
 
157
178
  _EVENT_FIELDS = frozenset(
158
179
  {
@@ -576,8 +597,8 @@ class _Recognizer:
576
597
  self.config = config
577
598
  self._emit_fn = emit
578
599
 
579
- def emit(self, state: str, **fields: Any) -> None:
580
- payload: Dict[str, Any] = {"kind": self.kind(), "state": state}
600
+ def emit(self, state: GestureState, **fields: Any) -> None:
601
+ payload: Dict[str, Any] = {"kind": self.kind(), "state": state.value}
581
602
  payload.update(fields)
582
603
  self._emit_fn(self.index, payload)
583
604
 
@@ -17,6 +17,25 @@ feedback), so the same code stays runnable off device. Third-party
17
17
  packages ship their own native modules the same way; see
18
18
  ``docs/guides/native-modules.md``.
19
19
 
20
+ Two rules hold across every facade, so you never have to look one up:
21
+
22
+ 1. **Sync or async is decided by what the OS has to do.** A method is
23
+ a plain function when the answer is already on the device and
24
+ returns on the calling thread (read the pasteboard, check a
25
+ permission, read the battery level, Keychain get/set, file I/O).
26
+ It is a coroutine when the OS has to prompt the user, drive
27
+ hardware, or hand off to another process (camera and gallery
28
+ pickers, biometric prompts, permission requests, the share sheet,
29
+ GPS fixes, notification scheduling, remote push registration).
30
+ 2. **Failures raise; "nothing happened" returns a value.** A native
31
+ error (a rejected promise, a missing module, a bad argument) is a
32
+ [`NativeModuleError`][pythonnative.native_modules.NativeModuleError]
33
+ and propagates to the caller like any other Python exception. Outcomes
34
+ that are not errors, such as the user cancelling a picker, denying a
35
+ permission, or dismissing the share sheet, come back as ``None``,
36
+ ``False``, or a status string, and are documented per method. No
37
+ facade converts an exception into a default value.
38
+
20
39
  Hardware / media:
21
40
 
22
41
  - [`Camera`][pythonnative.native_modules.Camera]: photo capture and
@@ -1,10 +1,11 @@
1
1
  """Battery level and charging state.
2
2
 
3
3
  [`Battery`][pythonnative.Battery] reports the current charge fraction
4
- (``0.0``–``1.0``, or ``-1.0`` when unknown) and charging state, and
5
- lets you subscribe to changes. The native ``Battery`` module pushes a
6
- ``change`` event with ``{"level", "state"}``; off device, tests drive
7
- the same path through
4
+ (``0.0`` to ``1.0``, or ``-1.0`` when the platform doesn't know) and
5
+ charging state, and lets you subscribe to changes. Both getters read a
6
+ value the OS already holds, so they are synchronous. The native
7
+ ``Battery`` module pushes a ``change`` event with ``{"level", "state"}``;
8
+ off device, tests drive the same path through
8
9
  [`dispatch_battery`][pythonnative.native_modules.battery.dispatch_battery].
9
10
  """
10
11
 
@@ -21,24 +22,22 @@ _listeners: List[Callable[[Dict[str, object]], None]] = []
21
22
 
22
23
 
23
24
  class Battery:
24
- """Battery interface (synchronous getters + change listener)."""
25
+ """Battery interface (synchronous getters + change listener).
26
+
27
+ Raises:
28
+ NativeModuleError: If the native module fails.
29
+ """
25
30
 
26
31
  @staticmethod
27
32
  def get_level() -> float:
28
- """Return the charge fraction in ``[0, 1]`` (``-1.0`` if unknown)."""
29
- try:
30
- level = float(native_module("Battery").call("get_level"))
31
- except Exception:
32
- return -1.0
33
+ """Return the charge fraction in ``[0, 1]``, or ``-1.0`` when the platform can't report it."""
34
+ level = float(native_module("Battery").call("get_level"))
33
35
  return level if 0.0 <= level <= 1.0 else -1.0
34
36
 
35
37
  @staticmethod
36
38
  def get_state() -> BatteryState:
37
39
  """Return ``"charging"`` / ``"full"`` / ``"unplugged"`` / ``"unknown"``."""
38
- try:
39
- state = str(native_module("Battery").call("get_state") or "unknown")
40
- except Exception:
41
- return "unknown"
40
+ state = str(native_module("Battery").call("get_state") or "unknown")
42
41
  return state if state in ("unknown", "unplugged", "charging", "full") else "unknown"
43
42
 
44
43
  @staticmethod
@@ -5,9 +5,9 @@ device's biometric hardware via ``LAContext`` (iOS) and
5
5
  ``BiometricPrompt`` (Android), both implemented in the native
6
6
  ``Biometrics`` module.
7
7
 
8
- ``is_available`` is synchronous; ``authenticate`` is a coroutine that
9
- presents the system prompt and resolves to ``True`` on success or
10
- ``False`` on failure / cancellation.
8
+ ``is_available`` is synchronous (a capability lookup); ``authenticate``
9
+ is a coroutine that presents the system prompt and resolves to ``True``
10
+ on success or ``False`` when the user fails or cancels the prompt.
11
11
 
12
12
  Example:
13
13
  ```python
@@ -25,20 +25,18 @@ from .registry import native_module
25
25
 
26
26
 
27
27
  class Biometrics:
28
- """Biometric authentication interface."""
28
+ """Biometric authentication interface.
29
+
30
+ Raises:
31
+ NativeModuleError: If the native module fails.
32
+ """
29
33
 
30
34
  @staticmethod
31
35
  def is_available() -> bool:
32
- """Return ``True`` when biometric auth can be attempted."""
33
- try:
34
- return bool(native_module("Biometrics").call("is_available"))
35
- except Exception:
36
- return False
36
+ """Return ``True`` when biometric auth can be attempted (enrolled hardware; ``False`` on desktop)."""
37
+ return bool(native_module("Biometrics").call("is_available"))
37
38
 
38
39
  @staticmethod
39
40
  async def authenticate(reason: str = "Authenticate") -> bool:
40
- """Present the biometric prompt; resolve ``True`` on success."""
41
- try:
42
- return bool(await native_module("Biometrics").call_async("authenticate", reason=reason))
43
- except Exception:
44
- return False
41
+ """Present the biometric prompt; resolve ``True`` on success, ``False`` on failure or cancel."""
42
+ return bool(await native_module("Biometrics").call_async("authenticate", reason=reason))