Check-in [09db10509f]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Added a unit that provides easy access to version info -- not only a file's, but also the current module's (without accessing the file). Use that for the about box.
Timelines: family | ancestors | descendants | both | feature/async-refresh
Files: files | file ages | folders
SHA1: 09db10509f9db24ca99a1685283636b26069e431
User & Date: tinus 2015-11-27 18:35:39
Context
2015-11-27
21:18
Added overloaded operators for TVersion. check-in: 6062443d50 user: tinus tags: feature/async-refresh
18:35
Added a unit that provides easy access to version info -- not only a file's, but also the current module's (without accessing the file). Use that for the about box. check-in: 09db10509f user: tinus tags: feature/async-refresh
2015-11-25
21:49
Merged in changes from trunk. check-in: a2497f0938 user: tinus tags: feature/async-refresh
Changes

Changes to src/DelphiXE5/VCSInfo.dpk.

29
30
31
32
33
34
35
36

37
38

requires
  rtl,
  designide;

contains
  VCSInfoMenuWzrd in '..\VCSInfoMenuWzrd.pas',
  u_FinalPathName;


end.







|
>


29
30
31
32
33
34
35
36
37
38
39

requires
  rtl,
  designide;

contains
  VCSInfoMenuWzrd in '..\VCSInfoMenuWzrd.pas',
  u_FinalPathName,
  u_VersionInfo;

end.

Changes to src/DelphiXE5/VCSInfo.dproj.

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
...
108
109
110
111
112
113
114




115
116
117
118
119
120
121
...
123
124
125
126
127
128
129

130
131
132
133
134
135
136
    <Import Project="..\Version.optset" Condition="'$(Base)'!='' And Exists('..\Version.optset')"/>
    <PropertyGroup Condition="'$(Base)'!=''">
        <DCC_UnitSearchPath>..;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
        <DCC_SYMBOL_PLATFORM>false</DCC_SYMBOL_PLATFORM>
        <DCC_UNIT_PLATFORM>false</DCC_UNIT_PLATFORM>
        <DCC_CBuilderOutput>All</DCC_CBuilderOutput>
        <GenPackage>true</GenPackage>
        <DCC_Namespace>System;Xml;Data;Datasnap;Web;Soap;$(DCC_Namespace)</DCC_Namespace>
        <GenDll>true</GenDll>
        <SanitizedProjectName>VCSInfo</SanitizedProjectName>
        <DCC_DcuOutput>.\$(Platform)\$(Config)</DCC_DcuOutput>
        <DCC_ExeOutput>.\$(Platform)\$(Config)</DCC_ExeOutput>
        <DCC_E>false</DCC_E>
        <DCC_N>false</DCC_N>
        <DCC_S>false</DCC_S>
        <DCC_F>false</DCC_F>
        <DCC_K>false</DCC_K>
        <VerInfo_IncludeVerInfo>true</VerInfo_IncludeVerInfo>
        <VerInfo_Keys>CompanyName=Martijn Coppoolse;FileDescription=VCS Info;FileVersion=0.1.0.0;InternalName=VCSInfo;LegalCopyright=;LegalTrademarks=;OriginalFilename=VCSInfo.bpl;ProductName=VCS Info;ProductVersion=1.0;Comments=http://fossil.2of4.net/vcsInfo</VerInfo_Keys>
        <VerInfo_Locale>1033</VerInfo_Locale>
        <CfgDependentOn>..\Version.optset</CfgDependentOn>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Base_Android)'!=''">
        <DCC_UsePackage>rtl;$(DCC_UsePackage)</DCC_UsePackage>
        <DCC_CBuilderOutput>None</DCC_CBuilderOutput>
    </PropertyGroup>
................................................................................
        <DCC_DebugDCUs>true</DCC_DebugDCUs>
        <DCC_Optimize>false</DCC_Optimize>
        <DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
        <DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
        <DCC_RemoteDebug>true</DCC_RemoteDebug>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Cfg_1_Win32)'!=''">




        <DCC_RemoteDebug>false</DCC_RemoteDebug>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Cfg_2)'!=''">
        <DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
        <DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
        <DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
        <DCC_DebugInformation>0</DCC_DebugInformation>
................................................................................
    <ItemGroup>
        <DelphiCompile Include="$(MainSource)">
            <MainSource>MainSource</MainSource>
        </DelphiCompile>
        <DCCReference Include="rtl.dcp"/>
        <DCCReference Include="designide.dcp"/>
        <DCCReference Include="..\VCSInfoMenuWzrd.pas"/>

        <None Include="..\..\todo.md"/>
        <BuildConfiguration Include="Release">
            <Key>Cfg_2</Key>
            <CfgParent>Base</CfgParent>
        </BuildConfiguration>
        <BuildConfiguration Include="Base">
            <Key>Base</Key>







<









<
<







 







>
>
>
>







 







>







62
63
64
65
66
67
68

69
70
71
72
73
74
75
76
77


78
79
80
81
82
83
84
...
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
...
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
    <Import Project="..\Version.optset" Condition="'$(Base)'!='' And Exists('..\Version.optset')"/>
    <PropertyGroup Condition="'$(Base)'!=''">
        <DCC_UnitSearchPath>..;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
        <DCC_SYMBOL_PLATFORM>false</DCC_SYMBOL_PLATFORM>
        <DCC_UNIT_PLATFORM>false</DCC_UNIT_PLATFORM>
        <DCC_CBuilderOutput>All</DCC_CBuilderOutput>
        <GenPackage>true</GenPackage>

        <GenDll>true</GenDll>
        <SanitizedProjectName>VCSInfo</SanitizedProjectName>
        <DCC_DcuOutput>.\$(Platform)\$(Config)</DCC_DcuOutput>
        <DCC_ExeOutput>.\$(Platform)\$(Config)</DCC_ExeOutput>
        <DCC_E>false</DCC_E>
        <DCC_N>false</DCC_N>
        <DCC_S>false</DCC_S>
        <DCC_F>false</DCC_F>
        <DCC_K>false</DCC_K>


        <VerInfo_Locale>1033</VerInfo_Locale>
        <CfgDependentOn>..\Version.optset</CfgDependentOn>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Base_Android)'!=''">
        <DCC_UsePackage>rtl;$(DCC_UsePackage)</DCC_UsePackage>
        <DCC_CBuilderOutput>None</DCC_CBuilderOutput>
    </PropertyGroup>
................................................................................
        <DCC_DebugDCUs>true</DCC_DebugDCUs>
        <DCC_Optimize>false</DCC_Optimize>
        <DCC_GenerateStackFrames>true</DCC_GenerateStackFrames>
        <DCC_DebugInfoInExe>true</DCC_DebugInfoInExe>
        <DCC_RemoteDebug>true</DCC_RemoteDebug>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Cfg_1_Win32)'!=''">
        <VerInfo_MajorVer>0</VerInfo_MajorVer>
        <VerInfo_PreRelease>true</VerInfo_PreRelease>
        <VerInfo_DLL>true</VerInfo_DLL>
        <VerInfo_MinorVer>1</VerInfo_MinorVer>
        <DCC_RemoteDebug>false</DCC_RemoteDebug>
    </PropertyGroup>
    <PropertyGroup Condition="'$(Cfg_2)'!=''">
        <DCC_LocalDebugSymbols>false</DCC_LocalDebugSymbols>
        <DCC_Define>RELEASE;$(DCC_Define)</DCC_Define>
        <DCC_SymbolReferenceInfo>0</DCC_SymbolReferenceInfo>
        <DCC_DebugInformation>0</DCC_DebugInformation>
................................................................................
    <ItemGroup>
        <DelphiCompile Include="$(MainSource)">
            <MainSource>MainSource</MainSource>
        </DelphiCompile>
        <DCCReference Include="rtl.dcp"/>
        <DCCReference Include="designide.dcp"/>
        <DCCReference Include="..\VCSInfoMenuWzrd.pas"/>
        <DCCReference Include="..\u_VersionInfo.pas"/>
        <None Include="..\..\todo.md"/>
        <BuildConfiguration Include="Release">
            <Key>Cfg_2</Key>
            <CfgParent>Base</CfgParent>
        </BuildConfiguration>
        <BuildConfiguration Include="Base">
            <Key>Base</Key>

Changes to src/VCSInfoMenuWzrd.pas.

19
20
21
22
23
24
25

26
27
28
29
30
31
32
..
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
...
107
108
109
110
111
112
113
114
115

116
117
118
119
120
121
122
...
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
...
502
503
504
505
506
507
508

















509
510
511
512
513
514
515
...
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
...
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
...
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
...
895
896
897
898
899
900
901

902



903
904
905
906
907
908
909
    function IsRepo: Boolean;
  end;

  // TODO: implement IOTAEditorNotifier and/or IOTAIDENotifier so we know which file is active
  TVCSInfoWizard = class(TNotifierObject, IOTAWizard, IOTAMenuWizard)
    private
      FRepos: TDictionary<string,TRepoInfo>;


      FToolbar: TToolBar;
      FPluginAbout: Integer;

      FButtonSync: TToolButton;
      FButtonStatus: TToolButton;
      FButtonBranch: TToolButton;
................................................................................
procedure Register;

implementation
uses
  System.SysUtils, System.UITypes, System.Classes, System.StrUtils,
  Winapi.Windows, Winapi.ShellAPI,
  Vcl.Forms, Vcl.Dialogs, Vcl.Graphics,
  u_FinalPathName;

const
  scMenuIDString = 'net.2of4.VCSInfoWizard';
  cLimit = 9;

type
  TRefreshTrigger = (trgCode, trgUser, trgFileSaved, trgFileSwitched, trgTimer);
................................................................................
begin
  RegisterPackageWizard(TVCSInfoWizard.Create);
  (* TODO: create multiple separate menu wizards:
    - pull (incoming) / push (outgoing)
  *)
end;


{$REGION 'Functions to execute command-line and capture output'}

//--- JclBase and JclSysUtils --------------------------------------------------
const
  // line delimiters for a version of Delphi/C++Builder
  NativeLineFeed       = Char(#10);
  NativeCarriageReturn = Char(#13);

function CharIsReturn(const C: Char): Boolean;
................................................................................
                                            PChar(ACurrentDir),
                                            SUI, ProcInfo);
  except
    Result := False;
  end;
end {CreateProcess};

function GetCurrentVersion(): string;
// http://stackoverflow.com/a/1720501/3092116
var
  verblock: PVSFixedFileInfo;
  versionMS, versionLS: cardinal;
  verlen: cardinal;
  rs: TResourceStream;
  m: TMemoryStream;
  p: pointer;
  s: cardinal;
begin
  m := TMemoryStream.Create;
  try
    rs := TResourceStream.CreateFromID(HInstance, 1, RT_VERSION);
    try
      m.CopyFrom(rs, rs.Size);
    finally
      rs.Free;
    end;
    m.Position := 0;
    if VerQueryValue(m.Memory, '\', pointer(verblock), verlen) then begin
      VersionMS := verblock.dwFileVersionMS;
      VersionLS := verblock.dwFileVersionLS;
      Result := IntToStr(versionMS shr 16) + '.' +
                IntToStr(versionMS and $FFFF) + '.' +
                IntToStr(VersionLS shr 16) + '.' +
                IntToStr(VersionLS and $FFFF);
    end;
    if VerQueryValue(m.Memory, PChar('\\StringFileInfo\\' +
      IntToHex(GetThreadLocale,4) + IntToHex(GetACP,4) + '\\FileDescription'), p, s) or
        VerQueryValue(m.Memory, '\\StringFileInfo\\040904E4\\FileDescription', p, s) then //en-us
          Result := PChar(p) + ' ' + Result;
  finally
    m.Free;
  end;
end;

{ ================================================================================================ }
{ TVCSInfoWizard }

{ ------------------------------------------------------------------------------------------------ }
constructor TVCSInfoWizard.Create;
var
................................................................................
  actBranch: TAction;
  i: Integer;
begin
  LogMessage(StringOfChar('-', 80));

  Services := ToolsAPI.BorlandIDEServices as INTAServices;


















  Toolbar := nil;
  Services.ReadToolbar(Application.MainForm, Application.MainForm.FindChildControl('Controlbar1') as TWinControl, scToolbarName, Toolbar);
  if not (Toolbar is TToolBar) then begin
    FToolbar := Services.NewToolbar(scToolbarName, 'Repository');
    FToolbar.AutoSize := True;
    Services.WriteToolbar(FToolbar);
  end else begin
................................................................................
  AddButtonMenuItem(Button, FImgSyncPush, 'Outgoing changesets (push)');
  AddButtonMenuItem(Button, FImgSyncBoth, 'Incoming and outgoing changesets');
  AddButtonMenuItem(Button, -1,           '-');
  AddButtonMenuItem(Button, FImgClean,    'Working dir is clean');
  AddButtonMenuItem(Button, FImgPending,  'Working dir has changes');
  AddButtonMenuItem(Button, FImgExtra,    'Working dir has untracked files');
  AddButtonMenuItem(Button, -1,           '-');
  AddButtonMenuItem(Button, FImgIcon,     GetCurrentVersion, actInfoMenuVCSClick);


  LogMessage('Creating sync button...');
  actSync := TAction.Create(FToolbar);
  actSync.Caption := 'Nothing to sync';
  actSync.Hint := actSync.Caption;
  actSync.Enabled := True;
................................................................................
  if not Assigned(Toolbar) then begin
    FToolbar.Left := Application.MainForm.Width - FToolbar.Width;
    FToolbar.Visible := True;
  end;
//  Services.ToolbarModified(FToolbar);
  FToolbar.Invalidate;

  LogMessage('Inserting about box...');
  AboutBox := ToolsAPI.BorlandIDEServices as IOTAAboutBoxServices;
  FPluginAbout := AboutBox.AddPluginInfo(GetCurrentVersion, GetCurrentVersion + sLineBreak +
                                          sLineBreak +
                                          '© Martijn Coppoolse - http://fossil.2of4.net/vcsInfo',
                                          0);
end {TVCSInfoWizard.Create};
{ ------------------------------------------------------------------------------------------------ }
destructor TVCSInfoWizard.Destroy;
var
  Services: INTAServices;
  Button: TToolButton;
  i: Integer;
................................................................................
        end;
        1: begin // fossil
          ExecuteCmd('fossil version', Output);
          if Output <> '' then
            Item.Caption := Output.Replace('This is f', 'F').TrimRight;
        end;
        else begin
          Item.Caption := GetCurrentVersion;
        end;
      end;
    end;
  except
    on E: Exception do begin
      LogMessage('actInfoMenuPopUp raised ' + E.ClassName + sLineBreak + E.ToString);
    end;
................................................................................
        end;
         0: begin
          NewImageIndex := FImgClean;
          NewHint := 'Working directory is clean';
         end
        else begin
          NewImageIndex := FImgPending;

          NewHint := Format('%d file(s) pending', [Repo.Pending]);



        end;
      end;
    end else begin
      NewImageIndex := -1; // FImgNeutral;
      NewHint := 'No repository';
    end;








>







 







|







 







<

>







 







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







|







 







<
<
<
<
<
<







 







|







 







>
|
>
>
>







19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
..
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
...
108
109
110
111
112
113
114

115
116
117
118
119
120
121
122
123
...
382
383
384
385
386
387
388




































389
390
391
392
393
394
395
...
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
...
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
...
598
599
600
601
602
603
604






605
606
607
608
609
610
611
...
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
...
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
    function IsRepo: Boolean;
  end;

  // TODO: implement IOTAEditorNotifier and/or IOTAIDENotifier so we know which file is active
  TVCSInfoWizard = class(TNotifierObject, IOTAWizard, IOTAMenuWizard)
    private
      FRepos: TDictionary<string,TRepoInfo>;
      FCurrentVersion: string;

      FToolbar: TToolBar;
      FPluginAbout: Integer;

      FButtonSync: TToolButton;
      FButtonStatus: TToolButton;
      FButtonBranch: TToolButton;
................................................................................
procedure Register;

implementation
uses
  System.SysUtils, System.UITypes, System.Classes, System.StrUtils,
  Winapi.Windows, Winapi.ShellAPI,
  Vcl.Forms, Vcl.Dialogs, Vcl.Graphics,
  u_FinalPathName, u_VersionInfo;

const
  scMenuIDString = 'net.2of4.VCSInfoWizard';
  cLimit = 9;

type
  TRefreshTrigger = (trgCode, trgUser, trgFileSaved, trgFileSwitched, trgTimer);
................................................................................
begin
  RegisterPackageWizard(TVCSInfoWizard.Create);
  (* TODO: create multiple separate menu wizards:
    - pull (incoming) / push (outgoing)
  *)
end;


{$REGION 'Functions to execute command-line and capture output'}

//--- JclBase and JclSysUtils --------------------------------------------------
const
  // line delimiters for a version of Delphi/C++Builder
  NativeLineFeed       = Char(#10);
  NativeCarriageReturn = Char(#13);

function CharIsReturn(const C: Char): Boolean;
................................................................................
                                            PChar(ACurrentDir),
                                            SUI, ProcInfo);
  except
    Result := False;
  end;
end {CreateProcess};






































{ ================================================================================================ }
{ TVCSInfoWizard }

{ ------------------------------------------------------------------------------------------------ }
constructor TVCSInfoWizard.Create;
var
................................................................................
  actBranch: TAction;
  i: Integer;
begin
  LogMessage(StringOfChar('-', 80));

  Services := ToolsAPI.BorlandIDEServices as INTAServices;

  LogMessage('Inserting about box...');
  with TFileVersionInfo.Create(HInstance) do begin
    try
      FCurrentVersion := Trim(FileDescription + ' ' + FileVersionText);

      AboutBox := ToolsAPI.BorlandIDEServices as IOTAAboutBoxServices;
      FPluginAbout := AboutBox.AddPluginInfo(FCurrentVersion,
                                              FCurrentVersion + sLineBreak +
                                              sLineBreak +
                                              '© ' + CompanyName + ' - ' + Comments,
                                              0);
    finally
      Free;
    end;
  end;

  LogMessage('Creating toolbar');
  Toolbar := nil;
  Services.ReadToolbar(Application.MainForm, Application.MainForm.FindChildControl('Controlbar1') as TWinControl, scToolbarName, Toolbar);
  if not (Toolbar is TToolBar) then begin
    FToolbar := Services.NewToolbar(scToolbarName, 'Repository');
    FToolbar.AutoSize := True;
    Services.WriteToolbar(FToolbar);
  end else begin
................................................................................
  AddButtonMenuItem(Button, FImgSyncPush, 'Outgoing changesets (push)');
  AddButtonMenuItem(Button, FImgSyncBoth, 'Incoming and outgoing changesets');
  AddButtonMenuItem(Button, -1,           '-');
  AddButtonMenuItem(Button, FImgClean,    'Working dir is clean');
  AddButtonMenuItem(Button, FImgPending,  'Working dir has changes');
  AddButtonMenuItem(Button, FImgExtra,    'Working dir has untracked files');
  AddButtonMenuItem(Button, -1,           '-');
  AddButtonMenuItem(Button, FImgIcon,     FCurrentVersion, actInfoMenuVCSClick);


  LogMessage('Creating sync button...');
  actSync := TAction.Create(FToolbar);
  actSync.Caption := 'Nothing to sync';
  actSync.Hint := actSync.Caption;
  actSync.Enabled := True;
................................................................................
  if not Assigned(Toolbar) then begin
    FToolbar.Left := Application.MainForm.Width - FToolbar.Width;
    FToolbar.Visible := True;
  end;
//  Services.ToolbarModified(FToolbar);
  FToolbar.Invalidate;







end {TVCSInfoWizard.Create};
{ ------------------------------------------------------------------------------------------------ }
destructor TVCSInfoWizard.Destroy;
var
  Services: INTAServices;
  Button: TToolButton;
  i: Integer;
................................................................................
        end;
        1: begin // fossil
          ExecuteCmd('fossil version', Output);
          if Output <> '' then
            Item.Caption := Output.Replace('This is f', 'F').TrimRight;
        end;
        else begin
          Item.Caption := FCurrentVersion;
        end;
      end;
    end;
  except
    on E: Exception do begin
      LogMessage('actInfoMenuPopUp raised ' + E.ClassName + sLineBreak + E.ToString);
    end;
................................................................................
        end;
         0: begin
          NewImageIndex := FImgClean;
          NewHint := 'Working directory is clean';
         end
        else begin
          NewImageIndex := FImgPending;
          if Repo.Pending = 1 then begin
            NewHint := Format('%d file pending', [Repo.Pending]);
          end else begin
            NewHint := Format('%d files pending', [Repo.Pending]);
          end;
        end;
      end;
    end else begin
      NewImageIndex := -1; // FImgNeutral;
      NewHint := 'No repository';
    end;

Added src/u_VersionInfo.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
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
unit u_VersionInfo;

interface

uses
  Windows, SysUtils, System.Classes;

type
  TVersion = record
    Major:    Word;
    Minor:    Word;
    Revision: Word;
    Build:    Word;
    function ToString(): string;
  end;

type
  TFileVersionInfo = class
  {$SCOPEDENUMS ON}
  type
    TFlag = (Debug, PreRelease, Patched, PrivateBuild, SpecialBuild);
    TFlags = set of TFlag;
  strict private const
    cFlags: array[TFlag] of Cardinal = (VS_FF_DEBUG,
                                        VS_FF_PRERELEASE,
                                        VS_FF_PATCHED,
                                        VS_FF_PRIVATEBUILD,
                                        VS_FF_SPECIALBUILD);
  type
    TFileType = (Unknown = VFT_UNKNOWN,
                 Application = VFT_APP,
                 DLL = VFT_DLL,
                 Driver = VFT_DRV,
                 Font = VFT_FONT,
                 VirtualDevice = VFT_VXD,
                 StaticLib = VFT_STATIC_LIB);
    TFileSubtype = (Unknown = VFT2_UNKNOWN,
                    PrinterPrinter = VFT2_DRV_PRINTER,
                    KeyboardDriver = VFT2_DRV_KEYBOARD,
                    LanguageDriver = VFT2_DRV_LANGUAGE,
                    DisplayDriver = VFT2_DRV_DISPLAY,
                    MouseDriver = VFT2_DRV_MOUSE,
                    NetworkDriver = VFT2_DRV_NETWORK,
                    SystemDriver = VFT2_DRV_SYSTEM,
                    InstallableDriver = VFT2_DRV_INSTALLABLE,
                    SoundDriver = VFT2_DRV_SOUND,
                    CommunicationsDriver = VFT2_DRV_COMM,
                    RasterFont = VFT2_FONT_RASTER,
                    VectorFont = VFT2_FONT_VECTOR,
                    TrueTypeFont = VFT2_FONT_TRUETYPE);
  {$SCOPEDENUMS OFF}
  strict private type
    TLangAndCP = record
      wLanguage : word;
      wCodePage : word;
    end;
    PLangAndCP = ^TLangAndCP;
  private
    { Private declarations }
    FBufferStream       : TMemoryStream;
    FBufferPtr          : Pointer;
    FFilename           : string;
    FHasVersionInfo     : boolean;
    FLang               : PLangAndCP;

    FCompanyName        : string;
    FFileDescription    : string;
    FFileVersionText    : string;
    FInternalname       : string;
    FLegalCopyright     : string;
    FLegalTradeMarks    : string;
    FOriginalFilename   : string;
    FProductName        : string;
    FProductVersionText : string;
    FComments           : string;
    FSpecialBuild       : string;
    FPrivateBuild       : string;
    FFileVersion        : TVersion;
    FProductVersion     : TVersion;
    FFlags              : cardinal;
    FFileType           : TFileType;
    FFileSubtype        : TFileSubtype;

    procedure Clear;
    procedure ReadVersionInfoFromFile(const AFileName: string);
    procedure ReadVersionInfoFromModule(const AInstance: THandle);
    procedure ReadVersionInfo(const ABuffer: Pointer);

    procedure SetFileName(const AFileName: string);
    function  QueryValue(const AName: string): string;
    function  GetFlags: TFlags;
  protected
    { Protected declarations }
  public
    { Public declarations }
    constructor Create(const AFileName: string); overload;
    constructor Create(const AInstance: THandle); overload;
    destructor  Destroy; override;

    property FileName                 : string        read FFileName          write SetFileName;
    property HasVersionInfo           : boolean       read FHasVersionInfo;
    property Flags                    : TFlags        read GetFlags;
    property FileType                 : TFileType     read FFileType;
    property FileSubtype              : TFileSubtype  read FFileSubtype;

    { Published declarations }
    property CompanyName              : string        read FCompanyName;
    property FileDescription          : string        read FFileDescription;
    property FileVersion              : TVersion      read FFileVersion;
    property FileVersionText          : string        read FFileVersionText;
    property InternalName             : string        read FInternalname;
    property LegalCopyright           : string        read FLegalCopyright;
    property LegalTradeMarks          : string        read FLegalTradeMarks;
    property OriginalFilename         : string        read FOriginalFilename;
    property ProductName              : string        read FProductName;
    property ProductVersion           : TVersion      read FProductVersion;
    property ProductVersionText       : string        read FProductVersionText;
    property Comments                 : string        read FComments;

    property Value[const Name: string]: string        read QueryValue;
  end;

implementation

constructor TFileVersionInfo.Create(const AFileName: string);
begin
  inherited Create;
  SetFileName(AFileName);
end;

constructor TFileVersionInfo.Create(const AInstance: THandle);
begin
  inherited Create;
  ReadVersionInfoFromModule(AInstance);
end;

destructor TFileVersionInfo.Destroy;
begin
  Clear;
  inherited Destroy;
end;

procedure TFileVersionInfo.Clear;
begin
  FFilename           := '';
  FCompanyname        := '';
  FFileDescription    := '';
  FFileVersionText    := '';
  FInternalname       := '';
  FLegalCopyright     := '';
  FLegalTradeMarks    := '';
  FOriginalFilename   := '';
  FProductName        := '';
  FProductVersionText := '';
  FComments           := '';
  FSpecialBuild       := '';
  FPrivateBuild       := '';
  FFileVersion        := Default(TVersion);
  FProductVersion     := Default(TVersion);
  FFlags              := 0;
  if FBufferStream <> nil then begin
    FBufferStream.Free;
    FBufferStream := nil;
  end else if FBufferPtr <> nil then begin
    FreeMem(FBufferPtr);
  end;
  FBufferPtr := nil;
end;

procedure TFileVersionInfo.ReadVersionInfoFromFile(const AFileName: string);
var
  Dummy     : cardinal;
  BufferSize: integer;
begin
  Clear;
  FFilename := AFileName;

  BufferSize := GetFileVersionInfoSize(PChar(AFileName), Dummy);
  FHasVersionInfo := (Buffersize > 0);
  if FHasVersionInfo then begin
    FBufferPtr := AllocMem(BufferSize);
    FHasVersionInfo := GetFileVersionInfo(PChar(AFileName), 0, BufferSize, FBufferPtr);
    if FHasVersionInfo then begin
      ReadVersionInfo(FBufferPtr);
    end else begin
      FreeMem(FBufferPtr, BufferSize);
      FBufferPtr := nil;
    end;
  end;
end;

procedure TFileVersionInfo.ReadVersionInfoFromModule(const AInstance: THandle);
var
  RS: TResourceStream;
  BufferSize, ResultSize: Cardinal;
begin
  Clear;
  // Inspired by http://stackoverflow.com/a/1720501/3092116
  FBufferStream := TMemoryStream.Create;
  try
    RS := TResourceStream.CreateFromID(AInstance, 1, RT_VERSION);
    try
      FBufferStream.CopyFrom(RS, RS.Size);
    finally
      RS.Free;
    end;
    FBufferStream.Position := 0;
    FBufferPtr := FBufferStream.Memory;
    ReadVersionInfo(FBufferPtr);
  except
    FBufferStream.Free;
    FBufferStream := nil;
  end;

  // also try to determine the filename of the given instance
  BufferSize := MAX_PATH;
  repeat
    FFilename := StringOfChar(#0, BufferSize);
    ResultSize := GetModuleFileName(AInstance, PChar(FFilename), BufferSize);
    SetLength(FFilename, ResultSize);
    BufferSize := BufferSize * 2;
  until (ResultSize < BufferSize) or (GetLastError <> ERROR_INSUFFICIENT_BUFFER);
end;

procedure TFileVersionInfo.ReadVersionInfo(const ABuffer: Pointer);
  { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
  function ReadVersion(const MS, LS: Cardinal): TVersion; inline;
  begin
    Result.Major    := MS shr 16;
    Result.Minor    := MS and 65535;
    Result.Revision := LS shr 16;
    Result.Build    := LS and 65535;
  end;
  { - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
var
  Dummy     : cardinal;
  SubBlock  : string;
  InfoPtr   : Pointer;
  InfoBlock : TVSFixedFileInfo;
begin
  SubBlock := '\\VarFileInfo\\Translation';
  VerQueryValue(ABuffer, PChar(SubBlock), Pointer(FLang), Dummy);

  FCompanyName        := QueryValue('CompanyName');
  FFileDescription    := QueryValue('FileDescription');
  FFileVersionText    := QueryValue('FileVersion');
  FInternalName       := QueryValue('InternalName');
  FLegalCopyright     := QueryValue('LegalCopyright');
  FLegalTradeMarks    := QueryValue('LegalTradeMarks');
  FOriginalFilename   := QueryValue('OriginalFilename');
  FProductName        := QueryValue('ProductName');
  FProductVersionText := QueryValue('ProductVersion');
  FComments           := QueryValue('Comments');
  FSpecialBuild       := QueryValue('SpecialBuild');
  FPrivateBuild       := QueryValue('PrivateBuild');

  VerQueryValue(ABuffer, '\', InfoPtr, Dummy);
  Move(InfoPtr^, InfoBlock, SizeOf(InfoBlock));
  FFileVersion    := ReadVersion(InfoBlock.dwFileVersionMS, InfoBlock.dwFileVersionLS);
  FProductVersion := ReadVersion(InfoBlock.dwProductVersionMS, InfoBlock.dwProductVersionLS);
  FFlags          := InfoBlock.dwFileFlags and InfoBlock.dwFileFlagsMask;
  FFileType       := TFileType(InfoBlock.dwFileType);
  FFileSubtype    := TFileSubtype(InfoBlock.dwFileSubtype);
end;

function TFileVersionInfo.QueryValue(const AName: string): string;
var
  SubBlock  : string;
  Dummy     : cardinal;
  Value     : PChar;
begin
  SubBlock := Format('\\StringFileInfo\\%.4x%.4x\\%s', [GetThreadLocale, GetACP, AName]);
  if VerQueryValue(FBufferPtr, PChar(SubBlock), Pointer(Value), Dummy) then begin
    Result := string(Value);
  end else begin
    SubBlock := Format('\\StringFileInfo\\%.4x%.4x\\%s', [FLang.wLanguage, FLang.wCodePage, AName]);
    VerQueryValue(FBufferPtr, PChar(SubBlock), Pointer(Value), Dummy);
    Result := string(Value);
  end;
end;

procedure TFileVersionInfo.SetFileName(const AFileName: string);
begin
  ReadVersionInfoFromFile(AFileName);
end {TFileVersionInfo.SetFileName};

function TFileVersionInfo.GetFlags: TFlags;
var
  Flag: TFlag;
begin
  Result := [];
  for Flag := Low(cFlags) to High(cFlags) do begin
    if (FFlags and cFlags[Flag]) <> 0 then begin
      Include(Result, Flag);
    end;
  end;
end;


{ TVersion }

function TVersion.ToString: string;
begin
  Result := Format('%d.%d.%d.%d', [Major, Minor, Revision, Build]);
end;

end.