• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kivy / python-for-android / 15970879696

30 Jun 2025 10:49AM UTC coverage: 59.171%. Remained the same
15970879696

Pull #3167

github

web-flow
Merge d06eae9ee into be3de2e28
Pull Request #3167: Update broadcast.py

1054 of 2377 branches covered (44.34%)

Branch coverage included in aggregate %.

4956 of 7780 relevant lines covered (63.7%)

2.54 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

23.29
/pythonforandroid/bootstraps/common/build/build.py
1
#!/usr/bin/env python3
2

3
from gzip import GzipFile
4✔
4
import hashlib
4✔
5
import json
4✔
6
from os.path import (
4✔
7
    dirname, join, isfile, realpath,
8
    relpath, split, exists, basename
9
)
10
from os import environ, listdir, makedirs, remove
4✔
11
import os
4✔
12
import shlex
4✔
13
import shutil
4✔
14
import subprocess
4✔
15
import sys
4✔
16
import tarfile
4✔
17
import tempfile
4✔
18
import time
4✔
19

20
from fnmatch import fnmatch
4✔
21
import jinja2
4✔
22

23
from pythonforandroid.bootstrap import SDL_BOOTSTRAPS
4✔
24
from pythonforandroid.util import rmdir, ensure_dir, max_build_tool_version
4✔
25

26

27
def get_dist_info_for(key, error_if_missing=True):
4✔
28
    try:
×
29
        with open(join(dirname(__file__), 'dist_info.json'), 'r') as fileh:
×
30
            info = json.load(fileh)
×
31
        value = info[key]
×
32
    except (OSError, KeyError) as e:
×
33
        if not error_if_missing:
×
34
            return None
×
35
        print("BUILD FAILURE: Couldn't extract the key `" + key + "` " +
×
36
              "from dist_info.json: " + str(e))
37
        sys.exit(1)
×
38
    return value
×
39

40

41
def get_hostpython():
4✔
42
    return get_dist_info_for('hostpython')
×
43

44

45
def get_bootstrap_name():
4✔
46
    return get_dist_info_for('bootstrap')
×
47

48

49
if os.name == 'nt':
4!
50
    ANDROID = 'android.bat'
×
51
    ANT = 'ant.bat'
×
52
else:
53
    ANDROID = 'android'
4✔
54
    ANT = 'ant'
4✔
55

56
curdir = dirname(__file__)
4✔
57

58
BLACKLIST_PATTERNS = [
4✔
59
    # code versioning
60
    '^*.hg/*',
61
    '^*.git/*',
62
    '^*.bzr/*',
63
    '^*.svn/*',
64

65
    # temp files
66
    '~',
67
    '*.bak',
68
    '*.swp',
69

70
    # Android artifacts
71
    '*.apk',
72
    '*.aab',
73
]
74

75
WHITELIST_PATTERNS = []
4✔
76

77
if os.environ.get("P4A_BUILD_IS_RUNNING_UNITTESTS", "0") != "1":
4!
78
    PYTHON = get_hostpython()
×
79
    _bootstrap_name = get_bootstrap_name()
×
80
else:
81
    PYTHON = "python3"
4✔
82
    _bootstrap_name = "sdl2"
4✔
83

84
if PYTHON is not None and not exists(PYTHON):
4!
85
    PYTHON = None
4✔
86

87
if _bootstrap_name in ('sdl2', 'sdl3', 'webview', 'service_only', 'qt'):
4!
88
    WHITELIST_PATTERNS.append('pyconfig.h')
4✔
89

90
environment = jinja2.Environment(loader=jinja2.FileSystemLoader(
4✔
91
    join(curdir, 'templates')))
92

93

94
DEFAULT_PYTHON_ACTIVITY_JAVA_CLASS = 'org.kivy.android.PythonActivity'
4✔
95
DEFAULT_PYTHON_SERVICE_JAVA_CLASS = 'org.kivy.android.PythonService'
4✔
96

97

98
def render(template, dest, **kwargs):
4✔
99
    '''Using jinja2, render `template` to the filename `dest`, supplying the
100

101
    keyword arguments as template parameters.
102
    '''
103

104
    dest_dir = dirname(dest)
×
105
    if dest_dir and not exists(dest_dir):
×
106
        makedirs(dest_dir)
×
107

108
    template = environment.get_template(template)
×
109
    text = template.render(**kwargs)
×
110

111
    f = open(dest, 'wb')
×
112
    f.write(text.encode('utf-8'))
×
113
    f.close()
×
114

115

116
def is_whitelist(name):
4✔
117
    return match_filename(WHITELIST_PATTERNS, name)
×
118

119

120
def is_blacklist(name):
4✔
121
    if is_whitelist(name):
×
122
        return False
×
123
    return match_filename(BLACKLIST_PATTERNS, name)
×
124

125

126
def match_filename(pattern_list, name):
4✔
127
    for pattern in pattern_list:
×
128
        if pattern.startswith('^'):
×
129
            pattern = pattern[1:]
×
130
        else:
131
            pattern = '*/' + pattern
×
132
        if fnmatch(name, pattern):
×
133
            return True
×
134

135

136
def listfiles(d):
4✔
137
    basedir = d
×
138
    subdirlist = []
×
139
    for item in os.listdir(d):
×
140
        fn = join(d, item)
×
141
        if isfile(fn):
×
142
            yield fn
×
143
        else:
144
            subdirlist.append(join(basedir, item))
×
145
    for subdir in subdirlist:
×
146
        for fn in listfiles(subdir):
×
147
            yield fn
×
148

149

150
def make_tar(tfn, source_dirs, byte_compile_python=False, optimize_python=True):
4✔
151
    '''
152
    Make a zip file `fn` from the contents of source_dis.
153
    '''
154

155
    def clean(tinfo):
×
156
        """cleaning function (for reproducible builds)"""
157
        tinfo.uid = tinfo.gid = 0
×
158
        tinfo.uname = tinfo.gname = ''
×
159
        tinfo.mtime = 0
×
160
        return tinfo
×
161

162
    # get the files and relpath file of all the directory we asked for
163
    files = []
×
164
    for sd in source_dirs:
×
165
        sd = realpath(sd)
×
166
        for fn in listfiles(sd):
×
167
            if is_blacklist(fn):
×
168
                continue
×
169
            if fn.endswith('.py') and byte_compile_python:
×
170
                fn = compile_py_file(fn, optimize_python=optimize_python)
×
171
            files.append((fn, relpath(realpath(fn), sd)))
×
172
    files.sort()  # deterministic
×
173

174
    # create tar.gz of those files
175
    gf = GzipFile(tfn, 'wb', mtime=0)  # deterministic
×
176
    tf = tarfile.open(None, 'w', gf, format=tarfile.USTAR_FORMAT)
×
177
    dirs = []
×
178
    for fn, afn in files:
×
179
        dn = dirname(afn)
×
180
        if dn not in dirs:
×
181
            # create every dirs first if not exist yet
182
            d = ''
×
183
            for component in split(dn):
×
184
                d = join(d, component)
×
185
                if d.startswith('/'):
×
186
                    d = d[1:]
×
187
                if d == '' or d in dirs:
×
188
                    continue
×
189
                dirs.append(d)
×
190
                tinfo = tarfile.TarInfo(d)
×
191
                tinfo.type = tarfile.DIRTYPE
×
192
                clean(tinfo)
×
193
                tf.addfile(tinfo)
×
194

195
        # put the file
196
        tf.add(fn, afn, filter=clean)
×
197
    tf.close()
×
198
    gf.close()
×
199

200

201
def compile_py_file(python_file, optimize_python=True):
4✔
202
    '''
203
    Compile python_file to *.pyc and return the filename of the *.pyc file.
204
    '''
205

206
    if PYTHON is None:
×
207
        return
×
208

209
    args = [PYTHON, '-m', 'compileall', '-b', '-f', python_file]
×
210
    if optimize_python:
×
211
        # -OO = strip docstrings
212
        args.insert(1, '-OO')
×
213
    return_code = subprocess.call(args)
×
214

215
    if return_code != 0:
×
216
        print('Error while running "{}"'.format(' '.join(args)))
×
217
        print('This probably means one of your Python files has a syntax '
×
218
              'error, see logs above')
219
        exit(1)
×
220

221
    return ".".join([os.path.splitext(python_file)[0], "pyc"])
×
222

223

224
def is_sdl_bootstrap():
4✔
225
    return get_bootstrap_name() in SDL_BOOTSTRAPS
4✔
226

227

228
def make_package(args):
4✔
229
    # If no launcher is specified, require a main.py/main.pyc:
230
    if (get_bootstrap_name() != "sdl" or args.launcher is None) and \
×
231
            get_bootstrap_name() not in ["webview", "service_library"]:
232
        # (webview doesn't need an entrypoint, apparently)
233
        if args.private is None or (
×
234
                not exists(join(realpath(args.private), 'main.py')) and
235
                not exists(join(realpath(args.private), 'main.pyc'))):
236
            print('''BUILD FAILURE: No main.py(c) found in your app directory. This
×
237
file must exist to act as the entry point for you app. If your app is
238
started by a file with a different name, rename it to main.py or add a
239
main.py that loads it.''')
240
            sys.exit(1)
×
241

242
    assets_dir = "src/main/assets"
×
243

244
    # Delete the old assets.
245
    rmdir(assets_dir, ignore_errors=True)
×
246
    ensure_dir(assets_dir)
×
247

248
    # Add extra environment variable file into tar-able directory:
249
    env_vars_tarpath = tempfile.mkdtemp(prefix="p4a-extra-env-")
×
250
    with open(os.path.join(env_vars_tarpath, "p4a_env_vars.txt"), "w") as f:
×
251
        if hasattr(args, "window"):
×
252
            f.write("P4A_IS_WINDOWED=" + str(args.window) + "\n")
×
253
        if hasattr(args, "sdl_orientation_hint"):
×
254
            f.write("KIVY_ORIENTATION=" + str(args.sdl_orientation_hint) + "\n")
×
255
        f.write("P4A_NUMERIC_VERSION=" + str(args.numeric_version) + "\n")
×
256
        f.write("P4A_MINSDK=" + str(args.min_sdk_version) + "\n")
×
257

258
    # Package up the private data (public not supported).
259
    use_setup_py = get_dist_info_for("use_setup_py",
×
260
                                     error_if_missing=False) is True
261
    private_tar_dirs = [env_vars_tarpath]
×
262
    _temp_dirs_to_clean = []
×
263
    try:
×
264
        if args.private:
×
265
            if not use_setup_py or (
×
266
                    not exists(join(args.private, "setup.py")) and
267
                    not exists(join(args.private, "pyproject.toml"))
268
                    ):
269
                print('No setup.py/pyproject.toml used, copying '
×
270
                      'full private data into .apk.')
271
                private_tar_dirs.append(args.private)
×
272
            else:
273
                print("Copying main.py's ONLY, since other app data is "
×
274
                      "expected in site-packages.")
275
                main_py_only_dir = tempfile.mkdtemp()
×
276
                _temp_dirs_to_clean.append(main_py_only_dir)
×
277

278
                # Check all main.py files we need to copy:
279
                copy_paths = ["main.py", join("service", "main.py")]
×
280
                for copy_path in copy_paths:
×
281
                    variants = [
×
282
                        copy_path,
283
                        copy_path.partition(".")[0] + ".pyc",
284
                    ]
285
                    # Check in all variants with all possible endings:
286
                    for variant in variants:
×
287
                        if exists(join(args.private, variant)):
×
288
                            # Make sure surrounding directly exists:
289
                            dir_path = os.path.dirname(variant)
×
290
                            if (len(dir_path) > 0 and
×
291
                                    not exists(
292
                                        join(main_py_only_dir, dir_path)
293
                                    )):
294
                                ensure_dir(join(main_py_only_dir, dir_path))
×
295
                            # Copy actual file:
296
                            shutil.copyfile(
×
297
                                join(args.private, variant),
298
                                join(main_py_only_dir, variant),
299
                            )
300

301
                # Append directory with all main.py's to result apk paths:
302
                private_tar_dirs.append(main_py_only_dir)
×
303
        if get_bootstrap_name() == "webview":
×
304
            for asset in listdir('webview_includes'):
×
305
                shutil.copy(join('webview_includes', asset), join(assets_dir, asset))
×
306

307
        for asset in args.assets:
×
308
            asset_src, asset_dest = asset.split(":")
×
309
            if isfile(realpath(asset_src)):
×
310
                ensure_dir(dirname(join(assets_dir, asset_dest)))
×
311
                shutil.copy(realpath(asset_src), join(assets_dir, asset_dest))
×
312
            else:
313
                shutil.copytree(realpath(asset_src), join(assets_dir, asset_dest))
×
314

315
        if args.private or args.launcher:
×
316
            for arch in get_dist_info_for("archs"):
×
317
                libs_dir = f"libs/{arch}"
×
318
                make_tar(
×
319
                    join(libs_dir, "libpybundle.so"),
320
                    [f"_python_bundle__{arch}"],
321
                    byte_compile_python=args.byte_compile_python,
322
                    optimize_python=args.optimize_python,
323
                )
324
            make_tar(
×
325
                join(assets_dir, "private.tar"),
326
                private_tar_dirs,
327
                byte_compile_python=args.byte_compile_python,
328
                optimize_python=args.optimize_python,
329
            )
330
    finally:
331
        for directory in _temp_dirs_to_clean:
×
332
            rmdir(directory)
×
333

334
    # Remove extra env vars tar-able directory:
335
    rmdir(env_vars_tarpath)
×
336

337
    # Prepare some variables for templating process
338
    res_dir = "src/main/res"
×
339
    res_dir_initial = "src/res_initial"
×
340
    # make res_dir stateless
341
    if exists(res_dir_initial):
×
342
        rmdir(res_dir, ignore_errors=True)
×
343
        shutil.copytree(res_dir_initial, res_dir)
×
344
    else:
345
        shutil.copytree(res_dir, res_dir_initial)
×
346

347
    # Add user resources
348
    for resource in args.resources:
×
349
        resource_src, resource_dest = resource.split(":")
×
350
        if isfile(realpath(resource_src)):
×
351
            ensure_dir(dirname(join(res_dir, resource_dest)))
×
352
            shutil.copy(realpath(resource_src), join(res_dir, resource_dest))
×
353
        else:
354
            shutil.copytree(realpath(resource_src),
×
355
                            join(res_dir, resource_dest), dirs_exist_ok=True)
356

357
    default_icon = 'templates/kivy-icon.png'
×
358
    default_presplash = 'templates/kivy-presplash.jpg'
×
359
    shutil.copy(
×
360
        args.icon or default_icon,
361
        join(res_dir, 'mipmap/icon.png')
362
    )
363
    if args.icon_fg and args.icon_bg:
×
364
        shutil.copy(args.icon_fg, join(res_dir, 'mipmap/icon_foreground.png'))
×
365
        shutil.copy(args.icon_bg, join(res_dir, 'mipmap/icon_background.png'))
×
366
        with open(join(res_dir, 'mipmap-anydpi-v26/icon.xml'), "w") as fd:
×
367
            fd.write("""<?xml version="1.0" encoding="utf-8"?>
×
368
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
369
    <background android:drawable="@mipmap/icon_background"/>
370
    <foreground android:drawable="@mipmap/icon_foreground"/>
371
</adaptive-icon>
372
""")
373
    elif args.icon_fg or args.icon_bg:
×
374
        print("WARNING: Received an --icon_fg or an --icon_bg argument, but not both. "
×
375
              "Ignoring.")
376

377
    if get_bootstrap_name() != "service_only":
×
378
        lottie_splashscreen = join(res_dir, 'raw/splashscreen.json')
×
379
        if args.presplash_lottie:
×
380
            shutil.copy(
×
381
                'templates/lottie.xml',
382
                join(res_dir, 'layout/lottie.xml')
383
            )
384
            ensure_dir(join(res_dir, 'raw'))
×
385
            shutil.copy(
×
386
                args.presplash_lottie,
387
                join(res_dir, 'raw/splashscreen.json')
388
            )
389
        else:
390
            if exists(lottie_splashscreen):
×
391
                remove(lottie_splashscreen)
×
392
                remove(join(res_dir, 'layout/lottie.xml'))
×
393

394
            shutil.copy(
×
395
                args.presplash or default_presplash,
396
                join(res_dir, 'drawable/presplash.jpg')
397
            )
398

399
    # If extra Java jars were requested, copy them into the libs directory
400
    jars = []
×
401
    if args.add_jar:
×
402
        for jarname in args.add_jar:
×
403
            if not exists(jarname):
×
404
                print('Requested jar does not exist: {}'.format(jarname))
×
405
                sys.exit(-1)
×
406
            shutil.copy(jarname, 'src/main/libs')
×
407
            jars.append(basename(jarname))
×
408

409
    # If extra aar were requested, copy them into the libs directory
410
    aars = []
×
411
    if args.add_aar:
×
412
        ensure_dir("libs")
×
413
        for aarname in args.add_aar:
×
414
            if not exists(aarname):
×
415
                print('Requested aar does not exists: {}'.format(aarname))
×
416
                sys.exit(-1)
×
417
            shutil.copy(aarname, 'libs')
×
418
            aars.append(basename(aarname).rsplit('.', 1)[0])
×
419

420
    versioned_name = (args.name.replace(' ', '').replace('\'', '') +
×
421
                      '-' + args.version)
422

423
    version_code = 0
×
424
    if not args.numeric_version:
×
425
        """
426
        Set version code in format (10 + minsdk + app_version)
427
        Historically versioning was (arch + minsdk + app_version),
428
        with arch expressed with a single digit from 6 to 9.
429
        Since the multi-arch support, has been changed to 10.
430
        """
431
        min_sdk = args.min_sdk_version
×
432
        for i in args.version.split('.'):
×
433
            version_code *= 100
×
434
            version_code += int(i)
×
435
        args.numeric_version = "{}{}{}".format("10", min_sdk, version_code)
×
436

437
    if args.intent_filters:
×
438
        with open(args.intent_filters) as fd:
×
439
            args.intent_filters = fd.read()
×
440

441
    if not args.add_activity:
×
442
        args.add_activity = []
×
443

444
    if not args.activity_launch_mode:
×
445
        args.activity_launch_mode = ''
×
446

447
    if args.extra_source_dirs:
×
448
        esd = []
×
449
        for spec in args.extra_source_dirs:
×
450
            if ':' in spec:
×
451
                specdir, specincludes = spec.split(':')
×
452
                print('WARNING: Currently gradle builds only support including source '
×
453
                      'directories, so when building using gradle all files in '
454
                      '{} will be included.'.format(specdir))
455
            else:
456
                specdir = spec
×
457
                specincludes = '**'
×
458
            esd.append((realpath(specdir), specincludes))
×
459
        args.extra_source_dirs = esd
×
460
    else:
461
        args.extra_source_dirs = []
×
462

463
    service = False
×
464
    if args.private:
×
465
        service_main = join(realpath(args.private), 'service', 'main.py')
×
466
        if exists(service_main) or exists(service_main + 'o'):
×
467
            service = True
×
468

469
    service_names = []
×
470
    base_service_class = args.service_class_name.split('.')[-1]
×
471
    for sid, spec in enumerate(args.services):
×
472
        spec = spec.split(':')
×
473
        name = spec[0]
×
474
        entrypoint = spec[1]
×
475
        options = spec[2:]
×
476

477
        foreground = 'foreground' in options
×
478
        sticky = 'sticky' in options
×
479

480
        service_names.append(name)
×
481
        service_target_path =\
×
482
            'src/main/java/{}/Service{}.java'.format(
483
                args.package.replace(".", "/"),
484
                name.capitalize()
485
            )
486
        render(
×
487
            'Service.tmpl.java',
488
            service_target_path,
489
            name=name,
490
            entrypoint=entrypoint,
491
            args=args,
492
            foreground=foreground,
493
            sticky=sticky,
494
            service_id=sid + 1,
495
            base_service_class=base_service_class,
496
        )
497

498
    # Find the SDK directory and target API
499
    with open('project.properties', 'r') as fileh:
×
500
        target = fileh.read().strip()
×
501
    android_api = target.split('-')[1]
×
502

503
    if android_api.isdigit():
×
504
        android_api = int(android_api)
×
505
    else:
506
        raise ValueError(
×
507
            "failed to extract the Android API level from " +
508
            "build.properties. expected int, got: '" +
509
            str(android_api) + "'"
510
        )
511

512
    with open('local.properties', 'r') as fileh:
×
513
        sdk_dir = fileh.read().strip()
×
514
    sdk_dir = sdk_dir[8:]
×
515

516
    # Try to build with the newest available build tools
517
    ignored = {".DS_Store", ".ds_store"}
×
518
    build_tools_versions = [x for x in listdir(join(sdk_dir, 'build-tools')) if x not in ignored]
×
519
    build_tools_version = max_build_tool_version(build_tools_versions)
×
520

521
    # Folder name for launcher (used by SDL2 bootstrap)
522
    url_scheme = 'kivy'
×
523

524
    # Copy backup rules file if specified and update the argument
525
    res_xml_dir = join(res_dir, 'xml')
×
526
    if args.backup_rules:
×
527
        ensure_dir(res_xml_dir)
×
528
        shutil.copy(join(args.private, args.backup_rules), res_xml_dir)
×
529
        args.backup_rules = split(args.backup_rules)[1][:-4]
×
530

531
    # Copy res_xml files to src/main/res/xml
532
    if args.res_xmls:
×
533
        ensure_dir(res_xml_dir)
×
534
        for xmlpath in args.res_xmls:
×
535
            if not os.path.exists(xmlpath):
×
536
                xmlpath = join(args.private, xmlpath)
×
537
            shutil.copy(xmlpath, res_xml_dir)
×
538

539
    # Render out android manifest:
540
    manifest_path = "src/main/AndroidManifest.xml"
×
541
    render_args = {
×
542
        "args": args,
543
        "service": service,
544
        "service_names": service_names,
545
        "android_api": android_api,
546
        "debug": "debug" in args.build_mode,
547
        "native_services": args.native_services
548
    }
549
    if is_sdl_bootstrap():
×
550
        render_args["url_scheme"] = url_scheme
×
551

552
    render(
×
553
        'AndroidManifest.tmpl.xml',
554
        manifest_path,
555
        **render_args)
556

557
    # Copy the AndroidManifest.xml to the dist root dir so that ant
558
    # can also use it
559
    if exists('AndroidManifest.xml'):
×
560
        remove('AndroidManifest.xml')
×
561
    shutil.copy(manifest_path, 'AndroidManifest.xml')
×
562

563
    # gradle build templates
564
    render(
×
565
        'build.tmpl.gradle',
566
        'build.gradle',
567
        args=args,
568
        aars=aars,
569
        jars=jars,
570
        android_api=android_api,
571
        build_tools_version=build_tools_version,
572
        debug_build="debug" in args.build_mode,
573
        is_library=(get_bootstrap_name() == 'service_library'),
574
        )
575

576
    # gradle properties
577
    render(
×
578
        'gradle.tmpl.properties',
579
        'gradle.properties',
580
        args=args,
581
        bootstrap_name=get_bootstrap_name())
582

583
    # ant build templates
584
    render(
×
585
        'build.tmpl.xml',
586
        'build.xml',
587
        args=args,
588
        versioned_name=versioned_name)
589

590
    # String resources:
591
    timestamp = time.time()
×
592
    if 'SOURCE_DATE_EPOCH' in environ:
×
593
        # for reproducible builds
594
        timestamp = int(environ['SOURCE_DATE_EPOCH'])
×
595
    private_version = "{} {} {}".format(
×
596
        args.version,
597
        args.numeric_version,
598
        timestamp
599
    )
600
    render_args = {
×
601
        "args": args,
602
        "private_version": hashlib.sha1(private_version.encode()).hexdigest()
603
    }
604
    if is_sdl_bootstrap():
×
605
        render_args["url_scheme"] = url_scheme
×
606
    render(
×
607
        'strings.tmpl.xml',
608
        join(res_dir, 'values/strings.xml'),
609
        **render_args)
610

611
    # Library resources from Qt
612
    # These are referred by QtLoader.java in Qt6AndroidBindings.jar
613
    # qt_libs and load_local_libs are loaded at App startup
614
    if get_bootstrap_name() == "qt":
×
615
        qt_libs = args.qt_libs.split(",")
×
616
        load_local_libs = args.load_local_libs.split(",")
×
617
        init_classes = args.init_classes
×
618
        if init_classes:
×
619
            init_classes = init_classes.split(",")
×
620
            init_classes = ":".join(init_classes)
×
621
        arch = get_dist_info_for("archs")[0]
×
622
        render(
×
623
            'libs.tmpl.xml',
624
            join(res_dir, 'values/libs.xml'),
625
            qt_libs=qt_libs,
626
            load_local_libs=load_local_libs,
627
            init_classes=init_classes,
628
            arch=arch
629
        )
630

631
    if exists(join("templates", "custom_rules.tmpl.xml")):
×
632
        render(
×
633
            'custom_rules.tmpl.xml',
634
            'custom_rules.xml',
635
            args=args)
636

637
    if get_bootstrap_name() == "webview":
×
638
        render('WebViewLoader.tmpl.java',
×
639
               'src/main/java/org/kivy/android/WebViewLoader.java',
640
               args=args)
641

642
    if args.sign:
×
643
        render('build.properties', 'build.properties')
×
644
    else:
645
        if exists('build.properties'):
×
646
            os.remove('build.properties')
×
647

648
    # Apply java source patches if any are present:
649
    if exists(join('src', 'patches')):
×
650
        print("Applying Java source code patches...")
×
651
        for patch_name in os.listdir(join('src', 'patches')):
×
652
            patch_path = join('src', 'patches', patch_name)
×
653
            print("Applying patch: " + str(patch_path))
×
654

655
            # -N: insist this is FORWARD patch, don't reverse apply
656
            # -p1: strip first path component
657
            # -t: batch mode, don't ask questions
658
            patch_command = ["patch", "-N", "-p1", "-t", "-i", patch_path]
×
659

660
            try:
×
661
                # Use a dry run to establish whether the patch is already applied.
662
                # If we don't check this, the patch may be partially applied (which is bad!)
663
                subprocess.check_output(patch_command + ["--dry-run"])
×
664
            except subprocess.CalledProcessError as e:
×
665
                if e.returncode == 1:
×
666
                    # Return code 1 means not all hunks could be applied, this usually
667
                    # means the patch is already applied.
668
                    print("Warning: failed to apply patch (exit code 1), "
×
669
                          "assuming it is already applied: ",
670
                          str(patch_path))
671
                else:
672
                    raise e
×
673
            else:
674
                # The dry run worked, so do the real thing
675
                subprocess.check_output(patch_command)
×
676

677

678
def parse_permissions(args_permissions):
4✔
679
    if args_permissions and isinstance(args_permissions[0], list):
4!
680
        args_permissions = [p for perm in args_permissions for p in perm]
4✔
681

682
    def _is_advanced_permission(permission):
4✔
683
        return permission.startswith("(") and permission.endswith(")")
4✔
684

685
    def _decode_advanced_permission(permission):
4✔
686
        SUPPORTED_PERMISSION_PROPERTIES = ["name", "maxSdkVersion", "usesPermissionFlags"]
4✔
687
        _permission_args = permission[1:-1].split(";")
4✔
688
        _permission_args = (arg.split("=") for arg in _permission_args)
4✔
689
        advanced_permission = dict(_permission_args)
4✔
690

691
        if "name" not in advanced_permission:
4!
692
            raise ValueError("Advanced permission must have a name property")
×
693

694
        for key in advanced_permission.keys():
4✔
695
            if key not in SUPPORTED_PERMISSION_PROPERTIES:
4✔
696
                raise ValueError(
4✔
697
                    f"Property '{key}' is not supported. "
698
                    "Advanced permission only supports: "
699
                    f"{', '.join(SUPPORTED_PERMISSION_PROPERTIES)} properties"
700
                )
701

702
        return advanced_permission
4✔
703

704
    _permissions = []
4✔
705
    for permission in args_permissions:
4✔
706
        if _is_advanced_permission(permission):
4✔
707
            _permissions.append(_decode_advanced_permission(permission))
4✔
708
        else:
709
            if "." in permission:
4✔
710
                _permissions.append(dict(name=permission))
4✔
711
            else:
712
                _permissions.append(dict(name=f"android.permission.{permission}"))
4✔
713
    return _permissions
4✔
714

715

716
def get_sdl_orientation_hint(orientations):
4✔
717
    SDL_ORIENTATION_MAP = {
4✔
718
        "landscape": "LandscapeLeft",
719
        "portrait": "Portrait",
720
        "portrait-reverse": "PortraitUpsideDown",
721
        "landscape-reverse": "LandscapeRight",
722
    }
723
    return " ".join(
4✔
724
        [SDL_ORIENTATION_MAP[x] for x in orientations if x in SDL_ORIENTATION_MAP]
725
    )
726

727

728
def get_manifest_orientation(orientations, manifest_orientation=None):
4✔
729
    # If the user has specifically set an orientation to use in the manifest,
730
    # use that.
731
    if manifest_orientation is not None:
4✔
732
        return manifest_orientation
4✔
733

734
    # If multiple or no orientations are specified, use unspecified in the manifest,
735
    # as we can only specify one orientation in the manifest.
736
    if len(orientations) != 1:
4✔
737
        return "unspecified"
4✔
738

739
    # Convert the orientation to a value that can be used in the manifest.
740
    # If the specified orientation is not supported, use unspecified.
741
    MANIFEST_ORIENTATION_MAP = {
4✔
742
        "landscape": "landscape",
743
        "portrait": "portrait",
744
        "portrait-reverse": "reversePortrait",
745
        "landscape-reverse": "reverseLandscape",
746
    }
747
    return MANIFEST_ORIENTATION_MAP.get(orientations[0], "unspecified")
4✔
748

749

750
def get_dist_ndk_min_api_level():
4✔
751
    # Get the default minsdk, equal to the NDK API that this dist is built against
752
    try:
4✔
753
        with open('dist_info.json', 'r') as fileh:
4!
754
            info = json.load(fileh)
×
755
            ndk_api = int(info['ndk_api'])
×
756
    except (OSError, KeyError, ValueError, TypeError):
4✔
757
        print('WARNING: Failed to read ndk_api from dist info, defaulting to 12')
4✔
758
        ndk_api = 12  # The old default before ndk_api was introduced
4✔
759
    return ndk_api
4✔
760

761

762
def create_argument_parser():
4✔
763
    ndk_api = get_dist_ndk_min_api_level()
4✔
764
    import argparse
4✔
765
    ap = argparse.ArgumentParser(description='''\
4✔
766
Package a Python application for Android (using
767
bootstrap ''' + get_bootstrap_name() + ''').
768

769
For this to work, Java and Ant need to be in your path, as does the
770
tools directory of the Android SDK.
771
''')
772

773
    # --private is required unless for sdl2, where there's also --launcher
774
    ap.add_argument('--private', dest='private',
4✔
775
                    help='the directory with the app source code files' +
776
                         ' (containing your main.py entrypoint)',
777
                    required=(not is_sdl_bootstrap()))
778
    ap.add_argument('--package', dest='package',
4✔
779
                    help=('The name of the java package the project will be'
780
                          ' packaged under.'),
781
                    required=True)
782
    ap.add_argument('--name', dest='name',
4✔
783
                    help=('The human-readable name of the project.'),
784
                    required=True)
785
    ap.add_argument('--numeric-version', dest='numeric_version',
4✔
786
                    help=('The numeric version number of the project. If not '
787
                          'given, this is automatically computed from the '
788
                          'version.'))
789
    ap.add_argument('--version', dest='version',
4✔
790
                    help=('The version number of the project. This should '
791
                          'consist of numbers and dots, and should have the '
792
                          'same number of groups of numbers as previous '
793
                          'versions.'),
794
                    required=True)
795
    if is_sdl_bootstrap():
4!
796
        ap.add_argument('--launcher', dest='launcher', action='store_true',
4✔
797
                        help=('Provide this argument to build a multi-app '
798
                              'launcher, rather than a single app.'))
799
        ap.add_argument('--home-app', dest='home_app', action='store_true', default=False,
4✔
800
                        help=('Turn your application into a home app (launcher)'))
801
    ap.add_argument('--display-cutout', dest='display_cutout', default='never',
4✔
802
                    help=('Enables display-cutout that renders around the area (notch) on '
803
                          'some devices that extends into the display surface'))
804
    ap.add_argument('--permission', dest='permissions', action='append', default=[],
4✔
805
                    help='The permissions to give this app.', nargs='+')
806
    ap.add_argument('--meta-data', dest='meta_data', action='append', default=[],
4✔
807
                    help='Custom key=value to add in application metadata')
808
    ap.add_argument('--uses-library', dest='android_used_libs', action='append', default=[],
4✔
809
                    help='Used shared libraries included using <uses-library> tag in AndroidManifest.xml')
810
    ap.add_argument('--asset', dest='assets',
4✔
811
                    action="append", default=[],
812
                    metavar="/path/to/source:dest",
813
                    help='Put this in the assets folder at assets/dest')
814
    ap.add_argument('--resource', dest='resources',
4✔
815
                    action="append", default=[],
816
                    metavar="/path/to/source:kind/asset",
817
                    help='Put this in the res folder at res/kind')
818
    ap.add_argument('--icon', dest='icon',
4✔
819
                    help=('A png file to use as the icon for '
820
                          'the application.'))
821
    ap.add_argument('--icon-fg', dest='icon_fg',
4✔
822
                    help=('A png file to use as the foreground of the adaptive icon '
823
                          'for the application.'))
824
    ap.add_argument('--icon-bg', dest='icon_bg',
4✔
825
                    help=('A png file to use as the background of the adaptive icon '
826
                          'for the application.'))
827
    ap.add_argument('--service', dest='services', action='append', default=[],
4✔
828
                    help='Declare a new service entrypoint: '
829
                         'NAME:PATH_TO_PY[:foreground]')
830
    ap.add_argument('--native-service', dest='native_services', action='append', default=[],
4✔
831
                    help='Declare a new native service: '
832
                         'package.name.service')
833
    if get_bootstrap_name() != "service_only":
4!
834
        ap.add_argument('--presplash', dest='presplash',
4✔
835
                        help=('A jpeg file to use as a screen while the '
836
                              'application is loading.'))
837
        ap.add_argument('--presplash-lottie', dest='presplash_lottie',
4✔
838
                        help=('A lottie (json) file to use as an animation while the '
839
                              'application is loading.'))
840
        ap.add_argument('--presplash-color',
4✔
841
                        dest='presplash_color',
842
                        default='#000000',
843
                        help=('A string to set the loading screen '
844
                              'background color. '
845
                              'Supported formats are: '
846
                              '#RRGGBB #AARRGGBB or color names '
847
                              'like red, green, blue, etc.'))
848
        ap.add_argument('--window', dest='window', action='store_true',
4✔
849
                        default=False,
850
                        help='Indicate if the application will be windowed')
851
        ap.add_argument('--manifest-orientation', dest='manifest_orientation',
4✔
852
                        help=('The orientation that will be set in the '
853
                              'android:screenOrientation attribute of the activity '
854
                              'in the AndroidManifest.xml file. If not set, '
855
                              'the value will be synthesized from the --orientation option.'))
856
        ap.add_argument('--orientation', dest='orientation',
4✔
857
                        action="append", default=[],
858
                        choices=['portrait', 'landscape', 'landscape-reverse', 'portrait-reverse'],
859
                        help=('The orientations that the app will display in. '
860
                              'Since Android ignores android:screenOrientation '
861
                              'when in multi-window mode (Which is the default on Android 12+), '
862
                              'this option will also set the window orientation hints '
863
                              'for apps using the (default) SDL bootstrap.'
864
                              'If multiple orientations are given, android:screenOrientation '
865
                              'will be set to "unspecified"'))
866

867
    ap.add_argument('--enable-androidx', dest='enable_androidx',
4✔
868
                    action='store_true',
869
                    help=('Enable the AndroidX support library, '
870
                          'requires api = 28 or greater'))
871
    ap.add_argument('--android-entrypoint', dest='android_entrypoint',
4✔
872
                    default=DEFAULT_PYTHON_ACTIVITY_JAVA_CLASS,
873
                    help='Defines which java class will be used for startup, usually a subclass of PythonActivity')
874
    ap.add_argument('--android-apptheme', dest='android_apptheme',
4✔
875
                    default='@android:style/Theme.NoTitleBar',
876
                    help='Defines which app theme should be selected for the main activity')
877
    ap.add_argument('--add-compile-option', dest='compile_options', default=[],
4✔
878
                    action='append', help='add compile options to gradle.build')
879
    ap.add_argument('--add-gradle-repository', dest='gradle_repositories',
4✔
880
                    default=[],
881
                    action='append',
882
                    help='Ddd a repository for gradle')
883
    ap.add_argument('--add-packaging-option', dest='packaging_options',
4✔
884
                    default=[],
885
                    action='append',
886
                    help='Dndroid packaging options')
887

888
    ap.add_argument('--wakelock', dest='wakelock', action='store_true',
4✔
889
                    help=('Indicate if the application needs the device '
890
                          'to stay on'))
891
    ap.add_argument('--blacklist', dest='blacklist',
4✔
892
                    default=join(curdir, 'blacklist.txt'),
893
                    help=('Use a blacklist file to match unwanted file in '
894
                          'the final APK'))
895
    ap.add_argument('--whitelist', dest='whitelist',
4✔
896
                    default=join(curdir, 'whitelist.txt'),
897
                    help=('Use a whitelist file to prevent blacklisting of '
898
                          'file in the final APK'))
899
    ap.add_argument('--release', dest='build_mode', action='store_const',
4✔
900
                    const='release', default='debug',
901
                    help='Build your app as a non-debug release build. '
902
                         '(Disables gdb debugging among other things)')
903
    ap.add_argument('--with-debug-symbols', dest='with_debug_symbols',
4✔
904
                    action='store_const', const=True, default=False,
905
                    help='Will keep debug symbols from `.so` files.')
906
    ap.add_argument('--add-jar', dest='add_jar', action='append',
4✔
907
                    help=('Add a Java .jar to the libs, so you can access its '
908
                          'classes with pyjnius. You can specify this '
909
                          'argument more than once to include multiple jars'))
910
    ap.add_argument('--add-aar', dest='add_aar', action='append',
4✔
911
                    help=('Add an aar dependency manually'))
912
    ap.add_argument('--depend', dest='depends', action='append',
4✔
913
                    help=('Add a external dependency '
914
                          '(eg: com.android.support:appcompat-v7:19.0.1)'))
915
    # The --sdk option has been removed, it is ignored in favour of
916
    # --android-api handled by toolchain.py
917
    ap.add_argument('--sdk', dest='sdk_version', default=-1,
4✔
918
                    type=int, help=('Deprecated argument, does nothing'))
919
    ap.add_argument('--minsdk', dest='min_sdk_version',
4✔
920
                    default=ndk_api, type=int,
921
                    help=('Minimum Android SDK version that the app supports. '
922
                          'Defaults to {}.'.format(ndk_api)))
923
    ap.add_argument('--allow-minsdk-ndkapi-mismatch', default=False,
4✔
924
                    action='store_true',
925
                    help=('Allow the --minsdk argument to be different from '
926
                          'the discovered ndk_api in the dist'))
927
    ap.add_argument('--intent-filters', dest='intent_filters',
4✔
928
                    help=('Add intent-filters xml rules to the '
929
                          'AndroidManifest.xml file. The argument is a '
930
                          'filename containing xml. The filename should be '
931
                          'located relative to the python-for-android '
932
                          'directory'))
933
    ap.add_argument('--res_xml', dest='res_xmls', action='append', default=[],
4✔
934
                    help='Add files to res/xml directory (for example device-filters)', nargs='+')
935
    ap.add_argument('--with-billing', dest='billing_pubkey',
4✔
936
                    help='If set, the billing service will be added (not implemented)')
937
    ap.add_argument('--add-source', dest='extra_source_dirs', action='append',
4✔
938
                    help='Include additional source dirs in Java build')
939
    if get_bootstrap_name() == "webview":
4!
940
        ap.add_argument('--port',
×
941
                        help='The port on localhost that the WebView will access',
942
                        default='5000')
943
    ap.add_argument('--try-system-python-compile', dest='try_system_python_compile',
4✔
944
                    action='store_true',
945
                    help='Use the system python during compileall if possible.')
946
    ap.add_argument('--sign', action='store_true',
4✔
947
                    help=('Try to sign the APK with your credentials. You must set '
948
                          'the appropriate environment variables.'))
949
    ap.add_argument('--add-activity', dest='add_activity', action='append',
4✔
950
                    help='Add this Java class as an Activity to the manifest.')
951
    ap.add_argument('--activity-launch-mode',
4✔
952
                    dest='activity_launch_mode',
953
                    default='singleTask',
954
                    help='Set the launch mode of the main activity in the manifest.')
955
    ap.add_argument('--allow-backup', dest='allow_backup', default='true',
4✔
956
                    help="if set to 'false', then android won't backup the application.")
957
    ap.add_argument('--backup-rules', dest='backup_rules', default='',
4✔
958
                    help=('Backup rules for Android Auto Backup. Argument is a '
959
                          'filename containing xml. The filename should be '
960
                          'located relative to the private directory containing your source code '
961
                          'files (containing your main.py entrypoint). '
962
                          'See https://developer.android.com/guide/topics/data/'
963
                          'autobackup#IncludingFiles for more information'))
964
    ap.add_argument('--no-byte-compile-python', dest='byte_compile_python',
4✔
965
                    action='store_false', default=True,
966
                    help='Skip byte compile for .py files.')
967
    ap.add_argument('--no-optimize-python', dest='optimize_python',
4✔
968
                    action='store_false', default=True,
969
                    help=('Whether to compile to optimised .pyc files, using -OO '
970
                          '(strips docstrings and asserts)'))
971
    ap.add_argument('--extra-manifest-xml', default='',
4✔
972
                    help=('Extra xml to write directly inside the <manifest> element of'
973
                          'AndroidManifest.xml'))
974
    ap.add_argument('--extra-manifest-application-arguments', default='',
4✔
975
                    help='Extra arguments to be added to the <manifest><application> tag of'
976
                         'AndroidManifest.xml')
977
    ap.add_argument('--manifest-placeholders', dest='manifest_placeholders',
4✔
978
                    default='[:]', help=('Inject build variables into the manifest '
979
                                         'via the manifestPlaceholders property'))
980
    ap.add_argument('--service-class-name', dest='service_class_name', default=DEFAULT_PYTHON_SERVICE_JAVA_CLASS,
4✔
981
                    help='Use that parameter if you need to implement your own PythonServive Java class')
982
    ap.add_argument('--activity-class-name', dest='activity_class_name', default=DEFAULT_PYTHON_ACTIVITY_JAVA_CLASS,
4✔
983
                    help='The full java class name of the main activity')
984
    if get_bootstrap_name() == "qt":
4!
985
        ap.add_argument('--qt-libs', dest='qt_libs', required=True,
×
986
                        help='comma separated list of Qt libraries to be loaded')
987
        ap.add_argument('--load-local-libs', dest='load_local_libs', required=True,
×
988
                        help='comma separated list of Qt plugin libraries to be loaded')
989
        ap.add_argument('--init-classes', dest='init_classes', default='',
×
990
                        help='comma separated list of java class names to be loaded from the Qt jar files, '
991
                             'specified through add_jar cli option')
992

993
    return ap
4✔
994

995

996
def parse_args_and_make_package(args=None):
4✔
997
    global BLACKLIST_PATTERNS, WHITELIST_PATTERNS, PYTHON
998

999
    ndk_api = get_dist_ndk_min_api_level()
×
1000
    ap = create_argument_parser()
×
1001

1002
    # Put together arguments, and add those from .p4a config file:
1003
    if args is None:
×
1004
        args = sys.argv[1:]
×
1005

1006
    def _read_configuration():
×
1007
        if not exists(".p4a"):
×
1008
            return
×
1009
        print("Reading .p4a configuration")
×
1010
        with open(".p4a") as fd:
×
1011
            lines = fd.readlines()
×
1012
        lines = [shlex.split(line)
×
1013
                 for line in lines if not line.startswith("#")]
1014
        for line in lines:
×
1015
            for arg in line:
×
1016
                args.append(arg)
×
1017
    _read_configuration()
×
1018

1019
    args = ap.parse_args(args)
×
1020

1021
    if args.name and args.name[0] == '"' and args.name[-1] == '"':
×
1022
        args.name = args.name[1:-1]
×
1023

1024
    if ndk_api != args.min_sdk_version:
×
1025
        print(('WARNING: --minsdk argument does not match the api that is '
×
1026
               'compiled against. Only proceed if you know what you are '
1027
               'doing, otherwise use --minsdk={} or recompile against api '
1028
               '{}').format(ndk_api, args.min_sdk_version))
1029
        if not args.allow_minsdk_ndkapi_mismatch:
×
1030
            print('You must pass --allow-minsdk-ndkapi-mismatch to build '
×
1031
                  'with --minsdk different to the target NDK api from the '
1032
                  'build step')
1033
            sys.exit(1)
×
1034
        else:
1035
            print('Proceeding with --minsdk not matching build target api')
×
1036

1037
    if args.billing_pubkey:
×
1038
        print('Billing not yet supported!')
×
1039
        sys.exit(1)
×
1040

1041
    if args.sdk_version != -1:
×
1042
        print('WARNING: Received a --sdk argument, but this argument is '
×
1043
              'deprecated and does nothing.')
1044
        args.sdk_version = -1  # ensure it is not used
×
1045

1046
    args.permissions = parse_permissions(args.permissions)
×
1047

1048
    args.manifest_orientation = get_manifest_orientation(
×
1049
        args.orientation, args.manifest_orientation
1050
    )
1051

1052
    if is_sdl_bootstrap():
×
1053
        args.sdl_orientation_hint = get_sdl_orientation_hint(args.orientation)
×
1054

1055
    if args.res_xmls and isinstance(args.res_xmls[0], list):
×
1056
        args.res_xmls = [x for res in args.res_xmls for x in res]
×
1057

1058
    if args.try_system_python_compile:
×
1059
        # Hardcoding python2.7 is okay for now, as python3 skips the
1060
        # compilation anyway
1061
        python_executable = 'python2.7'
×
1062
        try:
×
1063
            subprocess.call([python_executable, '--version'])
×
1064
        except (OSError, subprocess.CalledProcessError):
×
1065
            pass
×
1066
        else:
1067
            PYTHON = python_executable
×
1068

1069
    if args.blacklist:
×
1070
        with open(args.blacklist) as fd:
×
1071
            patterns = [x.strip() for x in fd.read().splitlines()
×
1072
                        if x.strip() and not x.strip().startswith('#')]
1073
        BLACKLIST_PATTERNS += patterns
×
1074

1075
    if args.whitelist:
×
1076
        with open(args.whitelist) as fd:
×
1077
            patterns = [x.strip() for x in fd.read().splitlines()
×
1078
                        if x.strip() and not x.strip().startswith('#')]
1079
        WHITELIST_PATTERNS += patterns
×
1080

1081
    if args.private is None and is_sdl_bootstrap() and args.launcher is None:
×
1082
        print('Need --private directory or ' +
×
1083
              '--launcher (SDL2/SDL3 bootstrap only)' +
1084
              'to have something to launch inside the .apk!')
1085
        sys.exit(1)
×
1086
    make_package(args)
×
1087

1088
    return args
×
1089

1090

1091
if __name__ == "__main__":
1092
    parse_args_and_make_package()
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc