flet-desktop 1.1.0.dev2__tar.gz → 1.1.0.dev4__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flet-desktop
3
- Version: 1.1.0.dev2
3
+ Version: 1.1.0.dev4
4
4
  Summary: Flet Desktop client in Flutter
5
5
  Author-email: "Appveyor Systems Inc." <hello@flet.dev>
6
6
  License-Expression: Apache-2.0
@@ -9,7 +9,7 @@ Project-URL: Repository, https://github.com/flet-dev/flet
9
9
  Project-URL: Documentation, https://flet.dev/docs
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
- Requires-Dist: flet==1.1.0.dev2
12
+ Requires-Dist: flet==1.1.0.dev4
13
13
  Requires-Dist: rich>=13.0.0
14
14
 
15
15
  # Flet Desktop client in Flutter
@@ -1,13 +1,13 @@
1
1
  [project]
2
2
  name = "flet-desktop"
3
- version = "1.1.0.dev2"
3
+ version = "1.1.0.dev4"
4
4
  description = "Flet Desktop client in Flutter"
5
5
  authors = [{ name = "Appveyor Systems Inc.", email = "hello@flet.dev" }]
6
6
  license = "Apache-2.0"
7
7
  readme = "README.md"
8
8
  requires-python = ">=3.10"
9
9
  dependencies = [
10
- "flet==1.1.0.dev2",
10
+ "flet==1.1.0.dev4",
11
11
  "rich >=13.0.0"
12
12
  ]
13
13
 
@@ -2,6 +2,7 @@ import asyncio
2
2
  import contextlib
3
3
  import ctypes
4
4
  import ctypes.util
5
+ import functools
5
6
  import hashlib
6
7
  import logging
7
8
  import os
@@ -30,6 +31,12 @@ from flet.utils import (
30
31
  safe_tar_extractall,
31
32
  safe_zip_extractall,
32
33
  )
34
+ from flet_desktop.extensions import (
35
+ find_extension_packages,
36
+ find_imported_modules,
37
+ find_installed_extensions,
38
+ get_client_extensions,
39
+ )
33
40
 
34
41
  logger = logging.getLogger(flet_desktop.__name__)
35
42
 
@@ -58,49 +65,203 @@ def get_package_bin_dir():
58
65
  return str(Path(__file__).parent.joinpath("app"))
59
66
 
60
67
 
61
- def __get_desktop_flavor():
68
+ def __read_pyproject_flavor(pyproject_path: Path) -> str | None:
62
69
  """
63
- Return the desktop client flavor to use: `"full"` or `"light"`.
70
+ Return `[tool.flet].desktop_flavor` from a `pyproject.toml`, if valid.
64
71
 
65
- Resolution order:
72
+ Args:
73
+ pyproject_path: Path of the `pyproject.toml` to read.
66
74
 
67
- 1. `FLET_DESKTOP_FLAVOR` environment variable.
68
- 2. `[tool.flet].desktop_flavor` in the project's `pyproject.toml`.
69
- 3. Default: `"light"` on Linux, `"full"` elsewhere.
75
+ Returns:
76
+ `"full"` or `"light"`, or `None` when the file is missing, unreadable
77
+ or has no valid setting.
70
78
  """
71
79
 
72
- env_flavor = os.environ.get("FLET_DESKTOP_FLAVOR", "").strip().lower()
73
- if env_flavor in ("full", "light"):
74
- return env_flavor
75
-
76
- # Try reading from pyproject.toml in the current working directory.
77
80
  try:
78
81
  if sys.version_info >= (3, 11):
79
82
  import tomllib
80
83
  else:
81
84
  import tomli as tomllib # type: ignore[no-redef]
82
85
 
83
- pyproject_path = Path(os.getcwd()) / "pyproject.toml"
84
- if pyproject_path.is_file():
85
- with pyproject_path.open("rb") as f:
86
- data = tomllib.load(f)
87
- flavor = data.get("tool", {}).get("flet", {}).get("desktop_flavor", "")
88
- if isinstance(flavor, str) and flavor.strip().lower() in (
89
- "full",
90
- "light",
91
- ):
92
- return flavor.strip().lower()
86
+ if not pyproject_path.is_file():
87
+ return None
88
+ with pyproject_path.open("rb") as f:
89
+ data = tomllib.load(f)
90
+ flavor = data.get("tool", {}).get("flet", {}).get("desktop_flavor", "")
91
+ if isinstance(flavor, str) and flavor.strip().lower() in ("full", "light"):
92
+ return flavor.strip().lower()
93
93
  except Exception:
94
94
  pass
95
+ return None
96
+
97
+
98
+ def __get_configured_desktop_flavor() -> str | None:
99
+ """
100
+ Return the desktop client flavor the user configured, or `None`.
95
101
 
96
- return "light" if is_linux() else "full"
102
+ Resolution order:
97
103
 
104
+ 1. `FLET_DESKTOP_FLAVOR` environment variable.
105
+ 2. `[tool.flet].desktop_flavor` in the `pyproject.toml` of the current
106
+ working directory.
107
+ 3. `[tool.flet].desktop_flavor` in the nearest `pyproject.toml` at or
108
+ above the directory of the started script, `sys.argv[0]`, so an app
109
+ started from another directory reads its own project's setting. It is
110
+ skipped when `sys.argv[0]` is not a file, as with `python -c`.
111
+
112
+ A frozen app, such as one made with `flet pack`, uses the environment
113
+ variable or the flavor of its bundled Linux client. A `pyproject.toml` in
114
+ the directory it is started from or installed in is ignored.
115
+
116
+ Invalid values are ignored.
117
+ """
118
+
119
+ env_flavor = os.environ.get("FLET_DESKTOP_FLAVOR", "").strip().lower()
120
+ if env_flavor in ("full", "light"):
121
+ return env_flavor
122
+ if getattr(sys, "frozen", False):
123
+ if is_linux():
124
+ arch = get_arch()
125
+ distro = __get_linux_distro_id(arch)
126
+ for flavor, suffix in (("full", ""), ("light", "-light")):
127
+ archive = Path(get_package_bin_dir()) / (
128
+ f"flet-linux-{distro}{suffix}-{arch}.tar.gz"
129
+ )
130
+ if archive.is_file():
131
+ return flavor
132
+ return None
133
+
134
+ candidates = [Path(os.getcwd()) / "pyproject.toml"]
135
+ script = Path(sys.argv[0] if sys.argv else "")
136
+ with contextlib.suppress(OSError):
137
+ if script.is_file():
138
+ for directory in script.resolve().parents:
139
+ pyproject_path = directory / "pyproject.toml"
140
+ if pyproject_path.is_file():
141
+ if pyproject_path != candidates[0]:
142
+ candidates.append(pyproject_path)
143
+ break
144
+ for pyproject_path in candidates:
145
+ flavor = __read_pyproject_flavor(pyproject_path)
146
+ if flavor:
147
+ return flavor
148
+ return None
149
+
150
+
151
+ def __get_desktop_flavor():
152
+ """
153
+ Return the desktop client flavor to use: `"full"` or `"light"`.
154
+
155
+ The configured flavor (see `__get_configured_desktop_flavor()`) wins;
156
+ otherwise `"light"` on Linux and `"full"` elsewhere.
157
+ """
158
+
159
+ return __get_configured_desktop_flavor() or ("light" if is_linux() else "full")
160
+
161
+
162
+ def __get_cached_client_extensions(
163
+ client_dir: Path, snapshot_path: Path
164
+ ) -> set[str] | None:
165
+ """
166
+ Return the Flutter packages compiled into a cached client.
167
+
168
+ They are read from the client's AOT snapshot once and stored in an
169
+ `.extensions` file in its cache directory, so later starts don't scan the
170
+ snapshot again.
171
+
172
+ Args:
173
+ client_dir: Cache directory of the client.
174
+ snapshot_path: Path to the client's AOT snapshot.
98
175
 
176
+ Returns:
177
+ Names of the packages, or `None` when they can't be told.
178
+ """
179
+
180
+ marker = client_dir / ".extensions"
181
+ with contextlib.suppress(OSError):
182
+ extensions = set(marker.read_text().split())
183
+ if "flet" in extensions:
184
+ return extensions
185
+ extensions = get_client_extensions(str(snapshot_path))
186
+ if extensions is not None:
187
+ with contextlib.suppress(OSError):
188
+ marker.write_text("\n".join(sorted(extensions)))
189
+ return extensions
190
+
191
+
192
+ def __warn_missing_extensions(
193
+ client_dir: Path, snapshot_path: Path, app_dir: str | Path | None
194
+ ) -> None:
195
+ """
196
+ Warn about the extensions the app uses that the cached client doesn't include.
197
+
198
+ Their controls render as unknown controls and their services never
199
+ answer, without either pointing at the client. An extension counts as used
200
+ when its module is already imported or one of the app's Python files
201
+ imports it. On Linux, the light client suggests the full one, which
202
+ includes more extensions; otherwise a client made with `flet build`, which
203
+ Flet uses when the app is started from its project folder, is suggested.
204
+ Problems while checking are logged at debug level and never stop the app.
205
+
206
+ Args:
207
+ client_dir: Cache directory of the client.
208
+ snapshot_path: Path to the client's AOT snapshot.
209
+ app_dir: Directory of the app's main script, or `None` to use the
210
+ directory of `sys.argv[0]` when that is a file.
211
+ """
212
+
213
+ try:
214
+ client_extensions = __get_cached_client_extensions(client_dir, snapshot_path)
215
+ if client_extensions is None:
216
+ return
217
+ if find_extension_packages() <= client_extensions:
218
+ return
219
+ missing = [
220
+ e for e in find_installed_extensions() if e.package not in client_extensions
221
+ ]
222
+ if not missing:
223
+ return
224
+ imported = {name.split(".")[0] for name in list(sys.modules)}
225
+ if any(not e.modules & imported for e in missing):
226
+ if app_dir is None:
227
+ script = Path(sys.argv[0] if sys.argv else "")
228
+ app_dir = script.resolve().parent if script.is_file() else None
229
+ if app_dir is not None:
230
+ imported |= find_imported_modules(Path(app_dir))
231
+ light = is_linux() and __get_desktop_flavor() == "light"
232
+ for extension in (e for e in missing if e.modules & imported):
233
+ source = (
234
+ f" (from {extension.distribution})" if extension.distribution else ""
235
+ )
236
+ if light:
237
+ fix = (
238
+ "If the full client includes it, set FLET_DESKTOP_FLAVOR=full "
239
+ 'or desktop_flavor = "full" under [tool.flet] in pyproject.toml: '
240
+ "https://flet.dev/docs/getting-started/installation#linux"
241
+ )
242
+ else:
243
+ fix = (
244
+ "Build a client that includes it with `flet build` and start the "
245
+ "app from the project folder: https://flet.dev/docs/extend/"
246
+ "user-extensions#change-python-files"
247
+ )
248
+ logger.warning(
249
+ f"The {'light ' if light else ''}Flet desktop client doesn't include "
250
+ f"the {extension.package} extension{source} the app uses, so its "
251
+ f"controls show as unknown controls and its services don't respond. "
252
+ f"{fix}"
253
+ )
254
+ except Exception as e:
255
+ logger.debug(f"Could not check the client's extensions: {e}")
256
+
257
+
258
+ @functools.cache
99
259
  def __get_system_glibc_version():
100
260
  """
101
261
  Return the system glibc version as a `(major, minor)` tuple.
102
262
 
103
- Falls back to `(0, 0)` when detection fails.
263
+ Falls back to `(0, 0)` when detection fails. The result is cached for the
264
+ process, since the system glibc can't change while it runs.
104
265
  """
105
266
 
106
267
  try:
@@ -132,6 +293,13 @@ def __get_linux_distro_id(arch: str):
132
293
  override = os.environ.get("FLET_LINUX_DISTRO", "").strip()
133
294
  if override:
134
295
  return override
296
+ return __get_glibc_distro_id(arch)
297
+
298
+
299
+ def __get_glibc_distro_id(arch: str):
300
+ """
301
+ Return the distro id of the newest build target the system glibc supports.
302
+ """
135
303
 
136
304
  targets = [
137
305
  (required_glibc, distro_id)
@@ -193,6 +361,10 @@ def __get_client_storage_dir(fingerprint: str | None = None) -> Path:
193
361
  from being shadowed by — or shadowing — the vanilla client or another
194
362
  app's patched client of the same Flet version.
195
363
 
364
+ On Linux the name is `flet-desktop-{flavor}-{distro}-{version}`. Each distro
365
+ build links the `libmpv` soname of that distro, so a client extracted before
366
+ an OS upgrade or a `FLET_LINUX_DISTRO` change is never reused.
367
+
196
368
  Args:
197
369
  fingerprint: Optional content fingerprint of the bundled client archive.
198
370
 
@@ -201,7 +373,13 @@ def __get_client_storage_dir(fingerprint: str | None = None) -> Path:
201
373
  """
202
374
 
203
375
  flavor = __get_desktop_flavor()
204
- name = f"flet-desktop-{flavor}-{flet_desktop.version.version}"
376
+ if is_linux():
377
+ name = (
378
+ f"flet-desktop-{flavor}-{__get_linux_distro_id(get_arch())}-"
379
+ f"{flet_desktop.version.version}"
380
+ )
381
+ else:
382
+ name = f"flet-desktop-{flavor}-{flet_desktop.version.version}"
205
383
  if fingerprint:
206
384
  name += f"-{fingerprint}"
207
385
  return Path.home().joinpath(".flet", "client", name)
@@ -263,15 +441,15 @@ def __gc_stale_client_dirs(cache_dir: Path, max_age_days: int = 30) -> None:
263
441
  """
264
442
  Best-effort eviction of superseded fingerprinted cache siblings.
265
443
 
266
- Removes sibling `flet-desktop-{flavor}-{version}-{fingerprint}` dirs not
267
- used for `max_age_days` (tracked via a `.last-used` marker). Dirs are
268
- renamed before deletion, so a dir whose files are in use by a running app
269
- fails the rename on Windows and is left untouched. Leftovers of
270
- interrupted deletions are swept too.
444
+ Removes sibling dirs whose name differs from `cache_dir` only in the
445
+ `-{fingerprint}` suffix and that were not used for `max_age_days` (tracked
446
+ via a `.last-used` marker). Dirs are renamed before deletion, so a dir whose
447
+ files are in use by a running app fails the rename on Windows and is left
448
+ untouched. Leftovers of interrupted deletions are swept too.
271
449
 
272
450
  Args:
273
451
  cache_dir: Cache directory of the client in use; its siblings with the
274
- same `flet-desktop-{flavor}-{version}-` prefix are candidates.
452
+ same name up to the fingerprint are candidates.
275
453
  max_age_days: Days a sibling must have been unused before eviction.
276
454
  """
277
455
 
@@ -504,7 +682,7 @@ def __linux_identity_args(args: list) -> tuple:
504
682
  return [app_id, *args[1:]], {"executable": executable}
505
683
 
506
684
 
507
- def open_flet_view(page_url, assets_dir, hidden, *, no_impeller=False):
685
+ def open_flet_view(page_url, assets_dir, hidden, *, no_impeller=False, app_dir=None):
508
686
  """
509
687
  Start a desktop view process and return the process object and PID file path.
510
688
 
@@ -513,6 +691,9 @@ def open_flet_view(page_url, assets_dir, hidden, *, no_impeller=False):
513
691
  assets_dir: Optional assets directory passed to the client process.
514
692
  hidden: Whether the window should start hidden.
515
693
  no_impeller: Whether the client renders with Skia instead of Impeller.
694
+ app_dir: Directory of the app's main script, searched for imports of
695
+ extensions the client lacks. Defaults to the directory of
696
+ `sys.argv[0]`.
516
697
 
517
698
  Returns:
518
699
  A tuple containing:
@@ -521,7 +702,7 @@ def open_flet_view(page_url, assets_dir, hidden, *, no_impeller=False):
521
702
  """
522
703
 
523
704
  args, flet_env, pid_file = __locate_and_unpack_flet_view(
524
- page_url, assets_dir, hidden, no_impeller
705
+ page_url, assets_dir, hidden, no_impeller, app_dir
525
706
  )
526
707
  args, extra = __linux_identity_args(args)
527
708
  p = subprocess.Popen(args, env=flet_env, **extra)
@@ -529,7 +710,9 @@ def open_flet_view(page_url, assets_dir, hidden, *, no_impeller=False):
529
710
  return p, pid_file
530
711
 
531
712
 
532
- async def open_flet_view_async(page_url, assets_dir, hidden, *, no_impeller=False):
713
+ async def open_flet_view_async(
714
+ page_url, assets_dir, hidden, *, no_impeller=False, app_dir=None
715
+ ):
533
716
  """
534
717
  Asynchronously start a desktop view process.
535
718
 
@@ -538,6 +721,9 @@ async def open_flet_view_async(page_url, assets_dir, hidden, *, no_impeller=Fals
538
721
  assets_dir: Optional assets directory passed to the client process.
539
722
  hidden: Whether the window should start hidden.
540
723
  no_impeller: Whether the client renders with Skia instead of Impeller.
724
+ app_dir: Directory of the app's main script, searched for imports of
725
+ extensions the client lacks. Defaults to the directory of
726
+ `sys.argv[0]`.
541
727
 
542
728
  Returns:
543
729
  A tuple containing:
@@ -546,7 +732,7 @@ async def open_flet_view_async(page_url, assets_dir, hidden, *, no_impeller=Fals
546
732
  """
547
733
 
548
734
  args, flet_env, pid_file = __locate_and_unpack_flet_view(
549
- page_url, assets_dir, hidden, no_impeller
735
+ page_url, assets_dir, hidden, no_impeller, app_dir
550
736
  )
551
737
  args, extra = __linux_identity_args(args)
552
738
  p = await asyncio.create_subprocess_exec(args[0], *args[1:], env=flet_env, **extra)
@@ -554,6 +740,40 @@ async def open_flet_view_async(page_url, assets_dir, hidden, *, no_impeller=Fals
554
740
  return p, pid_file
555
741
 
556
742
 
743
+ def explain_client_exit(returncode: int | None) -> None:
744
+ """
745
+ Log a hint when the dynamic loader could not start the desktop client.
746
+
747
+ On Linux the dynamic loader exits with status 127 when a shared library the
748
+ client links against is missing or too old, and prints a one-line error that
749
+ names only the library. With the full flavor, the usual cause is `libmpv` or
750
+ GStreamer, which only that flavor links.
751
+
752
+ Args:
753
+ returncode: Exit status of the client process, or `None` if it is
754
+ still running.
755
+ """
756
+
757
+ if returncode != 127 or not is_linux():
758
+ return
759
+ message = (
760
+ "The Flet desktop client could not start because a library it needs "
761
+ "could not be loaded (see the loader error above)."
762
+ )
763
+ if __get_desktop_flavor() == "full":
764
+ message += (
765
+ " The full client needs libmpv and GStreamer: on Debian 12+ and "
766
+ "Ubuntu 24.04+ run `sudo apt install libmpv2 "
767
+ "libgstreamer-plugins-base1.0-0` (libmpv1 on older releases). Apps "
768
+ "that need none of the extensions only the full client includes can "
769
+ "use the light client by setting FLET_DESKTOP_FLAVOR=light. See "
770
+ "https://flet.dev/docs/getting-started/installation#linux"
771
+ )
772
+ else:
773
+ message += " Install the system package that provides it."
774
+ logger.error(message)
775
+
776
+
557
777
  def __apply_taskbar_props(pid: int) -> None:
558
778
  """
559
779
  Stamp Windows taskbar identity properties on the client window, so packed
@@ -599,7 +819,9 @@ def close_flet_view(pid_file):
599
819
  os.remove(pid_file)
600
820
 
601
821
 
602
- def __locate_and_unpack_flet_view(page_url, assets_dir, hidden, no_impeller=False):
822
+ def __locate_and_unpack_flet_view(
823
+ page_url, assets_dir, hidden, no_impeller=False, app_dir=None
824
+ ):
603
825
  """
604
826
  Resolve desktop client executable, prepare launch arguments, and environment.
605
827
 
@@ -607,7 +829,8 @@ def __locate_and_unpack_flet_view(page_url, assets_dir, hidden, no_impeller=Fals
607
829
 
608
830
  1. Prefer app binaries produced by `flet build` in the current workspace.
609
831
  2. Use `FLET_VIEW_PATH` when provided.
610
- 3. Use cached / downloaded client from `~/.flet/client/`.
832
+ 3. Use cached / downloaded client from `~/.flet/client/`, warning about
833
+ the extensions the app uses that it doesn't include.
611
834
 
612
835
  Platform-specific launch commands are prepared for Windows, macOS, and Linux.
613
836
 
@@ -616,6 +839,9 @@ def __locate_and_unpack_flet_view(page_url, assets_dir, hidden, no_impeller=Fals
616
839
  assets_dir: Optional assets directory passed to the client process.
617
840
  hidden: Whether to set `FLET_HIDE_WINDOW_ON_START=true` in process env.
618
841
  no_impeller: Whether to set `FLET_NO_IMPELLER=true` in process env.
842
+ app_dir: Directory of the app's main script, searched for imports of
843
+ extensions a cached client lacks, or `None` for that of
844
+ `sys.argv[0]`.
619
845
 
620
846
  Returns:
621
847
  A tuple containing:
@@ -664,6 +890,9 @@ def __locate_and_unpack_flet_view(page_url, assets_dir, hidden, no_impeller=Fals
664
890
  if not flet_path:
665
891
  cache_dir = ensure_client_cached()
666
892
  flet_path = str(cache_dir.joinpath("flet", "flet.exe"))
893
+ __warn_missing_extensions(
894
+ cache_dir, cache_dir.joinpath("flet", "data", "app.so"), app_dir
895
+ )
667
896
 
668
897
  args = [flet_path, page_url, pid_file]
669
898
 
@@ -695,6 +924,11 @@ def __locate_and_unpack_flet_view(page_url, assets_dir, hidden, no_impeller=Fals
695
924
  raise FileNotFoundError(
696
925
  f"Application bundle not found in {temp_flet_dir}"
697
926
  )
927
+ __warn_missing_extensions(
928
+ temp_flet_dir,
929
+ Path(app_path, "Contents", "Frameworks", "App.framework", "App"),
930
+ app_dir,
931
+ )
698
932
 
699
933
  logger.info(f"page_url: {page_url}")
700
934
  logger.info(f"pid_file: {pid_file}")
@@ -731,6 +965,9 @@ def __locate_and_unpack_flet_view(page_url, assets_dir, hidden, no_impeller=Fals
731
965
  # 3. Use cached or downloaded client
732
966
  cache_dir = ensure_client_cached()
733
967
  app_path = str(cache_dir.joinpath("flet", "flet"))
968
+ __warn_missing_extensions(
969
+ cache_dir, cache_dir.joinpath("flet", "lib", "libapp.so"), app_dir
970
+ )
734
971
 
735
972
  args = [str(app_path), page_url, pid_file]
736
973
 
@@ -0,0 +1,197 @@
1
+ import ast
2
+ import importlib.metadata
3
+ import re
4
+ import sys
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ _PACKAGE_URI = re.compile(rb"package:([a-z][a-z0-9_]*)/")
10
+
11
+ # Directories that hold no app code, skipped when looking for the app's imports.
12
+ _SKIPPED_DIRS = {"__pycache__", "build", "dist", "node_modules", "site-packages"}
13
+
14
+
15
+ @dataclass
16
+ class InstalledExtension:
17
+ """
18
+ A Flet extension installed in the current environment.
19
+ """
20
+
21
+ package: str
22
+ """
23
+ Name of the extension's Flutter package.
24
+ """
25
+
26
+ distribution: Optional[str]
27
+ """
28
+ Name of the distribution that installed it, if known.
29
+ """
30
+
31
+ modules: set[str]
32
+ """
33
+ Top-level Python modules the extension provides.
34
+ """
35
+
36
+
37
+ def get_client_extensions(snapshot_path: str) -> Optional[set[str]]:
38
+ """
39
+ Return the Flutter packages compiled into a prebuilt Flet client.
40
+
41
+ Release builds keep the `package:<name>/` URI of every Dart library in the
42
+ app's AOT snapshot: `data/app.so` on Windows, `lib/libapp.so` on Linux and
43
+ `Contents/Frameworks/App.framework/App` in a macOS app bundle.
44
+
45
+ Args:
46
+ snapshot_path: Path to the client's AOT snapshot.
47
+
48
+ Returns:
49
+ Names of the packages, or `None` when the snapshot is missing or names no
50
+ `flet` library, so the client's extensions can't be told.
51
+ """
52
+
53
+ path = Path(snapshot_path)
54
+ if not path.is_file():
55
+ return None
56
+ packages = {m.decode() for m in _PACKAGE_URI.findall(path.read_bytes())}
57
+ return packages if "flet" in packages else None
58
+
59
+
60
+ def find_extension_packages() -> set[str]:
61
+ """
62
+ Return the Flutter package names of the extensions on `sys.path`.
63
+
64
+ Extensions install a `flutter/<package>/pubspec.yaml` file next to their
65
+ Python modules, so this only lists those folders, without reading any
66
+ distribution's metadata. Use `find_installed_extensions()` to learn which
67
+ distribution and modules a package comes with.
68
+ """
69
+
70
+ packages: set[str] = set()
71
+ for entry in sys.path:
72
+ flutter_dir = Path(entry or ".") / "flutter"
73
+ try:
74
+ packages.update(p.parent.name for p in flutter_dir.glob("*/pubspec.yaml"))
75
+ except OSError:
76
+ continue
77
+ return packages
78
+
79
+
80
+ def find_installed_extensions() -> list[InstalledExtension]:
81
+ """
82
+ Return the Flet extensions installed in the current environment.
83
+
84
+ An extension is a distribution that installs a `flutter/<package>/pubspec.yaml`
85
+ file. Editable installs list no such file in their `RECORD`, so a
86
+ `flutter/<package>` folder on `sys.path` that no distribution owns is reported
87
+ too when the same `sys.path` entry has a Python module named `<package>`.
88
+ """
89
+
90
+ extensions: dict[str, InstalledExtension] = {}
91
+ for dist in importlib.metadata.distributions():
92
+ files = dist.files or []
93
+ packages = {
94
+ f.parts[1]
95
+ for f in files
96
+ if len(f.parts) == 3
97
+ and f.parts[0] == "flutter"
98
+ and f.parts[2] == "pubspec.yaml"
99
+ }
100
+ if not packages:
101
+ continue
102
+ modules = {
103
+ Path(f.parts[0]).stem
104
+ for f in files
105
+ if f.parts[0] not in ("flutter", "..", "__pycache__")
106
+ and not f.parts[0].endswith((".dist-info", ".data", ".pth"))
107
+ and (len(f.parts) > 1 or f.suffix == ".py")
108
+ }
109
+ for package in packages:
110
+ extensions.setdefault(
111
+ package,
112
+ InstalledExtension(package, dist.metadata["Name"], modules),
113
+ )
114
+
115
+ for entry in sys.path:
116
+ entry_dir = Path(entry or ".")
117
+ if not (entry_dir / "flutter").is_dir():
118
+ continue
119
+ for pubspec in sorted((entry_dir / "flutter").glob("*/pubspec.yaml")):
120
+ package = pubspec.parent.name
121
+ if (entry_dir / package).is_dir() or (
122
+ entry_dir / f"{package}.py"
123
+ ).is_file():
124
+ extensions.setdefault(
125
+ package, InstalledExtension(package, None, {package})
126
+ )
127
+
128
+ return sorted(extensions.values(), key=lambda e: e.package)
129
+
130
+
131
+ def find_imported_modules(app_dir: Path) -> set[str]:
132
+ """
133
+ Return the top-level modules the app's Python files import.
134
+
135
+ Virtual environments, hidden folders, build output and symlinked folders in
136
+ `app_dir` are skipped, as are files that can't be read or don't parse.
137
+
138
+ Args:
139
+ app_dir: Directory of the app's main script.
140
+ """
141
+
142
+ modules: set[str] = set()
143
+ for path in _iter_app_files(app_dir):
144
+ try:
145
+ tree = ast.parse(path.read_bytes(), filename=str(path))
146
+ except (OSError, SyntaxError, ValueError):
147
+ continue
148
+ for node in ast.walk(tree):
149
+ if isinstance(node, ast.Import):
150
+ modules.update(alias.name.split(".")[0] for alias in node.names)
151
+ elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
152
+ modules.add(node.module.split(".")[0])
153
+ return modules
154
+
155
+
156
+ def find_missing_extensions(
157
+ app_dir: Path, client_extensions: set[str]
158
+ ) -> list[InstalledExtension]:
159
+ """
160
+ Return the installed extensions the app imports but the client lacks.
161
+
162
+ Args:
163
+ app_dir: Directory of the app's main script.
164
+ client_extensions: Flutter packages compiled into the client, as
165
+ returned by `get_client_extensions()`.
166
+ """
167
+
168
+ candidates = [
169
+ e for e in find_installed_extensions() if e.package not in client_extensions
170
+ ]
171
+ if not candidates:
172
+ return []
173
+ imported = find_imported_modules(app_dir)
174
+ return [e for e in candidates if e.modules & imported]
175
+
176
+
177
+ def _iter_app_files(directory: Path):
178
+ """
179
+ Yield the Python files of an app folder, recursively.
180
+ """
181
+
182
+ try:
183
+ paths = sorted(directory.iterdir())
184
+ except OSError:
185
+ return
186
+ for path in paths:
187
+ if path.is_dir():
188
+ if (
189
+ path.is_symlink()
190
+ or path.name.startswith(".")
191
+ or path.name in _SKIPPED_DIRS
192
+ or (path / "pyvenv.cfg").exists()
193
+ ):
194
+ continue
195
+ yield from _iter_app_files(path)
196
+ elif path.suffix == ".py":
197
+ yield path
@@ -0,0 +1 @@
1
+ version = "1.1.0.dev4"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: flet-desktop
3
- Version: 1.1.0.dev2
3
+ Version: 1.1.0.dev4
4
4
  Summary: Flet Desktop client in Flutter
5
5
  Author-email: "Appveyor Systems Inc." <hello@flet.dev>
6
6
  License-Expression: Apache-2.0
@@ -9,7 +9,7 @@ Project-URL: Repository, https://github.com/flet-dev/flet
9
9
  Project-URL: Documentation, https://flet.dev/docs
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
- Requires-Dist: flet==1.1.0.dev2
12
+ Requires-Dist: flet==1.1.0.dev4
13
13
  Requires-Dist: rich>=13.0.0
14
14
 
15
15
  # Flet Desktop client in Flutter
@@ -1,6 +1,7 @@
1
1
  README.md
2
2
  pyproject.toml
3
3
  src/flet_desktop/__init__.py
4
+ src/flet_desktop/extensions.py
4
5
  src/flet_desktop/version.py
5
6
  src/flet_desktop/win_taskbar.py
6
7
  src/flet_desktop.egg-info/PKG-INFO
@@ -8,4 +9,5 @@ src/flet_desktop.egg-info/SOURCES.txt
8
9
  src/flet_desktop.egg-info/dependency_links.txt
9
10
  src/flet_desktop.egg-info/requires.txt
10
11
  src/flet_desktop.egg-info/top_level.txt
12
+ tests/test_frozen_client_flavor.py
11
13
  tests/test_linux_client_artifact.py
@@ -0,0 +1,2 @@
1
+ flet==1.1.0.dev4
2
+ rich>=13.0.0
@@ -0,0 +1,73 @@
1
+ """Frozen apps keep the flavor of the Linux client bundled by flet pack."""
2
+
3
+ import sys
4
+ import tarfile
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ import flet_desktop
10
+
11
+
12
+ @pytest.fixture
13
+ def frozen_linux(tmp_path, monkeypatch):
14
+ monkeypatch.delenv("FLET_DESKTOP_FLAVOR", raising=False)
15
+ monkeypatch.delenv("FLET_LINUX_DISTRO", raising=False)
16
+ monkeypatch.setattr(sys, "frozen", True, raising=False)
17
+ monkeypatch.setattr(flet_desktop, "is_linux", lambda: True)
18
+ monkeypatch.setattr(flet_desktop, "is_windows", lambda: False)
19
+ monkeypatch.setattr(flet_desktop, "is_macos", lambda: False)
20
+ monkeypatch.setattr(flet_desktop, "get_arch", lambda: "amd64")
21
+ monkeypatch.setattr(flet_desktop, "__get_system_glibc_version", lambda: (2, 36))
22
+ monkeypatch.setattr(Path, "home", lambda: tmp_path / "home")
23
+ monkeypatch.setattr(flet_desktop, "get_package_bin_dir", lambda: str(tmp_path))
24
+ monkeypatch.chdir(tmp_path)
25
+
26
+ def download(artifact):
27
+ pytest.fail(f"Downloaded {artifact} instead of using the bundled client")
28
+
29
+ monkeypatch.setattr(flet_desktop, "__download_flet_client", download)
30
+ return tmp_path
31
+
32
+
33
+ @pytest.mark.parametrize("flavor", ["full", "light"])
34
+ def test_extracts_bundled_flavor_despite_nearby_project(frozen_linux, flavor):
35
+ other_flavor = "light" if flavor == "full" else "full"
36
+ (frozen_linux / "pyproject.toml").write_text(
37
+ f'[tool.flet]\ndesktop_flavor = "{other_flavor}"\n'
38
+ )
39
+ suffix = "-light" if flavor == "light" else ""
40
+ artifact = f"flet-linux-debian12{suffix}-amd64.tar.gz"
41
+ executable = frozen_linux / "patched-client"
42
+ executable.write_bytes(b"client with custom icon and metadata")
43
+ with tarfile.open(frozen_linux / artifact, "w:gz") as archive:
44
+ archive.add(executable, arcname="flet/flet")
45
+
46
+ assert flet_desktop.get_artifact_filename() == artifact
47
+ cache = flet_desktop.ensure_client_cached()
48
+ assert cache.name.startswith(f"flet-desktop-{flavor}-debian12-")
49
+ assert (cache / "flet" / "flet").read_bytes() == executable.read_bytes()
50
+ assert flet_desktop.ensure_client_cached() == cache
51
+
52
+
53
+ @pytest.mark.parametrize("flavor", ["full", "light"])
54
+ def test_explicit_environment_overrides_bundled_flavor(
55
+ frozen_linux, monkeypatch, flavor
56
+ ):
57
+ other_suffix = "-light" if flavor == "full" else ""
58
+ (frozen_linux / f"flet-linux-debian12{other_suffix}-amd64.tar.gz").touch()
59
+ monkeypatch.setenv("FLET_DESKTOP_FLAVOR", flavor)
60
+
61
+ suffix = "-light" if flavor == "light" else ""
62
+ assert flet_desktop.get_artifact_filename() == (
63
+ f"flet-linux-debian12{suffix}-amd64.tar.gz"
64
+ )
65
+
66
+
67
+ def test_frozen_app_without_archive_ignores_nearby_project(frozen_linux):
68
+ (frozen_linux / "pyproject.toml").write_text(
69
+ '[tool.flet]\ndesktop_flavor = "full"\n'
70
+ )
71
+ assert flet_desktop.get_artifact_filename() == (
72
+ "flet-linux-debian12-light-amd64.tar.gz"
73
+ )
@@ -1 +0,0 @@
1
- version = "1.1.0.dev2"
@@ -1,2 +0,0 @@
1
- flet==1.1.0.dev2
2
- rich>=13.0.0