Menu

[r3214]: / branches / experimental / Src / SyntaxHighlighting / Highlighters / CS.Hiliter.Themes.Persist.pas  Maximize  Restore  History

Download this file

550 lines (494 with data), 15.6 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
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
{
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/
*
* Copyright (C) 2013, Peter Johnson (www.delphidabbler.com).
*
* $Rev$
* $Date$
*
* Classes that can store and load syntax highlighter themes.
}
unit CS.Hiliter.Themes.Persist;
interface
uses
SysUtils,
Generics.Collections,
UBaseObjects,
UExceptions,
UIStringList,
CS.Hiliter.Themes;
type
TSyntaxHiliteThemesParser = class(TObject)
strict private
type
/// <summary>Type of list used to store themes.</summary>
TThemeList = TList<TSyntaxHiliteTheme>;
var
/// <summary>Lines of themes "file".</summary>
fLines: IStringList;
/// <summary>Index or cursor of line being processed.</summary>
fLineIdx: Integer;
/// <summary>Initialises parser ready to start parsing the given theme
/// "source code".</summary>
procedure Init(const Source: string);
/// <summary>Moves line cursor to next line of code, skipping blank and
/// comment lines.</summary>
procedure NextLine;
/// <summary>Returns line currently being processed or empty string if all
/// lines have been processed.</summary>
function CurrentLine: string;
function CurrentStatement: string;
function CurrentParameter: string;
function IsValidIdent(const S: string): Boolean;
procedure ValidateIdent(const Statement, Ident: string;
Existing: IStringList);
procedure ParseWatermark;
/// <summary>Parses all themes in file and stores them in a list.</summary>
/// <param name="ThemeList">TThemeList [in] List to receive themese.
/// </param>
/// <param name="IsBuiltIn">Boolean [in] Informs if the themes being parsed
/// are built in (True) or user-defined (False).</para>
/// <remarks>Assumes that the current line is a "Theme" statement.
/// </remarks>
procedure ParseThemes(const ThemeList: TThemeList;
const IsBuiltIn: Boolean);
/// <summary>Parses all brush styles within the given theme and adds them
/// to the theme.</summary>
/// <remarks>Assumes that the current line is a "Brush" statement.
/// </remarks>
procedure ParseBrushStyles(const Theme: TSyntaxHiliteTheme);
/// <summary>Parses all attribute styles within the given brush style and
/// adds them to the brush style.</summary>
/// <remarks>Assumes that the current line is an "Attr" statement.
/// </remarks>
procedure ParseAttrStyles(const BrushStyle: TSyntaxHiliteBrushStyle);
function ParseAttrStyle(const AttrID, Data: string): TSyntaxHiliteAttrStyle;
public
constructor Create;
destructor Destroy; override;
procedure Parse(const Content: string; const IsBuiltIn: Boolean;
const Themes: TSyntaxHiliteThemes);
end;
TSyntaxHiliteThemesIO = class(TNoConstructObject)
strict private
class procedure WriteBrushStyle(const SB: TStringBuilder;
const BrushID: string; const BrushStyle: TSyntaxHiliteBrushStyle);
class procedure InternalLoadThemes(const Content: string;
const IsBuiltIn: Boolean; const Themes: TSyntaxHiliteThemes);
public
class procedure SaveThemes(const Themes: TSyntaxHiliteThemes;
const FileName: string);
class procedure LoadThemes(const Themes: TSyntaxHiliteThemes;
const FileName: string);
class procedure LoadThemesFromResources(const Themes: TSyntaxHiliteThemes;
const ResName: string; const ResType: PChar);
end;
ESyntaxHiliteThemesIO = class(ECodeSnip);
implementation
uses
Graphics, IOUtils, Classes,
UConsts,
UEncodings,
UIOUtils,
UResourceUtils,
UStrUtils;
const
/// <summary>Map of syntax highlighter font styles to identifiers used in a
/// themes file.</summary>
FontStyleMap: array[TSyntaxHiliteFontStyle] of string = (
'*', 'bold', 'italic', 'underline'
);
/// <summary>Watermark that is present on the first line of a valid
/// themes file.</summary>
Watermark = #$25BA + ' CodeSnip Syntax Highlight Themes v1 ' + #$25C4;
// Names of themes file keywords
KwdTheme = 'Theme';
KwdBrush = 'Brush';
KwdAttr = 'Attr';
resourcestring
// I/O and parsing error messages
sMissingThemeStatement = 'THEME statement expected';
sMissingAttrData = 'Missing data for ATTR "%s"';
sMissingFriendlyThemeName = 'Missing friendly name in THEME statement';
sMissingID = 'Missing identifier in %s statement';
sBadID = 'Invalid identifier "%0:s" in %1:s statement';
sBadAttrColour = 'Invalid colour in ATTR "%s"';
sBadFontStyle = 'Invalid font style in ATTR "%s"';
sBadWatermark = 'Invalid or missing watermark line';
sDuplicateID = 'Duplicate identifier "%0:s" in %1:s statement';
{ TSyntaxHiliteThemesIO }
class procedure TSyntaxHiliteThemesIO.InternalLoadThemes(const Content: string;
const IsBuiltIn: Boolean; const Themes: TSyntaxHiliteThemes);
var
Parser: TSyntaxHiliteThemesParser;
begin
Parser := TSyntaxHiliteThemesParser.Create;
try
Parser.Parse(Content, IsBuiltIn, Themes);
finally
Parser.Free;
end;
end;
class procedure TSyntaxHiliteThemesIO.LoadThemes(
const Themes: TSyntaxHiliteThemes; const FileName: string);
begin
if not TFile.Exists(FileName) then
Exit;
try
InternalLoadThemes(
TFileIO.ReadAllText(FileName, TEncoding.UTF8, True), False, Themes
);
except
on E: EStreamError do
raise ESyntaxHiliteThemesIO.Create(E);
on E: EIOUtils do
raise ESyntaxHiliteThemesIO.Create(E);
else
raise;
end;
end;
class procedure TSyntaxHiliteThemesIO.LoadThemesFromResources(
const Themes: TSyntaxHiliteThemes; const ResName: string;
const ResType: PChar);
var
Content: string;
begin
Content := LoadResourceAsString(HInstance, ResName, ResType, etUTF8, True);
InternalLoadThemes(Content, True, Themes);
end;
class procedure TSyntaxHiliteThemesIO.SaveThemes(
const Themes: TSyntaxHiliteThemes; const FileName: string);
var
Theme: TSyntaxHiliteTheme;
BrushID: string;
SB: TStringBuilder;
begin
SB := TStringBuilder.Create;
try
SB.AppendLine(Watermark);
SB.AppendLine;
for Theme in Themes do
begin
// Don't save built-in themes
if Theme.BuiltIn then
Continue;
SB.AppendLine(Format('%s %s %s', [KwdTheme, Theme.ID, Theme.FriendlyName]));
WriteBrushStyle(SB, '*', Theme.DefaultBrushStyle);
for BrushID in Theme.SupportedBrushes do
WriteBrushStyle(SB, BrushID, Theme.BrushStyles[BrushID]);
SB.AppendLine;
end;
TDirectory.CreateDirectory(TPath.GetDirectoryName(FileName));
try
TFileIO.WriteAllText(FileName, SB.ToString, TEncoding.UTF8, True);
except
on E: EStreamError do
raise ESyntaxHiliteThemesIO.Create(E);
else
raise;
end;
finally
SB.Free;
end;
end;
class procedure TSyntaxHiliteThemesIO.WriteBrushStyle(const SB: TStringBuilder;
const BrushID: string; const BrushStyle: TSyntaxHiliteBrushStyle);
var
AttrID: string;
AttrIDs: TArray<string>;
AttrStyle: TSyntaxHiliteAttrStyle;
function FormatAttrColour(const Colour: TColor): string;
begin
if Colour = clNone then
Exit('*');
Result := IntToHex(Integer(Colour), 8);
end;
function FormatAttrFontStyles(const FontStyles: TSyntaxHiliteFontStyles):
string;
var
FontStyle: TSyntaxHiliteFontStyle;
SL: IStringList;
begin
if hfsDefault in FontStyles then
Exit(FontStyleMap[hfsDefault]);
SL := TIStringList.Create;
for FontStyle in FontStyles do
SL.Add(FontStyleMap[FontStyle]);
Result := '{' + SL.GetText(',', False) + '}';
end;
begin
SB.AppendLine(Format(' %s %s', [KwdBrush, BrushID]));
AttrIDs := BrushStyle.SupportedAttrs;
for AttrID in AttrIDs do
begin
AttrStyle := BrushStyle.AttrStyles[AttrID];
SB.Append(Format(' %s %s ', [KwdAttr, AttrID]));
SB.Append(FormatAttrColour(AttrStyle.Background));
SB.Append(',');
SB.Append(FormatAttrColour(AttrStyle.Foreground));
SB.Append(',');
SB.Append(FormatAttrFontStyles(AttrStyle.FontStyles));
SB.AppendLine;
end;
end;
{ TSyntaxHiliteThemesParser }
constructor TSyntaxHiliteThemesParser.Create;
begin
inherited Create;
fLines := TIStringList.Create;
Init('');
end;
function TSyntaxHiliteThemesParser.CurrentLine: string;
begin
if fLineIdx < fLines.Count then
Result := fLines[fLineIdx]
else
Result := EmptyStr;
end;
function TSyntaxHiliteThemesParser.CurrentParameter: string;
var
Dummy: string;
begin
StrSplit(CurrentLine, ' ', Dummy, Result);
Result := StrTrim(Result);
end;
function TSyntaxHiliteThemesParser.CurrentStatement: string;
var
Dummy: string;
begin
StrSplit(CurrentLine, ' ', Result, Dummy);
Result := StrTrim(Result);
end;
destructor TSyntaxHiliteThemesParser.Destroy;
begin
inherited;
end;
procedure TSyntaxHiliteThemesParser.Init(const Source: string);
begin
fLineIdx := -1;
fLines.Clear;
fLines.Add(Source, EOL, True, True);
NextLine;
end;
function TSyntaxHiliteThemesParser.IsValidIdent(const S: string): Boolean;
var
C: Char;
begin
// An identifier contains only non-whitespace ASCII characters
for C in S do
if not CharInSet(C, [#33..#126]) then
Exit(False);
Result := True;
end;
procedure TSyntaxHiliteThemesParser.NextLine;
begin
if fLineIdx = fLines.Count then
Exit;
Inc(fLineIdx);
while (fLineIdx < fLines.Count) and
((fLines[fLineIdx] = EmptyStr) or StrStartsStr('#', fLines[fLineIdx])) do
Inc(fLineIdx);
end;
procedure TSyntaxHiliteThemesParser.Parse(const Content: string;
const IsBuiltIn: Boolean; const Themes: TSyntaxHiliteThemes);
var
ThemeList: TThemeList;
Theme: TSyntaxHiliteTheme;
begin
Init(Content);
ParseWatermark;
// We read themes into a temporary theme list rather than directly into Themes
// so that Themes is not modified at all should a parsing error occur. Only if
// parsing is successful do we update Themes.
ThemeList := TThemeList.Create;
try
try
while CurrentStatement <> EmptyStr do
begin
if not StrSameText(CurrentStatement, KwdTheme) then
raise ESyntaxHiliteThemesIO.Create(sMissingThemeStatement);
ParseThemes(ThemeList, IsBuiltIn);
NextLine;
end;
except
for Theme in ThemeList do
Theme.Free;
raise;
end;
for Theme in ThemeList do
Themes.Add(Theme);
finally
ThemeList.Free;
end;
end;
function TSyntaxHiliteThemesParser.ParseAttrStyle(const AttrID, Data: string):
TSyntaxHiliteAttrStyle;
function ParseColour(const Field: string): TColor;
var
ColourInt: Integer;
begin
if Field = EmptyStr then
raise ESyntaxHiliteThemesIO.CreateFmt(sBadAttrColour, [AttrID]);
if Field = '*' then
Exit(clNone);
if not TryStrToInt(HexDisplayPrefix + Field, ColourInt) then
raise ESyntaxHiliteThemesIO.CreateFmt(sBadAttrColour, [AttrID]);
Result := TColor(ColourInt);
end;
function ParseFontStyle(const Field: string): TSyntaxHiliteFontStyles;
function LookupStyle(const StyleStr: string;
out Style: TSyntaxHiliteFontStyle): Boolean;
var
I: TSyntaxHiliteFontStyle;
begin
for I := Low(FontStyleMap) to High(FontStyleMap) do
begin
if StrSameText(StyleStr, FontStyleMap[I]) then
begin
Style := I;
Exit(True);
end;
end;
Exit(False);
end;
var
StyleStrings: IStringList;
StyleString: string;
FontStyle: TSyntaxHiliteFontStyle;
begin
if Field = EmptyStr then
raise ESyntaxHiliteThemesIO.CreateFmt(sBadFontStyle, [AttrID]);
if Field = '*' then
Exit([hfsDefault]);
if (Length(Field) < 2)
or (Field[1] <> '{') or (Field[Length(Field)] <> '}') then
raise Exception.CreateFmt(sBadFontStyle, [AttrID]);
StyleStrings := TIStringList.Create(
StrSlice(Field, 2, Length(Field) - 2), ',', False, True
);
Result := [];
for StyleString in StyleStrings do
begin
if not LookupStyle(StyleString, FontStyle)
or (FontStyle = hfsDefault) then
raise Exception.CreateFmt(sBadFontStyle, [AttrID]);
Include(Result, FontStyle);
end;
end;
var
BGColour: string;
FGColour: string;
FontStyles: string;
Fields: string;
begin
Fields := StrTrim(Data);
if Data = EmptyStr then
raise ESyntaxHiliteThemesIO.CreateFmt(sMissingAttrData, [AttrID]);
BGColour := StrTrim(StrPop(Fields, ','));
FGColour := StrTrim(StrPop(Fields, ','));
FontStyles := StrTrim(Fields);
Result := TSyntaxHiliteAttrStyle.Create(
ParseColour(BGColour), ParseColour(FGColour), ParseFontStyle(FontStyles)
);
end;
procedure TSyntaxHiliteThemesParser.ParseAttrStyles(
const BrushStyle: TSyntaxHiliteBrushStyle);
var
AttrID: string;
AttrData: string;
AttrStyle: TSyntaxHiliteAttrStyle;
AttrIDs: IStringList;
begin
AttrIDs := TIStringList.Create;
while StrSameText(CurrentStatement, KwdAttr) do
begin
StrSplit(CurrentParameter, ' ', AttrID, AttrData);
AttrID := StrTrim(AttrID);
ValidateIdent(KwdAttr, AttrID, AttrIDs);
AttrIDs.Add(AttrID);
AttrStyle := ParseAttrStyle(AttrID, AttrData);
NextLine;
BrushStyle.Add(AttrID, AttrStyle);
end;
end;
procedure TSyntaxHiliteThemesParser.ParseBrushStyles(
const Theme: TSyntaxHiliteTheme);
var
BrushID: string;
BrushStyle: TSyntaxHiliteBrushStyle;
BrushIDs: IStringList;
begin
BrushIDs := TIStringList.Create;
while StrSameText(CurrentStatement, KwdBrush) do
begin
BrushID := CurrentParameter;
ValidateIdent(KwdBrush, BrushID, BrushIDs);
BrushIDs.Add(BrushID);
NextLine;
if BrushID = '*' then
ParseAttrStyles(Theme.DefaultBrushStyle)
else
begin
BrushStyle := TSyntaxHiliteBrushStyle.Create;
try
ParseAttrStyles(BrushStyle);
Theme.AddBrushStyle(BrushID, BrushStyle);
except
BrushStyle.Free;
raise
end;
end;
end;
end;
procedure TSyntaxHiliteThemesParser.ParseThemes(const ThemeList: TThemeList;
const IsBuiltIn: Boolean);
var
ThemeID: string;
ThemeFriendlyName: string;
Theme: TSyntaxHiliteTheme;
ThemeIDs: IStringList;
begin
ThemeIDs := TIStringList.Create;
while StrSameText(CurrentStatement, KwdTheme) do
begin
StrSplit(CurrentParameter, ' ', ThemeID, ThemeFriendlyName);
ThemeID := StrTrim(ThemeID);
ValidateIdent(KwdTheme, ThemeID, ThemeIDs);
ThemeIDS.Add(ThemeID);
ThemeFriendlyName := StrTrim(ThemeFriendlyName);
if ThemeFriendlyName = EmptyStr then
raise ESyntaxHiliteThemesIO.Create(sMissingFriendlyThemeName);
NextLine;
Theme := TSyntaxHiliteTheme.Create(ThemeID, ThemeFriendlyName, IsBuiltIn);
try
ParseBrushStyles(Theme);
ThemeList.Add(Theme);
except
Theme.Free;
raise;
end;
end;
end;
procedure TSyntaxHiliteThemesParser.ParseWatermark;
begin
if CurrentLine <> Watermark then
raise ESyntaxHiliteThemesIO.Create(sBadWatermark);
NextLine;
end;
procedure TSyntaxHiliteThemesParser.ValidateIdent(const Statement,
Ident: string; Existing: IStringList);
begin
if Ident = EmptyStr then
raise ESyntaxHiliteThemesIO.CreateFmt(sMissingID, [StrToUpper(Statement)]);
if not IsValidIdent(Ident) then
raise ESyntaxHiliteThemesIO.CreateFmt(
sBadID, [Ident, StrToUpper(Statement)]
);
if Existing.Contains(Ident) then
raise ESyntaxHiliteThemesIO.CreateFmt(
sDuplicateID, [Ident, StrToUpper(Statement)]
)
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.