-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathXPM.pas
More file actions
459 lines (386 loc) · 11 KB
/
XPM.pas
File metadata and controls
459 lines (386 loc) · 11 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
(*
Greenfish Icon Editor Pro
Copyright (c) 2012-13 B. Szalkai
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/>.
*)
unit XPM;
interface
uses
LclIntf, LclType,
SysUtils, Classes, BitmapEx, bmExUtils,
PixelFormats, Math, StreamEx, StrUtils, Dialogs;
function xpmDetect(Data: Pointer; Size: integer): boolean;
function xpmLoadFromStream(bm: TBitmap32; var HotSpot: TPoint; st: TStream): boolean;
procedure xpmSaveToStream(bm: TBitmap32; const xpmID: string;
const HotSpot: TPoint; st: TStream);
function xpmLoadFromFile(bm: TBitmap32; var HotSpot: TPoint; const fn: string): boolean;
procedure xpmSaveToFile(bm: TBitmap32; const xpmID: string;
const HotSpot: TPoint; const fn: string);
implementation
function xpmDetect;
var
s: string;
begin
if (Size >= 2) and (PChar(Data)[0] = '/') and (PChar(Data)[1] = '*') then
Exit(True);
SetLength(s, Size);
Move(Data^, s[1], Size);
Result := (Pos('/* XPM */', s) > 0) or (Pos('char*', s) > 0) or
(Pos('char *', s) > 0);
end;
function xpmValidID(const s: string): string;
var
i: integer;
begin
Result := s;
for i := 1 to Length(Result) do if not (Result[i] in ['0'..'9', 'A'..'Z',
'a'..'z', '_']) then Result[i] := '_';
if (Length(Result) = 0) or (Result[1] in ['0'..'9']) then
Result := '_' + Result;
end;
const
cl32XpmNone = cl32Lime;
type
TxpmStringArray = array of string;
// Splits a whitespace-separated string
procedure xpmSplitString(const s: string; var a: TxpmStringArray);
const
WhiteSpace: set of char = [#0, #9, #10, #13, #32, #255];
var
i, Start: integer;
begin
SetLength(a, 0);
Start := 0;
for i := 1 to Length(s) + 1 do
if (Start <> 0) and ((i > Length(s)) or (s[i] in WhiteSpace)) then
begin
SetLength(a, Length(a) + 1);
a[Length(a) - 1] := Copy(s, Start, i - Start);
Start := 0;
end else
if (Start = 0) and (i <= Length(s)) and not (s[i] in WhiteSpace) then
Start := i;
end;
// Reads the next quoted character sequence
function xpmReadString(sr: TBufferedReader): string;
var
c: char;
CurrEscape, PrevEscape: boolean;
begin
Result := '';
// find and read the next quoted C-style string
repeat sr.Read(@c, 1); until c = '"';
PrevEscape := False;
while True do
begin
sr.Read(@c, 1);
CurrEscape := False;
if PrevEscape then
begin
case c of
'0': c := #0;
'a': c := #7;
'b': c := #8;
't': c := #9;
'n': c := #10;
'v': c := #11;
'f': c := #12;
'r': c := #13;
end;
Result += c;
end else
case c of
'"': Break; // end of string
'\': CurrEscape := True;
else Result += c;
end; // if not escaped
PrevEscape := CurrEscape;
end;
end;
// Parses an #rr...gg...bb... identifier or a symbolic color name
function xpmStrToColor(s: string): TColor32;
var
i, cpc: integer;
b: byte;
begin
Result := cl32XpmNone;
s := UpperCase(s);
if s = '' then Exit else
if s[1] = '#' then
// rgb code
begin
// chars per component
cpc := (Length(s) - 1) div 3;
if cpc <> 0 then
begin
Result := 0;
// read red, green and blue component
for i := 0 to 2 do
begin
if cpc = 1 then b := StrToInt('$' + s[2 + i]) shl 4 else
b := StrToInt('$' + Copy(s, 2 + i*cpc, 2));
Result := (Result shl 8) or b;
end;
Result := FlipColor32(Result) or cl32Opaque;
end; // if cpc <> 0
end else
// a selection of symbolic names
if s = 'BLACK' then Result := cl32Black else
if s = 'BLUE' then Result := cl32Blue else
if s = 'GREEN' then Result := cl32Green else
if s = 'CYAN' then Result := cl32Teal else
if s = 'RED' then Result := cl32Red else
if s = 'YELLOW' then Result := cl32Yellow else
if s = 'MAROON' then Result := cl32Maroon else
if (s = 'GRAY') or (s = 'GREY') then Result := cl32Gray else
if s = 'WHITE' then Result := cl32White else
if (s = 'NONE') or (s = 'TRANSPARENT') then Result := cl32Transparent;
end;
type
TxpmPalEntry = record
Key: string;
Value: TColor32;
end;
function xpmLoadFromStream;
var
sr: TBufferedReader;
i, j, x, y, cpp: integer;
s, s2, sPix, Pivot: string;
a: TxpmStringArray;
Palette: array of TxpmPalEntry;
tmp: TxpmPalEntry;
c: TColor32;
procedure PaletteQuickSort(iLo, iHi: integer);
var
Lo, Hi: Integer;
begin
repeat
Lo := iLo;
Hi := iHi;
Pivot := Palette[(iLo + iHi) div 2].Key;
repeat
while Palette[Lo].Key < Pivot do Inc(Lo);
while Palette[Hi].Key > Pivot do Dec(Hi);
if Lo <= Hi then
begin
tmp := Palette[Lo];
Palette[Lo] := Palette[Hi];
Palette[Hi] := tmp;
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
if Hi > iLo then PaletteQuickSort(iLo, Hi);
// if Lo < iHi then PaletteQuickSort(Lo, iHi);
iLo := Lo;
until Lo >= iHi;
end;
function PaletteLookup(const s: string): TColor32;
var
lo, hi, mid: integer;
begin
// find the corresponding color
lo := 0;
hi := Length(Palette);
if Palette[lo].Key = s then Exit(Palette[lo].Value);
while hi - lo > 1 do
begin
mid := (lo + hi) div 2;
if Palette[mid].Key = s then Exit(Palette[mid].Value);
if Palette[mid].Key < s then lo := mid else hi := mid;
end;
Result := cl32XpmNone;
end;
begin
Result := False;
try
sr := TBufferedReader.Create(st);
try
// load the header
s := xpmReadString(sr);
xpmSplitString(s, a);
// apply loaded data
bm.Resize(StrToInt(a[0]), StrToInt(a[1]));
SetLength(Palette, StrToInt(a[2]));
cpp := StrToInt(a[3]);
if Length(a) >= 6 then
begin
TryStrToInt(a[4], HotSpot.X);
TryStrToInt(a[5], HotSpot.Y);
end;
// load the palette
for i := 0 to Length(Palette) - 1 do
begin
s := xpmReadString(sr);
// memorize character sequence which means this color
s2 := Copy(s, 1, cpp);
Delete(s, 1, cpp+1);
// look for the c (color visual) entry
xpmSplitString(s, a);
c := cl32XpmNone;
for j := 0 to Length(a) - 2 do if UpperCase(a[j]) = 'C' then
begin
c := xpmStrToColor(a[j+1]);
Break;
end;
// add entry
with Palette[i] do
begin
Key := s2;
Value := c;
end;
end;
// sort the palette
PaletteQuickSort(0, Length(Palette) - 1);
// load the pixmap
SetLength(sPix, cpp);
for y := 0 to bm.Height - 1 do
begin
s := xpmReadString(sr);
for x := 0 to bm.Width - 1 do
begin
// load the code
Move(s[1 + x*cpp], sPix[1], cpp);
bm.PixelAddr(x, y)^ := PaletteLookup(sPix);
end; // for x
end; // for y
finally
sr.Free;
end;
// success
Result := True;
except
end;
end;
// We can use the characters from #32 to #126, except " and \
// We could escape them, but that may cause trouble in some image editors
const
XPM_CHAR_COUNT = 126-32+1 - 2;
function xpmGetCharsPerPixel(Count: integer): integer;
begin
if Count <= 0 then Result := 1 else Result := Ceil(Ln(Count) / Ln(XPM_CHAR_COUNT));
end;
function xpmIndexToStr(Index, cpp: integer): string;
var
i: integer;
c: char;
begin
Result := '';
for i := 1 to cpp do
begin
c := Char(32 + Index mod XPM_CHAR_COUNT);
// jump over " and \
if c >= '"' then inc(c);
if c >= '\' then inc(c);
Result += c;
// iterate
Index := Index div XPM_CHAR_COUNT;
end;
end;
procedure xpmSaveToStream;
var
i, x, y, Index, cpp: integer;
s, s2: string;
Palette: TiePalette;
CreateBMNew: boolean;
bmNew: TBitmap32;
p: PColor32;
procedure DoWrite(const s: string);
begin
st.WriteBuffer(s[1], Length(s));
end;
begin
// we need a palette
Palette := TiePalette.Create;
try
// remove alpha channel
CreateBMNew := GetPixelFormat32(bm, nil, nil, nil, nil) = pf32_32bit;
if CreateBMNew then
begin
bmNew := TBitmap32.Create;
bmNew.Assign(bm);
bmNew.ThresholdAlpha;
end else
bmNew := bm;
// build palette
p := bmNew.Data;
for i := 0 to bmNew.Width*bmNew.Height - 1 do
begin
if p^ and cl32Opaque <> 0 then Palette.Add(p^ and not cl32Opaque, False);
inc(p);
end;
try
// +1, because the transparent color is not the part of the palette
cpp := xpmGetCharsPerPixel(Palette.Count + 1);
// write header
DoWrite(Format('/* XPM */'#10'static char *%s[] = {'#10 +
'"%d %d %d %d %d %d",'#10,
[xpmValidID(xpmID), bm.Width, bm.Height, Palette.Count + 1, cpp,
HotSpot.X, HotSpot.Y]));
// write palette
for i := 0 to Palette.Count do
begin
s := xpmIndexToStr(i, cpp);
if i < Palette.Count then s2 := '#' + IntToHex(
FlipColor(Integer(Palette[i] and not cl32Opaque)), 6) else
s2 := 'None';
DoWrite(Format('"%s c %s",'#10, [s, s2]));
end;
// write bitmap
for y := 0 to bmNew.Height - 1 do
begin
s := '"';
for x := 0 to bmNew.Width - 1 do
begin
p := bmNew.PixelAddr(x, y);
if PByteArray(p)[3] = 0 then Index := Palette.Count else
Index := Palette.IndexOf(p^ and not cl32Opaque);
s := s + xpmIndexToStr(Index, cpp);
end; // for x
if y = bmNew.Height - 1 then s := s + '"'#10'};'#10 else
s := s + '",'#10;
DoWrite(s);
end; // for y
finally
if CreateBMNew then bmNew.Free;
end; // try bmNew
finally
Palette.Free;
end; // try Palette
end;
function xpmLoadFromFile;
var
s: TStream;
begin
try
s := TFileStream.Create(fn, fmOpenRead);
try
Result := xpmLoadFromStream(bm, HotSpot, s);
finally
s.Free;
end;
except
Result := False;
end;
end;
procedure xpmSaveToFile;
var
s: TStream;
begin
s := TFileStream.Create(fn, fmCreate);
try
xpmSaveToStream(bm, xpmID, HotSpot, s);
finally
s.Free;
end;
end;
end.