-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgimpPaletteParser.js
96 lines (78 loc) · 2.63 KB
/
gimpPaletteParser.js
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
/*
* Copyright 2019 Abakkk
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* SPDX-FileCopyrightText: 2019 Abakkk
* SPDX-License-Identifier: GPL-3.0-or-later
*/
/* jslint esversion: 6 */
/* exported parseFile */
const decoder = new TextDecoder('utf-8');
/*
* [
* [
* 'palette name 1', // a palette for each column
* [
* 'rgb(...)',
* 'rgb(...):color display name', // the optional name separated with ':'
* ...
* ]
* ],
* [
* 'palette name 2',
* [...]
* ],
* ...
* ]
*/
function parse(contents) {
let lines = contents.split('\n');
let line, name, columnNumber;
line = lines.shift();
if (!line || !line.startsWith('GIMP Palette'))
log("Missing magic header");
line = lines.shift();
if (line.startsWith('Name:')) {
name = line.slice(5).trim() || file.get_basename();
line = lines.shift();
}
if (line.startsWith('Columns:')) {
columnNumber = Number(line.slice(8).trim()) || 1;
line = lines.shift();
}
let columns = (new Array(columnNumber)).fill(null).map(() => []);
lines.forEach((line, index) => {
if (!line || line.startsWith('#'))
return;
line = line.split('#')[0].trim();
let [, color, displayName] = line.split(/(^[\d\s]+)/);
let values = color.trim().split(/\D+/gi).filter(value => value >= 0 && value <= 255);
if (values.length < 3)
return;
let string = `rgb(${values[0]},${values[1]},${values[2]})`;
if (displayName.trim())
string += `:${displayName.trim()}`;
columns[index % columns.length].push(string);
});
return columns.map((column, index) => [columnNumber > 1 ? `${name} ${index + 1}` : name, column]);
}
export function parseFile(file) {
if (!file.query_exists(null))
return [];
let [, contents] = file.load_contents(null);
if (contents instanceof Uint8Array)
contents = decoder.decode(contents);
return parse(contents);
}