-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbuild.sh
More file actions
executable file
·1373 lines (1196 loc) · 48.9 KB
/
build.sh
File metadata and controls
executable file
·1373 lines (1196 loc) · 48.9 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 bash
#===============================================================================
# Figma Desktop Linux Build Script
# Repackages Figma Desktop (Electron app) for Linux
# Based on claude-desktop-debian architecture
#===============================================================================
# Global variables (set by functions, used throughout)
architecture=''
distro_family='' # debian, rpm, or unknown
figma_download_url=''
figma_exe_filename='FigmaSetup.exe'
version=''
build_format='' # Will be set based on distro if not specified
cleanup_action='yes'
perform_cleanup=false
local_exe_path=''
original_user=''
original_home=''
project_root=''
work_dir=''
app_staging_dir=''
chosen_electron_module_path=''
asar_exec=''
figma_extract_dir=''
electron_resources_dest=''
final_output_path=''
# Package metadata (constants)
readonly PACKAGE_NAME='figma-desktop'
readonly MAINTAINER='Figma Desktop Linux Maintainers'
readonly DESCRIPTION='Figma Desktop for Linux'
# Figma download URLs
readonly FIGMA_RELEASES_URL='https://desktop.figma.com/win/RELEASES'
readonly FIGMA_EXE_URL='https://desktop.figma.com/win/FigmaSetup.exe'
#===============================================================================
# Utility Functions
#===============================================================================
check_command() {
if ! command -v "$1" &> /dev/null; then
echo "$1 not found"
return 1
else
echo "$1 found"
return 0
fi
}
section_header() {
echo -e "\033[1;36m--- $1 ---\033[0m"
}
section_footer() {
echo -e "\033[1;36m--- End $1 ---\033[0m"
}
#===============================================================================
# Setup Functions
#===============================================================================
detect_architecture() {
section_header 'Architecture Detection'
echo 'Detecting system architecture...'
local raw_arch
raw_arch=$(uname -m) || {
echo 'Failed to detect architecture' >&2
exit 1
}
echo "Detected machine architecture: $raw_arch"
case "$raw_arch" in
x86_64)
architecture='amd64'
echo 'Configured for amd64 (x86_64) build.'
;;
*)
echo "Unsupported architecture: $raw_arch. Figma Desktop Windows installer is only available for x86_64." >&2
exit 1
;;
esac
echo "Target Architecture: $architecture"
section_footer 'Architecture Detection'
}
detect_distro() {
section_header 'Distribution Detection'
echo 'Detecting Linux distribution family...'
if [[ -f /etc/debian_version ]]; then
distro_family='debian'
echo "Detected Debian-based distribution"
elif [[ -f /etc/fedora-release ]]; then
distro_family='rpm'
echo "Detected Fedora"
elif [[ -f /etc/redhat-release ]]; then
distro_family='rpm'
echo "Detected Red Hat-based distribution"
else
distro_family='unknown'
echo "Warning: Could not detect distribution family"
echo " AppImage build will still work, but native packages (deb/rpm) may not"
fi
echo "Distribution: $(grep 'PRETTY_NAME' /etc/os-release 2>/dev/null | cut -d'"' -f2 || echo 'Unknown')"
echo "Distribution family: $distro_family"
section_footer 'Distribution Detection'
}
check_system_requirements() {
# Allow running as root in CI/container environments
if (( EUID == 0 )); then
if [[ -n ${CI:-} || -n ${GITHUB_ACTIONS:-} || -f /.dockerenv ]]; then
echo 'Running as root in CI/container environment (allowed)'
else
echo 'This script should not be run using sudo or as the root user.' >&2
echo 'It will prompt for sudo password when needed for specific actions.' >&2
echo 'Please run as a normal user.' >&2
exit 1
fi
fi
original_user=$(whoami)
original_home=$(getent passwd "$original_user" | cut -d: -f6)
if [[ -z $original_home ]]; then
echo "Could not determine home directory for user $original_user." >&2
exit 1
fi
echo "Running as user: $original_user (Home: $original_home)"
# Check for NVM and source it if found
if [[ -d $original_home/.nvm ]]; then
echo "Found NVM installation for user $original_user, checking for Node.js 20+..."
export NVM_DIR="$original_home/.nvm"
if [[ -s $NVM_DIR/nvm.sh ]]; then
# shellcheck disable=SC1091
\. "$NVM_DIR/nvm.sh"
local node_bin_path=''
node_bin_path=$(nvm which current | xargs dirname 2>/dev/null || \
find "$NVM_DIR/versions/node" -maxdepth 2 -type d -name 'bin' | sort -V | tail -n 1)
if [[ -n $node_bin_path && -d $node_bin_path ]]; then
echo "Adding NVM Node bin path to PATH: $node_bin_path"
export PATH="$node_bin_path:$PATH"
else
echo 'Warning: Could not determine NVM Node bin path.'
fi
else
echo 'Warning: nvm.sh script not found or not sourceable.'
fi
fi
echo 'System Information:'
echo "Distribution: $(grep 'PRETTY_NAME' /etc/os-release 2>/dev/null | cut -d'"' -f2 || echo 'Unknown')"
echo "Distribution family: $distro_family"
echo "Target Architecture: $architecture"
}
parse_arguments() {
section_header 'Argument Parsing'
project_root="$(pwd)"
work_dir="$project_root/build"
app_staging_dir="$work_dir/electron-app"
# Set default build format based on detected distro
case "$distro_family" in
debian) build_format='deb' ;;
rpm) build_format='rpm' ;;
*) build_format='appimage' ;;
esac
while (( $# > 0 )); do
case "$1" in
-b|--build|-c|--clean|-e|--exe)
if [[ -z ${2:-} || $2 == -* ]]; then
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
case "$1" in
-b|--build) build_format="$2" ;;
-c|--clean) cleanup_action="$2" ;;
-e|--exe) local_exe_path="$2" ;;
esac
shift 2
;;
-h|--help)
echo "Usage: $0 [--build deb|rpm|appimage] [--clean yes|no] [--exe /path/to/FigmaSetup.exe]"
echo ' --build: Specify the build format (deb, rpm, or appimage).'
echo " Default: auto-detected based on distro (current: $build_format)"
echo ' --clean: Specify whether to clean intermediate build files (yes or no). Default: yes'
echo ' --exe: Use a local Figma installer exe instead of downloading'
exit 0
;;
*)
echo "Unknown option: $1" >&2
echo 'Use -h or --help for usage information.' >&2
exit 1
;;
esac
done
# Validate arguments
build_format="${build_format,,}"
cleanup_action="${cleanup_action,,}"
if [[ $build_format != 'deb' && $build_format != 'rpm' && $build_format != 'appimage' ]]; then
echo "Invalid build format specified: '$build_format'. Must be 'deb', 'rpm', or 'appimage'." >&2
exit 1
fi
# Warn if building native package for wrong distro
if [[ $build_format == 'deb' && $distro_family != 'debian' ]]; then
echo "Warning: Building .deb package on non-Debian system ($distro_family). This may fail." >&2
elif [[ $build_format == 'rpm' && $distro_family != 'rpm' ]]; then
echo "Warning: Building .rpm package on non-RPM system ($distro_family). This may fail." >&2
fi
if [[ $cleanup_action != 'yes' && $cleanup_action != 'no' ]]; then
echo "Invalid cleanup option specified: '$cleanup_action'. Must be 'yes' or 'no'." >&2
exit 1
fi
echo "Selected build format: $build_format"
echo "Cleanup intermediate files: $cleanup_action"
[[ $cleanup_action == 'yes' ]] && perform_cleanup=true
section_footer 'Argument Parsing'
}
check_dependencies() {
echo 'Checking dependencies...'
local deps_to_install=''
local common_deps='p7zip wget convert'
local all_deps="$common_deps"
# Add format-specific dependencies
case "$build_format" in
deb) all_deps="$all_deps dpkg-deb" ;;
rpm) all_deps="$all_deps rpmbuild" ;;
esac
# Command-to-package mappings per distro family
declare -A debian_pkgs=(
[p7zip]='p7zip-full' [wget]='wget'
[convert]='imagemagick'
[dpkg-deb]='dpkg-dev' [rpmbuild]='rpm'
)
declare -A rpm_pkgs=(
[p7zip]='p7zip p7zip-plugins' [wget]='wget'
[convert]='ImageMagick'
[dpkg-deb]='dpkg' [rpmbuild]='rpm-build'
)
local cmd
for cmd in $all_deps; do
if ! check_command "$cmd"; then
case "$distro_family" in
debian)
deps_to_install="$deps_to_install ${debian_pkgs[$cmd]}"
;;
rpm)
deps_to_install="$deps_to_install ${rpm_pkgs[$cmd]}"
;;
*)
echo "Warning: Cannot auto-install '$cmd' on unknown distro. Please install manually." >&2
;;
esac
fi
done
if [[ -n $deps_to_install ]]; then
echo "System dependencies needed:$deps_to_install"
# Determine if we need sudo (skip if already root)
local sudo_cmd='sudo'
if (( EUID == 0 )); then
sudo_cmd=''
echo 'Installing as root (no sudo needed)...'
else
echo 'Attempting to install using sudo...'
if ! sudo -v; then
echo 'Failed to validate sudo credentials. Please ensure you can run sudo.' >&2
exit 1
fi
fi
case "$distro_family" in
debian)
if ! $sudo_cmd apt update; then
echo "Failed to run 'apt update'." >&2
exit 1
fi
# shellcheck disable=SC2086
if ! $sudo_cmd apt install -y $deps_to_install; then
echo "Failed to install dependencies using 'apt install'." >&2
exit 1
fi
;;
rpm)
# shellcheck disable=SC2086
if ! $sudo_cmd dnf install -y $deps_to_install; then
echo "Failed to install dependencies using 'dnf install'." >&2
exit 1
fi
;;
*)
echo "Cannot auto-install dependencies on unknown distro." >&2
echo "Please install these packages manually: $deps_to_install" >&2
exit 1
;;
esac
echo 'System dependencies installed successfully.'
fi
}
setup_work_directory() {
rm -rf "$work_dir"
mkdir -p "$work_dir" || exit 1
mkdir -p "$app_staging_dir" || exit 1
}
setup_nodejs() {
section_header 'Node.js Setup'
echo 'Checking Node.js version...'
local node_version_ok=false
if command -v node &> /dev/null; then
local node_version node_major
node_version=$(node --version | cut -d'v' -f2)
node_major="${node_version%%.*}"
echo "System Node.js version: v$node_version"
if (( node_major >= 20 )); then
echo "System Node.js version is adequate (v$node_version)"
node_version_ok=true
else
echo "System Node.js version is too old (v$node_version). Need v20+"
fi
else
echo 'Node.js not found in system'
fi
if [[ $node_version_ok == true ]]; then
section_footer 'Node.js Setup'
return 0
fi
# Node.js version inadequate - install locally
echo 'Installing Node.js v20 locally in build directory...'
local node_arch='x64'
local node_version_to_install='20.18.1'
local node_tarball="node-v${node_version_to_install}-linux-${node_arch}.tar.xz"
local node_url="https://nodejs.org/dist/v${node_version_to_install}/${node_tarball}"
local node_install_dir="$work_dir/node"
echo "Downloading Node.js v${node_version_to_install} for ${node_arch}..."
cd "$work_dir" || exit 1
if ! wget -O "$node_tarball" "$node_url"; then
echo "Failed to download Node.js from $node_url" >&2
cd "$project_root" || exit 1
exit 1
fi
echo 'Extracting Node.js...'
if ! tar -xf "$node_tarball"; then
echo 'Failed to extract Node.js tarball' >&2
cd "$project_root" || exit 1
exit 1
fi
mv "node-v${node_version_to_install}-linux-${node_arch}" "$node_install_dir" || exit 1
export PATH="$node_install_dir/bin:$PATH"
if command -v node &> /dev/null; then
echo "Local Node.js installed successfully: $(node --version)"
else
echo 'Failed to install local Node.js' >&2
cd "$project_root" || exit 1
exit 1
fi
rm -f "$node_tarball"
cd "$project_root" || exit 1
section_footer 'Node.js Setup'
}
setup_electron_asar() {
section_header 'Electron & Asar Setup'
echo "Ensuring local Electron and Asar installation in $work_dir..."
cd "$work_dir" || exit 1
if [[ ! -f package.json ]]; then
echo "Creating temporary package.json in $work_dir for local install..."
echo '{"name":"figma-desktop-build","version":"0.0.1","private":true}' > package.json
fi
local electron_dist_path="$work_dir/node_modules/electron/dist"
local asar_bin_path="$work_dir/node_modules/.bin/asar"
local install_needed=false
[[ ! -d $electron_dist_path ]] && echo 'Electron distribution not found.' && install_needed=true
[[ ! -f $asar_bin_path ]] && echo 'Asar binary not found.' && install_needed=true
if [[ $install_needed == true ]]; then
echo "Installing Electron and Asar locally into $work_dir..."
if ! npm install --no-save electron @electron/asar; then
echo 'Failed to install Electron and/or Asar locally.' >&2
cd "$project_root" || exit 1
exit 1
fi
echo 'Electron and Asar installation command finished.'
else
echo 'Local Electron distribution and Asar binary already present.'
fi
if [[ -d $electron_dist_path ]]; then
echo "Found Electron distribution directory at $electron_dist_path."
chosen_electron_module_path="$(realpath "$work_dir/node_modules/electron")"
echo "Setting Electron module path for copying to $chosen_electron_module_path."
else
echo "Failed to find Electron distribution directory at '$electron_dist_path' after installation attempt." >&2
cd "$project_root" || exit 1
exit 1
fi
if [[ -f $asar_bin_path ]]; then
asar_exec="$(realpath "$asar_bin_path")"
echo "Found local Asar binary at $asar_exec."
else
echo "Failed to find Asar binary at '$asar_bin_path' after installation attempt." >&2
cd "$project_root" || exit 1
exit 1
fi
cd "$project_root" || exit 1
if [[ -z $chosen_electron_module_path || ! -d $chosen_electron_module_path ]]; then
echo 'Critical error: Could not resolve a valid Electron module path to copy.' >&2
exit 1
fi
echo "Using Electron module path: $chosen_electron_module_path"
echo "Using asar executable: $asar_exec"
section_footer 'Electron & Asar Setup'
}
#===============================================================================
# Download and Extract Functions
#===============================================================================
resolve_figma_version() {
section_header 'Resolving Figma Version'
echo 'Fetching latest Figma Desktop version from RELEASES API...'
local releases_data
releases_data=$(curl -s -L -H 'User-Agent: Figma/1 (Windows; x64)' "$FIGMA_RELEASES_URL")
if [[ -z $releases_data ]]; then
echo 'Failed to fetch Figma RELEASES data' >&2
exit 1
fi
local nupkg_name
nupkg_name=$(echo "$releases_data" | awk '{print $2}')
version=$(echo "$nupkg_name" | sed 's/Figma-\(.*\)-full\.nupkg/\1/')
if [[ -z $version ]]; then
echo 'Failed to extract version from RELEASES data' >&2
exit 1
fi
figma_download_url="$FIGMA_EXE_URL"
echo "Latest Figma version: $version"
echo "Download URL: $figma_download_url"
section_footer 'Resolving Figma Version'
}
download_figma_installer() {
section_header 'Download Figma Installer'
local figma_exe_path="$work_dir/$figma_exe_filename"
if [[ -n $local_exe_path ]]; then
echo "Using local Figma installer: $local_exe_path"
if [[ ! -f $local_exe_path ]]; then
echo "Local installer file not found: $local_exe_path" >&2
exit 1
fi
cp "$local_exe_path" "$figma_exe_path" || exit 1
echo 'Local installer copied to build directory'
else
echo "Downloading Figma Desktop installer..."
if ! wget -O "$figma_exe_path" "$figma_download_url"; then
echo "Failed to download Figma Desktop installer from $figma_download_url" >&2
exit 1
fi
echo "Download complete: $figma_exe_filename"
fi
echo "Extracting resources from $figma_exe_filename..."
figma_extract_dir="$work_dir/figma-extract"
mkdir -p "$figma_extract_dir" || exit 1
if ! 7z x -y "$figma_exe_path" -o"$figma_extract_dir"; then
echo 'Failed to extract installer' >&2
exit 1
fi
cd "$figma_extract_dir" || exit 1
local nupkg_path_relative
nupkg_path_relative=$(find . -maxdepth 1 -name 'Figma-*.nupkg' | head -1)
if [[ -z $nupkg_path_relative ]]; then
echo "Could not find Figma nupkg file in $figma_extract_dir" >&2
cd "$project_root" || exit 1
exit 1
fi
echo "Found nupkg: $nupkg_path_relative (in $figma_extract_dir)"
# Extract version from nupkg filename (e.g., Figma-126.1.2-full.nupkg)
local nupkg_version
nupkg_version=$(echo "$nupkg_path_relative" | LC_ALL=C grep -oP 'Figma-\K[0-9]+\.[0-9]+\.[0-9]+(?=-full)')
if [[ -n $nupkg_version ]]; then
version="$nupkg_version"
echo "Version from nupkg: $version"
fi
if ! 7z x -y "$nupkg_path_relative"; then
echo 'Failed to extract nupkg' >&2
cd "$project_root" || exit 1
exit 1
fi
echo 'Resources extracted from nupkg'
cd "$project_root" || exit 1
section_footer 'Download Figma Installer'
}
#===============================================================================
# Patching Functions
#===============================================================================
extract_app_asar() {
section_header 'Extracting app.asar'
echo 'Processing app.asar...'
local asar_source="$figma_extract_dir/lib/net45/resources/app.asar"
local unpacked_source="$figma_extract_dir/lib/net45/resources/app.asar.unpacked"
if [[ ! -f $asar_source ]]; then
echo "app.asar not found at $asar_source" >&2
exit 1
fi
cp "$asar_source" "$app_staging_dir/" || exit 1
if [[ -d $unpacked_source ]]; then
cp -a "$unpacked_source" "$app_staging_dir/" || exit 1
fi
cd "$app_staging_dir" || exit 1
# Extract app.asar - use Node.js script to handle Figma's special asar format
# (Figma's asar has entries with size=-1000 that crash standard extraction)
echo 'Extracting app.asar contents (handling Figma-specific format)...'
node -e "
const asar = require('@electron/asar');
const fs = require('fs');
const path = require('path');
const asarPath = 'app.asar';
const outDir = 'app.asar.contents';
const header = JSON.parse(asar.getRawHeader(asarPath).headerString);
function walk(obj, prefix) {
const results = [];
if (obj.files) {
for (const [name, data] of Object.entries(obj.files)) {
const fullPath = prefix + '/' + name;
if (data.files) {
results.push(...walk(data, fullPath));
} else {
results.push({ path: fullPath, size: data.size, offset: data.offset, unpacked: !!data.unpacked });
}
}
}
return results;
}
const files = walk(header, '');
fs.mkdirSync(outDir, { recursive: true });
const asarBuf = fs.readFileSync(asarPath);
const headerBufSize = asarBuf.readUInt32LE(4);
const dataStart = 8 + headerBufSize;
let extracted = 0, skipped = 0;
for (const f of files) {
const outPath = path.join(outDir, f.path);
fs.mkdirSync(path.dirname(outPath), { recursive: true });
if (f.unpacked || f.size < 0 || f.offset === undefined) {
skipped++;
continue;
}
try {
const buf = Buffer.alloc(f.size);
const fileOffset = parseInt(f.offset);
asarBuf.copy(buf, 0, dataStart + fileOffset, dataStart + fileOffset + f.size);
fs.writeFileSync(outPath, buf);
extracted++;
} catch(e) {
console.error('Failed to extract:', f.path, e.message);
}
}
console.log('Extracted: ' + extracted + ' files, Skipped: ' + skipped + ' (unpacked/special)');
" || exit 1
echo 'app.asar extraction complete'
cd "$project_root" || exit 1
section_footer 'Extracting app.asar'
}
patch_app_asar() {
section_header 'Patching app.asar'
cd "$app_staging_dir" || exit 1
# ---- Frame fix wrapper ----
echo 'Creating BrowserWindow frame fix wrapper...'
local original_main
original_main=$(node -e "const pkg = require('./app.asar.contents/package.json'); console.log(pkg.main);")
echo "Original main entry: $original_main"
cp "$project_root/scripts/frame-fix-wrapper.js" app.asar.contents/frame-fix-wrapper.js || exit 1
cat > app.asar.contents/frame-fix-entry.js << EOFENTRY
// Load frame fix first
require('./frame-fix-wrapper.js');
// Then load original main
require('./${original_main}');
EOFENTRY
# ---- Patch BrowserWindow creation in main.js ----
echo 'Patching BrowserWindow creation for native frames...'
local main_js='app.asar.contents/main.js'
if [[ -f $main_js ]]; then
# frame:!1 -> frame:true (minified false)
sed -i 's/frame:!1/frame:true/g' "$main_js"
# frame:!0 -> frame:true (minified true with NOT, i.e. false)
sed -i 's/frame:!0/frame:true/g' "$main_js"
# frame:false -> frame:true
sed -i 's/frame[[:space:]]*:[[:space:]]*false/frame:true/g' "$main_js"
# Remove titleBarStyle:"hidden"
sed -i 's/titleBarStyle:"hidden"/titleBarStyle:"default"/g' "$main_js"
echo "Patched $main_js for native frames"
# ---- Patch openFile to allow duplicate tabs (with tray toggle + persistent state) ----
# Adds a toggle to tray menu that persists across restarts using Figma's
# built-in settings system (H() to read, Me() to write).
echo 'Patching openFile IPC for duplicate tabs with persistent tray toggle...'
node -e "
const fs = require('fs');
let code = fs.readFileSync('$main_js', 'utf8');
let patched = 0;
// 1) Add allowDuplicateTabs:!1 to the default state object (next to showFigmaInMenuBar:!0)
// Pattern is stable — 'showFigmaInMenuBar:!0' is a property name, not a variable
if (code.includes('showFigmaInMenuBar:!0,allowDuplicateTabs:!1')) {
console.log('1/5: allowDuplicateTabs already in default state');
patched++;
} else if (code.includes('showFigmaInMenuBar:!0')) {
code = code.replace('showFigmaInMenuBar:!0', 'showFigmaInMenuBar:!0,allowDuplicateTabs:!1');
patched++;
} else {
console.error('Warning: default state pattern not found');
}
// 2) Add state restore validation (next to showFigmaInMenuBar restore)
// Regex: \"showFigmaInMenuBar\"in VAR&&typeof VAR.showFigmaInMenuBar==\"boolean\"&&(STATE.showFigmaInMenuBar=VAR.showFigmaInMenuBar)
const restorePattern = /\"showFigmaInMenuBar\"in (\w+)&&typeof \1\.showFigmaInMenuBar==\"boolean\"&&\((\w+)\.showFigmaInMenuBar=\1\.showFigmaInMenuBar\)/;
const restoreMatch = code.match(restorePattern);
if (restoreMatch) {
const [fullMatch, inputVar, stateVar] = restoreMatch;
if (code.includes(stateVar + '.allowDuplicateTabs=' + inputVar + '.allowDuplicateTabs')) {
console.log('2/5: allowDuplicateTabs restore already present');
patched++;
} else {
const restoreAdd = ',\"allowDuplicateTabs\"in ' + inputVar + '&&typeof ' + inputVar + '.allowDuplicateTabs==\"boolean\"&&(' + stateVar + '.allowDuplicateTabs=' + inputVar + '.allowDuplicateTabs)';
code = code.replace(fullMatch, fullMatch + restoreAdd);
patched++;
}
} else {
console.error('Warning: state restore pattern not found');
}
// 3) Patch openFileTab default parameter to read from persistent state
// Regex: allowDuplicateTab:VAR=!1 (VAR is any minified name)
// Also find the settings getter function: look for se().showFigmaInMenuBar pattern
const getterMatch = code.match(/(\w+)\(\)\.showFigmaInMenuBar/);
const getterFn = getterMatch ? getterMatch[1] : null;
const defaultPattern = /allowDuplicateTab:(\w+)=!1/;
const defaultMatch = code.match(defaultPattern);
if (defaultMatch && getterFn) {
const [fullMatch, varName] = defaultMatch;
const newDefault = 'allowDuplicateTab:' + varName + '=(typeof ' + getterFn + '===\"function\"?' + getterFn + '().allowDuplicateTabs:!1)';
code = code.replace(fullMatch, newDefault);
patched++;
} else {
console.error('Warning: openFileTab default parameter pattern not found (defaultMatch:', !!defaultMatch, 'getterFn:', getterFn, ')');
}
// Find the settings setter function: look for pt({showFigmaInMenuBar:...}) pattern
const setterMatch = code.match(/(\w+)\(\{showFigmaInMenuBar:\w+\.checked\}\)/);
const setterFn = setterMatch ? setterMatch[1] : null;
// 4) Add toggle checkbox to tray context menu using persistent state
// Regex: FN1(),FN2(),FN3(),FN4({inTrayContextMenu:!0})
const trayPattern = /(\w+\(\),\w+\(\),\w+\(\)),(\w+)\(\{inTrayContextMenu:!0\}\)/;
const trayMatch = code.match(trayPattern);
if (trayMatch && getterFn && setterFn) {
const [fullMatch, prefix, lastFn] = trayMatch;
if (fullMatch.includes('Allow Duplicate Tabs')) {
console.log('4/5: tray menu toggle already present');
patched++;
} else {
const toggle = ',{label:\"Allow Duplicate Tabs\",type:\"checkbox\",checked:' + getterFn + '().allowDuplicateTabs,click(n){' + setterFn + '({allowDuplicateTabs:n.checked})}}';
code = code.replace(fullMatch, prefix + toggle + ',' + lastFn + '({inTrayContextMenu:!0})');
patched++;
}
} else {
console.error('Warning: tray menu pattern not found (trayMatch:', !!trayMatch, 'getterFn:', getterFn, 'setterFn:', setterFn, ')');
}
// 5) Add 'Show App' button to tray context menu (after Allow Duplicate Tabs)
// Find the anchor: end of Allow Duplicate Tabs entry followed by the settings/quit function
// Pattern: }},FNLAST({inTrayContextMenu:!0}) — we insert Show App between them
const wmMatch = code.match(/(\w+)\.lastFocusedWindow\(\)/);
const wmVar = wmMatch ? wmMatch[1] : null;
const showAppAnchor = /\}\},(\w+)\(\{inTrayContextMenu:!0\}\)/;
const showAppMatch = code.match(showAppAnchor);
if (wmVar && showAppMatch && !code.includes('Show App')) {
const [anchorStr, lastFn] = showAppMatch;
const showApp = '}},{label:\"Show App\",click(){let w=' + wmVar + '.lastFocusedWindow();w?w.makeVisible():' + wmVar + '.createOrRestoreNewWindow()}},' + lastFn + '({inTrayContextMenu:!0})';
code = code.replace(anchorStr, showApp);
console.log('Show App button added to tray menu');
} else if (code.includes('Show App')) {
console.log('Show App already present');
} else {
console.error('Warning: Could not add Show App to tray menu');
}
// 6) Add toggle to Preferences menu
// Regex: function PREFSFN(){let VAR=[SETTINGSFN()]
const prefsPattern = /function (\w+)\(\)\{let (\w+)=\[(\w+)\(\)\]/;
const prefsMatch = code.match(prefsPattern);
if (prefsMatch && getterFn && setterFn) {
const [fullMatch, prefsFn, arrVar, settingsFn] = prefsMatch;
// Verify this is the right function by checking settingsFn matches the one used in tray
if (fullMatch.includes('Allow Duplicate Tabs')) {
console.log('5/5: Preferences menu toggle already present');
patched++;
} else {
const toggle = ',{label:\"Allow Duplicate Tabs\",type:\"checkbox\",checked:' + getterFn + '().allowDuplicateTabs,click(' + arrVar + '){' + setterFn + '({allowDuplicateTabs:' + arrVar + '.checked})}}';
code = code.replace(fullMatch, 'function ' + prefsFn + '(){let ' + arrVar + '=[' + settingsFn + '()' + toggle + ']');
patched++;
}
} else {
console.error('Warning: Preferences menu pattern not found');
}
fs.writeFileSync('$main_js', code);
console.log('Duplicate tabs patch applied (' + patched + '/5 patches)');
"
# ---- Enable Windows-style app menu popup on Linux ----
# The dropdown menu button in the tab bar calls getWindowsAppMenu().popup(),
# but windowsAppMenu is only built when process.platform==="win32".
# Remove the platform gate so the menu is also built on Linux.
sed -i 's|process.platform==="win32"&&(this.windowsAppMenu=|process.platform!=="darwin"\&\&(this.windowsAppMenu=|' "$main_js"
if grep -q 'process.platform!=="darwin"&&(this.windowsAppMenu=' "$main_js"; then
echo "Patched $main_js: app menu popup enabled on Linux"
else
echo "Warning: app menu popup patch did not match in $main_js"
fi
fi
# Also patch desktop_shell.js if it has BrowserWindow references
local shell_js='app.asar.contents/desktop_shell.js'
if [[ -f $shell_js ]]; then
sed -i 's/frame:!1/frame:true/g' "$shell_js"
sed -i 's/frame:!0/frame:true/g' "$shell_js"
# Show the app menu dropdown button AND recents button on Linux.
# These are gated by a variable like tO="win32"===e.platform.
# We change it to tO="darwin"!==e.platform so it's true on Linux.
# The variable name changes between Figma versions, so we match dynamically.
local win32_shell_var
win32_shell_var=$(grep -oP '\b\w{2}="win32"===\w\.platform\b' "$shell_js" | head -1)
if [[ -n $win32_shell_var ]]; then
local var_name=${win32_shell_var%%=*}
local new_val="${var_name}=\"darwin\"!==e.platform"
sed -i "s|${win32_shell_var}|${new_val}|" "$shell_js"
if grep -q "$new_val" "$shell_js"; then
echo "Patched $shell_js: platform check '$var_name' enabled for Linux (menu + recents)"
else
echo "Warning: platform check patch failed in $shell_js"
fi
else
echo "Warning: could not find win32 platform check in $shell_js"
fi
echo "Patched $shell_js"
fi
# Inject CSS to hide Windows caption buttons (minimize/maximize/close)
# but keep the app menu dropdown button visible on Linux
local shell_html='app.asar.contents/shell.html'
if [[ -f $shell_html ]]; then
sed -i 's|</head>|<style>\
#__MINIMIZE_CAPTION_BUTTON__,\
#__MAXIMIZE_CAPTION_BUTTON__,\
#__CLOSE_CAPTION_BUTTON__ { display: none !important; }\
</style>\
</head>|' "$shell_html"
echo "Patched $shell_html: hidden Windows caption buttons via CSS"
fi
# ---- Update package.json ----
echo 'Modifying package.json to load frame fix...'
node -e "
const fs = require('fs');
const pkg = require('./app.asar.contents/package.json');
pkg.originalMain = pkg.main;
pkg.main = 'frame-fix-entry.js';
fs.writeFileSync('./app.asar.contents/package.json', JSON.stringify(pkg, null, 2));
console.log('Updated package.json: main entry set to frame-fix-entry.js');
"
# ---- Create stub native modules ----
echo 'Creating stub native modules...'
# Stub bindings.node - replace the require with our JS stub
cp "$project_root/scripts/figma-native-stub.js" \
app.asar.contents/figma-native-stub.js || exit 1
# Patch main.js to load our stub instead of the native .node files
echo 'Patching native module loading in main.js...'
if [[ -f $main_js ]]; then
# Replace require("./bindings.node") with require("./figma-native-stub.js")
sed -i 's|require("./bindings.node")|require("./figma-native-stub.js")|g' "$main_js"
# Replace require("../build/Debug/bindings.node") with require("./figma-native-stub.js")
sed -i 's|require("../build/Debug/bindings.node")|require("./figma-native-stub.js")|g' "$main_js"
# Replace require("../build/Release/bindings.node") with require("./figma-native-stub.js")
sed -i 's|require("../build/Release/bindings.node")|require("./figma-native-stub.js")|g' "$main_js"
# Replace require("./desktop_rust.node") with require("./figma-native-stub.js").desktop_rust
sed -i 's|require("./desktop_rust.node")|require("./figma-native-stub.js").desktop_rust|g' "$main_js"
# Replace require("../rust/desktop_rust.node") with require("./figma-native-stub.js").desktop_rust
sed -i 's|require("../rust/desktop_rust.node")|require("./figma-native-stub.js").desktop_rust|g' "$main_js"
echo 'Native module loading patched in main.js'
fi
# Also patch bindings_worker.js - runs as a utility process for font enumeration
local worker_js="$app_staging_dir/app.asar.contents/bindings_worker.js"
if [[ -f $worker_js ]]; then
echo 'Patching native module loading in bindings_worker.js...'
sed -i 's|require("./desktop_rust.node")|require("./figma-native-stub.js").desktop_rust|g' "$worker_js"
sed -i 's|require("../rust/desktop_rust.node")|require("./figma-native-stub.js").desktop_rust|g' "$worker_js"
echo 'Native module loading patched in bindings_worker.js'
else
echo 'Warning: bindings_worker.js not found - font utility process may crash'
fi
# ---- Patch handleCommandLineArgs for Linux argv ----
# On Linux, Electron is invoked with CLI flags (--no-sandbox, --disable-features=...)
# before the app.asar path, so process.argv looks like:
# [electron, --no-sandbox, --disable-features=..., app.asar, figma://auth?...]
# But handleCommandLineArgs expects the URL at argv[1] (isPackaged) or argv[2] (dev).
# We patch it to scan all argv entries for a URL or file path instead.
# Uses regex to be resilient to minified variable name changes across Figma versions.
echo 'Patching handleCommandLineArgs for Linux argv layout...'
if [[ -f $main_js ]]; then
node -e "
const fs = require('fs');
let code = fs.readFileSync('$main_js', 'utf8');
// Regex matches the function regardless of minified variable names:
// async handleCommandLineArgs(ARG){let V=MOD.app.isPackaged?1:2;if(ARG.length>V){let A=ARG[V];if(FN(A,{isExternalOpen:!0}))return!0;if(STAT.default.statSync(A,{throwIfNoEntry:!1}))return await OPEN(A)}return!1}
const pattern = /async handleCommandLineArgs\((\w+)\)\{let (\w+)=(\w+)\.app\.isPackaged\?1:2;if\(\1\.length>\2\)\{let (\w+)=\1\[\2\];if\((\w+)\(\4,\{isExternalOpen:!0\}\)\)return!0;if\((\w+)\.default\.statSync\(\4,\{throwIfNoEntry:!1\}\)\)return await (\w+)\(\4\)\}return!1\}/;
const m = code.match(pattern);
if (m) {
const [fullMatch, arg, , , innerVar, urlFn, statMod, openFn] = m;
const replacement = 'async handleCommandLineArgs(' + arg + '){for(let _i=1;_i<' + arg + '.length;_i++){let ' + innerVar + '=' + arg + '[_i];if(' + innerVar + '.startsWith(\"-\")||' + innerVar + '.endsWith(\".asar\")||' + innerVar + '.endsWith(\".js\"))continue;if(' + urlFn + '(' + innerVar + ',{isExternalOpen:!0}))return!0;if(' + statMod + '.default.statSync(' + innerVar + ',{throwIfNoEntry:!1}))return await ' + openFn + '(' + innerVar + ')}return!1}';
code = code.replace(fullMatch, replacement);
fs.writeFileSync('$main_js', code);
console.log('handleCommandLineArgs patched for Linux argv (regex match)');
} else {
console.error('Warning: handleCommandLineArgs pattern not found - Figma may have updated');
console.error('Auth redirect from browser may not work');
process.exit(1);
}
"
fi
# ---- Patch platform detection ----
# Figma checks process.platform==="win32" for many features.
# We do NOT want to pretend to be Windows. Instead, we let it see "linux"
# and handle the cases where it explicitly blocks Linux.
echo 'Patching auto-updater to not block Linux...'
if [[ -f $main_js ]]; then
# The updater has: process.platform==="linux"&&(n="linux")
# which sets n to a string, disabling the updater. We want to keep this behavior
# (no auto-update on Linux is fine) - so we don't need to patch it.
echo 'Auto-updater Linux check preserved (updates disabled on Linux - expected)'
fi
# ---- Patch tray context menu for Linux ----
# On Linux with libappindicator (GNOME, KDE), Electron's 'right-click' event
# on Tray does NOT fire. Figma uses popUpContextMenu() inside a right-click
# handler, which never triggers. Fix: add setContextMenu() right after tray
# creation so appindicator can show the menu natively.
echo 'Patching tray context menu for Linux...'
if [[ -f $main_js ]]; then
node -e "
const fs = require('fs');
let code = fs.readFileSync('$main_js', 'utf8');
// Regex matches tray init regardless of minified variable names:
// this.electronTray.setToolTip(MOD.name),this.electronTray.on(\"right-click\",()=>{var V;(V=this.electronTray)==null||V.popUpContextMenu(MENUFN())})
const pattern = /this\.electronTray\.setToolTip\((\w+)\.name\),this\.electronTray\.on\(\"right-click\",\(\)=>\{var (\w+);\(\2=this\.electronTray\)==null\|\|\2\.popUpContextMenu\((\w+)\(\)\)\}\)/;
const m = code.match(pattern);
if (m) {
const [fullMatch, modName, varName, menuFn] = m;
const replacement = 'this.electronTray.setToolTip(' + modName + '.name),this.electronTray.setContextMenu(' + menuFn + '()),this.electronTray.on(\"right-click\",()=>{var ' + varName + ';(' + varName + '=this.electronTray)==null||' + varName + '.popUpContextMenu(' + menuFn + '())})';
code = code.replace(fullMatch, replacement);
fs.writeFileSync('$main_js', code);
console.log('Tray context menu patched: added setContextMenu() for Linux (regex match)');
} else {
console.error('Warning: Tray context menu pattern not found - Figma may have updated');
console.error('Right-click on tray icon may not show context menu on Linux');
}
"
fi
# ---- Patch tray window: CSS fixes + DevTools debug support ----
# Fix notification dropdown: remove border-radius, fix scroll, and
# when FIGMA_DEBUG=1, open DevTools for the tray notification window.
# Injected directly into main.js (monkey-patch doesn't reach tray window).
echo 'Patching tray notification window (CSS fixes + debug DevTools)...'
if [[ -f $main_js ]]; then
node -e "
const fs = require('fs');
let code = fs.readFileSync('$main_js', 'utf8');
// Regex to match: VAR.setAlwaysOnTop(!0,"pop-up-menu"),VAR.webContents.on("will-navigate"
// The variable name may change across Figma versions
const trayVarPattern = /(\w+)\.setAlwaysOnTop\(!0,"pop-up-menu"\),\1\.webContents\.on\("will-navigate"/;
const trayVarMatch = code.match(trayVarPattern);
const trayVar = trayVarMatch ? trayVarMatch[1] : 't';
const oldPattern = trayVar + '.setAlwaysOnTop(!0,\"pop-up-menu\"),' + trayVar + '.webContents.on(\"will-navigate\"';
// CSS to fix notification dropdown on Linux:
// 1. Remove border-radius on outer container
// 2. Fix scroll: the scrollContainer--E33Ej needs to actually scroll
// 3. Override overflow:hidden on parents that block scrolling
// 4. Disable Figma's JS wheel-event capture that breaks native scroll
const cssCode = \`
[class*=\"desktop_dropdown_container--container\"] {
border-radius: 0 !important;
}
[class*=\"desktop_dropdown_container--notificationContainer\"] {
overflow: visible !important;
}
[class*=\"desktop_dropdown_container--scrollContainer\"] {
overflow-y: auto !important;
overflow-x: hidden !important;
flex: 1 1 0% !important;
min-height: 0 !important;
}
[class*=\"scroll_container--clipContainer\"] {
overflow: visible !important;
height: auto !important;
pointer-events: auto !important;
}
[class*=\"scroll_container--scrollContainer\"] {
overflow: visible !important;
height: auto !important;
}
[class*=\"scroll_container--full\"] {
height: auto !important;
}
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: transparent; }