| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import plistlib |
| 5 |
import subprocess |
| 6 |
import time |
| 7 |
from pathlib import Path |
| 8 |
from uuid import UUID |
| 9 |
|
| 10 |
from packaging.version import Version |
| 11 |
|
| 12 |
from briefcase.commands import ( |
| 13 |
BuildCommand, |
| 14 |
CreateCommand, |
| 15 |
OpenCommand, |
| 16 |
PackageCommand, |
| 17 |
PublishCommand, |
| 18 |
RunCommand, |
| 19 |
UpdateCommand, |
| 20 |
) |
| 21 |
from briefcase.config import AppConfig |
| 22 |
from briefcase.debuggers.base import AppPackagesPathMappings |
| 23 |
from briefcase.exceptions import ( |
| 24 |
BriefcaseCommandError, |
| 25 |
InputDisabled, |
| 26 |
InvalidDeviceError, |
| 27 |
NoDistributionArtefact, |
| 28 |
) |
| 29 |
from briefcase.integrations.subprocess import is_process_dead |
| 30 |
from briefcase.integrations.xcode import DeviceState, get_device_state, get_simulators |
| 31 |
from briefcase.platforms.iOS import iOSMixin |
| 32 |
from briefcase.platforms.macOS.filters import XcodeBuildFilter, macOS_log_clean_filter |
| 33 |
|
| 34 |
|
| 35 |
class iOSXcodePassiveMixin(iOSMixin): |
| 36 |
output_format = "Xcode" |
| 37 |
|
| 38 |
@property |
| 39 |
def packaging_formats(self): |
| 40 |
return ["ipa"] |
| 41 |
|
| 42 |
@property |
| 43 |
def default_packaging_format(self): |
| 44 |
return "ipa" |
| 45 |
|
| 46 |
def project_path(self, app): |
| 47 |
return self.bundle_path(app) / f"{app.formal_name}.xcodeproj" |
| 48 |
|
| 49 |
def binary_path(self, app): |
| 50 |
return ( |
| 51 |
self.bundle_path(app) |
| 52 |
/ "build" |
| 53 |
/ "Debug-iphonesimulator" |
| 54 |
/ f"{app.formal_name}.app" |
| 55 |
) |
| 56 |
|
| 57 |
def distribution_path(self, app): |
| 58 |
# This path won't ever be *generated*, as distribution artefacts |
| 59 |
# can't be generated on iOS. |
| 60 |
raise NoDistributionArtefact(""" |
| 61 |
************************************************************************* |
| 62 |
** WARNING: No distributable artefact has been generated ** |
| 63 |
************************************************************************* |
| 64 |
|
| 65 |
Briefcase has not generated a standalone iOS artefact, as iOS apps |
| 66 |
must be published through Xcode. |
| 67 |
|
| 68 |
To open Xcode for your iOS project, run: |
| 69 |
|
| 70 |
briefcase open iOS |
| 71 |
|
| 72 |
and use Xcode's app distribution workflow described at: |
| 73 |
|
| 74 |
https://briefcase.readthedocs.io/en/stable/reference/platforms/iOS/xcode.html#ios-deploy |
| 75 |
|
| 76 |
************************************************************************* |
| 77 |
""") |
| 78 |
|
| 79 |
|
| 80 |
class iOSXcodeMixin(iOSXcodePassiveMixin): |
| 81 |
def __init__(self, *args, **kwargs): |
| 82 |
super().__init__(*args, **kwargs) |
| 83 |
|
| 84 |
# External service APIs. |
| 85 |
# These are abstracted to enable testing without patching. |
| 86 |
self.get_simulators = get_simulators |
| 87 |
|
| 88 |
def add_options(self, parser): |
| 89 |
super().add_options(parser) |
| 90 |
parser.add_argument( |
| 91 |
"-d", |
| 92 |
"--device", |
| 93 |
dest="udid", |
| 94 |
help=( |
| 95 |
"The device to target; either a UDID, " |
| 96 |
'a device name ("iPhone 11"), ' |
| 97 |
'or a device name and OS version ("iPhone 11::iOS 13.3")' |
| 98 |
), |
| 99 |
required=False, |
| 100 |
) |
| 101 |
|
| 102 |
def select_target_device(self, udid_or_device=None): |
| 103 |
"""Select the target device to use for iOS builds. |
| 104 |
|
| 105 |
Interrogates the system to get the list of available simulators |
| 106 |
|
| 107 |
If there is only a single iOS version available, that version |
| 108 |
will be selected automatically. |
| 109 |
|
| 110 |
If there is only one simulator available, that version will be selected |
| 111 |
automatically. |
| 112 |
|
| 113 |
If the user has specified a device at the command line, it will be |
| 114 |
used in preference to any |
| 115 |
|
| 116 |
:param udid_or_device: The device to target. Can be a device UUID, a |
| 117 |
device name ("iPhone 11"), or a device name and OS version |
| 118 |
("iPhone 11::13.3"). If ``None``, the user will be asked to select |
| 119 |
a device at runtime. |
| 120 |
:returns: A tuple containing the udid, iOS version, and device name |
| 121 |
for the selected device. |
| 122 |
""" |
| 123 |
simulators = self.get_simulators(self.tools, "iOS") |
| 124 |
try: |
| 125 |
# Try to convert to a UDID. If this succeeds, then the argument |
| 126 |
# is a UDID. |
| 127 |
udid = str(UUID(udid_or_device)).upper() |
| 128 |
# User has provided a UDID at the command line; look for it. |
| 129 |
for iOS_tag, devices in simulators.items(): |
| 130 |
try: |
| 131 |
device = devices[udid] |
| 132 |
# iOS_tag will be of the form "iOS 15.5" |
| 133 |
# Drop the "iOS" prefix when reporting the version. |
| 134 |
iOS_version = iOS_tag.split(" ", 1)[-1] |
| 135 |
return udid, iOS_version, device |
| 136 |
except KeyError: |
| 137 |
# UDID doesn't exist in this iOS version; try another. |
| 138 |
pass |
| 139 |
|
| 140 |
# We've iterated through all available iOS versions and |
| 141 |
# found no match; return an error. |
| 142 |
raise InvalidDeviceError("device UDID", udid) |
| 143 |
|
| 144 |
except (ValueError, TypeError) as e: |
| 145 |
# Provided value wasn't a UDID. |
| 146 |
# It must be a device or device+version |
| 147 |
if udid_or_device and "::" in udid_or_device: |
| 148 |
# A device name::version. |
| 149 |
device, iOS_tag = udid_or_device.split("::") |
| 150 |
|
| 151 |
try: |
| 152 |
# Convert the simulator dict into a dict where |
| 153 |
# the iOS versions are lower cased, then do a lookup |
| 154 |
# on the lower case name provided by the user. |
| 155 |
# However, also return the *unmodified* iOS version string |
| 156 |
# so we can convert the user-provided iOS version into the |
| 157 |
# "clean", official capitalization. |
| 158 |
iOS_tag, devices = { |
| 159 |
clean_iOS_tag.lower(): (clean_iOS_tag, details) |
| 160 |
for clean_iOS_tag, details in simulators.items() |
| 161 |
}[iOS_tag.lower()] |
| 162 |
|
| 163 |
# iOS_tag will be of the form "iOS 15.5" |
| 164 |
# Drop the "iOS" prefix when reporting the version. |
| 165 |
iOS_version = iOS_tag.split(" ", 1)[-1] |
| 166 |
try: |
| 167 |
# Do a reverse lookup for UDID, based on a |
| 168 |
# case-insensitive name lookup. |
| 169 |
udid = {name.lower(): udid for udid, name in devices.items()}[ |
| 170 |
device.lower() |
| 171 |
] |
| 172 |
|
| 173 |
# Found a match; |
| 174 |
# normalize back to the official name and return. |
| 175 |
device = devices[udid] |
| 176 |
return udid, iOS_version, device |
| 177 |
except KeyError as e: |
| 178 |
raise InvalidDeviceError("device name", device) from e |
| 179 |
except KeyError as e: |
| 180 |
raise InvalidDeviceError("iOS Version", iOS_tag) from e |
| 181 |
elif udid_or_device: |
| 182 |
# Just a device name |
| 183 |
device = udid_or_device |
| 184 |
|
| 185 |
# Search iOS versions, looking for most recent version first. |
| 186 |
# The iOS tag will be something like "iOS 15.4"; |
| 187 |
# Drop the prefix (if it exists), convert into the tuple (15, 4), |
| 188 |
# and sort numerically. |
| 189 |
for iOS_tag, devices in sorted( |
| 190 |
simulators.items(), |
| 191 |
key=lambda item: tuple( |
| 192 |
int(v) for v in item[0].split()[-1].split(".") |
| 193 |
), |
| 194 |
reverse=True, |
| 195 |
): |
| 196 |
try: |
| 197 |
udid = {name.lower(): udid for udid, name in devices.items()}[ |
| 198 |
device.lower() |
| 199 |
] |
| 200 |
|
| 201 |
# Found a match; |
| 202 |
# normalize back to the official name and return. |
| 203 |
device = devices[udid] |
| 204 |
|
| 205 |
# iOS_tag will be of the form "iOS 15.5" |
| 206 |
# Drop the "iOS" prefix when reporting the version. |
| 207 |
iOS_version = iOS_tag.split(" ", 1)[-1] |
| 208 |
|
| 209 |
return udid, iOS_version, device |
| 210 |
except KeyError: |
| 211 |
# UDID doesn't exist in this iOS version; try another. |
| 212 |
pass |
| 213 |
raise InvalidDeviceError("device name", device) from e |
| 214 |
|
| 215 |
if len(simulators) == 0: |
| 216 |
raise BriefcaseCommandError("No iOS simulators available.") |
| 217 |
elif len(simulators) == 1: |
| 218 |
iOS_tag = next(iter(simulators.keys())) |
| 219 |
else: |
| 220 |
iOS_tag = self.console.selection_question( |
| 221 |
intro="Select iOS version:", |
| 222 |
description="iOS Version", |
| 223 |
options=simulators.keys(), |
| 224 |
) |
| 225 |
|
| 226 |
devices = simulators[iOS_tag] |
| 227 |
|
| 228 |
if len(devices) == 0: |
| 229 |
raise BriefcaseCommandError(f"No simulators available for {iOS_tag}.") |
| 230 |
elif len(devices) == 1: |
| 231 |
udid = next(iter(devices.keys())) |
| 232 |
else: |
| 233 |
udid = self.console.selection_question( |
| 234 |
intro="Select simulator device to use:", |
| 235 |
description="Simulator", |
| 236 |
options=devices, |
| 237 |
) |
| 238 |
|
| 239 |
device = devices[udid] |
| 240 |
|
| 241 |
self.console.info(f""" |
| 242 |
In the future, you could specify this device by running: |
| 243 |
|
| 244 |
$ briefcase {self.command} iOS -d "{device}::{iOS_tag}" |
| 245 |
|
| 246 |
or: |
| 247 |
|
| 248 |
$ briefcase {self.command} iOS -d {udid} |
| 249 |
""") |
| 250 |
|
| 251 |
# iOS_tag will be of the form "iOS 15.5" |
| 252 |
# Drop the "iOS" prefix when reporting the version. |
| 253 |
iOS_version = iOS_tag.split(" ", 1)[-1] |
| 254 |
|
| 255 |
return udid, iOS_version, device |
| 256 |
|
| 257 |
|
| 258 |
class iOSXcodeCreateCommand(iOSXcodePassiveMixin, CreateCommand): |
| 259 |
description = "Create and populate a iOS Xcode project." |
| 260 |
|
| 261 |
def permissions_context(self, app: AppConfig, x_permissions: dict[str, str]): |
| 262 |
"""Additional template context for permissions. |
| 263 |
|
| 264 |
:param app: The config object for the app |
| 265 |
:param x_permissions: The dictionary of known cross-platform permission |
| 266 |
definitions. |
| 267 |
:returns: The template context describing permissions for the app. |
| 268 |
""" |
| 269 |
# The collection of info.plist entries |
| 270 |
info = {} |
| 271 |
|
| 272 |
if x_permissions["bluetooth"]: |
| 273 |
info["NSBluetoothAlwaysUsageDescription"] = x_permissions["bluetooth"] |
| 274 |
if x_permissions["camera"]: |
| 275 |
info["NSCameraUsageDescription"] = x_permissions["camera"] |
| 276 |
if x_permissions["microphone"]: |
| 277 |
info["NSMicrophoneUsageDescription"] = x_permissions["microphone"] |
| 278 |
|
| 279 |
if x_permissions["fine_location"]: |
| 280 |
info["NSLocationWhenInUseUsageDescription"] = x_permissions["fine_location"] |
| 281 |
info["NSLocationDefaultAccuracyReduced"] = False |
| 282 |
elif x_permissions["coarse_location"]: |
| 283 |
info["NSLocationWhenInUseUsageDescription"] = x_permissions[ |
| 284 |
"coarse_location" |
| 285 |
] |
| 286 |
info["NSLocationDefaultAccuracyReduced"] = True |
| 287 |
|
| 288 |
if x_permissions["background_location"]: |
| 289 |
if "NSLocationWhenInUseUsageDescription" not in info: |
| 290 |
info["NSLocationWhenInUseUsageDescription"] = x_permissions[ |
| 291 |
"background_location" |
| 292 |
] |
| 293 |
info["NSLocationAlwaysAndWhenInUseUsageDescription"] = x_permissions[ |
| 294 |
"background_location" |
| 295 |
] |
| 296 |
info["UIBackgroundModes"] = ["processing", "location"] |
| 297 |
|
| 298 |
if x_permissions["photo_library"]: |
| 299 |
info["NSPhotoLibraryAddUsageDescription"] = x_permissions["photo_library"] |
| 300 |
|
| 301 |
# Override any info.plist entries with the platform specific definitions |
| 302 |
info.update(getattr(app, "info", {})) |
| 303 |
|
| 304 |
return { |
| 305 |
"info": info, |
| 306 |
} |
| 307 |
|
| 308 |
def _extra_pip_args(self, app: AppConfig): |
| 309 |
"""Any additional arguments that must be passed to pip when installing packages. |
| 310 |
|
| 311 |
:param app: The app configuration |
| 312 |
:returns: A list of additional arguments |
| 313 |
""" |
| 314 |
return [ |
| 315 |
*super()._extra_pip_args(app), |
| 316 |
"--only-binary=:all:", |
| 317 |
"--extra-index-url", |
| 318 |
"https://pypi.anaconda.org/beeware/simple", |
| 319 |
] |
| 320 |
|
| 321 |
def _install_app_requirements( |
| 322 |
self, |
| 323 |
app: AppConfig, |
| 324 |
requires: list[str], |
| 325 |
app_packages_path: Path, |
| 326 |
**kwargs, |
| 327 |
): |
| 328 |
try: |
| 329 |
# Determine the min iOS version from the framework metadata |
| 330 |
# of the ios-arm64 slice of the XCframework |
| 331 |
plist_file = ( |
| 332 |
self.support_path(app) |
| 333 |
/ "Python.xcframework/ios-arm64/Python.framework/Info.plist" |
| 334 |
) |
| 335 |
with plist_file.open("rb") as f: |
| 336 |
info_plist = plistlib.load(f) |
| 337 |
|
| 338 |
support_min_version = info_plist["MinimumOSVersion"] |
| 339 |
except KeyError: |
| 340 |
raise BriefcaseCommandError( |
| 341 |
"Your iOS XCframework doesn't specify a minimum iOS version." |
| 342 |
) from None |
| 343 |
except FileNotFoundError: |
| 344 |
# If a plist file couldn't be found, it's an old-style support package; |
| 345 |
# Determine min. iOS version from the VERSIONS file in the support package |
| 346 |
versions = dict( |
| 347 |
[part.strip() for part in line.split(": ", 1)] |
| 348 |
for line in ( |
| 349 |
(self.support_path(app) / "VERSIONS") |
| 350 |
.read_text(encoding="UTF-8") |
| 351 |
.split("\n") |
| 352 |
) |
| 353 |
if ": " in line |
| 354 |
) |
| 355 |
support_min_version = versions.get("Min iOS version", "13.0") |
| 356 |
|
| 357 |
# Check that the app's definition is compatible with the support package. |
| 358 |
# If the app doesn't specify a minimum version, use the support package |
| 359 |
# minimum version as a default. |
| 360 |
ios_min_version = getattr(app, "min_os_version", support_min_version) |
| 361 |
|
| 362 |
if Version(ios_min_version) < Version(support_min_version): |
| 363 |
raise BriefcaseCommandError( |
| 364 |
f"Your iOS app specifies a minimum iOS version of {ios_min_version}, " |
| 365 |
f"but the support package only supports {support_min_version}" |
| 366 |
) |
| 367 |
|
| 368 |
ios_min_tag = ios_min_version.replace(".", "_") |
| 369 |
|
| 370 |
# Feb 2025: The platform-site was moved into the xcframework as |
| 371 |
# `platform-config`. Look for the new location; fall back to the old location. |
| 372 |
device_platform_site = ( |
| 373 |
self.support_path(app) |
| 374 |
/ "Python.xcframework/ios-arm64/platform-config/arm64-iphoneos" |
| 375 |
) |
| 376 |
simulator_platform_site = ( |
| 377 |
self.support_path(app) |
| 378 |
/ "Python.xcframework/ios-arm64_x86_64-simulator" |
| 379 |
/ f"platform-config/{self.tools.host_arch}-iphonesimulator" |
| 380 |
) |
| 381 |
if not device_platform_site.exists(): |
| 382 |
device_platform_site = ( |
| 383 |
self.support_path(app) / "platform-site/iphoneos.arm64" |
| 384 |
) |
| 385 |
simulator_platform_site = ( |
| 386 |
self.support_path(app) |
| 387 |
/ f"platform-site/iphonesimulator.{self.tools.host_arch}" |
| 388 |
) |
| 389 |
|
| 390 |
# Perform the initial install pass targeting the "iphoneos" platform |
| 391 |
super()._install_app_requirements( |
| 392 |
app, |
| 393 |
requires=requires, |
| 394 |
app_packages_path=app_packages_path.parent / "app_packages.iphoneos", |
| 395 |
progress_message="Installing app requirements for iPhone device...", |
| 396 |
pip_args=[ |
| 397 |
f"--platform=ios_{ios_min_tag}_arm64_iphoneos", |
| 398 |
], |
| 399 |
pip_kwargs={ |
| 400 |
"env": { |
| 401 |
"PYTHONPATH": str(device_platform_site), |
| 402 |
"PIP_REQUIRE_VIRTUALENV": None, |
| 403 |
} |
| 404 |
}, |
| 405 |
install_hint=f""" |
| 406 |
|
| 407 |
This may be because the `iphoneos` wheels that are available are not compatible |
| 408 |
with a minimum iOS version of {ios_min_version}. |
| 409 |
""", |
| 410 |
) |
| 411 |
|
| 412 |
# Perform a second install pass targeting the "iphonesimulator" platform for the |
| 413 |
# current architecture |
| 414 |
super()._install_app_requirements( |
| 415 |
app, |
| 416 |
requires=requires, |
| 417 |
app_packages_path=app_packages_path.parent / "app_packages.iphonesimulator", |
| 418 |
progress_message="Installing app requirements for iPhone simulator...", |
| 419 |
pip_args=[ |
| 420 |
f"--platform=ios_{ios_min_tag}_{self.tools.host_arch}_iphonesimulator", |
| 421 |
], |
| 422 |
pip_kwargs={ |
| 423 |
"env": { |
| 424 |
"PYTHONPATH": str(simulator_platform_site), |
| 425 |
"PIP_REQUIRE_VIRTUALENV": None, |
| 426 |
}, |
| 427 |
}, |
| 428 |
install_hint=f""" |
| 429 |
|
| 430 |
This may indicate that an `iphoneos` wheel could be found, but an |
| 431 |
`iphonesimulator` wheel could not be found; or that the `iphonesimulator` |
| 432 |
binary wheels that are available are not compatible with a minimum iOS |
| 433 |
version of {ios_min_version}. |
| 434 |
""", |
| 435 |
) |
| 436 |
|
| 437 |
|
| 438 |
class iOSXcodeUpdateCommand(iOSXcodeCreateCommand, UpdateCommand): |
| 439 |
description = "Update an existing iOS Xcode project." |
| 440 |
supports_debugger = True |
| 441 |
|
| 442 |
|
| 443 |
class iOSXcodeOpenCommand(iOSXcodePassiveMixin, OpenCommand): |
| 444 |
description = "Open an existing iOS Xcode project." |
| 445 |
|
| 446 |
|
| 447 |
class iOSXcodeBuildCommand(iOSXcodePassiveMixin, BuildCommand): |
| 448 |
description = "Build an iOS Xcode project." |
| 449 |
supports_debugger = True |
| 450 |
|
| 451 |
def info_plist_path(self, app: AppConfig): |
| 452 |
"""Obtain the path to the application's plist file. |
| 453 |
|
| 454 |
:param app: The config object for the app |
| 455 |
:return: The full path of the application's plist file. |
| 456 |
""" |
| 457 |
return self.bundle_path(app) / self.path_index(app, "info_plist_path") |
| 458 |
|
| 459 |
def update_app_metadata(self, app: AppConfig): |
| 460 |
with self.console.wait_bar("Setting main module..."): |
| 461 |
# Load the original plist |
| 462 |
with self.info_plist_path(app).open("rb") as f: |
| 463 |
info_plist = plistlib.load(f) |
| 464 |
|
| 465 |
# Set the name of the app's main module; this will depend |
| 466 |
# on whether we're in test mode. |
| 467 |
info_plist["MainModule"] = app.main_module() |
| 468 |
|
| 469 |
# Write the modified plist |
| 470 |
with self.info_plist_path(app).open("wb") as f: |
| 471 |
plistlib.dump(info_plist, f) |
| 472 |
|
| 473 |
def build_app(self, app: AppConfig, **kwargs): |
| 474 |
"""Build the Xcode project for the application. |
| 475 |
|
| 476 |
:param app: The application to build |
| 477 |
""" |
| 478 |
self.console.info("Updating app metadata...", prefix=app.app_name) |
| 479 |
self.update_app_metadata(app=app) |
| 480 |
|
| 481 |
self.console.info("Building Xcode project...", prefix=app.app_name) |
| 482 |
with self.console.wait_bar("Building..."): |
| 483 |
try: |
| 484 |
self.tools.subprocess.run( |
| 485 |
[ |
| 486 |
"xcodebuild", |
| 487 |
"build", |
| 488 |
"-project", |
| 489 |
self.project_path(app), |
| 490 |
"-configuration", |
| 491 |
"Debug", |
| 492 |
"-arch", |
| 493 |
self.tools.host_arch, |
| 494 |
"-sdk", |
| 495 |
"iphonesimulator", |
| 496 |
"-verbose" if self.tools.console.is_deep_debug else "-quiet", |
| 497 |
], |
| 498 |
check=True, |
| 499 |
filter_func=( |
| 500 |
None if self.tools.console.is_deep_debug else XcodeBuildFilter() |
| 501 |
), |
| 502 |
) |
| 503 |
except subprocess.CalledProcessError as e: |
| 504 |
raise BriefcaseCommandError( |
| 505 |
f"Unable to build app {app.app_name}." |
| 506 |
) from e |
| 507 |
|
| 508 |
|
| 509 |
class iOSXcodeRunCommand(iOSXcodeMixin, RunCommand): |
| 510 |
description = "Run an iOS Xcode project." |
| 511 |
supports_debugger = True |
| 512 |
|
| 513 |
def __init__(self, *args, **kwargs): |
| 514 |
super().__init__(*args, **kwargs) |
| 515 |
|
| 516 |
# External service APIs. |
| 517 |
# This is abstracted to enable testing without patching. |
| 518 |
self.get_device_state = get_device_state |
| 519 |
|
| 520 |
def debugger_app_packages_path_mapping( |
| 521 |
self, app: AppConfig |
| 522 |
) -> AppPackagesPathMappings: |
| 523 |
"""Get the path mappings for the app packages. |
| 524 |
|
| 525 |
:param app: The config object for the app |
| 526 |
:returns: The path mappings for the app packages |
| 527 |
""" |
| 528 |
return AppPackagesPathMappings( |
| 529 |
sys_path_regex="app_packages$", |
| 530 |
host_folder=str( |
| 531 |
self.app_packages_path(app).parent / "app_packages.iphonesimulator" |
| 532 |
), |
| 533 |
) |
| 534 |
|
| 535 |
def run_app( |
| 536 |
self, |
| 537 |
app: AppConfig, |
| 538 |
*, |
| 539 |
passthrough: list[str], |
| 540 |
udid=None, |
| 541 |
**options, |
| 542 |
) -> dict | None: |
| 543 |
"""Start the application. |
| 544 |
|
| 545 |
:param app: The config object for the app |
| 546 |
:param passthrough: The list of arguments to pass to the app |
| 547 |
:param udid: The device UDID to target. If ``None``, the user will |
| 548 |
be asked to select a device at runtime. |
| 549 |
""" |
| 550 |
try: |
| 551 |
udid, iOS_version, device = self.select_target_device(udid) |
| 552 |
except InputDisabled as e: |
| 553 |
raise BriefcaseCommandError( |
| 554 |
"Input has been disabled; can't select a device to target." |
| 555 |
) from e |
| 556 |
|
| 557 |
if app.test_mode: |
| 558 |
label = "test suite" |
| 559 |
else: |
| 560 |
label = "app" |
| 561 |
|
| 562 |
self.console.info( |
| 563 |
( |
| 564 |
f"Starting {label} on an {device} running iOS {iOS_version} " |
| 565 |
f"(device UDID {udid})" |
| 566 |
), |
| 567 |
prefix=app.app_name, |
| 568 |
) |
| 569 |
|
| 570 |
# The simulator needs to be booted before being started. |
| 571 |
# If it's shut down, we can boot it again; but if it's currently |
| 572 |
# shutting down, we need to wait for it to shut down before restarting. |
| 573 |
device_state = self.get_device_state(self.tools, udid) |
| 574 |
if device_state not in {DeviceState.SHUTDOWN, DeviceState.BOOTED}: |
| 575 |
with self.console.wait_bar("Waiting for simulator shutdown..."): |
| 576 |
while device_state not in {DeviceState.SHUTDOWN, DeviceState.BOOTED}: |
| 577 |
time.sleep(2) |
| 578 |
device_state = self.get_device_state(self.tools, udid) |
| 579 |
|
| 580 |
# We now know the simulator is either shut down or booted; |
| 581 |
# if it's shut down, start it again. |
| 582 |
if device_state == DeviceState.SHUTDOWN: |
| 583 |
try: |
| 584 |
with self.console.wait_bar("Booting simulator..."): |
| 585 |
self.tools.subprocess.run( |
| 586 |
["xcrun", "simctl", "boot", udid], |
| 587 |
check=True, |
| 588 |
) |
| 589 |
except subprocess.CalledProcessError as e: |
| 590 |
raise BriefcaseCommandError( |
| 591 |
f"Unable to boot {device} simulator running {iOS_version}" |
| 592 |
) from e |
| 593 |
|
| 594 |
if not app.test_mode: |
| 595 |
# We now know the simulator is *running*, so we can open it. |
| 596 |
# We don't need to open the simulator to run the test suite. |
| 597 |
try: |
| 598 |
with self.console.wait_bar("Opening simulator..."): |
| 599 |
self.tools.subprocess.run( |
| 600 |
[ |
| 601 |
"open", |
| 602 |
"-a", |
| 603 |
"Simulator", |
| 604 |
"--args", |
| 605 |
"-CurrentDeviceUDID", |
| 606 |
udid, |
| 607 |
], |
| 608 |
check=True, |
| 609 |
) |
| 610 |
except subprocess.CalledProcessError as e: |
| 611 |
raise BriefcaseCommandError( |
| 612 |
f"Unable to open {device} simulator running {iOS_version}" |
| 613 |
) from e |
| 614 |
|
| 615 |
# Try to uninstall the app first. If the app hasn't been installed |
| 616 |
# before, this will still succeed. |
| 617 |
self.console.info(f"Installing {label}...", prefix=app.app_name) |
| 618 |
with ( |
| 619 |
self.console.wait_bar( |
| 620 |
"Uninstalling any existing app version..." |
| 621 |
) as keep_alive, |
| 622 |
self.tools.subprocess.Popen( |
| 623 |
["xcrun", "simctl", "uninstall", udid, app.bundle_identifier] |
| 624 |
) as uninstall_popen, |
| 625 |
): |
| 626 |
while (ret_code := uninstall_popen.poll()) is None: |
| 627 |
keep_alive.update() |
| 628 |
time.sleep(0.25) |
| 629 |
if ret_code != 0: |
| 630 |
self.console.error(f"{ret_code=}") |
| 631 |
raise BriefcaseCommandError( |
| 632 |
f"Unable to uninstall old version of app {app.app_name}." |
| 633 |
) |
| 634 |
|
| 635 |
# Install the app. |
| 636 |
with ( |
| 637 |
self.console.wait_bar(f"Installing new {label} version...") as keep_alive, |
| 638 |
self.tools.subprocess.Popen( |
| 639 |
["xcrun", "simctl", "install", udid, self.binary_path(app)] |
| 640 |
) as install_popen, |
| 641 |
): |
| 642 |
while (ret_code := install_popen.poll()) is None: |
| 643 |
keep_alive.update() |
| 644 |
time.sleep(0.25) |
| 645 |
if ret_code != 0: |
| 646 |
raise BriefcaseCommandError( |
| 647 |
f"Unable to install new version of app {app.app_name}." |
| 648 |
) |
| 649 |
|
| 650 |
# Start log stream for the app. |
| 651 |
# The following sets up a log stream filter that looks for: |
| 652 |
# 1. a log sender that matches that app binary; or, |
| 653 |
# 2. a log sender of that is a Python extension module, |
| 654 |
# and a process that matches the app binary. |
| 655 |
# Case (1) works when the standard library is statically linked, |
| 656 |
# and for native NSLog() calls in the bootstrap binary |
| 657 |
# Case (2) works when the standard library is dynamically linked, |
| 658 |
# and ctypes (which handles the NSLog integration) is an |
| 659 |
# extension module. |
| 660 |
# It's not enough to filter on *just* the processImagePath, |
| 661 |
# as the process will generate lots of system-level messages. |
| 662 |
# We can't filter on *just* the senderImagePath, because other |
| 663 |
# apps will generate log messages that would be caught by the filter. |
| 664 |
simulator_log_popen = self.tools.subprocess.Popen( |
| 665 |
[ |
| 666 |
"xcrun", |
| 667 |
"simctl", |
| 668 |
"spawn", |
| 669 |
udid, |
| 670 |
"log", |
| 671 |
"stream", |
| 672 |
"--style", |
| 673 |
"compact", |
| 674 |
"--predicate", |
| 675 |
( |
| 676 |
f'senderImagePath ENDSWITH "/{app.formal_name}"' |
| 677 |
f' OR (processImagePath ENDSWITH "/{app.formal_name}"' |
| 678 |
' AND (senderImagePath ENDSWITH "-iphonesimulator.so"' |
| 679 |
' OR senderImagePath ENDSWITH "-iphonesimulator.dylib"' |
| 680 |
' OR senderImagePath ENDSWITH "_ctypes.framework/_ctypes"))' |
| 681 |
), |
| 682 |
], |
| 683 |
stdout=subprocess.PIPE, |
| 684 |
stderr=subprocess.STDOUT, |
| 685 |
bufsize=1, |
| 686 |
) |
| 687 |
|
| 688 |
# Wait for the log stream start up |
| 689 |
time.sleep(0.25) |
| 690 |
|
| 691 |
# Add additional environment variables |
| 692 |
env = {} |
| 693 |
if app.debugger: |
| 694 |
env["BRIEFCASE_DEBUGGER"] = app.debugger.get_env_config(self, app) |
| 695 |
|
| 696 |
# Set additional environment variables while the app is running |
| 697 |
# (no-op if no environment variables are set). |
| 698 |
with self.setup_env(env, udid): |
| 699 |
try: |
| 700 |
self.console.info(f"Starting {label}...", prefix=app.app_name) |
| 701 |
with self.console.wait_bar(f"Launching {label}..."): |
| 702 |
output = self.tools.subprocess.check_output( |
| 703 |
[ |
| 704 |
"xcrun", |
| 705 |
"simctl", |
| 706 |
"launch", |
| 707 |
udid, |
| 708 |
app.bundle_identifier, |
| 709 |
*passthrough, |
| 710 |
] |
| 711 |
) |
| 712 |
try: |
| 713 |
app_pid = int(output.split(":")[1].strip()) |
| 714 |
except (IndexError, ValueError) as e: |
| 715 |
raise BriefcaseCommandError( |
| 716 |
f"Unable to determine PID of {label} {app.app_name}." |
| 717 |
) from e |
| 718 |
|
| 719 |
# Start streaming logs for the app. |
| 720 |
self.console.info( |
| 721 |
"Following simulator log output (type CTRL-C to stop log)...", |
| 722 |
prefix=app.app_name, |
| 723 |
) |
| 724 |
|
| 725 |
# Stream the app logs, |
| 726 |
self._stream_app_logs( |
| 727 |
app, |
| 728 |
popen=simulator_log_popen, |
| 729 |
clean_filter=macOS_log_clean_filter, |
| 730 |
clean_output=True, |
| 731 |
stop_func=lambda: is_process_dead(app_pid), |
| 732 |
log_stream=True, |
| 733 |
) |
| 734 |
except subprocess.CalledProcessError as e: |
| 735 |
raise BriefcaseCommandError( |
| 736 |
f"Unable to launch {label} {app.app_name}." |
| 737 |
) from e |
| 738 |
|
| 739 |
# Preserve the device selection as state. |
| 740 |
return {"udid": udid} |
| 741 |
|
| 742 |
@contextlib.contextmanager |
| 743 |
def setup_env( |
| 744 |
self, |
| 745 |
env: dict[str, str] | None, |
| 746 |
udid: str, |
| 747 |
): |
| 748 |
"""Context manager to set up the environment for the command.""" |
| 749 |
if env: |
| 750 |
with self.console.wait_bar("Setting environment variables in simulator..."): |
| 751 |
for env_key, env_value in env.items(): |
| 752 |
self.tools.subprocess.check_output( |
| 753 |
[ |
| 754 |
"xcrun", |
| 755 |
"simctl", |
| 756 |
"spawn", |
| 757 |
udid, |
| 758 |
"launchctl", |
| 759 |
"setenv", |
| 760 |
f"{env_key}", |
| 761 |
f"{env_value}", |
| 762 |
] |
| 763 |
) |
| 764 |
|
| 765 |
yield |
| 766 |
|
| 767 |
with self.console.wait_bar( |
| 768 |
"Removing environment variables from simulator..." |
| 769 |
): |
| 770 |
for env_key in env: |
| 771 |
self.tools.subprocess.check_output( |
| 772 |
[ |
| 773 |
"xcrun", |
| 774 |
"simctl", |
| 775 |
"spawn", |
| 776 |
udid, |
| 777 |
"launchctl", |
| 778 |
"unsetenv", |
| 779 |
f"{env_key}", |
| 780 |
] |
| 781 |
) |
| 782 |
else: |
| 783 |
yield # no-op if no environment variables are set |
| 784 |
|
| 785 |
|
| 786 |
class iOSXcodePackageCommand(iOSXcodeMixin, PackageCommand): |
| 787 |
description = "Package an iOS app." |
| 788 |
|
| 789 |
|
| 790 |
class iOSXcodePublishCommand(iOSXcodeMixin, PublishCommand): |
| 791 |
description = "Publish an iOS app." |
| 792 |
|
| 793 |
|
| 794 |
# Declare the briefcase command bindings |
| 795 |
create = iOSXcodeCreateCommand |
| 796 |
update = iOSXcodeUpdateCommand |
| 797 |
open = iOSXcodeOpenCommand |
| 798 |
build = iOSXcodeBuildCommand |
| 799 |
run = iOSXcodeRunCommand |
| 800 |
package = iOSXcodePackageCommand |
| 801 |
publish = iOSXcodePublishCommand |