-
-
Notifications
You must be signed in to change notification settings - Fork 7k
/
Copy pathTheme.java
750 lines (618 loc) · 22.1 KB
/
Theme.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
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-06 Ben Fry and Casey Reas
Copyright (c) 2001-04 Massachusetts Institute of Technology
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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.app;
import static processing.app.I18n.format;
import static processing.app.I18n.tr;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.font.TextAttribute;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.UIManager;
import javax.swing.text.StyleContext;
import org.apache.batik.transcoder.Transcoder;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.lang3.StringUtils;
import processing.app.helpers.OSUtils;
import processing.app.helpers.PreferencesHelper;
import processing.app.helpers.PreferencesMap;
/**
* Storage class for theme settings. This was separated from the Preferences
* class for 1.0 so that the coloring wouldn't conflict with previous releases
* and to make way for future ability to customize.
*/
public class Theme {
static final String THEME_DIR = "theme/";
static final String THEME_FILE_NAME = "theme.txt";
static final String NAMESPACE_APP = "app:";
static final String NAMESPACE_USER = "user:";
/**
* A theme resource, this is returned instead of {@link File} so that we can
* support zip-packaged resources as well as files in the file system
*/
public static class Resource {
// Priority levels used to determine whether one resource should override
// another
static public final int PRIORITY_DEFAULT = 0;
static public final int PRIORITY_USER_ZIP = 1;
static public final int PRIORITY_USER_FILE = 2;
/**
* Priority of this resource.
*/
private final int priority;
/**
* Resource name (original name of requested resource, relative path only).
*/
private final String name;
/**
* File if this resource represents a file, can be null.
*/
private final File file;
/**
* Zip theme if the resource is contained within a zipped theme
*/
private final ZippedTheme theme;
/**
* Zip entry if this resource represents a zip entry, can be null.
*/
private final ZipEntry zipEntry;
/**
* URL of this resource regardless of type, theoretically shouldn't ever be
* null though it might be if a particular resource path can't be
* successfully transformed into a URL (eg. {@link Theme#getUrl} traps a
* <tt>MalformedURLException</tt>).
*/
private final URL url;
/**
* If this resource supercedes a resource with a lower priority, this field
* stores a reference to the superceded resource. This allows consumers to
* traverse the resource hierarchy if required.
*/
private Resource parent;
/**
* ctor for file resources
*/
Resource(int priority, String name, URL url, File file) {
this(priority, name, url, file, null, null);
}
/**
* ctor for zip resources
*/
Resource(int priority, String name, URL url, ZippedTheme theme, ZipEntry entry) {
this(priority, name, url, null, theme, entry);
}
private Resource(int priority, String name, URL url, File file, ZippedTheme theme, ZipEntry zipEntry) {
this.priority = priority;
this.name = name;
this.file = file;
this.theme = theme;
this.zipEntry = zipEntry;
this.url = url;
}
public Resource getParent() {
return this.parent;
}
public String getName() {
return this.name;
}
public URL getUrl() {
return this.url;
}
public int getPriority() {
return this.priority;
}
public boolean isUserDefined() {
return this.priority > PRIORITY_DEFAULT;
}
public boolean exists() {
return this.zipEntry != null || this.file == null || this.file.exists();
}
public InputStream getInputStream() throws IOException {
if (this.file != null) {
return new FileInputStream(this.file);
}
if (this.zipEntry != null) {
return this.theme.getZip().getInputStream(this.zipEntry);
}
if (this.url != null) {
return this.url.openStream();
}
throw new FileNotFoundException(this.name);
}
public String toString() {
return this.name;
}
Resource withParent(Resource parent) {
this.parent = parent;
return this;
}
}
/**
* Struct which keeps information about a discovered .zip theme file
*/
public static class ZippedTheme {
/**
* Configuration key, this key consists of a "namespace" which determines
* the root folder the theme was found in without actually storing the path
* itself, followed by the file name.
*/
private final String key;
/**
* File containing the theme
*/
private final File file;
/**
* Zip file handle for retrieving entries
*/
private final ZipFile zip;
/**
* Display name, defaulted to filename but can be read from metadata
*/
private final String name;
/**
* Version number, plain text string read from metadata
*/
private final String version;
private ZippedTheme(String namespace, File file, ZipFile zip, String name, String version) {
this.key = namespace + file.getName();
this.file = file;
this.zip = zip;
this.name = name;
this.version = version;
}
public String getKey() {
return this.key;
}
public File getFile() {
return this.file;
}
public ZipFile getZip() {
return this.zip;
}
public String getName() {
return this.name;
}
public String getVersion() {
return this.version;
}
public String toString() {
String description = String.format("%s %s (%s)", this.getName(), this.getVersion(), this.file.getName());
return StringUtils.abbreviate(description, 40);
}
/**
* Attempts to parse the supplied zip file as a theme file. This is largely
* determined by the file being readable and containing a theme.txt entry.
* Returns null if the file is unreadable or doesn't contain theme.txt
*/
static ZippedTheme load(String namespace, File file) {
ZipFile zip = null;
try {
zip = new ZipFile(file);
ZipEntry themeTxtEntry = zip.getEntry(THEME_FILE_NAME);
if (themeTxtEntry != null) {
String name = file.getName().substring(0, file.getName().length() - 4);
String version = "";
ZipEntry themePropsEntry = zip.getEntry("theme.properties");
if (themePropsEntry != null) {
Properties themeProperties = new Properties();
themeProperties.load(zip.getInputStream(themePropsEntry));
name = themeProperties.getProperty("name", name);
version = themeProperties.getProperty("version", version);
}
return new ZippedTheme(namespace, file, zip, name, version);
}
} catch (Exception ex) {
System.err.println(format(tr("Error loading theme {0}: {1}"),
file.getAbsolutePath(), ex.getMessage()));
IOUtils.closeQuietly(zip);
}
return null;
}
}
/**
* Copy of the defaults in case the user mangles a preference.
*/
static PreferencesMap defaults;
/**
* Table of attributes/values for the theme.
*/
static PreferencesMap table = new PreferencesMap();
/**
* Available zipped themes
*/
static private final Map<String, ZippedTheme> availableThemes = new TreeMap<>();
/**
* Zip file containing user-defined theme elements
*/
static private ZippedTheme zipTheme;
static protected void init() {
zipTheme = openZipTheme();
try {
loadFromResource(table, THEME_DIR + THEME_FILE_NAME);
} catch (Exception te) {
Base.showError(null, tr("Could not read color theme settings.\n"
+ "You'll need to reinstall Arduino."),
te);
}
// other things that have to be set explicitly for the defaults
setColor("run.window.bgcolor", SystemColor.control);
// clone the hash table
defaults = new PreferencesMap(table);
// Set the look and feel before opening the window
try {
String laf = defaults.get("ui.laf");
if(laf != null && ! laf.trim().isEmpty()) {
try {
UIManager.setLookAndFeel(laf);
} catch (Exception e) {
e.printStackTrace();
BaseNoGui.getPlatform().setLookAndFeel();
}
}else {
BaseNoGui.getPlatform().setLookAndFeel();
}
} catch (Exception e) {
// ignore
}
}
static private ZippedTheme openZipTheme() {
refreshAvailableThemes();
String selectedTheme = PreferencesData.get("theme.file", "");
synchronized(availableThemes) {
return availableThemes.get(selectedTheme);
}
}
static private void refreshAvailableThemes() {
Map<String, ZippedTheme> discoveredThemes = new TreeMap<>();
refreshAvailableThemes(discoveredThemes, NAMESPACE_APP, new File(BaseNoGui.getContentFile("lib"), THEME_DIR));
refreshAvailableThemes(discoveredThemes, NAMESPACE_USER, new File(BaseNoGui.getSketchbookFolder(), THEME_DIR));
synchronized (availableThemes) {
availableThemes.clear();
availableThemes.putAll(discoveredThemes);
}
}
static private void refreshAvailableThemes(Map<String, ZippedTheme> discoveredThemes, String namespace, File folder) {
if (!folder.isDirectory()) {
return;
}
for (File zipFile : folder.listFiles((dir, name) -> name.endsWith(".zip"))) {
ZippedTheme theme = ZippedTheme.load(namespace, zipFile);
if (theme != null) {
discoveredThemes.put(theme.getKey(), theme);
}
}
}
public static Collection<ZippedTheme> getAvailablethemes() {
refreshAvailableThemes();
return Collections.unmodifiableCollection(availableThemes.values());
}
static public String get(String attribute) {
return table.get(attribute);
}
static public String getDefault(String attribute) {
return defaults.get(attribute);
}
static public void set(String attribute, String value) {
table.put(attribute, value);
}
static public boolean getBoolean(String attribute) {
return table.getBoolean(attribute);
}
static public void setBoolean(String attribute, boolean value) {
table.putBoolean(attribute, value);
}
static public int getInteger(String attribute) {
return Integer.parseInt(get(attribute));
}
static public void setInteger(String key, int value) {
set(key, String.valueOf(value));
}
static public int getScale() {
try {
int scale = PreferencesData.getInteger("gui.scale", -1);
if (scale != -1)
return scale;
} catch (NumberFormatException ignore) {
}
return BaseNoGui.getPlatform().getSystemDPI() * 100 / 96;
}
static public int scale(int size) {
return size * getScale() / 100;
}
static public Dimension scale(Dimension dim) {
return new Dimension(scale(dim.width), scale(dim.height));
}
static public Font scale(Font font) {
float size = scale(font.getSize());
// size must be float to call the correct Font.deriveFont(float)
// method that is different from Font.deriveFont(int)!
Font scaled = font.deriveFont(size);
return scaled;
}
static public Rectangle scale(Rectangle rect) {
Rectangle res = new Rectangle(rect);
res.x = scale(res.x);
res.y = scale(res.y);
res.width = scale(res.width);
res.height = scale(res.height);
return res;
}
static public Color getColorCycleColor(String name, int i) {
int cycleSize = getInteger(name + ".size");
name = String.format("%s.%02d", name, i % cycleSize);
return PreferencesHelper.parseColor(get(name));
}
static public void setColorCycleColor(String name, int i, Color color) {
name = String.format("%s.%02d", name, i);
PreferencesHelper.putColor(table, name, color);
int cycleSize = getInteger(name + ".size");
setInteger(name + ".size", (i + 1) > cycleSize ? (i + 1) : cycleSize);
}
static public Color getColor(String name) {
return PreferencesHelper.parseColor(get(name));
}
static public void setColor(String attr, Color color) {
PreferencesHelper.putColor(table, attr, color);
}
static public Font getFont(String attr) {
Font font = PreferencesHelper.getFont(table, attr);
if (font == null) {
String value = getDefault(attr);
set(attr, value);
font = PreferencesHelper.getFont(table, attr);
if (font == null) {
return null;
}
}
return font.deriveFont((float) scale(font.getSize()));
}
/**
* Returns the default font for text areas.
*
* @return The default font.
*/
public static final Font getDefaultFont() {
// Use StyleContext to get a composite font for better Asian language
// support; see Sun bug S282887.
StyleContext sc = StyleContext.getDefaultStyleContext();
Font font = null;
if (OSUtils.isMacOS()) {
// Snow Leopard (1.6) uses Menlo as default monospaced font,
// pre-Snow Leopard used Monaco.
font = sc.getFont("Menlo", Font.PLAIN, 12);
if (!"Menlo".equals(font.getFamily())) {
font = sc.getFont("Monaco", Font.PLAIN, 12);
if (!"Monaco".equals(font.getFamily())) { // Shouldn't happen
font = sc.getFont("Monospaced", Font.PLAIN, 13);
}
}
} else {
// Consolas added in Vista, used by VS2010+.
font = sc.getFont("Consolas", Font.PLAIN, 13);
if (!"Consolas".equals(font.getFamily())) {
font = sc.getFont("Monospaced", Font.PLAIN, 13);
}
}
// System.out.println(font.getFamily() + ", " + font.getName());
return font;
}
public static Map<String, Object> getStyledFont(String what, Font font) {
String split[] = get("editor." + what + ".style").split(",");
Color color = PreferencesHelper.parseColor(split[0]);
String style = split[1];
boolean bold = style.contains("bold");
boolean italic = style.contains("italic");
boolean underlined = style.contains("underlined");
Font styledFont = new Font(font.getFamily(),
(bold ? Font.BOLD : 0) | (italic ? Font.ITALIC : 0), font.getSize());
if (underlined) {
Map<TextAttribute, Object> attr = new Hashtable<>();
attr.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
styledFont = styledFont.deriveFont(attr);
}
Map<String, Object> result = new HashMap<>();
result.put("color", color);
result.put("font", styledFont);
return result;
}
/**
* Return an Image object from inside the Processing lib folder.
*/
static public Image getLibImage(String filename, Component who, int width,
int height) {
Image image = null;
// Use vector image when available
Resource vectorFile = getThemeResource(filename + ".svg");
if (vectorFile.exists()) {
try {
image = imageFromSVG(vectorFile.getUrl(), width, height);
} catch (Exception e) {
System.err.println("Failed to load " + vectorFile + ": " + e.getMessage());
}
}
Resource bitmapFile = getThemeResource(filename + ".png");
// Otherwise fall-back to PNG bitmaps, allowing user-defined bitmaps to
// override built-in svgs
if (image == null || bitmapFile.getPriority() > vectorFile.getPriority()) {
Resource bitmap2xFile = getThemeResource(filename + "@2x.png");
Resource imageFile;
if (((getScale() > 125 && bitmap2xFile.exists()) || !bitmapFile.exists())
&& (bitmapFile.isUserDefined() && bitmap2xFile.isUserDefined())) {
imageFile = bitmap2xFile;
} else {
imageFile = bitmapFile;
}
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(imageFile.getUrl());
}
MediaTracker tracker = new MediaTracker(who);
try {
tracker.addImage(image, 0);
tracker.waitForAll();
} catch (InterruptedException e) {
}
if (image.getWidth(null) != width || image.getHeight(null) != height) {
image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
try {
tracker.addImage(image, 1);
tracker.waitForAll();
} catch (InterruptedException e) {
}
}
return image;
}
/**
* Get an image associated with the current color theme.
*/
static public Image getThemeImage(String name, Component who, int width,
int height) {
return getLibImage(THEME_DIR + name, who, width, height);
}
private static Image imageFromSVG(URL url, int width, int height)
throws TranscoderException {
Transcoder t = new PNGTranscoder();
t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(width));
t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(height));
TranscoderInput input = new TranscoderInput(url.toString());
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(ostream);
t.transcode(input, output);
byte[] imgData = ostream.toByteArray();
return Toolkit.getDefaultToolkit().createImage(imgData);
}
static public Graphics2D setupGraphics2D(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
if (PreferencesData.getBoolean("editor.antialias")) {
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
}
return g;
}
/**
* Loads the supplied {@link PreferencesMap} from the specified resource,
* recursively loading parent resources such that entries are loaded in order
* of priority (lowest first).
*
* @param map preference map to populate
* @param name name of resource to load
*/
static public PreferencesMap loadFromResource(PreferencesMap map, String name) throws IOException {
return loadFromResource(map, getThemeResource(name));
}
static private PreferencesMap loadFromResource(PreferencesMap map, Resource resource) throws IOException {
if (resource != null) {
loadFromResource(map, resource.getParent());
map.load(resource.getInputStream());
}
return map;
}
/**
* @param name
* @return
*/
static public Resource getThemeResource(String name) {
File defaultfile = getDefaultFile(name);
Resource resource = new Resource(Resource.PRIORITY_DEFAULT, name, getUrl(defaultfile), defaultfile);
ZipEntry themeZipEntry = getThemeZipEntry(name);
if (themeZipEntry != null) {
resource = new Resource(Resource.PRIORITY_USER_ZIP, name, getUrl(themeZipEntry), zipTheme, themeZipEntry).withParent(resource);
}
File themeFile = getThemeFile(name);
if (themeFile != null) {
resource = new Resource(Resource.PRIORITY_USER_FILE, name, getUrl(themeFile), themeFile).withParent(resource);
}
return resource;
}
static private File getThemeFile(String name) {
File sketchBookThemeFolder = new File(BaseNoGui.getSketchbookFolder(), THEME_DIR);
File themeFile = new File(sketchBookThemeFolder, name);
if (themeFile.exists()) {
return themeFile;
}
if (name.startsWith(THEME_DIR)) {
themeFile = new File(sketchBookThemeFolder, name.substring(THEME_DIR.length()));
if (themeFile.exists()) {
return themeFile;
}
}
return null;
}
static private ZipEntry getThemeZipEntry(String name) {
if (zipTheme == null) {
return null;
}
if (name.startsWith(THEME_DIR)) {
name = name.substring(THEME_DIR.length());
}
return zipTheme.getZip().getEntry(name);
}
static private File getDefaultFile(String name) {
return new File(BaseNoGui.getContentFile("lib"), name);
}
static URL getUrl(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException ex) {
return null;
}
}
static URL getUrl(ZipEntry entry) {
try {
// Adjust file name for URL format on Windows
String zipFile = zipTheme.getZip().getName().replace('\\', '/');
if (!zipFile.startsWith("/")) {
zipFile = "/" + zipFile;
}
// Construct a URL which points to the internal resource
URI uri = new URI("jar", "file:" + zipFile + "!/" + entry.getName(), null);
return uri.toURL();
} catch (MalformedURLException | URISyntaxException ex) {
return null;
}
}
}