Repository navigation
Expand file tree
/
Copy pathJavaScriptBuildHints.java
More file actions
489 lines (461 loc) · 22.1 KB
/
Copy pathJavaScriptBuildHints.java
File metadata and controls
489 lines (461 loc) · 22.1 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
/*
* Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Codename One designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Codename One through http://www.codenameone.com/ if you
* need additional information or have any questions.
*/
package com.codename1.builders;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/// The build hints of the JavaScript port, and where each one has to go.
///
/// A JavaScript build has three audiences for a hint, and a hint that reaches the wrong one
/// silently does nothing:
///
/// - the **running application**, which reads `Display.getProperty` -- the launcher sets these
/// (see [#launcherProperties(BuildRequest)]);
/// - the **page** the translator writes, `index.html`, which exists before any Java runs --
/// these become translator system properties (see [#translatorOptions(BuildRequest)]);
/// - the **bundle**, which should carry only the native themes the application can reach at
/// run time (see [#themesToShip(BuildRequest, Set)]).
///
/// The cloud builder (BuildDaemon's `ParparVMJavascriptBuilder`) carries a copy of this class;
/// keep the two identical apart from the package and the `BuildRequest` import.
public final class JavaScriptBuildHints {
/// Hints the running application reads through `Display.getProperty`. Before this list
/// existed the launcher set none of them, so `nativeTheme` and friends only worked when the
/// application called `Display.setProperty` itself.
static final String[] RUNTIME_HINTS = {
"nativeTheme",
"cn1.nativeTheme",
"ios.themeMode",
"and.themeMode",
"cn1.androidTheme",
"javascript.native.theme",
"javascript.desktopTheme",
"javascript.titleBar",
"javascript.textSelection"
};
/// Every native theme the port bundle can carry in `assets/`, by resource name.
static final List<String> ALL_THEMES = Collections.unmodifiableList(Arrays.asList(
"iOS7Theme", "iPhoneTheme", "iOSModernTheme", "iOSModern27Theme",
"androidTheme", "android_holo_light", "AndroidMaterialTheme",
"WindowsFluentTheme", "MacOSAquaTheme", "GnomeAdwaitaTheme"));
/// The runtime property the port publishes with the OS-appropriate modern theme. Code that
/// reads it can open either modern theme, so an application naming it keeps both.
static final String MODERN_THEME_PROPERTY = "cn1.modernThemeResource";
/// Marker [#scanThemeReferences(File)] records when the application's own code names one of
/// the theme hints as a string: it can set them with `Display.setProperty` before the native
/// theme is installed, choosing at run time what the build hints did not say.
static final String RUNTIME_THEME_CHOICE = "runtime theme choice";
/// The theme hints an application can also set itself at run time; the runtime resolver
/// reads each of them through `Display.getProperty`.
static final String[] THEME_PROPERTIES = {
"nativeTheme", "cn1.nativeTheme", "ios.themeMode", "and.themeMode", "cn1.androidTheme",
"javascript.native.theme", "javascript.desktopTheme"
};
/// The `javascript.splash.*` hints that style the loading screen, each passed to the
/// translator as `codename1.<hint>` (see `JavascriptBundleWriter.SplashSettings`, which
/// validates them).
static final String[] SPLASH_HINTS = {
"javascript.splash.appearance", "javascript.splash.background",
"javascript.splash.textColor", "javascript.splash.accentColor",
"javascript.splash.darkBackground", "javascript.splash.darkTextColor",
"javascript.splash.darkAccentColor", "javascript.splash.logo"
};
/// The 192px icon `JavaScriptPwa` writes into every bundle.
static final String SPLASH_DEFAULT_LOGO = "_icons/icon-192.png";
private JavaScriptBuildHints() {
}
/// Java source lines, for the generated launcher, that publish the runtime hints the
/// request sets. Hints the request does not set are left out, so the port's own defaults
/// apply.
static String launcherProperties(BuildRequest request) {
StringBuilder out = new StringBuilder();
for (String hint : RUNTIME_HINTS) {
String value = request.getArg(hint, null);
if (value == null) {
continue;
}
out.append(" Display.getInstance().setProperty(\"")
.append(hint).append("\", \"").append(javaString(value)).append("\");\n");
}
return out.toString();
}
/// `-D` options for the translator JVM, which writes `index.html` (see
/// `JavascriptBundleWriter.applyPageSettings` in the ByteCodeTranslator). Only what the
/// request actually decides is passed; the translator's defaults are the documented ones,
/// so an older builder that passes nothing still gets the viewport and the opt-outs.
static List<String> translatorOptions(BuildRequest request) {
List<String> out = new ArrayList<String>();
String title = request.getDisplayName();
if (title != null && title.trim().length() > 0) {
out.add("-Dcodename1.javascript.title=" + title.trim());
}
String translation = request.getArg("javascript.allowBrowserTranslation", null);
if (translation != null) {
out.add("-Dcodename1.javascript.allowBrowserTranslation=" + "true".equalsIgnoreCase(translation.trim()));
}
String darkReader = request.getArg("javascript.darkreaderLock", null);
if (darkReader != null) {
out.add("-Dcodename1.javascript.darkreaderLock=" + !"false".equalsIgnoreCase(darkReader.trim()));
}
for (String hint : SPLASH_HINTS) {
String value = request.getArg(hint, null);
if (value != null && value.trim().length() > 0) {
out.add("-Dcodename1." + hint + "=" + value.trim());
}
}
// The loading screen shows the application's icon unless the developer named another
// logo (or none). JavaScriptPwa writes the icon to this path after the translator runs,
// from the same request.getIcon(); without an icon it writes a placeholder square, which
// identifies nothing, so then there is no logo.
String logo = request.getArg("javascript.splash.logo", null);
if ((logo == null || logo.trim().length() == 0) && request.getIcon() != null) {
out.add("-Dcodename1.javascript.splash.logo=" + SPLASH_DEFAULT_LOGO);
}
return out;
}
/// The themes to delete from a bundle carrying `present` so that it ships `keep`: every
/// present theme outside `keep` -- or nothing at all when any theme in `keep` is missing.
///
/// All or nothing because the runtime falls back. A theme the resolver picks but cannot
/// open sends it to the legacy pair (iOS 7 and Android Holo), which `keep` may not
/// include: pruning a bundle that lacks, say, the macOS theme left a Mac with neither the
/// theme it asked for nor the fallback, and no theme installed at all. A partial or
/// mismatched bundle is therefore shipped whole.
///
/// #### Parameters
///
/// - `keep`: what `#themesToShip` answered
/// - `present`: the theme names (without `.res`) the bundle's assets actually carry
static List<String> themesToDelete(Set<String> keep, Set<String> present) {
List<String> out = new ArrayList<String>();
for (String theme : keep) {
if (!present.contains(theme)) {
return out;
}
}
for (String theme : ALL_THEMES) {
if (!keep.contains(theme) && present.contains(theme)) {
out.add(theme);
}
}
return out;
}
/// The native themes this application can open at run time, which is what the bundle has
/// to carry. Everything else in [#ALL_THEMES] is dead weight in the public web root -- up to
/// 2.5MB of it.
///
/// This mirrors `HTML5Implementation.resolveNativeThemeResource()` in the JavaScript port,
/// which picks the theme from these hints AND the browser's user agent. The user agent is
/// unknown here, so the answer is the union over every browser the hints leave possible.
/// Change the two together.
///
/// #### Parameters
///
/// - `request`: the build hints
/// - `referencedByApp`: theme names (and [#MODERN_THEME_PROPERTY]) that appear as strings
/// in the application's own classes; an application that opens a theme itself keeps it
static Set<String> themesToShip(BuildRequest request, Set<String> referencedByApp) {
Set<String> out = new LinkedHashSet<String>();
if ("false".equals(lower(request.getArg("javascript.pruneThemes", null)))) {
// The application names its theme in a way no scan can see -- a path it computes,
// a name read from its configuration -- and has said so.
out.addAll(ALL_THEMES);
return out;
}
if (referencedByApp.contains(RUNTIME_THEME_CHOICE)) {
// The application picks the theme itself, so the hints do not say which one it
// will open. Keep them all rather than delete the one it asks for.
out.addAll(ALL_THEMES);
return out;
}
for (String name : ALL_THEMES) {
if (referencedByApp.contains(name)) {
out.add(name);
}
}
if (referencedByApp.contains(MODERN_THEME_PROPERTY)) {
out.add("iOSModernTheme");
out.add("AndroidMaterialTheme");
}
String explicit = request.getArg("javascript.native.theme", null);
if (explicit != null && explicit.trim().length() > 0) {
String name = baseName(explicit.trim());
if (ALL_THEMES.contains(name)) {
out.add(name);
} else {
// A theme the application ships itself. If it fails to open the port falls
// back to the legacy pair, so keep that pair.
out.add("android_holo_light");
out.add("iOS7Theme");
}
return out;
}
String shared = lower(request.getArg("nativeTheme", request.getArg("cn1.nativeTheme", null)));
// Desktop browsers: a desktop theme replaces the mobile branch there, but phones and
// tablets still take the mobile branch, so the two sets add up.
String desktop = desktopThemeFor(lower(request.getArg("javascript.desktopTheme", null)), shared, null);
if (desktop != null) {
out.add(desktop);
} else if (isAutoDesktop(lower(request.getArg("javascript.desktopTheme", null)), shared)) {
out.add("WindowsFluentTheme");
out.add("MacOSAquaTheme");
out.add("GnomeAdwaitaTheme");
}
// iOS-like browsers (iOS, iPadOS and a Mac that is not given a desktop theme).
String iosMode = lower(request.getArg("ios.themeMode", null));
if (iosMode == null && shared != null) {
if ("modern".equals(shared) || "auto".equals(shared) || "native".equals(shared)) {
iosMode = "modern";
} else if ("legacy".equals(shared)) {
iosMode = "ios7";
}
}
if (iosMode == null || "ios7".equals(iosMode) || "flat".equals(iosMode)) {
out.add("iOS7Theme");
} else if ("legacy".equals(iosMode) || "iphone".equals(iosMode)) {
out.add("iPhoneTheme");
} else {
out.add("iOSModernTheme");
}
// Every other browser.
String androidMode = lower(request.getArg("and.themeMode", request.getArg("cn1.androidTheme", null)));
if (androidMode == null && shared != null) {
if ("modern".equals(shared) || "auto".equals(shared) || "native".equals(shared)) {
androidMode = "material";
} else if ("legacy".equals(shared)) {
androidMode = "hololight";
}
}
if (androidMode == null) {
// The port's historical default: Holo Light on an Android user agent, iOS 7 on the
// rest.
out.add("android_holo_light");
out.add("iOS7Theme");
} else if ("legacy".equals(androidMode)) {
out.add("androidTheme");
} else if ("hololight".equals(androidMode) || "holo".equals(androidMode)) {
out.add("android_holo_light");
} else {
out.add("AndroidMaterialTheme");
}
return out;
}
/// The desktop theme a desktop browser gets, or null when it keeps the mobile branch (or,
/// for `auto`, when the answer depends on the browser's OS -- see [#isAutoDesktop]).
///
/// #### Parameters
///
/// - `desktopHint`: `javascript.desktopTheme`, lower case, or null
/// - `shared`: `nativeTheme`, lower case, or null
/// - `os`: `win`, `mac` or `linux` to resolve `auto`; null when unknown
static String desktopThemeFor(String desktopHint, String shared, String os) {
if ("fluent".equals(desktopHint) || "windows".equals(desktopHint)) {
return "WindowsFluentTheme";
}
if ("aqua".equals(desktopHint) || "mac".equals(desktopHint) || "macos".equals(desktopHint)) {
return "MacOSAquaTheme";
}
if ("adwaita".equals(desktopHint) || "gnome".equals(desktopHint) || "linux".equals(desktopHint)) {
return "GnomeAdwaitaTheme";
}
if (os != null && isAutoDesktop(desktopHint, shared)) {
if ("win".equals(os)) {
return "WindowsFluentTheme";
}
if ("mac".equals(os)) {
return "MacOSAquaTheme";
}
return "GnomeAdwaitaTheme";
}
return null;
}
/// Whether a desktop browser picks its theme by OS. Only `nativeTheme=native` asks for it:
/// `modern` means the mobile modern themes, exactly as it does for the JavaSE desktop build.
static boolean isAutoDesktop(String desktopHint, String shared) {
return (desktopHint == null || "auto".equals(desktopHint)) && "native".equals(shared);
}
/// Scans the application's classes -- loose, or inside jars -- for the theme names in
/// [#ALL_THEMES] (as `Name.res`), for [#MODERN_THEME_PROPERTY], and for the
/// [#THEME_PROPERTIES] (recorded as [#RUNTIME_THEME_CHOICE]). A class that names a resource
/// or a property stores the string verbatim in its constant pool, so a byte search finds it.
///
/// The framework's annotation and implementation packages are skipped (see
/// [#isFrameworkPath(String)]): the tree is the application merged with the framework, and
/// those spell the hint names too.
/// Call this BEFORE the port is merged in, for the same reason: the port names every theme.
static Set<String> scanThemeReferences(File classesDir) throws IOException {
Set<String> found = new LinkedHashSet<String>();
if (classesDir != null && classesDir.isDirectory()) {
scanDirectory(classesDir, "", found);
}
return found;
}
/// The framework packages that spell the theme hint names without choosing a theme: the
/// build-hint annotations declare them, and the ports read them. Only these are skipped --
/// not all of `com/codename1/`, which applications and cn1libs use for their own packages
/// too, and whose calls to `Display.setProperty` must still be seen.
static boolean isFrameworkPath(String relativePath) {
return relativePath.startsWith("com/codename1/annotations/")
|| relativePath.startsWith("com/codename1/impl/");
}
private static void scanDirectory(File dir, String relativePath, Set<String> found) throws IOException {
File[] children = dir.listFiles();
if (children == null) {
return;
}
for (File child : children) {
String childPath = relativePath.length() == 0 ? child.getName() : relativePath + "/" + child.getName();
if (child.isDirectory()) {
if (!isFrameworkPath(childPath + "/")) {
scanDirectory(child, childPath, found);
}
} else if (child.getName().endsWith(".class")) {
InputStream in = new FileInputStream(child);
try {
scanBytes(readAll(in), found);
} finally {
in.close();
}
} else if (child.getName().endsWith(".jar")) {
ZipInputStream zin = new ZipInputStream(new FileInputStream(child));
try {
ZipEntry e;
while ((e = zin.getNextEntry()) != null) {
if (!e.isDirectory() && e.getName().endsWith(".class") && !isFrameworkPath(e.getName())) {
scanBytes(readAll(zin), found);
}
}
} finally {
zin.close();
}
}
}
}
static void scanBytes(byte[] data, Set<String> found) {
// ISO-8859-1 maps each byte to one char, so an ASCII needle is found exactly where the
// bytes are, whatever else the class file contains.
String text = new String(data, StandardCharsets.ISO_8859_1);
for (String name : ALL_THEMES) {
// "Name.res" anywhere (a path such as "/Name.res" included), or the bare name as a
// whole constant: Resources.openLayered("/Name") appends the extension itself, so
// its argument never contains ".res". Whole constants only for the bare form, so a
// longer identifier that merely starts with a theme name is not a reference.
if (text.indexOf(name + ".res") >= 0 || containsConstant(text, name)
|| containsConstant(text, "/" + name)) {
found.add(name);
}
}
if (text.indexOf(MODERN_THEME_PROPERTY) >= 0) {
found.add(MODERN_THEME_PROPERTY);
}
for (String property : THEME_PROPERTIES) {
if (containsConstant(text, property)) {
found.add(RUNTIME_THEME_CHOICE);
break;
}
}
}
/// Whether `text` holds `value` as a whole constant-pool string: a CONSTANT_Utf8 entry is a
/// tag byte 1 and a two-byte length before its bytes. "nativeTheme" must not match inside
/// "nativeThemeResource" or another longer name.
static boolean containsConstant(String text, String value) {
int len = value.length();
int from = 0;
while (true) {
int at = text.indexOf(value, from);
if (at < 0) {
return false;
}
if (at >= 3 && text.charAt(at - 3) == 1 && text.charAt(at - 2) == (char) ((len >> 8) & 0xff)
&& text.charAt(at - 1) == (char) (len & 0xff)) {
return true;
}
from = at + 1;
}
}
private static byte[] readAll(InputStream in) throws IOException {
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) > 0) {
out.write(buf, 0, n);
}
return out.toByteArray();
}
private static String baseName(String path) {
int slash = path.lastIndexOf('/');
String name = slash >= 0 ? path.substring(slash + 1) : path;
return name.endsWith(".res") ? name.substring(0, name.length() - 4) : name;
}
private static String lower(String s) {
if (s == null) {
return null;
}
s = s.trim();
if (s.length() == 0) {
return null;
}
// An ASCII fold: these are hint keywords, and toLowerCase() is locale sensitive.
StringBuilder b = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
b.append(c >= 'A' && c <= 'Z' ? (char) (c + 32) : c);
}
return b.toString();
}
private static String javaString(String value) {
StringBuilder b = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '\\': b.append("\\\\"); break;
case '"': b.append("\\\""); break;
case '\n': b.append("\\n"); break;
case '\r': b.append("\\r"); break;
case '\t': b.append("\\t"); break;
default:
if (c < 0x20 || c > 0x7e) {
String hex = Integer.toHexString(c);
b.append("\\u");
for (int p = hex.length(); p < 4; p++) {
b.append('0');
}
b.append(hex);
} else {
b.append(c);
}
}
}
return b.toString();
}
}