Debian Codegraph @

src/briefcase/platforms/android/gradle.py

raw
1 from __future__ import annotations
2
3 import contextlib
4 import datetime
5 import re
6 import subprocess
7 import time
8 from collections.abc import Collection
9 from pathlib import Path
10
11 from briefcase.commands import (
12 BuildCommand,
13 CreateCommand,
14 OpenCommand,
15 PackageCommand,
16 PublishCommand,
17 RunCommand,
18 UpdateCommand,
19 )
20 from briefcase.config import AppConfig
21 from briefcase.console import ANSI_ESC_SEQ_RE_DEF
22 from briefcase.debuggers.base import (
23 AppPackagesPathMappings,
24 DebuggerConnectionMode,
25 )
26 from briefcase.exceptions import BriefcaseCommandError
27 from briefcase.integrations.android_sdk import ADB, AndroidSDK
28 from briefcase.integrations.subprocess import SubprocessArgT
29
30
31 def safe_formal_name(name):
32 """Converts the name into a safe name on Android.
33
34 Certain characters (``/\\:<>"?*|``) can't be used as app names
35 on Android; ``!`` causes problems with Android build tooling.
36 Also ensure that trailing, leading, and consecutive whitespace
37 caused by removing punctuation is collapsed.
38
39 :param name: The candidate name
40 :returns: The safe version of the name.
41 """
42 return re.sub(r"\s+", " ", re.sub(r'[!/\\:<>"\?\*\|]', "", name)).strip()
43
44
45 # Matches zero or more ANSI control chars wrapping the message for when
46 # the Android emulator is printing in color.
47 ANDROID_LOG_PREFIX_REGEX = re.compile(
48 rf"(?:{ANSI_ESC_SEQ_RE_DEF})*[A-Z]/(?P<tag>.*?):"
49 rf" (?P<content>.*?(?=\x1B|$))(?:{ANSI_ESC_SEQ_RE_DEF})*"
50 )
51
52
53 def android_log_clean_filter(line):
54 """Filter an ADB log to extract the Python-generated message content.
55
56 Any system or stub messages are ignored; all logging prefixes are stripped.
57 Python code is identified as coming from the ``python.stdout``
58
59 :param line: The raw line from the system log
60 :returns: A tuple, containing (a) the log line, stripped of any system
61 logging context, and (b) a boolean indicating if the message should be
62 included for analysis purposes (i.e., it's Python content, not a system
63 message).
64 """
65 match = ANDROID_LOG_PREFIX_REGEX.match(line)
66 if match:
67 groups = match.groupdict()
68 include = groups["tag"] in {"python.stdout", "python.stderr"}
69 return groups["content"], include
70
71 return line, False
72
73
74 class GradleMixin:
75 output_format = "gradle"
76 platform = "android"
77 platform_target_version = "0.3.27"
78
79 @property
80 def packaging_formats(self):
81 return ["aab", "apk", "debug-apk"]
82
83 @property
84 def default_packaging_format(self):
85 return "aab"
86
87 def __init__(self, *args, **kwargs):
88 super().__init__(*args, **kwargs)
89
90 def project_path(self, app):
91 return self.bundle_path(app)
92
93 def binary_path(self, app):
94 return (
95 self.bundle_path(app)
96 / "app"
97 / "build"
98 / "outputs"
99 / "apk"
100 / "debug"
101 / "app-debug.apk"
102 )
103
104 def distribution_path(self, app):
105 extension = {
106 "aab": "aab",
107 "apk": "apk",
108 "debug-apk": "debug.apk",
109 }[app.packaging_format]
110 return self.dist_path / f"{app.formal_name}-{app.version}.{extension}"
111
112 def run_gradle(self, app, args: list[SubprocessArgT]):
113 # Gradle may install the emulator via the dependency chain build-tools > tools >
114 # emulator. (The `tools` package only shows up in sdkmanager if you pass
115 # `--include_obsolete`.) However, the old sdkmanager built into Android Gradle
116 # plugin 4.2 doesn't know about macOS on ARM, so it'll install an x86_64
117 # emulator which won't work with ARM system images.
118 #
119 # Work around this by pre-installing the emulator with our own sdkmanager before
120 # running Gradle. For simplicity, we do this on all platforms, since the user
121 # will almost certainly want an emulator soon enough.
122 self.tools.android_sdk.verify_emulator()
123
124 gradlew = "gradlew.bat" if self.tools.host_os == "Windows" else "gradlew"
125 self.tools.subprocess.run(
126 # Windows needs the full path to `gradlew`; macOS & Linux can find it
127 # via `./gradlew`. For simplicity of implementation, we always provide
128 # the full path.
129 [
130 self.bundle_path(app) / gradlew,
131 "--console",
132 "plain",
133 ]
134 + (["--debug"] if self.tools.console.is_deep_debug else [])
135 + args,
136 env=self.tools.android_sdk.env,
137 # Set working directory so gradle can use the app bundle path as its
138 # project root, i.e., to avoid 'Task assembleDebug not found'.
139 cwd=self.bundle_path(app),
140 check=True,
141 # Gradle writes to stdout using the system encoding. So, explicitly use it
142 # here to avoid defaulting to the console encoding for the subprocess call.
143 # This is mostly for the benefit of Windows where the system encoding may
144 # not be the same as the console encoding and typically neither are UTF-8.
145 # See #1425 for details.
146 encoding=self.tools.system_encoding,
147 )
148
149 def verify_tools(self):
150 """Verify that the Android APK tools in `briefcase` will operate on this system,
151 downloading tools as needed."""
152 super().verify_tools()
153 AndroidSDK.verify(tools=self.tools)
154 if not self.is_clone:
155 self.console.add_log_file_extra(self.tools.android_sdk.list_packages)
156
157
158 class GradleCreateCommand(GradleMixin, CreateCommand):
159 description = "Create and populate an Android Gradle project."
160 hidden_app_properties: Collection[str] = {"permission", "feature"}
161
162 def support_package_filename(self, support_revision):
163 """The query arguments to use in a support package query request."""
164 return (
165 f"Python-{self.python_version_tag}-Android-support.b{support_revision}.zip"
166 )
167
168 def output_format_template_context(self, app: AppConfig):
169 """Additional template context required by the output format.
170
171 :param app: The config object for the app
172 """
173 # Android requires an integer "version code". If a version code
174 # isn't explicitly provided, generate one from the version number.
175 # The build number will also be appended, if provided.
176 try:
177 version_code = app.version_code
178 except AttributeError:
179 v = ([*app.version.release, 0, 0])[:3] # version triple
180 build = int(getattr(app, "build", "0"))
181 version_code = f"{v[0]:d}{v[1]:02d}{v[2]:02d}{build:02d}".lstrip("0")
182
183 # The default runtime libraries included in an app. The default value is the
184 # list that was hard-coded in the Briefcase 0.3.16 Android template, prior to
185 # the introduction of customizable system requirements for Android.
186 try:
187 dependencies = app.build_gradle_dependencies
188 except AttributeError:
189 self.console.warning("""
190 *************************************************************************
191 ** WARNING: App does not define build_gradle_dependencies **
192 *************************************************************************
193
194 The Android configuration for this app does not contain a
195 `build_gradle_dependencies` definition. Briefcase will use a default
196 value of:
197
198 build_gradle_dependencies = [
199 "androidx.appcompat:appcompat:1.0.2",
200 "androidx.constraintlayout:constraintlayout:1.1.3",
201 "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0",
202 ]
203
204 You should add this definition to the Android configuration
205 of your project's pyproject.toml file. See:
206
207 https://briefcase.readthedocs.io/en/stable/reference/platforms/android/gradle.html#build-gradle-dependencies
208
209 for more information.
210
211 *************************************************************************
212
213 """)
214 dependencies = [
215 "androidx.appcompat:appcompat:1.0.2",
216 "androidx.constraintlayout:constraintlayout:1.1.3",
217 "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0",
218 ]
219
220 return {
221 "version_code": version_code,
222 "safe_formal_name": safe_formal_name(app.formal_name),
223 "build_gradle_dependencies": {"implementation": dependencies},
224 }
225
226 def permissions_context(self, app: AppConfig, x_permissions: dict[str, str]):
227 """Additional template context for permissions.
228
229 :param app: The config object for the app
230 :param x_permissions: The dictionary of known cross-platform permission
231 definitions.
232 :returns: The template context describing permissions for the app.
233 """
234 # Default permissions for all Android apps
235 permissions = {
236 "android.permission.INTERNET": {},
237 "android.permission.ACCESS_NETWORK_STATE": {},
238 }
239
240 # Default feature usage for all Android apps
241 features = {}
242
243 if x_permissions["bluetooth"]:
244 permissions["android.permission.ACCESS_COARSE_LOCATION"] = {
245 "android:maxSdkVersion": "30"
246 }
247 permissions["android.permission.ACCESS_FINE_LOCATION"] = {
248 "android:maxSdkVersion": "30"
249 }
250 permissions["android.permission.BLUETOOTH"] = {
251 "android:maxSdkVersion": "30"
252 }
253 permissions["android.permission.BLUETOOTH_ADMIN"] = {
254 "android:maxSdkVersion": "30"
255 }
256 permissions["android.permission.BLUETOOTH_CONNECT"] = {}
257 permissions["android.permission.BLUETOOTH_SCAN"] = {
258 "android:usesPermissionFlags": "neverForLocation"
259 }
260
261 if x_permissions["camera"]:
262 permissions["android.permission.CAMERA"] = {}
263 features["android.hardware.camera"] = False
264 features["android.hardware.camera.any"] = False
265 features["android.hardware.camera.front"] = False
266 features["android.hardware.camera.external"] = False
267 features["android.hardware.camera.autofocus"] = False
268
269 if x_permissions["microphone"]:
270 permissions["android.permission.RECORD_AUDIO"] = {}
271
272 if x_permissions["fine_location"]:
273 permissions["android.permission.ACCESS_FINE_LOCATION"] = {}
274 features["android.hardware.location.network"] = False
275 features["android.hardware.location.gps"] = False
276 # We're good with the location. So we can also use BLUETOOTH_SCAN.
277 bt_scan_perm = permissions.get("android.permission.BLUETOOTH_SCAN")
278 if bt_scan_perm:
279 bt_scan_perm.pop("android:usesPermissionFlags", None)
280
281 if x_permissions["coarse_location"]:
282 permissions["android.permission.ACCESS_COARSE_LOCATION"] = {}
283 features["android.hardware.location.network"] = False
284 features["android.hardware.location.gps"] = False
285 # We're good with the location. So we can also use BLUETOOTH_SCAN.
286 bt_scan_perm = permissions.get("android.permission.BLUETOOTH_SCAN")
287 if bt_scan_perm:
288 bt_scan_perm.pop("android:usesPermissionFlags", None)
289
290 if x_permissions["background_location"]:
291 permissions["android.permission.ACCESS_BACKGROUND_LOCATION"] = {}
292 features["android.hardware.location.network"] = False
293 features["android.hardware.location.gps"] = False
294
295 if x_permissions["photo_library"]:
296 permissions["android.permission.READ_MEDIA_VISUAL_USER_SELECTED"] = {}
297
298 # Override any permission and entitlement definitions
299 # with the platform-specific definitions
300 permissions.update(app.permission)
301 features.update(getattr(app, "feature", {}))
302
303 return {
304 "permissions": permissions,
305 "features": features,
306 }
307
308
309 class GradleUpdateCommand(GradleCreateCommand, UpdateCommand):
310 description = "Update an existing Android Gradle project."
311 supports_debugger = True
312
313
314 class GradleOpenCommand(GradleMixin, OpenCommand):
315 description = "Open the folder for an existing Android Gradle project."
316
317
318 class GradleBuildCommand(GradleMixin, BuildCommand):
319 description = "Build an Android debug APK."
320 supports_debugger = True
321
322 def metadata_resource_path(self, app: AppConfig):
323 return self.bundle_path(app) / self.path_index(app, "metadata_resource_path")
324
325 def extract_packages_path(self, app: AppConfig):
326 return self.bundle_path(app) / self.path_index(app, "extract_packages_path")
327
328 def update_app_metadata(self, app: AppConfig):
329 with (
330 self.console.wait_bar("Setting main module..."),
331 self.metadata_resource_path(app).open("w", encoding="utf-8") as f,
332 ):
333 # Set the name of the app's main module; this will depend
334 # on whether we're in test mode.
335 f.write(f"""\
336 <resources>
337 <string name="main_module">{app.main_module()}</string>
338 </resources>
339 """)
340
341 with (
342 self.console.wait_bar("Setting packages to extract..."),
343 self.extract_packages_path(app).open("w", encoding="utf-8") as f,
344 ):
345 if app.debugger:
346 # In debug mode include the .py files and extract all of them so
347 # that the debugger can get the source code at runtime. This is
348 # e.g. necessary for setting breakpoints in VS Code.
349 extract_packages = ["*"]
350 else:
351 # Extract test packages, to enable features like test discovery and
352 # assertion rewriting.
353 extract_sources = app.test_sources or []
354 extract_packages = [
355 name for path in extract_sources if (name := Path(path).name)
356 ]
357
358 f.write("\n".join(extract_packages))
359
360 def build_app(self, app: AppConfig, **kwargs):
361 """Build an application.
362
363 :param app: The application to build
364 """
365 self.console.info("Updating app metadata...", prefix=app.app_name)
366 self.update_app_metadata(app=app)
367
368 self.console.info("Building Android APK...", prefix=app.app_name)
369 with self.console.wait_bar("Building..."):
370 try:
371 self.run_gradle(app, ["assembleDebug"])
372 except subprocess.CalledProcessError as e:
373 raise BriefcaseCommandError("Error while building project.") from e
374
375
376 class GradleRunCommand(GradleMixin, RunCommand):
377 description = "Run an Android debug APK on a device (physical or virtual)."
378 supports_debugger = True
379
380 def verify_tools(self):
381 super().verify_tools()
382 self.tools.android_sdk.verify_emulator()
383
384 def add_options(self, parser):
385 super().add_options(parser)
386 parser.add_argument(
387 "-d",
388 "--device",
389 dest="device_or_avd",
390 help=(
391 "The device to target; either a device ID for a physical device, "
392 " or an AVD name ('@emulatorName') "
393 ),
394 required=False,
395 )
396 parser.add_argument(
397 "--Xemulator",
398 action="append",
399 dest="extra_emulator_args",
400 help="Additional arguments to use when starting the emulator",
401 required=False,
402 )
403 parser.add_argument(
404 "--shutdown-on-exit",
405 action="store_true",
406 help="Shutdown the emulator on exit",
407 required=False,
408 )
409 parser.add_argument(
410 "--revoke-permission",
411 metavar="PERMISSION",
412 action="append",
413 dest="revoke_permissions",
414 help="Revoke specified permission before launching the app",
415 required=False,
416 )
417 parser.add_argument(
418 "--forward-port",
419 action="append",
420 dest="forward_ports",
421 type=int,
422 help="Forward the specified port from host to device.",
423 )
424 parser.add_argument(
425 "--reverse-port",
426 action="append",
427 dest="reverse_ports",
428 type=int,
429 help="Reverse the specified port from device to host.",
430 )
431
432 def debugger_app_packages_path_mapping(
433 self, app: AppConfig
434 ) -> AppPackagesPathMappings:
435 """Get the path mappings for the app packages.
436
437 :param app: The config object for the app
438 :returns: The path mappings for the app packages
439 """
440 app_packages_path = self.bundle_path(app) / "app/build/python/pip/debug/common"
441 return AppPackagesPathMappings(
442 sys_path_regex="requirements$",
443 host_folder=f"{app_packages_path}",
444 )
445
446 def run_app(
447 self,
448 app: AppConfig,
449 passthrough: list[str],
450 device_or_avd=None,
451 extra_emulator_args=None,
452 shutdown_on_exit=False,
453 revoke_permissions: list[str] | None = None,
454 forward_ports: list[int] | None = None,
455 reverse_ports: list[int] | None = None,
456 **kwargs,
457 ):
458 """Start the application.
459
460 :param app: The config object for the app
461 :param passthrough: The list of arguments to pass to the app
462 :param device_or_avd: The device to target. If ``None``, the user will
463 be asked to re-run the command selecting a specific device.
464 :param extra_emulator_args: Any additional arguments to pass to the emulator.
465 :param shutdown_on_exit: Should the emulator be shut down on exit?
466 :param revoke_permissions: A list of permissions to revoke before launching
467 the app.
468 :param forward_ports: A list of ports to forward for the app.
469 :param reverse_ports: A list of ports to reversed for the app.
470 """
471 device, name, avd = self.tools.android_sdk.select_target_device(device_or_avd)
472
473 # If there's no device ID, that means the emulator isn't running.
474 # If there's no AVD either, it means the user has chosen to create
475 # an entirely new emulator. Create the emulator (if necessary),
476 # then start it.
477 if device is None:
478 if avd is None:
479 avd = self.tools.android_sdk.create_emulator()
480 else:
481 # Ensure the system image for the requested emulator is available.
482 # This step is only needed if the AVD already existed; you have to
483 # have an image available to create an AVD.
484 self.tools.android_sdk.verify_avd(avd)
485
486 if extra_emulator_args:
487 extra = f" (with {' '.join(extra_emulator_args)})"
488 else:
489 extra = ""
490 self.console.info(f"Starting emulator {avd}{extra}...", prefix=app.app_name)
491 device, name = self.tools.android_sdk.start_emulator(
492 avd, extra_emulator_args
493 )
494
495 try:
496 label = "test suite" if app.test_mode else "app"
497
498 self.console.info(
499 f"Starting {label} on {name} (device ID {device})", prefix=app.app_name
500 )
501
502 # Create an ADB wrapper for the selected device
503 adb = self.tools.android_sdk.adb(device=device)
504
505 # Compute Android package name. The Android template uses
506 # `package_name` and `module_name`, so we use those here as well.
507 package = f"{app.package_name}.{app.module_name}"
508
509 # We force-stop the app to ensure the activity launches freshly.
510 self.console.info("Installing app...", prefix=app.app_name)
511 with self.console.wait_bar("Stopping old versions of the app..."):
512 adb.force_stop_app(package)
513
514 # Install the latest APK file onto the device.
515 with self.console.wait_bar("Installing new app version..."):
516 adb.install_apk(self.binary_path(app))
517
518 if revoke_permissions:
519 # Revoke specified app permissions to ensure a reproducible
520 # starting state.
521 with self.console.wait_bar("Revoking app permissions..."):
522 for permission in revoke_permissions:
523 self.console.info(
524 f"Revoking permission: {permission}", prefix=app.app_name
525 )
526 adb.revoke_permission(package, permission)
527
528 forward_ports = forward_ports or []
529 reverse_ports = reverse_ports or []
530
531 env = {}
532 if self.console.is_debug:
533 env["BRIEFCASE_DEBUG"] = "1"
534
535 if app.debugger:
536 env["BRIEFCASE_DEBUGGER"] = app.debugger.get_env_config(self, app)
537 if app.debugger.connection_mode == DebuggerConnectionMode.SERVER:
538 forward_ports.append(app.debugger_port)
539 else:
540 reverse_ports.append(app.debugger_port)
541
542 # Forward/Reverse requested ports
543 with self.forward_ports(adb, forward_ports, reverse_ports):
544 # To start the app, we launch `org.beeware.android.MainActivity`.
545 with self.console.wait_bar(f"Launching {label}..."):
546 # capture the earliest time for device logging in case PID not found
547 device_start_time = adb.datetime()
548
549 adb.start_app(
550 package, "org.beeware.android.MainActivity", passthrough, env
551 )
552
553 # Try to get the PID for 5 seconds.
554 pid = None
555 fail_time = datetime.datetime.now() + datetime.timedelta(seconds=5)
556 while not pid and datetime.datetime.now() < fail_time:
557 # Try to get the PID; run in quiet mode because we may
558 # need to do this a lot in the next 5 seconds.
559 pid = adb.pidof(package, quiet=2)
560 if not pid:
561 time.sleep(0.01)
562
563 if pid:
564 self.console.info(
565 "Following device log output (type CTRL-C to stop log)...",
566 prefix=app.app_name,
567 )
568 # Start adb's logcat in a way that lets us stream the logs
569 log_popen = adb.logcat(pid=pid)
570
571 # Stream the app logs.
572 self._stream_app_logs(
573 app,
574 popen=log_popen,
575 clean_filter=android_log_clean_filter,
576 clean_output=False,
577 # Check for the PID in quiet mode so logs aren't corrupted.
578 stop_func=lambda: not adb.pid_exists(pid=pid, quiet=2),
579 log_stream=True,
580 )
581 else:
582 self.console.error(
583 "Unable to find PID for app", prefix=app.app_name
584 )
585 self.console.error("Logs for launch attempt follow...")
586 self.console.error("=" * 75)
587
588 # Show the log from the start time of the app
589 adb.logcat_tail(since=device_start_time)
590
591 raise BriefcaseCommandError(
592 f"Problem starting app {app.app_name!r}"
593 )
594
595 finally:
596 if shutdown_on_exit:
597 with self.tools.console.wait_bar("Stopping emulator..."):
598 adb.kill()
599
600 @contextlib.contextmanager
601 def forward_ports(
602 self, adb: ADB, forward_ports: list[int], reverse_ports: list[int]
603 ):
604 """Establish a port forwarding/reversion.
605
606 :param adb: The ADB wrapper for the device
607 :param forward_ports: Ports to forward via ADB
608 :param reverse_ports: Ports to reverse via ADB
609 """
610 for port in forward_ports:
611 adb.forward(port, port)
612 for port in reverse_ports:
613 adb.reverse(port, port)
614
615 yield
616
617 for port in forward_ports:
618 adb.forward_remove(port)
619 for port in reverse_ports:
620 adb.reverse_remove(port)
621
622
623 class GradlePackageCommand(GradleMixin, PackageCommand):
624 description = "Create a release artefact from an Android Gradle project."
625
626 def package_app(self, app: AppConfig, **kwargs):
627 """Package the app for distribution.
628
629 This involves building the release app bundle.
630
631 :param app: The application to build
632 """
633 self.console.info(
634 "Building Android App Bundle and APK in release mode...",
635 prefix=app.app_name,
636 )
637 with self.console.wait_bar("Bundling..."):
638 build_type, build_artefact_path = {
639 "aab": ("bundleRelease", "bundle/release/app-release.aab"),
640 "apk": ("assembleRelease", "apk/release/app-release-unsigned.apk"),
641 "debug-apk": ("assembleDebug", "apk/debug/app-debug.apk"),
642 }[app.packaging_format]
643
644 try:
645 self.run_gradle(app, [build_type])
646 except subprocess.CalledProcessError as e:
647 raise BriefcaseCommandError("Error while building project.") from e
648
649 # Move artefact to final location.
650 self.tools.shutil.move(
651 self.bundle_path(app) / "app/build/outputs" / build_artefact_path,
652 self.distribution_path(app),
653 )
654
655
656 class GradlePublishCommand(GradleMixin, PublishCommand):
657 description = "Publish an Android Gradle project."
658
659
660 # Declare the briefcase command bindings
661 create = GradleCreateCommand
662 open = GradleOpenCommand
663 update = GradleUpdateCommand
664 build = GradleBuildCommand
665 run = GradleRunCommand
666 package = GradlePackageCommand
667 publish = GradlePublishCommand