Repository navigation
Expand file tree
/
Copy pathautoporter.py
More file actions
5461 lines (5093 loc) · 237 KB
/
Copy pathautoporter.py
File metadata and controls
5461 lines (5093 loc) · 237 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
HyperOS AutoPorter - Automated Firmware Porting Tool
"""
import argparse
import os
import re
import stat
import struct
import sys
import shutil
import tempfile
import zipfile
import subprocess
from collections import Counter
from pathlib import Path
from typing import List
import requests
from tqdm import tqdm
# Directory definitions
BASE_DIR = Path(__file__).parent.resolve()
TOOLS_DIR = BASE_DIR / "tools"
MODDED_HOS3_DIR = BASE_DIR / "moddedapps_hos3"
MODDED_HOS4_DIR = BASE_DIR / "moddedapps_hos4"
MODDED_HOS4_GL_DIR = BASE_DIR / "moddedapps_hos4_gl"
EXTRACTED_STOCK_DIR = BASE_DIR / "extracted_stock"
EXTRACTED_PORT_DIR = BASE_DIR / "extracted_port"
UNPACKED_STOCK_DIR = BASE_DIR / "unpacked_stock"
UNPACKED_PORT_DIR = BASE_DIR / "unpacked_port"
PACKAGE_DIR = BASE_DIR / "package"
PORT_META_DIR = BASE_DIR / "port_meta"
# Supported devices. Everything device-specific lives here (add a record
# per phone — stock URL, fingerprint, template prefix, ...); the only
# device today is duchamp.
DEVICES = {
"duchamp": {
"template_prefix": "duchamp_template",
"fingerprint": ("POCO/duchamp_global/duchamp:16/BP2A.250605.031.A3/"
"OS3.0.9.0.WNLMIXM:user/release-keys"),
},
}
def template_dir_for(device: str, variant: str) -> Path:
"""Flash template dir for a device + build variant (base -> nonfenrir,
fenrir -> fenrir)."""
suffix = "fenrir" if variant == "fenrir" else "nonfenrir"
return BASE_DIR / f"{DEVICES[device]['template_prefix']}_{suffix}"
# Flash templates are NOT in git anymore (the repo stays light, no LFS
# quota): each template rides a release asset on the "templates" tag and is
# downloaded at build time. Updating a template = re-upload the asset, no
# commit needed.
TEMPLATES_RELEASE = (
"https://github.com/wectazz/HyperOS-AutoPorter-Python/releases/download/"
"templates/{archive}.zip"
)
def fetch_template_release(device: str, variant: str) -> Path:
"""Download + unpack the flash template for device+variant from the
GitHub release into the repo-root dir template_dir_for() returns.
An existing dir is kept as-is (delete it to refresh); payloads are
validated right after unpacking so a broken asset fails before build
time is burned. Zips are Windows-made (no unix modes), so exec bits
for scripts/binaries are restored afterwards."""
dest = template_dir_for(device, variant)
if dest.is_dir() and any(dest.iterdir()):
print(f"Flash template already present, skip download: {dest}\n")
return dest
suffix = "fenrir" if variant == "fenrir" else "nonfenrir"
archive = f"{DEVICES[device]['template_prefix']}_{suffix}"
url = TEMPLATES_RELEASE.format(archive=archive)
print(f"=== Fetching flash template (GitHub release): {archive} ===")
zip_path = BASE_DIR / f"{archive}.zip"
download_file_with_progress(url, zip_path)
if zip_path.stat().st_size < 1024:
raise RuntimeError(f"Template archive too small: {zip_path}")
dest.mkdir(parents=True, exist_ok=True)
print(f"Unpacking {zip_path.name} into {dest}...")
try:
shutil.unpack_archive(str(zip_path), str(dest))
except Exception:
# Fallback to 7z like the mod-set path (non-standard archives)
subprocess.run(["7z", "x", str(zip_path), f"-o{dest}", "-y"], check=True)
zip_path.unlink(missing_ok=True)
# Zip may carry one wrapper dir — flatten it onto dest.
items = [p for p in dest.iterdir()]
if len(items) == 1 and items[0].is_dir() and not items[0].is_symlink():
inner = items[0]
for entry in list(inner.iterdir()):
shutil.move(str(entry), str(dest / entry.name))
inner.rmdir()
# Windows zips carry no unix modes: dirs 0755, files 0644, scripts and
# bin/ tools executable (matches what git checkout used to give).
exec_bits = 0
for path in dest.rglob("*"):
if path.is_symlink():
continue
if path.is_dir():
path.chmod(0o755)
elif path.suffix == ".sh" or "bin" in path.relative_to(dest).parts[:-1]:
path.chmod(0o755)
exec_bits += 1
else:
path.chmod(0o644)
print(f" restored exec bits on {exec_bits} script/bin entries")
validate_template_payloads(dest)
return dest
# Download URLs
STOCK_URL_DUCHAMP = (
"https://bkt-sgp-miui-ota-update-alisgp.oss-ap-southeast-1.aliyuncs.com/"
"OS3.0.9.0.WNLMIXM/duchamp_global-ota_full-OS3.0.9.0.WNLMIXM-user-16.0-20cd32d00e.zip"
)
PORT_URL = (
"https://bkt-sgp-miui-ota-update-alisgp.oss-ap-southeast-1.aliyuncs.com/"
"OS4.0.0.11.XPTMIXM/chagall_global-ota_full-OS4.0.0.11.XPTMIXM-user-17.0-cfe6c12441.zip"
)
HOS3_MOD_URL = (
"https://github.com/wectazz/HyperOS-AutoPorter-Python/releases/download/"
"modded-apps/moddedapps_hos3.zip"
)
HOS4_MOD_URL = (
"https://github.com/wectazz/HyperOS-AutoPorter-Python/releases/download/"
"modded-apps/moddedapps_hos4.zip"
)
HOS4_GL_MOD_URL = (
"https://github.com/wectazz/HyperOS-AutoPorter-Python/releases/download/"
"modded-apps/moddedapps_hos4_gl.zip"
)
# Modded apps sets per HyperOS version: (download_url, output_dir, archive_name).
# Hosted as release assets on GitHub (direct links, no auth, no quotas).
MODDED_APPS = {
"hos3": (HOS3_MOD_URL, MODDED_HOS3_DIR, "moddedapps_hos3"),
"hos4": (HOS4_MOD_URL, MODDED_HOS4_DIR, "moddedapps_hos4"),
"hos4_gl": (HOS4_GL_MOD_URL, MODDED_HOS4_GL_DIR, "moddedapps_hos4_gl"),
}
def select_modded_apps(hyper_version: str, region: str) -> tuple:
"""Pick the modded-apps set for a HyperOS version + firmware region:
global hos4 takes the hos4_gl set, everything else the version set.
A global firmware on a version without a gl set (hos3) falls back to
the version set with a warning."""
if hyper_version == "hos4" and region != "CN":
print("Global firmware: using moddedapps_hos4_gl set")
return MODDED_APPS["hos4_gl"]
if hyper_version != "hos4" and region != "CN":
print(f" [warn] no global mod set for {hyper_version}, "
f"using {hyper_version} set")
return MODDED_APPS[hyper_version]
# Firmware region codes: 2 letters before the trailing XM in the OS version
# (e.g. OS3.0.304.0.WNLCNXM -> CN, OS4.0.6.0.XPSEUXM -> EU). CN = China,
# anything else (MI/EU/RU/ID/...) = global. Matched against the OTA URL
# or file name alike.
REGION_VERSION_RE = re.compile(r"OS\d[\d.]*\.[A-Z]*([A-Z]{2})XM")
def port_codename_candidates(url: str) -> list:
"""Device codename candidates from an OTA URL/filename: the full head
before -ota (warhol_global / chagall), then the short token before _
(warhol / chagall). CN names carry no _global part (both coincide)."""
base = url.rsplit("/", 1)[-1]
head = base.split("-ota")[0]
cands = []
for cand in (head, head.split("_")[0]):
if cand and cand not in cands:
cands.append(cand)
return cands
def detect_region_code(source: str) -> str:
"""Return the 2-letter firmware region code from an OTA URL/filename.
Unparseable sources fall back to CN (status quo) with a warning."""
m = REGION_VERSION_RE.search(source)
if not m:
print(f" [warn] cannot detect region in {source}, assume CN")
return "CN"
return m.group(1)
# Target Partition lists
STOCK_PARTITIONS = ["odm", "vendor", "odm_dlkm", "system_dlkm", "vendor_dlkm"]
PORT_PARTITIONS = ["mi_ext", "product", "system", "system_ext"]
# Extra stock partitions: dumped + unpacked for reference/patching only,
# NOT packed into super.img (super takes product/system_ext from the port)
STOCK_EXTRA_PARTITIONS = ["product", "system_ext"]
# Full stock partition set for --mode mod (stock-only modification, no port):
# every dynamic partition comes from STOCK_URL_DUCHAMP (device's own firmware).
# Order mirrors the port-mode super layout (stock slots first, then the rest),
# so mod and port super.img have the same partition order.
MOD_PARTITIONS = STOCK_PARTITIONS + [
p for p in PORT_PARTITIONS if p not in STOCK_PARTITIONS
] + [
p for p in STOCK_EXTRA_PARTITIONS
if p not in STOCK_PARTITIONS and p not in PORT_PARTITIONS
]
# Extra files taken from the OTA zip (before it is deleted) for the
# final flashable package: recovery META-INF descriptor of the build.
# Port mode takes them from the port OTA, mod mode from the stock OTA.
PORT_META_FILES = ["META-INF/com/android/metadata", "META-INF/com/android/metadata.pb"]
# Unpacked as a donor/mod source only (mi_ext content is relocated into
# product/ by the tweaks above) — never rebuilt, never packed into super.
SUPER_EXCLUDE = {"mi_ext"}
# Smali patching (signature-check neutering -> XdConfig). Applied to jars from
# the unpacked port tree BEFORE the rebuild bakes them back in. Extra smali to
# inject lives in dsv/<jar-key>/<dex>/ and lands in the matching decompiled dex
# dir at the path from its own .class declaration (e.g. XdConfig goes to
# android/os/ of classes6). Extend per jar (miui-services.jar, services.jar).
DSV_DIR = BASE_DIR / "dsv"
# Method-body replacements: (target basenames, [method name + '('], registers,
# call). The whole body between the .method header and .end method is replaced
# (annotations/.params inside are dropped with it). The original header line
# (with blacklist/greylist markers) is kept. registers: int (fixed
# .registers) or "keep" (reuse the original .registers/.locals line). call:
# XdConfig method name, None (plain void body), or a list of custom body lines.
FRAMEWORK_METHOD_PATCHES = [
(["AssetManager.smali"], ["containsAllocatedTable("], 2, "RETURN_FALSE"),
(["PackageParser$SigningDetails.smali", "SigningDetails.smali"],
["checkCapability(", "checkCapabilityRecover(", "hasCommonAncestor(",
"signaturesMatchExactly("], 4, "RETURN_TRUE"),
(["StrictJarVerifier.smali"], ["verifyMessageDigest("], 3, "RETURN_TRUE"),
]
MIUI_SERVICES_METHOD_PATCHES = [
(["PackageManagerServiceImpl.smali"], ["verifyIsolationViolation("], 3, None),
(["PackageManagerServiceImpl.smali"], ["canBeUpdate("], 2, None),
]
# Method-start insertions: (target basenames, header fragments, insert lines,
# required body markers). The block is inserted after the method prologue
# (.registers/.params/annotations) and before the first instruction, under a
# unique :bypass_secure_flag label (never :cond_N — those collide with
# baksmali's own labels). Matched by descriptor + markers, not by method name.
# Shared secure-flag bypass block (method start): if
# WindowState.isBypassSecureFlag() is true, return false (not secure).
# Inserted under a unique :bypass_secure_flag label — never :cond_N, those
# collide with baksmali's own labels (it renumbers them itself on re-decompile).
SECURE_BYPASS_FALSE = [
"invoke-static {}, Lcom/android/server/wm/WindowState;->isBypassSecureFlag()Z",
"move-result v0",
"if-eqz v0, :bypass_secure_flag",
"const/4 v0, 0x0",
"return v0",
":bypass_secure_flag",
]
MIUI_SERVICES_START_PATCHES = [
(["WindowManagerServiceImpl.smali"],
["notAllowCaptureDisplay(", "(Lcom/android/server/wm/RootWindowContainer;I)Z"],
SECURE_BYPASS_FALSE,
["ActivityRecordStub;->isCompatibilityMode"]),
]
# Literal string replacements across whole files: (target basenames, old, new).
# E.g. notification patch for Chinese ROMs (applies to hos3 and hos4 alike,
# like all dsv rules — dsv has no version branching).
MIUI_SERVICES_REPLACE_PATCHES = [
(["ProcessSceneCleaner.smali", "BroadcastQueueModernStubImpl.smali",
"ProcessManagerService.smali"],
"Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z",
"Lmiui/os/Build;->IS_MIUI:Z"),
]
# Same, but the bypassed method returns a List (screenshot listeners):
# bypass returns an empty list instead of false.
SERVICES_START_PATCHES = [
(["WindowManagerService.smali"],
["notifyScreenshotListeners("],
[
"invoke-static {}, Lcom/android/server/wm/WindowState;->isBypassSecureFlag()Z",
"move-result v0",
"if-eqz v0, :bypass_secure_flag",
"invoke-static {}, Ljava/util/Collections;->emptyList()Ljava/util/List;",
"move-result-object v0",
"return-object v0",
":bypass_secure_flag",
],
["notifyScreenshotListeners()", "android.permission.STATUS_BAR_SERVICE"]),
(["WindowState.smali"],
["isSecureLocked("],
SECURE_BYPASS_FALSE,
[]),
]
# Whole new methods to insert: (target basenames, new method name fragment for
# the duplicate guard, anchor method fragment to insert before, method block).
SERVICES_NEW_METHODS = [
(["WindowState.smali"],
"isBypassSecureFlag(",
"isLegacyPolicyVisibility(",
".method public static isBypassSecureFlag()Z\n"
" .registers 2\n"
" const-string/jumbo v0, \"persist.sys.secure_flag\"\n"
" const/4 v1, 0x1\n"
" invoke-static {v0, v1}, Landroid/os/SystemProperties;->getBoolean(Ljava/lang/String;Z)Z\n"
" move-result v0\n"
" return v0\n"
".end method\n"),
]
SERVICES_METHOD_PATCHES = [
(["KeySetManagerService.smali"], ["checkUpgradeKeySetLocked("], "keep", "RETURN_TRUE"),
(["PackageManagerServiceUtils.smali"], ["checkDowngrade("], "keep", None),
(["PackageManagerServiceUtils.smali"],
["matchSignatureInSystem(", "matchSignaturesCompat(", "matchSignaturesRecover(",
"verifySignatures("], "keep", "RETURN_FALSE"),
(["VerifyingSession.smali"], ["isVerificationEnabled("], "keep", "RETURN_FALSE"),
(["ReconcilePackageUtils.smali"], ["<clinit>("], 1, [
"invoke-static {}, Landroid/os/XdConfig;->RETURN_TRUE()Z",
"move-result v0",
"sput-boolean v0, Lcom/android/server/pm/ReconcilePackageUtils;->ALLOW_NON_PRELOADS_SYSTEM_SHAREDUIDS:Z",
"return-void",
]),
]
# Invoke insertions: (target basenames, invoke-line regex). An
# `XdConfig;->RETURN_TRUE()Z` call is inserted after EVERY matching line (with
# no move-result, so the following original move-result picks up our forced
# true — that is the point).
FRAMEWORK_INSERT_PATCHES = [
(["ApkSignatureSchemeV2Verifier.smali", "ApkSignatureSchemeV3Verifier.smali",
"ApkSignatureSchemeV4Verifier.smali"],
r"invoke-virtual\s+\{[^}]*\},\s*Ljava/security/Signature;->verify\(\[B\)Z"),
(["ApkSigningBlockUtils.smali"],
r"invoke-static\s+\{[^}]*\},\s*Ljava/security/MessageDigest;->isEqual\(\[B\[B\)Z"),
]
# mi_ext tweaks (step 4c3, both modes: mi_ext is the port's in port mode,
# the stock's in mod mode). build.prop key edits + moves of uninstall blobs
# from the nested mi_ext/product/ into the real product partition.
MI_EXT_BUILD_PROP = "mi_ext/etc/build.prop"
MI_EXT_MOD_DEVICE = "duchamp"
# build.prop keys dropped from mi_ext (matched by key, any value).
MI_EXT_DROP_PROP_KEYS = [
"ro.mi.xms.version.incremental",
"ro.mi.os.custfeatureresolve",
"ro.mi.os.version.beta",
"ro.vendor.build.ab_ota_partitions",
]
# Set to 3 when the key exists ("if possible" — never added when absent).
MI_EXT_RADIO_5G_KEY = "ro.vendor.radio.5g"
# "TengeOS | " is prepended to its value (e.g. OS4.0.0.12.XPTCNXM ->
# "TengeOS | OS4.0.0.12.XPTCNXM"); already-prefixed values are left alone.
MI_EXT_VERSION_INCR_KEY = "ro.mi.os.version.incremental"
MI_EXT_VERSION_PREFIX = "TengeOS | "
# Moved out of mi_ext/etc/build.prop into product/etc/build.prop.
MI_EXT_UNINSTALL_FLAG = "ro.miui.support.system.app.uninstall.v2"
# (mi_ext/product/... source, product/... dest, hyper-version gate or None).
# NOTE: the on-device name is platform-miui-uninstall.xml.
MI_EXT_PRODUCT_MOVES = [
("mi_ext/product/etc/permissions/platform-miui-uninstall.xml",
"product/etc/permissions/platform-miui-uninstall.xml", None),
("mi_ext/product/etc/permissions/rustruntime_cfg_v3_v5.xml",
"product/etc/permissions/rustruntime_cfg_v3_v5.xml", "hos4"),
("mi_ext/product/framework/miui-uninstall-empty.jar",
"product/framework/miui-uninstall-empty.jar", None),
]
# Nested dirs dropped from the mi_ext tree (never baked into mi_ext.img).
MI_EXT_DROP_DIRS = ["mi_ext/system", "mi_ext/system_ext", "mi_ext/product/app"]
# GMS permission XML removed from product on CN firmwares only (both modes,
# not debloat-gated; global firmwares keep it).
PRODUCT_GMS_PERMISSION = "product/etc/permissions/cn.google.services.xml"
# Global firmwares only: named entries moved from mi_ext/product/* into
# product/* ((mi_ext source dir, product dest dir, [names]) — files are
# moved, dirs merged recursively). CN firmwares keep MI_EXT_PRODUCT_MOVES.
MI_EXT_GLOBAL_DIR_MOVES = [
("mi_ext/product/app", "product/app",
["Gemini_arm64", "IFAAService", "SoterService", "XiaomiInCallUI"]),
("mi_ext/product/data-app", "product/data-app",
["GlobalWPSLITE", "MiuiCalendarGlobal", "MIUICompassGlobal",
"XMRemoteController"]),
("mi_ext/product/priv-app", "product/priv-app",
["AndroidSystemIntelligence_Features_arm64", "CotaService",
"CrossDeviceServices", "PrivateComputeServices_arm64",
"SearchSelector"]),
("mi_ext/product/etc", "product/etc",
["ecc_list.xml", "vendor_miui.xml", "miext_removable_apk_info.xml",
"default-permissions", "permissions", "sysconfig", "cust_features"]),
("mi_ext/product", "product",
["framework", "opcust", "overlay"]),
]
# Removed from product/overlay after the mi_ext overlay move (global only).
PRODUCT_TELEPHONY_OVERLAY = "product/overlay/MiuiTelephonyResCustOverlay.apk"
# device_features patch (step 4c5, both modes, on patch_root): applies the
# duchamp_mod.xml tweaks to product/etc/device_features/duchamp.xml.
# support_aod_fullscreen follows --aod-fullscreen (yaml choice true/false),
# everything else is fixed.
DEVICE_FEATURES_XML = "product/etc/device_features/duchamp.xml"
# Vibrator fix for hos3->hos4 ports (step 4c6 on the stock tree + services.jar
# rule below, port mode only): duchamp's vibrator HAL/service is published
# as /vibratorfeature, the hos4 tree expects /default.
VIBRATOR_XML = ("odm/etc/vintf/manifest/"
"vendor.xiaomi.hardware.vibratorfeature.service.xml")
VIBRATOR_XML_OLD = "/vibratorfeature"
VIBRATOR_XML_NEW = "/default"
VIBRATOR_BIN = "odm/bin/hw/vendor.xiaomi.hardware.vibratorfeature.service"
VIBRATOR_BIN_OLD = b"/vibratorfeature\x00"
VIBRATOR_BIN_NEW = b"/default\x00"
# Smali sequence replacement in VibratorManagerServiceStub$Holder (port mode
# services.jar): MiuiStubUtil.getImpl lookup -> direct instantiation.
# NOTE: exact baksmali formatting — the vendored baksmali separates every
# instruction with a blank line, so multi-line blocks must include them;
# unmatched files only warn.
VIBRATOR_SMALI_OLD = (
" const-class v0, Lcom/android/server/vibrator/VibratorManagerServiceStub;\n"
"\n"
" invoke-static {v0}, Lcom/miui/base/MiuiStubUtil;->getImpl(Ljava/lang/Class;)Ljava/lang/Object;\n"
"\n"
" move-result-object v0\n"
"\n"
" check-cast v0, Lcom/android/server/vibrator/VibratorManagerServiceStub;\n"
)
VIBRATOR_SMALI_NEW = (
" new-instance v0, Lcom/android/server/vibrator/VibratorManagerServiceStub;\n"
"\n"
" invoke-direct {v0}, Lcom/android/server/vibrator/VibratorManagerServiceStub;-><init>()V\n"
)
SERVICES_VIBRATOR_REPLACE_PATCHES = [
(["VibratorManagerServiceStub$Holder.smali"],
VIBRATOR_SMALI_OLD, VIBRATOR_SMALI_NEW),
]
# Extended keyboard (Baidu -> Gboard), always applied in both modes (step
# 4f2 jars + step 4g2 APKs). Both the dotted form (const-string component
# names, proven in Settings.apk) and the slashed form (type descriptors).
BAIDU_PKG_DOTTED = "com.baidu.input_mi"
GBOARD_PKG_DOTTED = "com.google.android.inputmethod.latin"
BAIDU_PKG_SLASHED = "com/baidu/input_mi"
GBOARD_PKG_SLASHED = "com/google/android/inputmethod/latin"
# Force-enable IME bottom support: const/4 v0, 0x1 right after the getInt
# move-result (same blank-line formatting note as the vibrator blocks).
FUNCTION_SELECT_OLD = (
" invoke-static {v0, v1}, Landroid/os/SystemProperties;->getInt(Ljava/lang/String;I)I\n"
"\n"
" move-result v0\n"
)
FUNCTION_SELECT_NEW = (
" invoke-static {v0, v1}, Landroid/os/SystemProperties;->getInt(Ljava/lang/String;I)I\n"
"\n"
" move-result v0\n"
" const/4 v0, 0x1\n"
)
# DRM broadcast removal in ActivityManagerServiceImpl (always, both modes):
# the 4-line DrmBroadcast sequence is deleted outright (replaced with "").
# Same blank-line-exact block style as the vibrator/function-select rules.
DRM_BROADCAST_OLD = (
" iget-object v4, p0, Lcom/android/server/am/ActivityManagerServiceImpl;->mContext:Landroid/content/Context;\n"
"\n"
" invoke-static {v4}, Lmiui/drm/DrmBroadcast;->getInstance(Landroid/content/Context;)Lmiui/drm/DrmBroadcast;\n"
"\n"
" move-result-object v4\n"
"\n"
" invoke-virtual {v4}, Lmiui/drm/DrmBroadcast;->broadcast()V\n"
)
MIUI_SERVICES_DRM_REPLACE_PATCHES = [
(["ActivityManagerServiceImpl.smali"], DRM_BROADCAST_OLD, ""),
]
# Fullscreen-AOD catch patch (step 4f, miui-services.jar only, gated by
# --aod-fullscreen like the duchamp.xml flag — NOT dsv-gated, it's
# functional). Tuples: (target basenames, previous exception, anchor
# exception, new exception). After every `.catch <anchor>` whose previous
# .catch line is `<prev>` with the same try range + handler, a
# `.catch <new>` with that same range + handler is inserted (same indent).
# Try/catch labels are captured from the file itself (e.g. try_start_3f /
# catch_49), so hos3/hos4 numbering differences don't matter. The prev-line
# guard keeps unrelated SecurityException catches elsewhere untouched;
# "*.smali" scans every decompiled dex dir since the owning class isn't
# pinned. Idempotent: an already-present identical line is not duplicated.
MIUI_SERVICES_AOD_CATCH_PATCHES = [
(["*.smali"], "Landroid/os/RemoteException;",
"Ljava/lang/SecurityException;", "Ljava/util/NoSuchElementException;"),
]
# (apk/jar-relative rules built per target, basenames + both pkg forms).
MIUIFREQUENTPHRASE_APK = "product/app/MIUIFrequentPhrase/MIUIFrequentPhrase.apk"
SETTINGS_APK = "system_ext/priv-app/Settings/Settings.apk"
# Provision.apk Poco gate (always, both modes): isPocoDevice()Z -> return
# false (const/4 v0 + return v0, original registers kept).
PROVISION_APK = "system_ext/priv-app/Provision/Provision.apk"
PROVISION_METHOD_PATCHES = [
(["provision/Utils.smali"], ["isPocoDevice("], "keep",
["const/4 v0, 0x0", "return v0"]),
]
# PowerKeeper.apk thermal/display neutering (always, both modes):
# getDisplayCtrlCode()I -> return 0; setScreenEffect(+Internal) -> void.
POWERKEEPER_APK = "system_ext/app/PowerKeeper/PowerKeeper.apk"
POWERKEEPER_METHOD_PATCHES = [
(["feedbackcontrol/ThermalManager.smali"], ["getDisplayCtrlCode("], "keep",
["const/4 p0, 0x0", "return p0"]),
(["statemachine/DisplayFrameSetting.smali"],
["setScreenEffect(Ljava/lang/String;II)V",
"setScreenEffectInternal(ILjava/lang/String;)V"], "keep", None),
]
# MIUI dialer (global firmwares only — CN ships it already; gated by
# --dialer). EU firmwares carry no dialer in mi_ext, so the committed
# dialer_gl/ set is used; other global regions move the apps from the
# port/stock mi_ext instead. Either way GmsConfigOverlayComms.apk gets
# its Google dialer/contacts/messages strings repointed at the MIUI apps.
DIALER_GL_DIR = BASE_DIR / "dialer_gl"
DIALER_GL_APPS = ["InCallUI", "MIUIContactsTGlobal", "MiuiMmsGlobal"]
DIALER_PRIV_APP = "product/priv-app"
DIALER_MI_EXT_PRIV_APP = "mi_ext/product/priv-app"
GMS_OVERLAY_APK = "product/overlay/GmsConfigOverlayComms.apk"
GMS_DIALER_RES_PATCHES = [
("strings.xml",
r"com\.google\.android\.dialer", "com.android.contacts"),
("strings.xml",
r"com\.google\.android\.contacts", "com.android.contacts"),
("strings.xml",
r"com\.google\.android\.apps\.messaging", "com.android.mms"),
]
# DevicesOverlay.apk resource patch (step 4g3, always, both modes):
# status_bar_padding_top 14.0px -> 25.0px in any decoded xml carrying it
# (the value lives in dimen-port variants, not plain dimen.xml, so the glob
# is deliberately broad — the tag+value regex itself is the guard).
# (glob matched against every decoded file name, pattern is a regex —
# the dimen line indent may vary, so only the tag+value is anchored).
DEVICE_OVERLAY_APK = "product/overlay/DevicesOverlay.apk"
DEVICE_OVERLAY_RES_PATCHES = [
("*.xml",
r'(<dimen name="status_bar_padding_top">)14\.0px(</dimen>)',
r"\g<1>25.0px\g<2>"),
]
# MiuiHome.apk res patch (CTS on the pull-down shade, always, both modes):
# CN builds gate entities by regionType="global" (hidden on CN) — switch to
# "all" so the region gate opens everywhere. On global firmwares the tag is
# usually absent and the rule warn-skips.
MIUIHOME_APK = "product/priv-app/MiuiHome/MiuiHome.apk"
MIUIHOME_RES_PATCHES = [
("entity_config.xml",
r'(regionType=["\'])global(["\'])',
r"\g<1>all\g<2>"),
]
# Settings.apk .array-data replacements (step 4g2, always, both modes).
# Old blocks are matched by their 16 float values (as ints — robust to the
# декомпилер's :array_NNN label numbering, which shifts between builds),
# new blocks repeat a 4-value pattern x4. Hex without 0x prefix, lowercase.
SETTINGS_ARRAY_GROUP1_OLD = [
("3e4ccccd", "3d75c28f", "3f6147ae", "3ecccccd",
"3e99999a", "3e0f5c29", "3f0ccccd", "3f000000",
"0", "3f23d70a", "3f75c28f", "3f000000",
"3de147ae", "3e23d70a", "3f547ae1", "3ecccccd"),
("3d8f5c29", "3e19999a", "3f4a3d71", "3f000000",
"3f1eb852", "3e570a3d", "3f2b851f", "3f000000",
"3d75c28f", "3e800000", "3f570a3d", "3f000000",
"0", "3e4ccccd", "3f47ae14", "3f000000"),
("3f147ae1", "3e99999a", "3f3d70a4", "3ecccccd",
"3e8a3d71", "3e3851ec", "3f19999a", "3f000000",
"3f28f5c3", "3e851eb8", "3f1eb852", "3f000000",
"3df5c28f", "3e23d70a", "3f333333", "3f19999a"),
]
SETTINGS_ARRAY_GROUP1_NEW = (
("3d4ccccd", "0.05f"), ("3e4ccccd", "0.2f"),
("3dcccccd", "0.1f"), ("3f800000", "1.0f"),
) * 4
SETTINGS_ARRAY_GROUP2_OLD = [
("3f800000", "3f666666", "3f70a3d7", "3f800000",
"3f800000", "3f570a3d", "3f63d70a", "3f800000",
"3f7851ec", "3f3ae148", "3f51eb85", "3f800000",
"3f23d70a", "3f266666", "3f7ae148", "3f800000"),
("3f147ae1", "3f3d70a4", "3f800000", "3f800000",
"3f800000", "3f666666", "3f6e147b", "3f800000",
"3f3d70a4", "3f428f5c", "3f800000", "3f800000",
"3f7851ec", "3f451eb8", "3f570a3d", "3f800000"),
("3f7ae148", "3f5c28f6", "3f666666", "3f800000",
"3f19999a", "3f3ae148", "3f7ae148", "3f800000",
"3f6b851f", "3f6e147b", "3f800000", "3f800000",
"3f0f5c29", "3f30a3d7", "3f800000", "3f800000"),
]
SETTINGS_ARRAY_GROUP2_NEW = (
("3f333333", "0.7f"), ("3f4ccccd", "0.8f"),
("3f2e147b", "0.68f"), ("3f4ccccd", "0.8f"),
) * 4
# (target basenames, old values, new (hex, comment) items). "*.smali" scans
# every decoded dex dir since the owning class isn't pinned — the 16-value
# match itself is the guard (accidental collisions are ~impossible).
SETTINGS_ARRAY_PATCHES = (
[(["*.smali"], old, SETTINGS_ARRAY_GROUP1_NEW)
for old in SETTINGS_ARRAY_GROUP1_OLD]
+ [(["*.smali"], old, SETTINGS_ARRAY_GROUP2_NEW)
for old in SETTINGS_ARRAY_GROUP2_OLD]
)
# Settings.apk notification-icon-count extension (always, both modes):
# notification_icon_counts entries 0,1,3 -> 0,1,3,3,3 and values 0,1,3 ->
# 0,1,3,5,7, plus the setupShowNotificationIconCount()V smali widening
# (registers -> 8, extra consts, 5-elem filled-new-array) to match.
NOTIF_ICON_ENTRIES_ARRAY = "notification_icon_counts_entries"
NOTIF_ICON_ENTRIES_ITEM = "<item>@string/display_notification_icon_3</item>"
NOTIF_ICON_ENTRIES_WANT = 3
NOTIF_ICON_VALUES_ARRAY = "notification_icon_counts_values"
NOTIF_ICON_VALUES_ADD = ["5", "7"]
# (target basenames, func). "*.smali" scans every decoded dex dir since the
# owning class (IconDisplayCustomizationSettings) isn't pinned — the method
# name itself is the guard.
NOTIF_COUNT_METHOD_FRAG = "setupShowNotificationIconCount("
KASHI_PRESENTER_OLD = (
'.method private getLineNum()I\n'
' .locals 3\n'
'\n'
' .line 153\n'
' iget-object v0, p0, Lcom/android/settings/device/DeviceBasicInfoPresenter;->mContext:Landroid/content/Context;\n'
'\n'
' invoke-static {v0}, Lcom/android/settings/display/LargeFontUtils;->isLargeFontLevel(Landroid/content/Context;)Z\n'
'\n'
' move-result v0\n'
'\n'
' const/4 v1, 0x1\n'
'\n'
' if-eqz v0, :cond_0\n'
'\n'
' return v1\n'
'\n'
' .line 154\n'
' :cond_0\n'
' iget-boolean v0, p0, Lcom/android/settings/device/DeviceBasicInfoPresenter;->isUseMiui15CardStyle:Z\n'
'\n'
' const/4 v2, 0x2\n'
'\n'
' if-eqz v0, :cond_2\n'
'\n'
' .line 155\n'
' invoke-static {}, Lcom/android/settings/utils/SettingsFeatures;->isSplitTabletDevice()Z\n'
'\n'
' move-result p0\n'
'\n'
' if-eqz p0, :cond_1\n'
'\n'
' return v2\n'
'\n'
' :cond_1\n'
' return v1\n'
'\n'
' .line 157\n'
' :cond_2\n'
' iget-object p0, p0, Lcom/android/settings/device/DeviceBasicInfoPresenter;->mContext:Landroid/content/Context;\n'
'\n'
' invoke-static {p0}, Lcom/android/settings/MiuiUtils;->isLandScape(Landroid/content/Context;)Z\n'
'\n'
' move-result p0\n'
'\n'
' if-eqz p0, :cond_3\n'
'\n'
' invoke-static {}, Lcom/android/settings/utils/SettingsFeatures;->isSplitTabletDevice()Z\n'
'\n'
' move-result p0\n'
'\n'
' if-eqz p0, :cond_3\n'
'\n'
' const/4 p0, 0x3\n'
'\n'
' return p0\n'
'\n'
' :cond_3\n'
' return v2\n'
'.end method\n'
)
KASHI_PRESENTER_NEW = (
'.method private getLineNum()I\n'
' .locals 2\n'
'\n'
' iget-boolean v0, p0, Lcom/android/settings/device/DeviceBasicInfoPresenter;->isUseMiui15CardStyle:Z\n'
'\n'
' const/4 v1, 0x2\n'
'\n'
' if-eqz v0, :cond_0\n'
'\n'
' return v1\n'
'\n'
' :cond_0\n'
' iget-object p0, p0, Lcom/android/settings/device/DeviceBasicInfoPresenter;->mContext:Landroid/content/Context;\n'
'\n'
' invoke-static {p0}, Lcom/android/settings/MiuiUtils;->isLandScape(Landroid/content/Context;)Z\n'
'\n'
' move-result p0\n'
'\n'
' if-eqz p0, :cond_1\n'
'\n'
' invoke-static {}, Lcom/android/settings/utils/SettingsFeatures;->isSplitTabletDevice()Z\n'
'\n'
' move-result p0\n'
'\n'
' if-eqz p0, :cond_1\n'
'\n'
' const/4 v1, 0x3\n'
'\n'
' :cond_1\n'
' return v1\n'
'.end method'
)
# Settings.apk kashi "About phone" page merge (always, both modes — the
# reference is the hand-patched warhol Settings): 17 committed files under
# kashi_settings/ (10 smali into the classes12 dex, 6 new res incl. 2 PNGs,
# miui_version_card.xml as a full replacement; public.xml is deliberately
# NOT carried — the rebuild reassigns IDs), wiring edits in 3 device cards
# + DeviceBasicInfoPresenter.getLineNum() + MiuiSettings ALPHA swaps +
# res appends. Validated against the warhol base only: PORT_URL must be
# that firmware, otherwise anchors warn-skip and the merge must be
# re-diffed. Matching resource IDs in the copied smali are proven only by
# the on-device About-page render, never by the build going green.
KASHI_DIR = BASE_DIR / "kashi_settings"
# Basenames that may legitimately appear in the rebuilt APK (new kashi
# resources — layouts/drawables stay individual entries, PNGs too);
# anything else in the entry-set diff still fails fast.
KASHI_EXPECTED_NEW_ENTRIES = frozenset({
"version_card_img_dark.png", "version_card_img_light.png",
"device_info_item_kashi.xml", "storage_info_item_kashi.xml",
"ic_device_name_info.xml", "storage_progress_drawable.xml",
})
# Literal exact-once smali block replaces for the kashi wiring:
# (target basenames, old, new). Applied when old occurs exactly once;
# skipped silently when already applied (new present, old absent);
# anything else warns (usually a firmware drifted from the reference).
KASHI_CARD_REPLACE = [
(["MiuiVersionCard.smali"],
" invoke-virtual {p0}, Lcom/android/settings/device/MiuiVersionCard;->refreshVersionName()V\n"
"\n"
" .line 102\n",
" invoke-virtual {p0}, Lcom/android/settings/device/MiuiVersionCard;->refreshVersionName()V\n"
"\n"
" invoke-static {p0}, Lcom/android/settings/kashi/Utils;->setVersionCardBgElement(Lcom/android/settings/device/MiuiVersionCard;)V\n"
"\n"
" .line 102\n"),
(["MiuiVersionCard.smali"],
" invoke-static {}, Lcom/android/settings/MiuiUtils;->isLiteOrLowDevice()Z\n"
"\n"
" move-result v0\n"
"\n"
" if-nez v0, :cond_2\n",
" invoke-static {}, Lcom/android/settings/MiuiUtils;->isLiteOrLowDevice()Z\n"
"\n"
" move-result v0\n"
"\n"
" const/4 v0, 0x0\n"
"\n"
" if-nez v0, :cond_2\n"),
(["MiuiMemoryCard.smali"],
" const/4 v2, 0x1\n"
"\n"
" invoke-virtual {v0, v1, p0, v2}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;Z)Landroid/view/View;\n",
" const/4 v2, 0x1\n"
"\n"
" invoke-static {p0}, Lcom/android/settings/kashi/Utils;->getStorageLayout(Landroid/widget/FrameLayout;)I\n"
"\n"
" move-result v1\n"
"\n"
" invoke-virtual {v0, v1, p0, v2}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;Z)Landroid/view/View;\n"),
(["MiuiDeviceNameCard.smali"],
" const/4 v2, 0x1\n"
"\n"
" invoke-virtual {v0, v1, p0, v2}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;Z)Landroid/view/View;\n",
" const/4 v2, 0x1\n"
"\n"
" invoke-static {p0}, Lcom/android/settings/kashi/Utils;->getDeviceLayout(Landroid/widget/FrameLayout;)I\n"
"\n"
" move-result v1\n"
"\n"
" invoke-virtual {v0, v1, p0, v2}, Landroid/view/LayoutInflater;->inflate(ILandroid/view/ViewGroup;Z)Landroid/view/View;\n"),
]
# MiuiSettings ALPHA swaps (IS_INTERNATIONAL_BUILD -> IS_ALPHA_BUILD at the
# reference sites only — the other 8 occurrences in the file stay): each
# old block carries its R$id context, so same-shaped blocks for other
# preferences never match.
KASHI_ALPHA_REPLACE = [
(["MiuiSettings.smali"],
" sget-boolean p2, Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z\n",
" sget-boolean p2, Lmiui/os/Build;->IS_ALPHA_BUILD:Z\n"),
(["MiuiSettings.smali"],
" sget-boolean v10, Lcom/android/settings/utils/SettingsFeatures;->IS_NEED_REMOVE_THEME:Z\n"
"\n"
" if-nez v10, :cond_b\n"
"\n"
" sget-boolean v10, Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z\n"
"\n"
" if-eqz v10, :cond_b\n",
" sget-boolean v10, Lcom/android/settings/utils/SettingsFeatures;->IS_NEED_REMOVE_THEME:Z\n"
"\n"
" if-nez v10, :cond_b\n"
"\n"
" sget-boolean v10, Lmiui/os/Build;->IS_ALPHA_BUILD:Z\n"
"\n"
" if-eqz v10, :cond_b\n"),
(["MiuiSettings.smali"],
" sget v10, Lcom/android/settings/R$id;->wallpaper_settings:I\n"
"\n"
" if-ne v9, v10, :cond_a\n"
"\n"
" if-nez v3, :cond_8\n"
"\n"
" .line 1051\n"
" sget-boolean v10, Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z\n"
"\n"
" if-eqz v10, :cond_8\n",
" sget v10, Lcom/android/settings/R$id;->wallpaper_settings:I\n"
"\n"
" if-ne v9, v10, :cond_a\n"
"\n"
" if-nez v3, :cond_8\n"
"\n"
" .line 1051\n"
" sget-boolean v10, Lmiui/os/Build;->IS_ALPHA_BUILD:Z\n"
"\n"
" if-eqz v10, :cond_8\n"),
(["MiuiSettings.smali"],
" sget v10, Lcom/android/settings/R$id;->security_status:I\n"
"\n"
" if-ne v9, v10, :cond_15\n"
"\n"
" .line 1085\n"
" sget-boolean v10, Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z\n"
"\n"
" if-nez v10, :cond_14\n",
" sget v10, Lcom/android/settings/R$id;->security_status:I\n"
"\n"
" if-ne v9, v10, :cond_15\n"
"\n"
" .line 1085\n"
" sget-boolean v10, Lmiui/os/Build;->IS_ALPHA_BUILD:Z\n"
"\n"
" if-nez v10, :cond_14\n"),
(["MiuiSettings.smali"],
" sget v10, Lcom/android/settings/R$id;->privacy_protection_settings:I\n"
"\n"
" if-ne v9, v10, :cond_36\n"
"\n"
" .line 1206\n"
" sget-boolean v10, Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z\n"
"\n"
" if-nez v10, :cond_35\n",
" sget v10, Lcom/android/settings/R$id;->privacy_protection_settings:I\n"
"\n"
" if-ne v9, v10, :cond_36\n"
"\n"
" .line 1206\n"
" sget-boolean v10, Lmiui/os/Build;->IS_ALPHA_BUILD:Z\n"
"\n"
" if-nez v10, :cond_35\n"),
(["MiuiSettings.smali"],
" sget v10, Lcom/android/settings/R$id;->personalize_title:I\n"
"\n"
" if-ne v9, v10, :cond_38\n"
"\n"
" sget-boolean v10, Lmiui/os/Build;->IS_INTERNATIONAL_BUILD:Z\n"
"\n"
" if-nez v10, :cond_37\n",
" sget v10, Lcom/android/settings/R$id;->personalize_title:I\n"
"\n"
" if-ne v9, v10, :cond_38\n"
"\n"
" sget-boolean v10, Lmiui/os/Build;->IS_ALPHA_BUILD:Z\n"
"\n"
" if-nez v10, :cond_37\n"),
(["MiuiSettings.smali"],
" sget-boolean v10, Lmiui/os/Build;->IS_GLOBAL_BUILD:Z\n"
"\n"
" if-nez v10, :cond_44\n",
" sget-boolean v10, Lmiui/os/Build;->IS_GLOBAL_BUILD:Z\n"
"\n"
" const/4 v10, 0x0\n"
"\n"
" if-nez v10, :cond_44\n"),
]
# Resource appends (glob, full lines incl. indent): inserted before
# </resources> when the name="..." is absent (order is irrelevant —
# aapt sorts the table, so appended position never affects IDs).
KASHI_RES_APPENDS = [
("values/colors.xml", [
' <color name="bw">#ff000000</color>',
' <color name="storage_progress_bg">#11000000</color>',
]),
("values-night/colors.xml", [
' <color name="bw">#ffffff</color>',
' <color name="storage_progress_bg">#33ffffff</color>',
]),
("values/ids.xml", [
' <id name="storage_progress_kchi" />',
' <id name="device_info_version_card_bg" />',
' <id name="device_name_in_banner" />',
]),
]
def _append_missing_xml_items(text: str, items) -> tuple:
"""Insert full-line XML items before </resources> when their name="..."
is absent (order is irrelevant — aapt sorts the table, so appended
position never affects IDs). Returns (new_text, added)."""
if "</resources>" not in text:
return text, 0
have = set()
for line in text.splitlines():
m = re.search(r'name="([^"]+)"', line)
if m:
have.add(m.group(1))
missing = [ln for ln in items
if re.search(r'name="([^"]+)"', ln).group(1) not in have]
if not missing:
return text, 0
new_text = text.replace("</resources>",
"\n".join(missing) + "\n</resources>")
return new_text, len(missing)
def apply_kashi_overlay(work_root: Path, dex_dirs: list) -> None:
"""Merge the committed kashi_settings/ overlay into an apktool-decoded
Settings tree: new smali into the classes12 dex dir (located by its
vendor/.../misys content), new/overwritten res into res/ (public.xml
is deliberately NOT carried — the rebuild reassigns IDs), wiring +
ALPHA smali block replaces (exact-once or warn-skip), and res appends.
Missing sources only warn."""
if not KASHI_DIR.is_dir():
print(f" [warn] kashi overlay not found: {KASHI_DIR}, skip")
return
print("=== Applying kashi Settings overlay ===")
# 1. new smali into the classes12 dex dir
dex_target = next(
(d for d in dex_dirs if (d / "vendor/xiaomi/hardware/misys").is_dir()),
None)
if dex_target is None:
print(" [warn] classes12 dex dir not found, skip kashi smali")
else:
smali_src = KASHI_DIR / "smali_classes12"
copied = 0
for src in sorted(smali_src.rglob("*.smali")):
dest = dex_target / src.relative_to(smali_src)
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
copied += 1
print(f" copied {copied} kashi smali files into {dex_target.name}/")
# 2. new/overwritten res into res/ (miui_version_card.xml included:
# full replacement rides the same overwrite copy)
res_root = work_root / "res"
if not res_root.is_dir():
print(" [warn] decoded res/ not found, skip kashi res")
res_root = None
else:
res_src = KASHI_DIR / "res"
copied = 0
for src in sorted(res_src.rglob("*")):
if src.is_dir() or src.is_symlink() or not src.is_file():
continue
# kashi_public.xml (ID pinning) is deliberately NOT carried:
# pinned IDs clash with the stock table whenever the port
# firmware changes (aapt2: "entry ID is already assigned",
# proven on chagall 4.0.0.11). The stock public.xml keeps every
# stock ID pinned (R-class consts in the dex stay valid) and
# aapt2 auto-assigns the new kashi resources into free slots —
# no smali in the overlay hardcodes 0x7f values, so any
# assignment works.
if src.name == "kashi_public.xml":
continue
dest = res_root / src.relative_to(res_src)
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
copied += 1
print(f" copied {copied} kashi res files into res/ "
f"(kashi IDs auto-assigned)")
# 3. wiring + ALPHA + Presenter smali block replaces (exact-once).
for basenames, old, new in KASHI_CARD_REPLACE + KASHI_ALPHA_REPLACE + [
(["DeviceBasicInfoPresenter.smali"],
KASHI_PRESENTER_OLD, KASHI_PRESENTER_NEW)]:
for base_name in basenames:
found = [p for d in dex_dirs for p in d.rglob(base_name)]
if not found:
print(f" [warn] {base_name} not found in any dex")
continue
for path in found:
text = path.read_text()
if old not in text and new in text:
continue # already applied
if text.count(old) != 1:
print(f" [warn] kashi anchor x{text.count(old)} in "
f"{path.relative_to(work_root)}, skip")
continue
path.write_text(text.replace(old, new))
print(f" patched {path.name}: kashi block")
# 4. res appends (colors/night-colors/ids)
if res_root is not None:
for glob, items in KASHI_RES_APPENDS:
total = 0
for path in sorted(work_root.rglob(glob)):
if not path.is_file() or path.is_symlink():
continue
try:
text = path.read_text()
except (UnicodeDecodeError, OSError):
continue
new_text, added = _append_missing_xml_items(text, items)
if not added:
continue
path.write_text(new_text)
print(f" patched {path.relative_to(work_root)}: +{added} res item(s)")
total += added
if not total: