/
AndroidBuild.java
1718 lines (1457 loc) · 67.7 KB
/
AndroidBuild.java
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
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2012-16 The Processing Foundation
Copyright (c) 2009-12 Ben Fry and Casey Reas
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package processing.mode.android;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import processing.app.Base;
import processing.app.Library;
import processing.app.Messages;
import processing.app.Platform;
import processing.app.Sketch;
import processing.app.SketchException;
import processing.app.Util;
import processing.app.exec.ProcessHelper;
import processing.app.exec.ProcessResult;
import processing.core.PApplet;
import processing.mode.java.JavaBuild;
import processing.mode.java.preproc.SurfaceInfo;
import java.io.*;
import java.util.HashMap;
class AndroidBuild extends JavaBuild {
static public final int FRAGMENT = 0;
static public final int WALLPAPER = 1;
static public final int WATCHFACE = 2;
static public final int CARDBOARD = 3;
static public final String DEFAULT_COMPONENT = "app";
static private final String FRAGMENT_ACTIVITY_TEMPLATE = "FragmentActivity.java.tmpl";
static private final String WALLPAPER_SERVICE_TEMPLATE = "WallpaperService.java.tmpl";
static private final String WATCHFACE_SERVICE_TEMPLATE = "WatchFaceService.java.tmpl";
static private final String CARDBOARD_ACTIVITY_TEMPLATE = "CardboardActivity.java.tmpl";
static private final String HANDHELD_ACTIVITY_TEMPLATE = "HandheldActivity.java.tmpl";
static private final String HANDHELD_MANIFEST_TEMPLATE = "HandheldManifest.xml.tmpl";
static private final String HANDHELD_LAYOUT_TEMPLATE = "HandheldLayout.xml.tmpl";
static private final String WEARABLE_DESCRIPTION_TEMPLATE = "WearableDescription.xml.tmpl";
static private final String LAYOUT_ACTIVITY_TEMPLATE = "LayoutActivity.xml.tmpl";
static private final String STYLES_FRAGMENT_TEMPLATE = "StylesFragment.xml.tmpl";
static private final String STYLES_CARDBOARD_TEMPLATE = "StylesCardboard.xml.tmpl";
static private final String XML_WALLPAPER_TEMPLATE = "XMLWallpaper.xml.tmpl";
static private final String STRINGS_WALLPAPER_TEMPLATE = "StringsWallpaper.xml.tmpl";
static private final String XML_WATCHFACE_TEMPLATE = "XMLWatchFace.xml.tmpl";
static private final String BUILD_TEMPLATE = "Build.xml.tmpl";
// TODO: ask base package name when exporting signed apk
// static final String basePackage = "changethispackage.beforesubmitting.tothemarket";
static final String basePackage = "processing.test";
// Minimum SDK levels required for each app component
// https://source.android.com/source/build-numbers.html
// We should use 17 (4.2) as minimum for fragment and wallpaper at some point,
// once combined usage of all previous versions is falls below 5%:
// http://developer.android.com/about/dashboards/index.html
// because 17 give us getRealSize and getRealMetrics:
// http://developer.android.com/reference/android/view/Display.html#getRealSize(android.graphics.Point)
// http://developer.android.com/reference/android/view/Display.html#getRealMetrics(android.util.DisplayMetrics)
// which allows us to exactly determine the size of the screen.
static public final String min_sdk_fragment = "16"; // Jelly Bean (4.1)
static public final String min_sdk_wallpaper = "16"; //
static public final String min_sdk_cardboard = "19"; // KitKat (4.4)
static public final String min_sdk_watchface = "21"; // Lollipop (5.0)
// Hard-coded target SDK, no longer user-selected.
static public final String target_sdk = "23"; // Marshmallow (6.0)
static public final String target_platform = "android-" + target_sdk;
// Versions of Wear and VR in use
static public final String wear_version = "1.4.0";
static public final String gvr_sdk_version = "1.10.0";
private boolean runOnEmulator = false;
private int appComponent = FRAGMENT;
private boolean rewriteManifest = false;
private String renderer = "";
private final AndroidSDK sdk;
private final File coreZipFile;
/** whether this is a "debug" or "release" build */
private String target;
private Manifest manifest;
/** temporary folder safely inside a 8.3-friendly folder */
private File tmpFolder;
/** build.xml file for this project */
private File buildFile;
public AndroidBuild(final Sketch sketch, final AndroidMode mode,
final int appComp, final boolean emu) {
super(sketch);
runOnEmulator = emu;
appComponent = appComp;
sdk = mode.getSDK();
coreZipFile = mode.getCoreZipLocation();
}
// public static void setSdkTarget(AndroidSDK.SDKTarget target, Sketch sketch) {
// sdkName = target.name;
// sdkVersion = Integer.toString(target.version);
// sdkTarget = "android-" + sdkVersion;
//
// Preferences.set("android.sdk.version", target_);
// Preferences.set("android.sdk.name", target.name);
// }
/**
* Build into temporary folders (needed for the Windows 8.3 bugs in the Android SDK).
* @param target "debug" or "release"
* @throws SketchException
* @throws IOException
*/
public File build(String target) throws IOException, SketchException {
this.target = target;
if (appComponent == WATCHFACE && !runOnEmulator) {
// We are building a watchface not to run on the emulator. We need the
// handheld app:
// https://developer.android.com/training/wearables/apps/creating.html
// so the watchface can be uninstalled from the phone, and can be
// published on Google Play.
File wearFolder = createProject(true);
if (wearFolder != null) {
if (!antBuild()) {
return null;
}
}
File folder = createHandheldProject(wearFolder, null);
if (folder != null) {
if (!antBuild()) {
return null;
}
}
return folder;
} else {
File folder = createProject(false);
if (folder != null) {
if (!antBuild()) {
return null;
}
}
return folder;
}
}
/**
* Tell the PDE to not complain about android.* packages and others that are
* part of the OS library set as if they're missing.
*/
protected boolean ignorableImport(String pkg) {
if (pkg.startsWith("android.")) return true;
if (pkg.startsWith("java.")) return true;
if (pkg.startsWith("javax.")) return true;
if (pkg.startsWith("org.apache.http.")) return true;
if (pkg.startsWith("org.json.")) return true;
if (pkg.startsWith("org.w3c.dom.")) return true;
if (pkg.startsWith("org.xml.sax.")) return true;
if (pkg.startsWith("processing.core.")) return true;
if (pkg.startsWith("processing.data.")) return true;
if (pkg.startsWith("processing.event.")) return true;
if (pkg.startsWith("processing.opengl.")) return true;
return false;
}
/**
* Create an Android project folder, and run the preprocessor on the sketch.
* Populates the 'src' folder with Java code, and 'libs' folder with the
* libraries and code folder contents. Also copies data folder to 'assets'.
*/
public File createProject(boolean wear) throws IOException, SketchException {
tmpFolder = createTempBuildFolder(sketch);
if (wear) {
tmpFolder = new File(tmpFolder, "wear");
}
// Create the 'src' folder with the preprocessed code.
// final File srcFolder = new File(tmpFolder, "src");
srcFolder = new File(tmpFolder, "src");
// this folder isn't actually used, but it's used by the java preproc to
// figure out the classpath, so we have to set it to something
// binFolder = new File(tmpFolder, "bin");
// use the src folder, since 'bin' might be used by the ant build
binFolder = srcFolder;
if (processing.app.Base.DEBUG) {
Platform.openFolder(tmpFolder);
}
manifest = new Manifest(sketch, appComponent, mode.getFolder(), rewriteManifest);
manifest.setSdkTarget(target_sdk);
rewriteManifest = false;
// grab code from current editing window (GUI only)
// prepareExport(null);
// build the preproc and get to work
AndroidPreprocessor preproc = new AndroidPreprocessor(sketch, getPackageName());
// On Android, this init will throw a SketchException if there's a problem with size()
SurfaceInfo info = preproc.initSketchSize(sketch.getMainProgram());
preproc.initSketchSmooth(sketch.getMainProgram());
sketchClassName = preprocess(srcFolder, getPackageName(), preproc, false);
if (sketchClassName != null) {
File tempManifest = new File(tmpFolder, "AndroidManifest.xml");
manifest.writeBuild(tempManifest, sketchClassName, target.equals("debug"));
writeAntProps(new File(tmpFolder, "ant.properties"));
buildFile = new File(tmpFolder, "build.xml");
writeBuildXML(buildFile, sketch.getName());
writeProjectProps(new File(tmpFolder, "project.properties"));
writeLocalProps(new File(tmpFolder, "local.properties"));
final File resFolder = new File(tmpFolder, "res");
writeRes(resFolder);
renderer = info.getRenderer();
writeMainClass(srcFolder, renderer);
final File libsFolder = mkdirs(tmpFolder, "libs");
final File assetsFolder = mkdirs(tmpFolder, "assets");
// InputStream input = PApplet.createInput(getCoreZipLocation());
// PApplet.saveStream(new File(libsFolder, "processing-core.jar"), input);
Util.copyFile(coreZipFile, new File(libsFolder, "processing-core.jar"));
////////////////////////////////////////////////////////////////////////
// determine target id needed by library projects
String targetID = "";
final String[] params = {
sdk.getAndroidToolPath(),
"list", "targets"
};
ProcessHelper p = new ProcessHelper(params);
try {
final ProcessResult abiListResult = p.execute();
String id = null;
String platform = null;
String api = null;
for (String line : abiListResult) {
if (line.indexOf("id:") == 0) {
String[] parts = line.substring(4).split("or");
if (parts.length == 2) {
id = parts[0];
platform = parts[1].replaceAll("\"", "").trim();
}
// System.out.println("***********");
// System.out.println("ID: " + id);
// System.out.println("PLATFORM: " + platform);
}
String[] mapi = PApplet.match(line, "API\\slevel:\\s(\\S+)");
if (mapi != null) {
api = mapi[1];
// System.out.println("API: " + api);
}
if (platform != null && platform.equals(target_platform) &&
api != null && api.equals(target_sdk)) {
targetID = id;
break;
}
}
} catch (InterruptedException e) {}
if (getAppComponent() == FRAGMENT) {
// Need to add appcompat as a library project (includes v4 support)
////////////////////////////////////////////////////////////////////////
// first step: unpack the cardboard packages in the project's
// libs folder:
File appCompatFile = mode.getContentFile("mode/appcompat.zip");
AndroidMode.extractFolder(appCompatFile, libsFolder, true);
File appCompatFolder = new File(libsFolder, "appcompat");
////////////////////////////////////////////////////////////////////////
// second step: create library projects
boolean appCompatRes = createLibraryProject("appcompat", targetID,
appCompatFolder.getAbsolutePath(), "android.support.v7.appcompat");
////////////////////////////////////////////////////////////////////////
// third step: reference library projects from main project
if (appCompatRes) {
System.out.println("Library project created succesfully in " + libsFolder.toString());
appCompatRes = referenceLibraryProject(targetID, tmpFolder.getAbsolutePath(), "libs/appcompat");
if (appCompatRes) {
System.out.println("Library project referenced succesfully!");
// Finally, re-write the build files so they use org.eclipse.jdt.core.JDTCompilerAdapter
// instead of com.sun.tools.javac.Main
// TODO: use the build file generated by the android tools, and
// add the custom section redefining the target
File appCompatBuildFile = new File(appCompatFolder, "build.xml");
writeBuildXML(appCompatBuildFile, "appcompat");
}
}
} else {
// Copy the v4 support package only, needed for the permission handling
// in all other components
File compatJarFile = mode.getContentFile("mode/android-support-v4.jar");
Util.copyFile(compatJarFile, new File(libsFolder, "android-support-v4.jar"));
}
// if (getAppComponent() == WATCHFACE) {
// The wear jar is needed even when the app is not a watch face, because on
// devices with android < 5 the dependencies of the PWatchFace* classes
// cannot be resolved.
// TODO: temporary hack until I find a better way to include the wearable aar
// package included in the SDK:
File wearJarFile = mode.getContentFile("mode/wearable-" + wear_version + ".jar");
System.out.println(wearJarFile.toString());
Util.copyFile(wearJarFile, new File(libsFolder, "wearable-" + wear_version + ".jar"));
// }
// Copy any imported libraries (their libs and assets),
// and anything in the code folder contents to the project.
copyLibraries(libsFolder, assetsFolder);
copyCodeFolder(libsFolder);
if (getAppComponent() == CARDBOARD) {
// TODO: temporary hack until I find a better way to include the cardboard aar
// packages included in the cardboard SDK:
////////////////////////////////////////////////////////////////////////
// first step: unpack the cardboard packages in the project's
// libs folder:
File baseZipFile = mode.getContentFile("libraries/cardboard/gvrsdk/" + gvr_sdk_version + "/sdk-base.zip");
File commonZipFile = mode.getContentFile("libraries/cardboard/gvrsdk/" + gvr_sdk_version + "/sdk-common.zip");
File audioZipFile = mode.getContentFile("libraries/cardboard/gvrsdk/" + gvr_sdk_version + "/sdk-audio.zip");
AndroidMode.extractFolder(baseZipFile, libsFolder, true);
AndroidMode.extractFolder(commonZipFile, libsFolder, true);
AndroidMode.extractFolder(audioZipFile, libsFolder, true);
File baseLibsFolder = new File(libsFolder, "sdk-base");
File commonLibsFolder = new File(libsFolder, "sdk-common");
File audioLibsFolder = new File(libsFolder, "sdk-audio");
////////////////////////////////////////////////////////////////////////
// second step: create library projects
boolean baseRes = createLibraryProject("sdk_base", targetID,
baseLibsFolder.getAbsolutePath(), "com.google.vr.sdk.base");
boolean commonRes = createLibraryProject("sdk_common", targetID,
commonLibsFolder.getAbsolutePath(), "com.google.vr.cardboard");
boolean audioRes = createLibraryProject("sdk_audio", targetID,
audioLibsFolder.getAbsolutePath(), "com.google.vr.sdk.audio");
////////////////////////////////////////////////////////////////////////
// third step: reference library projects from main project
if (baseRes && commonRes && audioRes) {
System.out.println("Library projects created succesfully in " + libsFolder.toString());
baseRes = referenceLibraryProject(targetID, tmpFolder.getAbsolutePath(), "libs/sdk-base");
commonRes = referenceLibraryProject(targetID, tmpFolder.getAbsolutePath(), "libs/sdk-common");
audioRes = referenceLibraryProject(targetID, tmpFolder.getAbsolutePath(), "libs/sdk-audio");
if (baseRes && commonRes && audioRes) {
System.out.println("Library projects referenced succesfully!");
// Finally, re-write the build files so they use org.eclipse.jdt.core.JDTCompilerAdapter
// instead of com.sun.tools.javac.Main
// TODO: use the build file generated by the android tools, and
// add the custom section redefining the target
File baseBuildFile = new File(baseLibsFolder, "build.xml");
writeBuildXML(baseBuildFile, "sdk-base");
File commonBuildFile = new File(commonLibsFolder, "build.xml");
writeBuildXML(commonBuildFile, "sdk-common");
File audioBuildFile = new File(audioLibsFolder, "build.xml");
writeBuildXML(audioBuildFile, "sdk-audio");
}
}
}
// Copy the data folder (if one exists) to the project's 'assets' folder
final File sketchDataFolder = sketch.getDataFolder();
if (sketchDataFolder.exists()) {
Util.copyDir(sketchDataFolder, assetsFolder);
}
// Do the same for the 'res' folder.
// http://code.google.com/p/processing/issues/detail?id=767
final File sketchResFolder = new File(sketch.getFolder(), "res");
if (sketchResFolder.exists()) {
Util.copyDir(sketchResFolder, resFolder);
}
}
return tmpFolder;
}
// This creates the special activity project only needed to serve as the
// (invisible) app on the handheld that allows to uninstall the watchface
// from the watch.
public File createHandheldProject(File wearFolder, File wearPackage)
throws IOException, SketchException {
// According to these instructions:
// https://developer.android.com/training/wearables/apps/packaging.html#PackageManually
// we need to:
// 1. Include all the permissions declared in the manifest file of the
// wearable app in the manifest file of the mobile app
// 2. Ensure that both the wearable and mobile APKs have the same package name
// and version number.
// 3. Copy the signed wearable app to your handheld project's res/raw directory.
// We'll refer to the APK as wearable_app.apk.
// 4. Create a res/xml/wearable_app_desc.xml file that contains the version
// and path information of the wearable app. For example:
// 5. Add a meta-data tag to your handheld app's <application> tag to reference
// the wearable_app_desc.xml file.
// So, let's start by using the parent folder as the project file
tmpFolder = wearFolder.getParentFile();
// Now, we need to create the folder structure for the handheld project:
// src
// package-name (same to wear app)
// HandheldActivity.java (this will be a dummy activity that quits right after starting up).
// res
// drawable containing the app icon in 42x42 res
// drawable-hdpi (all the others res up to xxxhdpi)
// ...
// drawable-xxxhdpi
// layout
// activity_handheld.xml (the layout for the dummy activity)
// xml
// wearable_app_desc.xml (version and path info of the wearable app)
// raw
// wearable-apk (copied from the build process conducted in the wear folder)
// Create source folder, and dummy handheld activity
srcFolder = new File(tmpFolder, "src");
binFolder = srcFolder;
writeHandheldActivity();
// Copy the compatibility package, needed for the permission handling
final File libsFolder = mkdirs(tmpFolder, "libs");
File compatJarFile = mode.getContentFile("mode/android-support-v4.jar");
Util.copyFile(compatJarFile, new File(libsFolder, "android-support-v4.jar"));
// Create manifest file
String[] permissions = manifest.getPermissions();
// for (String perm: permissions) {
// System.out.println(perm);
// }
writeHandheldManifest(tmpFolder, "1", "1.0", permissions);
// Write property and build files.
writeAntProps(new File(tmpFolder, "ant.properties"));
buildFile = new File(tmpFolder, "build.xml");
writeBuildXML(buildFile, sketch.getName());
writeProjectProps(new File(tmpFolder, "project.properties"));
writeLocalProps(new File(tmpFolder, "local.properties"));
final File resFolder = new File(tmpFolder, "res");
// Write icons for handheld app
File sketchFolder = sketch.getFolder();
writeIconFiles(sketchFolder, resFolder);
// Copy the wearable apk
String apkName = "";
if (wearPackage == null) {
String suffix = target.equals("release") ? "release_unsigned" : "debug";
apkName = sketch.getName().toLowerCase() + "_" + suffix;
} else {
String name = wearPackage.getName();
int dot = name.lastIndexOf('.');
if (dot == -1) {
apkName = name;
} else {
apkName = name.substring(0, dot);
}
}
File rawFolder = mkdirs(resFolder, "raw");
File wearApk = new File(wearFolder, "bin/" + apkName + ".apk");
Util.copyFile(wearApk, new File(rawFolder, apkName + ".apk"));
// Create dummy layout/activity_handheld.xml
writeHandheldLayout(resFolder);
// Create the wearable app description
writeWearableDescription(resFolder, apkName, "1", "1.0");
return tmpFolder;
}
private void writeHandheldActivity() {
File javaTemplate = mode.getContentFile("templates/" + HANDHELD_ACTIVITY_TEMPLATE);
File javaFile = new File(new File(srcFolder, getPackageName().replace(".", "/")), "HandheldActivity.java");
HashMap<String, String> replaceMap = new HashMap<String, String>();
replaceMap.put("@@package_name@@", getPackageName());
AndroidMode.createFileFromTemplate(javaTemplate, javaFile, replaceMap);
}
private void writeHandheldManifest(final File tmpFolder, String versionCode, String versionName,
String[] permissions) {
File xmlTemplate = mode.getContentFile("templates/" + HANDHELD_MANIFEST_TEMPLATE);
File xmlFile = new File(tmpFolder, "AndroidManifest.xml");
String usesPermissions = "";
for (String name: permissions) {
if (name.equals("WAKE_LOCK")) continue;
usesPermissions += " <uses-permission android:name=\"android.permission." + name + "\"/>\n";
}
HashMap<String, String> replaceMap = new HashMap<String, String>();
replaceMap.put("@@package_name@@", getPackageName());
replaceMap.put("@@version_code@@", versionCode);
replaceMap.put("@@version_name@@", versionName);
replaceMap.put("@@sketch_class_name@@", sketchClassName);
replaceMap.put("@@uses_permissions@@", usesPermissions);
AndroidMode.createFileFromTemplate(xmlTemplate, xmlFile, replaceMap);
}
private void writeHandheldLayout(final File resFolder) {
File xmlTemplate = mode.getContentFile("templates/" + HANDHELD_LAYOUT_TEMPLATE);
File xmlFile = new File(resFolder, "layout/activity_handheld.xml");
HashMap<String, String> replaceMap = new HashMap<String, String>();
replaceMap.put("@@package_name@@", getPackageName());
AndroidMode.createFileFromTemplate(xmlTemplate, xmlFile, replaceMap);
// final PrintWriter writer = PApplet.createWriter(file);
// writer.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
// writer.println("<RelativeLayout");
// writer.println(" xmlns:android=\"http://schemas.android.com/apk/res/android\"");
// writer.println(" xmlns:tools=\"http://schemas.android.com/tools\"");
// writer.println(" android:layout_width=\"match_parent\"");
// writer.println(" android:layout_height=\"match_parent\"");
// writer.println(" android:paddingBottom=\"16dp\"");
// writer.println(" android:paddingLeft=\"16dp\"");
// writer.println(" android:paddingRight=\"16dp\"");
// writer.println(" android:paddingTop=\"16dp\"");
// writer.println(" tools:context=\"" + getPackageName() + ".HandheldActivity\">");
// writer.println("</RelativeLayout>");
// writer.flush();
// writer.close();
}
private void writeWearableDescription(final File resFolder, final String apkName,
final String versionCode, String versionName) {
File xmlTemplate = mode.getContentFile("templates/" + WEARABLE_DESCRIPTION_TEMPLATE);
File xmlFile = new File(resFolder, "xml/wearable_app_desc.xml");
HashMap<String, String> replaceMap = new HashMap<String, String>();
replaceMap.put("@@package_name@@", getPackageName());
replaceMap.put("@@version_code@@", versionCode);
replaceMap.put("@@version_name@@", versionName);
replaceMap.put("@@apk_name@@", apkName);
AndroidMode.createFileFromTemplate(xmlTemplate, xmlFile, replaceMap);
// final PrintWriter writer = PApplet.createWriter(file);
// writer.println("<wearableApp package=\"" + getPackageName() + "\">");
// writer.println(" <versionCode>" + versionCode + "</versionCode>");
// writer.println(" <versionName>" + versionName + "</versionName>");
// writer.println(" <rawPathResId>" + apkName + "</rawPathResId>");
// writer.println("</wearableApp>");
// writer.flush();
// writer.close();
}
protected boolean createLibraryProject(String name, String target,
String path, String pck) {
final String[] params = {
sdk.getAndroidToolPath(),
"create", "lib-project",
"--name", name,
"--target", target,
"--path", path,
"--package", pck
};
ProcessHelper p = new ProcessHelper(params);
ProcessResult pr;
try {
pr = p.execute();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
return false;
}
if (pr.succeeded()) {
return true;
} else {
System.err.println(pr.getStderr());
Messages.showWarning("Failed to create library project", "Something wrong happened", null);
return false;
}
}
protected boolean referenceLibraryProject(String target, String path, String lib) {
final String[] params = {
sdk.getAndroidToolPath(),
"update", "project",
"--target", target,
"--path", path,
"--library", lib
};
ProcessHelper p = new ProcessHelper(params);
ProcessResult pr;
try {
pr = p.execute();
} catch (InterruptedException | IOException e) {
e.printStackTrace();
return false;
}
if (pr.succeeded()) {
return true;
} else {
System.err.println(pr.getStderr());
Messages.showWarning("Failed to add library project", "Something wrong happened", null);
return false;
}
}
/**
* The Android dex util pukes on paths containing spaces, which will happen
* most of the time on Windows, since Processing sketches wind up in
* "My Documents". Therefore, build android in a temp file.
* http://code.google.com/p/android/issues/detail?id=4567
*
* TODO: better would be to retrieve the 8.3 name for the sketch folder!
*
* @param sketch
* @return A folder in which to build the android sketch
* @throws IOException
*/
private File createTempBuildFolder(final Sketch sketch) throws IOException {
final File tmp = File.createTempFile("android", "sketch");
if (!(tmp.delete() && tmp.mkdir())) {
throw new IOException("Cannot create temp dir " + tmp + " to build android sketch");
}
return tmp;
}
public boolean isWear() {
return appComponent == WATCHFACE;
}
public int getAppComponent() {
return appComponent;
}
// public void setAppComponent(int opt) {
// if (appComponent != opt) {
// appComponent = opt;
// resetManifest = true;
// }
// }
public void resetManifest() {
rewriteManifest = true;
}
protected boolean usesGPU() {
return renderer != null && (renderer.equals("P2D") || renderer.equals("P3D"));
}
protected File createExportFolder() throws IOException {
// Sketch sketch = editor.getSketch();
// Create the 'android' build folder, and move any existing version out.
File androidFolder = new File(sketch.getFolder(), "android");
if (androidFolder.exists()) {
// Date mod = new Date(androidFolder.lastModified());
String stamp = AndroidMode.getDateStamp(androidFolder.lastModified());
File dest = new File(sketch.getFolder(), "android." + stamp);
boolean result = androidFolder.renameTo(dest);
if (!result) {
ProcessHelper mv;
ProcessResult pr;
try {
System.err.println("createProject renameTo() failed, resorting to mv/move instead.");
mv = new ProcessHelper("mv", androidFolder.getAbsolutePath(), dest.getAbsolutePath());
pr = mv.execute();
// } catch (IOException e) {
// editor.statusError(e);
// return null;
//
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
if (!pr.succeeded()) {
System.err.println(pr.getStderr());
Messages.showWarning("Failed to rename",
"Could not rename the old “android” build folder.\n" +
"Please delete, close, or rename the folder\n" +
androidFolder.getAbsolutePath() + "\n" +
"and try again." , null);
Platform.openFolder(sketch.getFolder());
return null;
}
}
} else {
boolean result = androidFolder.mkdirs();
if (!result) {
Messages.showWarning("Folders, folders, folders",
"Could not create the necessary folders to build.\n" +
"Perhaps you have some file permissions to sort out?", null);
return null;
}
}
return androidFolder;
}
public File exportProject() throws IOException, SketchException {
// this will set debuggable to true in the .xml file
target = "debug";
if (appComponent == WATCHFACE) {
// We are building a watchface not to run on the emulator. We need the
// handheld app:
File wearFolder = createProject(true);
if (wearFolder == null) return null;
if (!antBuild()) return null;
File projectFolder = createHandheldProject(wearFolder, null);
if (projectFolder != null) {
File exportFolder = createExportFolder();
Util.copyDir(projectFolder, exportFolder);
return exportFolder;
}
return null;
} else {
File projectFolder = createProject(false);
if (projectFolder != null) {
File exportFolder = createExportFolder();
Util.copyDir(projectFolder, exportFolder);
return exportFolder;
}
return null;
}
}
public File exportPackage(String keyStorePassword) throws Exception {
File projectFolder = null;
if (appComponent == WATCHFACE) {
this.target = "release";
// We need to sign and align the wearable and handheld apps:
File wearFolder = createProject(true);
if (wearFolder == null) return null;
if (!antBuild()) return null;
File signedWearPackage = signPackage(wearFolder, keyStorePassword);
if (signedWearPackage == null) return null;
// Handheld package
projectFolder = createHandheldProject(wearFolder, signedWearPackage);
if (projectFolder == null) return null;
if (!antBuild()) return null;
File signedPackage = signPackage(projectFolder, keyStorePassword);
if (signedPackage == null) return null;
} else {
projectFolder = build("release");
if (projectFolder == null) return null;
File signedPackage = signPackage(projectFolder, keyStorePassword);
if (signedPackage == null) return null;
}
// Final export folder
File exportFolder = createExportFolder();
Util.copyDir(projectFolder, exportFolder);
return new File(exportFolder, "/bin/");
}
private File signPackage(File projectFolder, String keyStorePassword) throws Exception {
File keyStore = AndroidKeyStore.getKeyStore();
if (keyStore == null) return null;
File unsignedPackage = new File(projectFolder, "bin/" + sketch.getName().toLowerCase() + "_release_unsigned.apk");
if (!unsignedPackage.exists()) return null;
File signedPackage = new File(projectFolder, "bin/" + sketch.getName().toLowerCase() + "_release_signed.apk");
JarSigner.signJar(unsignedPackage, signedPackage, AndroidKeyStore.ALIAS_STRING, keyStorePassword, keyStore.getAbsolutePath(), keyStorePassword);
//if (verifySignedPackage(unsignedPackage)) {
/*File signedPackage = new File(projectFolder, "bin/" + sketch.getName() + "-release-signed.apk");
if (signedPackage.exists()) {
boolean deleteResult = signedPackage.delete();
if (!deleteResult) {
Base.showWarning("Error during package signing",
"Unable to delete old signed package");
return null;
}
}
boolean renameResult = unsignedPackage.renameTo(signedPackage);
if (!renameResult) {
Base.showWarning("Error during package signing",
"Unable to rename package file");
return null;
}*/
File alignedPackage = zipalignPackage(signedPackage, projectFolder);
return alignedPackage;
/*} else {
Base.showWarning("Error during package signing",
"Verification of the signed package has failed");
return null;
}*/
}
private File zipalignPackage(File signedPackage, File projectFolder) throws IOException, InterruptedException {
File buildToolsFolder = new File(sdk.getSdkFolder(), "build-tools").listFiles()[0];
String zipalignPath = buildToolsFolder.getAbsolutePath() + "/zipalign";
File alignedPackage = new File(projectFolder, "bin/" + sketch.getName().toLowerCase() + "_release_signed_aligned.apk");
String[] args = {
zipalignPath, "-v", "-f", "4",
signedPackage.getAbsolutePath(), alignedPackage.getAbsolutePath()
};
Process alignProcess = Runtime.getRuntime().exec(args);
alignProcess.waitFor();
if (alignedPackage.exists()) return alignedPackage;
return null;
}
protected boolean antBuild() throws SketchException {
// System.setProperty("user.dir", tmpFolder.getAbsolutePath()); // oh why not { because it doesn't help }
final Project p = new Project();
// p.setBaseDir(tmpFolder); // doesn't seem to do anything
// System.out.println(tmpFolder.getAbsolutePath());
// p.setUserProperty("user.dir", tmpFolder.getAbsolutePath());
String path = buildFile.getAbsolutePath().replace('\\', '/');
p.setUserProperty("ant.file", path);
// deals with a problem where javac error messages weren't coming through
//p.setUserProperty("build.compiler", "extJavac");
// p.setUserProperty("build.compiler.emacs", "true"); // does nothing
// try to spew something useful to the console
final DefaultLogger consoleLogger = new DefaultLogger();
consoleLogger.setErrorPrintStream(System.err);
consoleLogger.setOutputPrintStream(System.out); // ? uncommented before
// WARN, INFO, VERBOSE, DEBUG
// consoleLogger.setMessageOutputLevel(Project.MSG_ERR);
consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
// consoleLogger.setMessageOutputLevel(Project.MSG_DEBUG);
p.addBuildListener(consoleLogger);
// This logger is used to pick up javac errors to be parsed into
// SketchException objects. Note that most errors seem to show up on stdout
// since that's where the [javac] prefixed lines are coming through.
final DefaultLogger errorLogger = new DefaultLogger();
final ByteArrayOutputStream errb = new ByteArrayOutputStream();
final PrintStream errp = new PrintStream(errb);
errorLogger.setErrorPrintStream(errp);
final ByteArrayOutputStream outb = new ByteArrayOutputStream();
final PrintStream outp = new PrintStream(outb);
errorLogger.setOutputPrintStream(outp);
errorLogger.setMessageOutputLevel(Project.MSG_INFO);
// errorLogger.setMessageOutputLevel(Project.MSG_DEBUG);
p.addBuildListener(errorLogger);
try {
// editor.statusNotice("Building sketch for Android...");
p.fireBuildStarted();
p.init();
final ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
// p.executeTarget(p.getDefaultTarget());
p.executeTarget(target);
// editor.statusNotice("Finished building sketch.");
renameAPK();
return true;
} catch (final BuildException e) {
// Send a "build finished" event to the build listeners for this project.
p.fireBuildFinished(e);
// PApplet.println(new String(errb.toByteArray()));
// PApplet.println(new String(outb.toByteArray()));
// String errorOutput = new String(errb.toByteArray());
// String[] errorLines =
// errorOutput.split(System.getProperty("line.separator"));
// PApplet.println(errorLines);
//final String outPile = new String(outb.toByteArray());
//antBuildProblems(new String(outb.toByteArray())
antBuildProblems(new String(outb.toByteArray()),
new String(errb.toByteArray()));
}
return false;
}
void antBuildProblems(String outPile, String errPile) throws SketchException {
final String[] outLines =
outPile.split(System.getProperty("line.separator"));
final String[] errLines =
errPile.split(System.getProperty("line.separator"));
for (final String line : outLines) {
final String javacPrefix = "[javac]";
final int javacIndex = line.indexOf(javacPrefix);
if (javacIndex != -1) {
// System.out.println("checking: " + line);
// final Sketch sketch = editor.getSketch();
// String sketchPath = sketch.getFolder().getAbsolutePath();
int offset = javacIndex + javacPrefix.length() + 1;
String[] pieces =
PApplet.match(line.substring(offset), "^(.+):([0-9]+):\\s+(.+)$");
if (pieces != null) {
// PApplet.println(pieces);
String fileName = pieces[1];
// remove the path from the front of the filename
//fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);
final int lineNumber = PApplet.parseInt(pieces[2]) - 1;
// PApplet.println("looking for " + fileName + " line " + lineNumber);
SketchException rex = placeException(pieces[3], fileName, lineNumber);
if (rex != null) {
// System.out.println("found a rex");
// rex.hideStackTrace();
// editor.statusError(rex);
// return false; // get outta here
throw rex;
}
}
}
}
// Couldn't parse the exception, so send something generic
SketchException skex =
new SketchException("Error from inside the Android tools, " +
"check the console.");
// Try to parse anything else we might know about
for (final String line : errLines) {
if (line.contains("Unable to resolve target '" + target_platform + "'")) {
System.err.println("Use the Android SDK Manager (under the Android");
System.err.println("menu) to install the SDK platform and ");
System.err.println("Google APIs for Android " + target_sdk);
skex = new SketchException("Please install the SDK platform and " +
"Google APIs for Android " + target_sdk);
}
}
// Stack trace is not relevant, just the message.
skex.hideStackTrace();
throw skex;
}
String getPathForAPK() {
String suffix = target.equals("release") ? "release_unsigned" : "debug";
String apkName = "bin/" + sketch.getName().toLowerCase() + "_" + suffix + ".apk";
final File apkFile = new File(tmpFolder, apkName);