summaryrefslogtreecommitdiff
path: root/packages/winunits-base/src/comserv.pp
blob: 522b6e8ad934d884eac83c3ad98ea46df02c7a49 (plain)
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
{
    This file is part of the Free Pascal run time library.
    Copyright (c) 2006 by Florian Klaempfl
    member of the Free Pascal development team.

    See the file COPYING.FPC, included in this distribution,
    for details about the copyright.

    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.

 **********************************************************************}
{$mode objfpc}
{$H+}
{$inline on}
unit ComServ;

interface

uses
  Classes, SysUtils, comobj, ActiveX;

{ $define DEBUG_COM}

//according to doc
// * ComServer Variable
// * DllCanUnloadNow Routine
// * DllGetClassObject Routine
// * DllRegisterServer Routine
// * DllUnregisterServer Routine
// * TComServer Class

//TODO Fix this
const
  CLASS_E_CLASSNOTAVAILABLE = -1;
  SELFREG_E_CLASS = -2;

type
  TStartMode = (smStandalone, smAutomation,smRegserver,smUnregserver);
  TLastReleaseEvent = procedure(var shutdown: Boolean) of object;

  { TComServer }

  TComServer = class(TComServerObject)
  class var orgInitProc: codepointer;
  private
    fCountObject: Integer;
    fCountFactory: Integer;
    fTypeLib: ITypeLib;
    fServerName,
    fServerFileName: String;
    fHelpFileName : String;
    fRegister: Boolean;
    fStartSuspended : Boolean;
    FIsInproc: Boolean;
    FIsInteractive: Boolean;
    FStartMode: TStartMode;
    FOnLastRelease: TLastReleaseEvent;

    class function AutomationDone: Boolean;
    class procedure AutomationStart;
    procedure CheckCmdLine;
    procedure FactoryFree(Factory: TComObjectFactory);
    procedure FactoryRegisterClassObject(Factory: TComObjectFactory);
    procedure FactoryUpdateRegistry(Factory: TComObjectFactory);
    procedure CheckReleased;
    function GetTypeLibName: widestring;
    procedure RegisterObjectWith(Factory: TComObjectFactory);
    procedure Start;
  protected
    function CountObject(Created: Boolean): Integer; override;
    function CountFactory(Created: Boolean): Integer; override;
    function GetHelpFileName: string; override;
    function GetServerFileName: string; override;
    function GetServerKey: string; override;
    function GetServerName: string; override;
    function GetStartSuspended: Boolean; override;
    function GetTypeLib: ITypeLib; override;
    procedure SetHelpFileName(const Value: string); override;


    procedure RegisterServerFactory(Factory: TComObjectFactory);
    procedure UnregisterServerFactory(Factory: TComObjectFactory);
  public
    constructor Create;
    destructor Destroy; override;
    function CanUnloadNow: Boolean;
    procedure RegisterServer;
    procedure UnRegisterServer;
    property IsInprocServer: Boolean read FIsInproc write FIsInproc;
    property IsInteractive: Boolean read fIsInteractive;
    property StartMode: TStartMode read FStartMode;
    property ServerObjects:integer read fCountObject;
  end;

var
  ComServer: TComServer = nil;
  haut :TLibHandle;


//http://msdn.microsoft.com/en-us/library/ms690368%28VS.85%29.aspx
//If the function succeeds, the return value is S_OK. Otherwise, it is S_FALSE.
function DllCanUnloadNow: HResult; stdcall;


//S_OK - The object was retrieved successfully.
//CLASS_E_CLASSNOTAVAILABLE - The DLL does not support the class (object definition).
function DllGetClassObject(constref rclsid: REFIID {should be REFCLSID}; constref riid: REFIID; out ppv: Pointer): HResult; stdcall;

//S_OK - The registry entries were created successfully.
//SELFREG_E_TYPELIB - The server was unable to complete the registration of all the type libraries used by its classes.
//SELFREG_E_CLASS - The server was unable to complete the registration of all the object classes.
function DllRegisterServer: HResult; stdcall;

//S_OK - The registry entries were deleted successfully.
//S_FALSE - Unregistration of this server's known entries was successful, but other entries still exist for this server's classes.
//SELFREG_E_TYPELIB - The server was unable to remove the entries of all the type libraries used by its classes.
//SELFREG_E_CLASS - The server was unable to remove the entries of all the object classes.
function DllUnregisterServer: HResult; stdcall;

implementation

uses
  Windows;

function DllCanUnloadNow: HResult; stdcall;
begin
{$ifdef DEBUG_COM}
  WriteLn('DllCanUnloadNow called');
{$endif}
  if ComServer.CanUnloadNow then
    Result := S_OK
  else
    Result := S_FALSE;
{$ifdef DEBUG_COM}
    WriteLn('DllCanUnloadNow return: ', Result);
{$endif}
end;

(*
    //FROM MSDN (Error messages are different in MSDN.DllGetClassObject)

    HRESULT hres = E_OUTOFMEMORY;
    *ppvObj = NULL;

    CClassFactory *pClassFactory = new CClassFactory(rclsid);
    if (pClassFactory != NULL)   {
        hRes = pClassFactory->QueryInterface(riid, ppvObj);
        pClassFactory->Release();
    }
    return hRes;
*)

function DllGetClassObject(constref rclsid: REFIID {should be REFCLSID}; constref riid: REFIID; out ppv: Pointer): HResult; stdcall;
var
  factory: TComObjectFactory;
begin
{$ifdef DEBUG_COM}
  WriteLn('DllGetClassObject called: ', GUIDToString(rclsid), ' ', GUIDToString(riid));
{$endif}

  factory := ComClassManager.GetFactoryFromClassID(rclsid);
  if factory = nil then
    Result := CLASS_E_CLASSNOTAVAILABLE
  else
  begin
    if factory.GetInterface(riid,ppv) then
      Result := S_OK
    else
      Result := CLASS_E_CLASSNOTAVAILABLE;
{$ifdef DEBUG_COM}
    WriteLn('DllGetClassObject return: ', Result);
{$endif}
  end;
end;

function DllRegisterServer: HResult; stdcall;
begin
{$ifdef DEBUG_COM}
  WriteLn('DllRegisterServer called');
{$endif}
  try
    ComServer.RegisterServer;
    Result := S_OK;
  except
    Result := SELFREG_E_CLASS;
  end;

end;

function DllUnregisterServer: HResult; stdcall;
begin
{$ifdef DEBUG_COM}
  WriteLn('DllUnregisterServer called');
{$endif}
  try
    ComServer.UnregisterServer;
    Result := S_OK;
  except
    Result := SELFREG_E_CLASS;
  end;
end;

function GetModuleFileName: String;
const
  MAX_PATH_SIZE = 2048;
var
  FileName: WideString;
begin
  SetLength(FileName, MAX_PATH_SIZE);
  SetLength(FileName, Windows.GetModuleFileNameW(HInstance, @FileName[1], MAX_PATH_SIZE));
  Result := FileName;
end;

function GetModuleName: String;
begin
  Result := ExtractFileName(GetModuleFileName);
  Result := Copy(Result, 1,LastDelimiter('.', Result)-1);
end;

procedure RegisterTypeLib(TypeLib: ITypeLib; const ModuleName: string);
var
  FullPath: WideString;
begin
  FullPath := ModuleName;
  //according to MSDN helpdir can be null
  OleCheck(ActiveX.RegisterTypeLib(TypeLib, @FullPath[1], nil));
end;

procedure UnRegisterTypeLib(TypeLib: ITypeLib);
var
  ptla: PTLibAttr;
begin
  //http://www.experts-exchange.com/Programming/Misc/Q_20634807.html
  OleCheck(TypeLib.GetLibAttr(ptla));
  try
    ActiveX.UnRegisterTypeLib(ptla^.guid, ptla^.wMajorVerNum, ptla^.wMinorVerNum, ptla^.lcid, ptla^.syskind);
  finally
    TypeLib.ReleaseTLibAttr(ptla);
  end;
end;


{ TComServer }

function TComServer.CountObject(Created: Boolean): Integer;
begin
  if Created then
  begin
    Result := InterlockedIncrement(FCountObject);
    if (not IsInProcServer) and (StartMode = smAutomation)
      and Assigned(ComObj.CoAddRefServerProcess) then
      ComObj.CoAddRefServerProcess;
  end
  else
  begin
    Result := InterlockedDecrement(FCountObject);
    if (not IsInProcServer) and (StartMode = smAutomation)
      and Assigned(ComObj.CoReleaseServerProcess) then
    begin
      if ComObj.CoReleaseServerProcess() = 0 then
        CheckReleased;
    end
    else if Result = 0 then
      CheckReleased;
  end;
end;

function TComServer.CountFactory(Created: Boolean): Integer;
begin
  if Created then
    Result:=InterLockedIncrement(fCountFactory)
  else
    Result:=InterLockedDecrement(fCountFactory);
end;

procedure TComServer.FactoryFree(Factory: TComObjectFactory);
begin
  Factory.Free;
end;

procedure TComServer.FactoryRegisterClassObject(Factory: TComObjectFactory);
begin
  Factory.RegisterClassObject;
end;

procedure TComServer.FactoryUpdateRegistry(Factory: TComObjectFactory);
begin
  if Factory.Instancing <> ciInternal then
    Factory.UpdateRegistry(FRegister);
end;

function TComServer.GetHelpFileName: string;
begin
  result:=fhelpfilename;
end;

function TComServer.GetServerFileName: string;
begin
  Result := fServerFileName;
end;

function TComServer.GetServerKey: string;
begin
  if FIsInproc then
    Result := 'InprocServer32'
  else
    Result := 'LocalServer32';
end;

function TComServer.GetServerName: string;
begin
  if FServerName <> '' then
    Result := FServerName
  else
    if FTypeLib <> nil then
      Result := GetTypeLibName
    else
      Result := GetModuleName;
end;

function TComServer.GetTypeLibName: widestring;
begin
  OleCheck(TypeLib.GetDocumentation(-1, @Result, nil, nil, nil));
end;


function TComServer.GetStartSuspended: Boolean;
begin
  result:=fStartSuspended;
end;

function TComServer.GetTypeLib: ITypeLib;
begin
  Result := fTypeLib;
end;

procedure TComServer.RegisterObjectWith(Factory: TComObjectFactory);
begin
  Factory.RegisterClassObject;
end;


procedure TComServer.Start;
begin
  case fStartMode of
  smRegServer:
    begin
      Self.RegisterServer;
      Halt;
    end;
  smUnregServer:
    begin
      Self.UnRegisterServer;
      Halt;
    end;
  end;
  ComClassManager.ForEachFactory(Self, @RegisterObjectWith);
end;


procedure TComServer.SetHelpFileName(const Value: string);
begin
  FHelpFileName:=value;
end;

procedure TComServer.RegisterServerFactory(Factory: TComObjectFactory);
begin
  Factory.UpdateRegistry(True);
end;

procedure TComServer.UnregisterServerFactory(Factory: TComObjectFactory);
begin
  Factory.UpdateRegistry(False);
end;

procedure TComServer.CheckCmdLine;
const
  sw_set:TSysCharSet = ['/','-'];
begin
  if FindCmdLineSwitch('automation',sw_set,true) or
     FindCmdLineSwitch('embedding',sw_set,true) then
    fStartMode := smAutomation
  else if FindCmdlIneSwitch('regserver',sw_set,true) then
    fStartMode := smRegServer
  else if FindCmdLineSwitch('unregserver',sw_set,true) then
    fStartMode := smUnregServer;
end;

constructor TComServer.Create;
var
  name: WideString;
begin
  haut := SafeLoadLibrary('oleaut32.DLL');
  CheckCmdLine;
  inherited Create;
{$ifdef DEBUG_COM}
  WriteLn('TComServer.Create');
{$endif}
  fCountFactory := 0;
  fCountObject := 0;

  FTypeLib := nil;
  FIsInproc := ModuleIsLib;

  fServerFileName := GetModuleFileName();

  name := fServerFileName;
  if not(Succeeded(LoadTypeLib(@name[1], fTypeLib))) then
    fTypeLib := nil;

  if FTypeLib <> nil then
  begin
    fTypeLib.GetDocumentation(-1, @name, nil, nil, nil);
    fServerName := name;
  end
  else
    fServerName := GetModuleName;

  if not ModuleIsLib then
  begin
    orgInitProc := InitProc;
    InitProc := @TComServer.AutomationStart;
  //  AddTerminateProc(TTerminateProc(@TComServer.AutomationDone));
  end;

  Self.FIsInteractive := True;
end;

class procedure TComServer.AutomationStart;
begin
  if orgInitProc <> nil then TProcedure(orgInitProc)();
  ComServer.FStartSuspended := (CoInitFlags <> -1) and
    Assigned(ComObj.CoInitializeEx) and Assigned(ComObj.CoResumeClassObjects);
  ComServer.Start;
  if ComServer.FStartSuspended then
    ComObj.CoResumeClassObjects;
end;

class function TComServer.AutomationDone: Boolean;
begin
  Result := True;
  if (ComServer <> nil) and (ComServer.ServerObjects > 0) and ComServer.IsInteractive then
  begin
    Result := MessageBox(0, PChar('COM server is in use'),
      PChar('OLE Automation'), MB_YESNO or MB_TASKMODAL or
      MB_ICONWARNING or MB_DEFBUTTON2) = IDYES;
  end;
end;


procedure TComServer.CheckReleased;
var
  Shutdown: Boolean;
begin
  if not FIsInproc then
  begin
    Shutdown := FStartMode = smAutomation;
    try
      if Assigned(FOnLastRelease) then FOnLastRelease(Shutdown);
    finally
      if Shutdown then PostThreadMessage(MainThreadID, WM_QUIT, 0, 0);
    end;
  end;
end;


destructor TComServer.Destroy;
begin
  ComClassManager.ForEachFactory(Self, @FactoryFree,true);
  Self.fTypeLib:=nil;
  inherited Destroy;
  FreeLibrary(haut);
{$ifdef DEBUG_COM}
  WriteLn('TComServer.Destroy');
{$endif}
end;

function TComServer.CanUnloadNow: Boolean;
begin
  Result := False;
end;

procedure TComServer.RegisterServer;
begin
  if fTypeLib <> nil then
    RegisterTypeLib(fTypeLib, fServerFileName);

  ComClassManager.ForEachFactory(self, @RegisterServerFactory);
end;

procedure TComServer.UnRegisterServer;
begin
  if fTypeLib <> nil then
    UnRegisterTypeLib(fTypeLib);

  ComClassManager.ForEachFactory(self, @UnregisterServerFactory);
end;


initialization
{$ifdef DEBUG_COM}
  WriteLn('comserv initialization begin');
{$endif}
  ComServer := TComServer.Create;

{$ifdef DEBUG_COM}
  WriteLn('comserv initialization end');
{$endif}
finalization
  ComServer.AutomationDone;
  FreeAndNil(ComServer);
end.