forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathassets-generation-service.ts
277 lines (248 loc) · 7.45 KB
/
assets-generation-service.ts
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
import JimpModule = require("jimp");
import * as Color from "color";
import { exported } from "../../common/decorators";
import { AssetConstants } from "../../constants";
import {
IAssetsGenerationService,
IOptions,
IResourceGenerationData,
} from "../../declarations";
import {
IProjectDataService,
IAssetGroup,
IAssetSubGroup,
} from "../../definitions/project";
import { IDictionary, IFileSystem } from "../../common/declarations";
import * as _ from "lodash";
import { injector } from "../../common/yok";
import { EOL } from "os";
export const enum Operations {
OverlayWith = "overlayWith",
Blank = "blank",
Resize = "resize",
OuterScale = "outerScale",
}
export class AssetsGenerationService implements IAssetsGenerationService {
private get propertiesToEnumerate(): IDictionary<string[]> {
return {
icon: ["icons"],
splash: ["splashBackgrounds", "splashCenterImages", "splashImages"],
};
}
constructor(
private $logger: ILogger,
private $projectDataService: IProjectDataService,
private $fs: IFileSystem,
private $options: IOptions,
) {}
@exported("assetsGenerationService")
public async generateIcons(
resourceGenerationData: IResourceGenerationData,
): Promise<void> {
if (this.$options.hostProjectPath) {
return;
}
this.$logger.info("Generating icons ...");
await this.generateImagesForDefinitions(
resourceGenerationData,
this.propertiesToEnumerate.icon,
);
this.$logger.info("Icons generation completed.");
}
@exported("assetsGenerationService")
public async generateSplashScreens(
splashesGenerationData: IResourceGenerationData,
): Promise<void> {
this.$logger.info("Generating splash screens ...");
await this.generateImagesForDefinitions(
splashesGenerationData,
this.propertiesToEnumerate.splash,
);
this.$logger.info("Splash screens generation completed.");
}
private async generateImagesForDefinitions(
generationData: IResourceGenerationData,
propertiesToEnumerate: string[],
): Promise<void> {
const background = generationData.background || "white";
const assetsStructure =
await this.$projectDataService.getAssetsStructure(generationData);
const assetItems = _(assetsStructure)
.filter(
(assetGroup: IAssetGroup, platform: string) =>
!generationData.platform ||
platform.toLowerCase() === generationData.platform.toLowerCase(),
)
.map((assetGroup: IAssetGroup) =>
_.filter(
assetGroup,
(assetSubGroup: IAssetSubGroup, imageTypeKey: string) =>
assetSubGroup && propertiesToEnumerate.indexOf(imageTypeKey) !== -1,
),
)
.flatten()
.map((assetSubGroup: IAssetSubGroup) => assetSubGroup.images)
.flatten()
.filter((assetItem: any) => !!assetItem.filename)
.value();
for (const assetItem of assetItems) {
if (assetItem.operation === "delete") {
if (this.$fs.exists(assetItem.path)) {
this.$fs.deleteFile(assetItem.path);
}
continue;
}
if (assetItem.operation === "writeXMLColor") {
const colorName = assetItem.data?.colorName;
if (!colorName) {
continue;
}
try {
const color =
(generationData as any)[assetItem.data?.fromKey] ??
assetItem.data?.default ??
"white";
const colorHEX: number = JimpModule.cssColorToHex(color);
const hex = colorHEX?.toString(16).substring(0, 6) ?? "FFFFFF";
this.$fs.writeFile(
assetItem.path,
[
`<?xml version="1.0" encoding="utf-8"?>`,
`<resources>`,
` <color name="${colorName}">#${hex.toUpperCase()}</color>`,
`</resources>`,
].join(EOL),
);
} catch (err) {
this.$logger.info(
`Failed to write provided color to ${assetItem.path} -> ${colorName}. See --log trace for more info.`,
);
this.$logger.trace(err);
}
continue;
}
const operation = assetItem.resizeOperation || Operations.Resize;
let tempScale: number = null;
if (assetItem.scale) {
if (_.isNumber(assetItem.scale)) {
tempScale = assetItem.scale;
} else {
const splittedElements = `${assetItem.scale}`.split(
AssetConstants.sizeDelimiter,
);
tempScale =
splittedElements &&
splittedElements.length &&
splittedElements[0] &&
+splittedElements[0];
}
}
const scale = tempScale || AssetConstants.defaultScale;
const outputPath = assetItem.path;
const width = assetItem.width * scale;
const height = assetItem.height * scale;
if (!width || !height) {
this.$logger.warn(
`Image ${assetItem.filename} is skipped as its width and height are invalid.`,
);
continue;
}
let image: JimpModule.JimpInstance;
switch (operation) {
case Operations.OverlayWith:
const overlayImageScale =
assetItem.overlayImageScale ||
AssetConstants.defaultOverlayImageScale;
const imageResize = Math.round(
Math.min(width, height) * overlayImageScale,
);
image = await this.resize(
generationData.imagePath,
imageResize,
imageResize,
);
image = this.generateImage(background, width, height, image);
break;
case Operations.Blank:
image = this.generateImage(background, width, height);
break;
case Operations.Resize:
image = await this.resize(generationData.imagePath, width, height);
break;
case Operations.OuterScale:
// Resize image without applying scale
image = await this.resize(
generationData.imagePath,
assetItem.width,
assetItem.height,
);
// The scale will apply to the underlying layer of the generated image
image = this.generateImage("#00000000", width, height, image);
break;
default:
throw new Error(`Invalid image generation operation: ${operation}`);
}
// This code disables the alpha chanel, as some images for the Apple App Store must not have transparency.
if (assetItem.rgba === false) {
// Add an underlying white layer
image = this.generateImage("#FFFFFF", image.width, image.height, image);
}
if (this.isAssetFilePath(outputPath)) {
image.write(outputPath);
} else {
this.$logger.warn(
`Incorrect destination path ${outputPath} for image ${assetItem.filename}`,
);
}
}
}
private async resize(
imagePath: string,
width: number,
height: number,
): Promise<JimpModule.JimpInstance> {
const image = await JimpModule.Jimp.read(imagePath);
return image.scaleToFit({
w: width,
h: height,
}) as JimpModule.JimpInstance;
}
private generateImage(
background: string,
width: number,
height: number,
overlayImage?: JimpModule.JimpInstance,
): JimpModule.JimpInstance {
const backgroundColor = this.getRgbaNumber(background);
let image = new JimpModule.Jimp({
width,
height,
color: backgroundColor,
});
if (overlayImage) {
const centeredWidth = (width - overlayImage.width) / 2;
const centeredHeight = (height - overlayImage.height) / 2;
image = image.composite(overlayImage, centeredWidth, centeredHeight);
}
return image;
}
private getRgbaNumber(colorString: string): number {
const color = new Color(colorString);
const colorRgb = color.rgb();
const alpha = Math.round(colorRgb.alpha() * 255);
return JimpModule.rgbaToInt(
colorRgb.red(),
colorRgb.green(),
colorRgb.blue(),
alpha,
);
}
private isAssetFilePath(path: string): path is `${string}.${string}` {
if (!path) {
return false;
}
const index = path.lastIndexOf(".");
return index > -1 && index < path.length - 1;
}
}
injector.register("assetsGenerationService", AssetsGenerationService);