-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConfigHandlerINIFile.pas
110 lines (86 loc) · 3.18 KB
/
ConfigHandlerINIFile.pas
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
unit ConfigHandlerINIFile;
interface
uses
ConfigManager, ConfigState,
Forms, Classes, IniFiles, SysUtils;
const
R3T3_INI_FILE_NAME = 'R3T3.ini';
type
TConfigHandlerINIFile = class(TInterfacedObject, IConfigObserver)
private
FConfigManager: TConfigManager;
FINIFileName: String;
procedure LoadFileContents;
published
constructor Create(ConfigManager: TConfigManager);
procedure Update(Subject: TConfigManager);
end;
implementation
{ TConfigHandlerINIFile }
constructor TConfigHandlerINIFile.Create(ConfigManager: TConfigManager);
begin
inherited Create;
FConfigManager := ConfigManager;
FINIFileName := ExtractFileDir(Application.ExeName) + '\' + R3T3_INI_FILE_NAME;
LoadFileContents;
end;
procedure TConfigHandlerINIFile.LoadFileContents;
var
INIFile: TMemIniFile;
Sections, Keys: TStringList;
SectIdx, KeyIdx: Integer;
NewState: TConfigState;
begin
INIFile := TMemIniFile.Create(FINIFileName);
Sections := TStringList.Create;
INIFile.ReadSections(Sections);
If Sections.Count > 0
Then Begin
NewState := TConfigState.Clone(FConfigManager.CurrentState);
// Loop through all values and sections, over-writing that variable in the state
For SectIdx := 0 to Sections.Count - 1 do
Begin
Keys := TStringList.Create;
INIFile.ReadSection(Sections[SectIdx], Keys);
For KeyIdx := 0 to Keys.Count - 1 do
Begin
NewState.StringValues[ Sections[SectIdx], Keys[KeyIdx] ]
:= INIFile.ReadString(Sections[SectIdx], Keys[KeyIdx], '');
End;
End;
// Send the new state to the ConfigManager, and then free the local copy
FConfigManager.CurrentState := NewState;
NewState.Free;
End;
INIFile.Free;
end;
procedure TConfigHandlerINIFile.Update(Subject: TConfigManager);
var
INIFile: TMemIniFile;
Sections, Keys: TStringList;
SectIdx, KeyIdx: Integer;
begin
Sections := TStringList.Create;
Subject.CurrentState.ReadSections(Sections);
If Sections.Count > 0
Then Begin
INIFile := TMemIniFile.Create(FINIFileName);
// Pull all values out of current state, and write them to the file
For SectIdx := 0 to Sections.Count - 1 do
Begin
Keys := TStringList.Create;
Subject.CurrentState.ReadSection(Sections[SectIdx], Keys);
For KeyIdx := 0 to Keys.Count - 1 do
Begin
INIFile.WriteString(
Sections[SectIdx], Keys[KeyIdx],
Subject.CurrentState.StringValues[ Sections[SectIdx], Keys[KeyIdx] ]
);
End;
End;
// Save file, and free object
INIFile.UpdateFile;
INIFile.Free;
End;
end;
end.