File: ideinstances.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (857 lines) | stat: -rw-r--r-- 26,413 bytes parent folder | download
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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
{
 /***************************************************************************
                              ideinstances.pas
                              ----------------

 ***************************************************************************/

 ***************************************************************************
 *                                                                         *
 *   This source 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code 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.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************

  Author: Ondrej Pokorny

  Abstract:
    This unit handles one/multiple Lazarus IDE instances.

}
unit IDEInstances;

{$mode objfpc}{$H+}

interface

uses
  sysutils, Interfaces, Classes, Controls, Forms, Dialogs, ExtCtrls,
  LCLProc, LCLIntf, LCLType, LazFileUtils, LazUTF8, laz2_XMLRead, laz2_XMLWrite,
  Laz2_DOM, LazarusIDEStrConsts, IDECmdLine, crc,
  {$IF (FPC_FULLVERSION >= 30101)}
  AdvancedIPC
  {$ELSE}
  LazAdvancedIPC
  {$ENDIF}
  ;

type
  TStartNewInstanceResult = (ofrStartNewInstance, ofrDoNotStart, ofrModalError,
                             ofrForceSingleInstanceModalError, ofrNotResponding);
  TStartNewInstanceEvent = procedure(const aFiles: TStrings;
    var outResult: TStartNewInstanceResult; var outSourceWindowHandle: HWND) of object;
  TGetCurrentProjectEvent = procedure(var outProjectFileName: string) of object;

  TMessageParam = record
    Name: string;
    Value: string;
  end;
  TMessageParams = array of TMessageParam;

  TUniqueServer = class(TIPCServer)
  public
    procedure StartUnique(const aServerPrefix: string);
  end;

  TMainServer = class(TUniqueServer)
  private
    FStartNewInstanceEvent: TStartNewInstanceEvent;
    FGetCurrentProjectEvent: TGetCurrentProjectEvent;
    FTimer: TTimer;
    FMsgStream: TMemoryStream;

    procedure DoStartNewInstance(const aMsgID: Integer; const aInParams: TMessageParams);
    procedure DoGetCurrentProject(const aMsgID: Integer; const {%H-}aInParams: TMessageParams);

    procedure SimpleResponse(const aResponseToMsgID: Integer;
      const aResponseType: string; const aParams: array of TMessageParam);

    procedure DoCheckMessages;
    procedure CheckMessagesOnTimer(Sender: TObject);

    procedure StartListening(const aStartNewInstanceEvent: TStartNewInstanceEvent;
      const aGetCurrentProjectEvent: TGetCurrentProjectEvent);
    procedure StopListening;

  public
    constructor Create(aOwner: TComponent); override;
    destructor Destroy; override;
  end;

  TResponseClient = class(TIPCClient)
  public
    function GetCurrentProjectFileName: string;
    function AllowStartNewInstance(
      const aFiles: TStrings; var outModalErrorMessage,
      outModalErrorForceUniqueMessage, outNotRespondingErrorMessage: string;
      var outHandleBringToFront: HWND): TStartNewInstanceResult;
  end;

  TIDEInstances = class(TComponent)
  private
    FMainServer: TMainServer;//running IDE
    FStartIDE: Boolean;// = True;
    FForceNewInstance: Boolean;
    FFilesToOpen: TStrings;

    class procedure AddFilesToParams(const aFiles: TStrings;
      var ioParams: TMessageParams); static;
    class procedure AddFilesFromParams(const aParams: TMessageParams;
      const aFiles: TStrings); static;
    class procedure BuildMessage(const aMessageType: string;
      const aParams: array of TMessageParam; const aStream: TStream); static;
    class function MessageParam(const aName, aValue: string): TMessageParam; static;
    class function ParseMessage(const aStream: TStream; out outMessageType: string;
      out outParams: TMessageParams): Boolean; static;
    class function GetMessageParam(const aParams: array of TMessageParam;
      const aParamName: string): string; static;

    function CheckParamsForForceNewInstanceOpt: Boolean;

    procedure CollectFiles(out
      outFilesWereSentToCollectingServer: Boolean);

    function AllowStartNewInstance(const aFiles: TStrings;
      var outModalErrorMessage, outModalErrorForceUniqueMessage, outNotRespondingErrorMessage: string;
      var outHandleBringToFront: HWND): TStartNewInstanceResult;
    procedure InitIDEInstances;
  public
    constructor Create(aOwner: TComponent); override;
    destructor Destroy; override;
  public
    procedure PerformCheck;//call PerformCheck after Application.Initialize - it can open dialogs!

    procedure StartServer;
    procedure StopServer;
    procedure StartListening(const aStartNewInstanceEvent: TStartNewInstanceEvent;
      const aGetCurrentProjectEvent: TGetCurrentProjectEvent);
    procedure StopListening;

    function StartIDE: Boolean;//can the IDE be started?
    function ProjectIsOpenInAnotherInstance(aProjectFileName: string): Boolean;
    function FilesToOpen: TStrings;
  end;

function LazIDEInstances: TIDEInstances;

implementation

const
  SERVERNAME_COLLECT = 'LazarusCollect';
  MESSAGETYPE_XML = 2;
  ELEMENT_ROOT = 'ideinstances';
  ATTR_VALUE = 'value';
  ATTR_MESSAGE_TYPE = 'msgtype';
  MESSAGE_STARTNEWINSTANCE = 'startnewinstance';
  RESPONSE_OPENFILES = 'openfilesResponse';
  TIMEOUT_OPENFILES = 1000;
  MESSAGE_COLLECTFILES = 'collectfiles';
  TIMEOUT_COLLECTFILES = 100;
  PARAM_FILE = 'file';
  PARAM_RESULT = 'result';
  PARAM_HANDLEBRINGTOFRONT = 'handlebringtofront';
  PARAM_MODALERRORMESSAGE = 'modalerrormessage';
  PARAM_FORCEUNIQUEMODALERRORMESSAGE = 'forceuniquemodalerrormessage';
  PARAM_NOTRESPONDINGERRORMESSAGE = 'notrespondingerrormessage';
  MESSAGE_GETOPENEDPROJECT = 'getopenedproject';
  RESPONSE_GETOPENEDPROJECT = 'getopenedprojectResponse';
  TIMEOUT_GETOPENEDPROJECT = 100;
var
  FLazIDEInstances: TIDEInstances;
  FServerPrefix: string;

function LazIDEInstances: TIDEInstances;
begin
  Result := FLazIDEInstances;
end;

function LazServerPrefix: string;
// allow for multiple users on lazarus host system - encode to prevent illegal chars
begin
  if FServerPrefix = '' then
  begin
    // Calculate the user specific instance prefix only once.
    FServerPrefix := GetEnvironmentVariable('USER');    // current user
    // encode to cover illegal chars ('-' etc)
    FServerPrefix := IntToStr( crc32(0, pbyte(FServerPrefix), Length(FServerPrefix)) )
                     + '_LazarusMain';
  end;
  Result := FServerPrefix;
end;


{ TIDEInstances }

class function TIDEInstances.MessageParam(const aName, aValue: string): TMessageParam;
begin
  Result.Name := aName;
  Result.Value := aValue;
end;

function TIDEInstances.StartIDE: Boolean;
begin
  Result := FStartIDE;
end;

function TIDEInstances.ProjectIsOpenInAnotherInstance(aProjectFileName: string
  ): Boolean;
var
  xStartClient: TResponseClient;
  I: Integer;
  xServerIDs, xOpenedProjectFiles: TStringList;
  xProjFileName: string;
begin
  aProjectFileName := ExtractFilePath(aProjectFileName)+ExtractFileNameOnly(aProjectFileName);

  xStartClient := nil;
  xServerIDs := nil;
  xOpenedProjectFiles := nil;
  try
    xStartClient := TResponseClient.Create(nil);
    xServerIDs := TStringList.Create;
    xOpenedProjectFiles := TStringList.Create;

    xStartClient.FindRunningServers(LazServerPrefix, xServerIDs);

    for I := 0 to xServerIDs.Count-1 do
    begin
      if FMainServer.ServerID = xServerIDs[I] then
        continue; // ignore current instance
      xStartClient.ServerID := xServerIDs[I];
      xProjFileName := xStartClient.GetCurrentProjectFileName;
      if (xProjFileName='') then
        continue;
      xProjFileName := ExtractFilePath(xProjFileName)+ExtractFileNameOnly(xProjFileName);
      if CompareFilenames(xProjFileName, aProjectFileName)=0 then
        Exit(True);
    end;
  finally
    xStartClient.Free;
    xServerIDs.Free;
    xOpenedProjectFiles.Free;
  end;

  Result := False;
end;

function TIDEInstances.FilesToOpen: TStrings;
begin
  if not Assigned(FFilesToOpen) then
    FFilesToOpen := TStringList.Create;
  Result := FFilesToOpen;
end;

procedure TIDEInstances.StartListening(
  const aStartNewInstanceEvent: TStartNewInstanceEvent;
  const aGetCurrentProjectEvent: TGetCurrentProjectEvent);
begin
  Assert(Assigned(FMainServer));

  FMainServer.StartListening(aStartNewInstanceEvent, aGetCurrentProjectEvent);
end;

procedure TIDEInstances.StartServer;
begin
  Assert(FMainServer = nil);

  FMainServer := TMainServer.Create(Self);
  FMainServer.StartUnique(LazServerPrefix);
end;

procedure TIDEInstances.StopListening;
begin
  FMainServer.StopListening;
end;

procedure TIDEInstances.StopServer;
begin
  FreeAndNil(FMainServer);
end;

class procedure TIDEInstances.AddFilesFromParams(const aParams: TMessageParams;
  const aFiles: TStrings);
var
  I: Integer;
begin
  //do not clear aFiles
  for I := Low(aParams) to High(aParams) do
    if aParams[I].Name = PARAM_FILE then
      aFiles.Add(aParams[I].Value);
end;

class procedure TIDEInstances.AddFilesToParams(const aFiles: TStrings;
  var ioParams: TMessageParams);
var
  xStartIndex: Integer;
  I: Integer;
begin
  xStartIndex := Length(ioParams);
  SetLength(ioParams, xStartIndex+aFiles.Count);
  for I := 0 to aFiles.Count-1 do
    ioParams[xStartIndex+I] := MessageParam(PARAM_FILE, aFiles[I]);
end;

class function TIDEInstances.GetMessageParam(
  const aParams: array of TMessageParam; const aParamName: string): string;
var
  I: Integer;
begin
  for I := Low(aParams) to High(aParams) do
  if aParams[I].Name = aParamName then
    Exit(aParams[I].Value);

  Result := '';//not found
end;

class procedure TIDEInstances.BuildMessage(const aMessageType: string;
  const aParams: array of TMessageParam; const aStream: TStream);
var
  xDOM: TXMLDocument;
  xRoot: TDOMElement;
  xParam: TDOMElement;
  I: Integer;
begin
  xDOM := TXMLDocument.Create;
  try
    xRoot := xDOM.CreateElement(ELEMENT_ROOT);
    xRoot.AttribStrings[ATTR_MESSAGE_TYPE] := aMessageType;
    xDOM.AppendChild(xRoot);

    for I := Low(aParams) to High(aParams) do
    begin
      xParam := xDOM.CreateElement(aParams[I].Name);
      xRoot.AppendChild(xParam);
      xParam.AttribStrings[ATTR_VALUE] := aParams[I].Value;
    end;

    WriteXMLFile(xDOM, aStream);
  finally
    xDOM.Free;
  end;
end;

class function TIDEInstances.ParseMessage(const aStream: TStream; out
  outMessageType: string; out outParams: TMessageParams): Boolean;
var
  xDOM: TXMLDocument;
  xChildList: TDOMNodeList;
  I, J: Integer;
begin
  Result := False;

  outMessageType := '';
  SetLength(outParams, 0);
  try
    ReadXMLFile(xDOM, aStream, []);
  except
    on EXMLReadError do
      Exit;//eat XML exceptions
  end;
  try
    if (xDOM = nil) or (xDOM.DocumentElement = nil) or (xDOM.DocumentElement.NodeName <> ELEMENT_ROOT) then
      Exit;

    outMessageType := xDOM.DocumentElement.AttribStrings[ATTR_MESSAGE_TYPE];

    xChildList := xDOM.DocumentElement.ChildNodes;
    SetLength(outParams, xChildList.Count);
    J := 0;
    for I := 0 to xChildList.Count-1 do
    if xChildList[I] is TDOMElement then
    begin
      outParams[J].Name := xChildList[I].NodeName;
      outParams[J].Value := TDOMElement(xChildList[I]).AttribStrings[ATTR_VALUE];
      Inc(J);
    end;
    SetLength(outParams, J);
    Result := True;
  finally
    xDOM.Free;
  end;
end;

function TIDEInstances.AllowStartNewInstance(const aFiles: TStrings;
  var outModalErrorMessage, outModalErrorForceUniqueMessage,
  outNotRespondingErrorMessage: string; var outHandleBringToFront: HWND
  ): TStartNewInstanceResult;
var
  xStartClient: TResponseClient;
  I: Integer;
  xServerIDs: TStringList;
begin
  Result := ofrStartNewInstance;
  xStartClient := TResponseClient.Create(nil);
  xServerIDs := TStringList.Create;
  try                                      //check for multiple instances
    xStartClient.FindRunningServers(LazServerPrefix, xServerIDs);
    xServerIDs.Sort;

    for I := xServerIDs.Count-1 downto 0 do//last started is first to choose
    begin
      xStartClient.ServerID := xServerIDs[I];
      if xStartClient.ServerRunning then
      begin
        Result := xStartClient.AllowStartNewInstance(aFiles, outModalErrorMessage,
          outModalErrorForceUniqueMessage, outNotRespondingErrorMessage, outHandleBringToFront);
        if not(Result in [ofrModalError, ofrForceSingleInstanceModalError, ofrNotResponding]) then
          Exit;//handle only one running Lazarus IDE
      end;
    end;
  finally
    xStartClient.Free;
    xServerIDs.Free;
  end;
end;

function TIDEInstances.CheckParamsForForceNewInstanceOpt: Boolean;
var
  I: Integer;
begin
  Result := False;
  for I := 1 to ParamsAndCfgCount do
    if ParamIsOption(i, ForceNewInstanceOpt) then//ignore the settings and start new Lazarus IDE instance
      Result := True;
end;

procedure TIDEInstances.PerformCheck;
var
  xResult: TStartNewInstanceResult;
  xModalErrorMessage: string = '';
  xModalErrorForceUniqueMessage: string = '';
  xNotRespondingErrorMessage: string = '';
  xHandleBringToFront: HWND = 0;
begin
  if not FStartIDE then//InitIDEInstances->CollectOtherOpeningFiles decided not to start the IDE
    Exit;

  if not FForceNewInstance then
    xResult := AllowStartNewInstance(FilesToOpen, xModalErrorMessage, xModalErrorForceUniqueMessage, xNotRespondingErrorMessage, xHandleBringToFront)
  else
    xResult := ofrStartNewInstance;

  if xModalErrorMessage = '' then
    xModalErrorMessage := dlgRunningInstanceModalError;
  if xNotRespondingErrorMessage = '' then
    xNotRespondingErrorMessage := dlgRunningInstanceNotRespondingError;
  if xModalErrorForceUniqueMessage = '' then
    xModalErrorForceUniqueMessage := dlgForceUniqueInstanceModalError;

  FStartIDE := (xResult = ofrStartNewInstance);
  case xResult of
    ofrModalError:
      FStartIDE := MessageDlg(lisLazarusIDE, Format(xModalErrorMessage, [FilesToOpen.Text]), mtWarning, mbYesNo, 0, mbYes) = mrYes;
    ofrNotResponding:
      MessageDlg(lisLazarusIDE, xNotRespondingErrorMessage, mtError, [mbOK], 0);
    ofrForceSingleInstanceModalError:
      MessageDlg(lisLazarusIDE, xModalErrorForceUniqueMessage, mtError, [mbOK], 0);
  end;

  {$IFDEF MSWINDOWS}
  if not FStartIDE and (xHandleBringToFront <> 0) then
  begin
    try
      SetForegroundWindow(xHandleBringToFront);//SetForegroundWindow works (on Windows) only if the calling process is the foreground process, therefore it must be here!
    except
      //eat all widget exceptions
    end;
  end;
  {$ENDIF}
end;

constructor TIDEInstances.Create(aOwner: TComponent);
begin
  inherited Create(aOwner);

  FStartIDE := True;
end;

destructor TIDEInstances.Destroy;
begin
  StopServer;
  FreeAndNil(FMainServer);
  FreeAndNil(FFilesToOpen);

  inherited Destroy;
end;

procedure TIDEInstances.CollectFiles(out
  outFilesWereSentToCollectingServer: Boolean);

var
  xThisClientMessageId: Integer;

  procedure _SendToServer;
  var
    xClient: TIPCClient;
    xOutParams: TMessageParams;
    xStream: TMemoryStream;
  begin
    xClient := TIPCClient.Create(nil);
    try
      xClient.ServerID := SERVERNAME_COLLECT;

      SetLength(xOutParams, 0);
      AddFilesToParams(FilesToOpen, xOutParams);

      xStream := TMemoryStream.Create;
      try
        BuildMessage(MESSAGE_COLLECTFILES, xOutParams, xStream);
        xStream.Position := 0;
        xThisClientMessageId := xClient.PostRequest(MESSAGETYPE_XML, xStream);
      finally
        xStream.Free;
      end;
    finally
      xClient.Free;
    end;
  end;

  procedure _WaitForFiles;
  var
    xLastCount, xNewCount: Integer;
    xServer: TIPCServer;
  begin
    xServer := TIPCServer.Create(nil);
    try
      xServer.ServerID := SERVERNAME_COLLECT;
      //do not start server here
      xLastCount := -1;
      xNewCount := xServer.GetPendingRequestCount;
      while xLastCount <> xNewCount do
      begin
        xLastCount := xNewCount;
        Sleep(TIMEOUT_COLLECTFILES);
        xNewCount := xServer.GetPendingRequestCount;
      end;
    finally
      xServer.Free;
    end;
  end;

  function _ReceiveAsServer: Boolean;
  var
    xServer: TIPCServer;
    xInParams: TMessageParams;
    xStream: TMemoryStream;
    xMsgType: Integer;
    xMessageType: string;
  begin
    xStream := TMemoryStream.Create;
    xServer := TIPCServer.Create(nil);
    try
      xServer.ServerID := SERVERNAME_COLLECT;
      //files have to be handled only by one instance!
      Result := xServer.FindHighestPendingRequestId = xThisClientMessageId;
      if Result then
      begin
        //we are the highest client, handle the files
        xServer.StartServer(False);
      end else
      begin
        //we are not the highest client, maybe there are pending files, check that
        {$IFNDEF MSWINDOWS}
        //this code is not slowing up IDE start because if there was highest client found (the normal way), we close anyway
        Randomize;  //random sleep in order to prevent double file locks on unix
        Sleep((PtrInt(Random($3F)) + {%H-}PtrInt(GetCurrentThreadId)) and $3F);
        {$ENDIF}
        if not (xServer.StartServer(False) and (xServer.GetPendingRequestCount > 0)) then
          Exit;//server is already running or there are no pending message -> close
        Result := True;//no one handled handled the files, do it by myself
      end;

      FilesToOpen.Clear;
      while xServer.PeekRequest(xStream, xMsgType{%H-}) do
      if xMsgType = MESSAGETYPE_XML then
      begin
        if ParseMessage(xStream, xMessageType, xInParams) and
           (xMessageType = MESSAGE_COLLECTFILES)
        then
          AddFilesFromParams(xInParams, FilesToOpen);
      end;
    finally
      xStream.Free;
      xServer.Free;
    end;
  end;
begin
  //if you select more files in explorer and open them, they are not opened in one process but one process is started per file
  // -> collect them

  //first send messages to queue (there is no server, no problem, it will collect the messages when it is created)
  _SendToServer;

  //now wait until we have everything
  _WaitForFiles;

  //now send them to one instance
  outFilesWereSentToCollectingServer := not _ReceiveAsServer;
end;

procedure TIDEInstances.InitIDEInstances;
var
  xFilesWereSentToCollectingServer: Boolean;
  I: Integer;
begin
  FForceNewInstance := CheckParamsForForceNewInstanceOpt;

  //get cmd line filenames
  FFilesToOpen := ExtractCmdLineFilenames;
  for I := 0 to FilesToOpen.Count-1 do
    FilesToOpen[I] := CleanAndExpandFilename(FilesToOpen[I]);

  if FilesToOpen.Count > 0 then//if there are file in the cmd, check for multiple starting instances
  begin
    CollectFiles(xFilesWereSentToCollectingServer);
    if xFilesWereSentToCollectingServer then
    begin
      FilesToOpen.Clear;
      FStartIDE := False;
    end;
  end;
end;

{ TUniqueServer }

procedure TUniqueServer.StartUnique(const aServerPrefix: string);
var
  I: Integer;
begin
  if Active then
    StopServer;

  I := 0;
  while not Active do
  begin
    Inc(I);
    if I < 10 then
      ServerID := aServerPrefix+'0'+IntToStr(I)
    else
      ServerID := aServerPrefix+IntToStr(I);
    StartServer;
  end;
end;

{ TResponseClient }

function TResponseClient.AllowStartNewInstance(const aFiles: TStrings;
  var outModalErrorMessage, outModalErrorForceUniqueMessage,
  outNotRespondingErrorMessage: string; var outHandleBringToFront: HWND
  ): TStartNewInstanceResult;
var
  xStream: TMemoryStream;
  xMsgType: Integer;
  xResponseType: string;
  xOutParams, xInParams: TMessageParams;
begin
  Result := ofrStartNewInstance;
  xStream := TMemoryStream.Create;
  try
    //ask to show prompt
    xStream.Clear;
    SetLength(xOutParams, 0);
    TIDEInstances.AddFilesToParams(aFiles, xOutParams);
    TIDEInstances.BuildMessage(MESSAGE_STARTNEWINSTANCE, xOutParams, xStream);
    xStream.Position := 0;
    Self.PostRequest(MESSAGETYPE_XML, xStream);
    xStream.Clear;
    if PeekResponse(xStream, xMsgType{%H-}, TIMEOUT_OPENFILES) and
       (xMsgType = MESSAGETYPE_XML) then
    begin
      xStream.Position := 0;
      if TIDEInstances.ParseMessage(xStream, xResponseType, xInParams) and
         (xResponseType = RESPONSE_OPENFILES) then
      begin
        Result := TStartNewInstanceResult(StrToIntDef(TIDEInstances.GetMessageParam(xInParams, PARAM_RESULT), 0));
        outModalErrorMessage := TIDEInstances.GetMessageParam(xInParams, PARAM_MODALERRORMESSAGE);
        outModalErrorForceUniqueMessage := TIDEInstances.GetMessageParam(xInParams, PARAM_FORCEUNIQUEMODALERRORMESSAGE);
        outNotRespondingErrorMessage := TIDEInstances.GetMessageParam(xInParams, PARAM_NOTRESPONDINGERRORMESSAGE);
        outHandleBringToFront := StrToInt64Def(TIDEInstances.GetMessageParam(xInParams, PARAM_HANDLEBRINGTOFRONT), 0);
      end;
    end else//no response
    begin
      DeleteRequest;
      Result := ofrNotResponding;
    end;
  finally
    xStream.Free;
  end;
end;

function TResponseClient.GetCurrentProjectFileName: string;
var
  xStream: TMemoryStream;
  xMsgType: Integer;
  xResponseType: string;
  xOutParams, xInParams: TMessageParams;
begin
  Result := '';
  xStream := TMemoryStream.Create;
  try
    xStream.Clear;
    SetLength(xOutParams, 0);
    TIDEInstances.BuildMessage(MESSAGE_GETOPENEDPROJECT, xOutParams, xStream);
    xStream.Position := 0;
    Self.PostRequest(MESSAGETYPE_XML, xStream);
    xStream.Clear;
    if PeekResponse(xStream, xMsgType{%H-}, TIMEOUT_GETOPENEDPROJECT) and
       (xMsgType = MESSAGETYPE_XML) then
    begin
      xStream.Position := 0;
      if TIDEInstances.ParseMessage(xStream, xResponseType, xInParams) and
         (xResponseType = RESPONSE_GETOPENEDPROJECT) then
      begin
        Result := TIDEInstances.GetMessageParam(xInParams, PARAM_RESULT);
      end;
    end else//no response
    begin
      DeleteRequest;
      Result := '';
    end;
  finally
    xStream.Free;
  end;
end;

{ TMainServer }

procedure TMainServer.CheckMessagesOnTimer(Sender: TObject);
begin
  DoCheckMessages;
end;

constructor TMainServer.Create(aOwner: TComponent);
begin
  inherited Create(aOwner);

  FMsgStream := TMemoryStream.Create;
end;

destructor TMainServer.Destroy;
begin
  FMsgStream.Free;
  StopListening;

  inherited Destroy;
end;

procedure TMainServer.DoStartNewInstance(const aMsgID: Integer;
  const aInParams: TMessageParams);
var
  xResult: TStartNewInstanceResult;
  xFiles: TStrings;
  xParams: TMessageParams;
  xSourceWindowHandle: HWND = 0;
begin
  xResult := ofrStartNewInstance;
  if Assigned(FStartNewInstanceEvent) then
  begin
    xFiles := TStringList.Create;
    try
      TIDEInstances.AddFilesFromParams(aInParams, xFiles);
      FStartNewInstanceEvent(xFiles, xResult, xSourceWindowHandle);
    finally
      xFiles.Free;
    end;
  end;

  SetLength(xParams, 5);
  xParams[0] := TIDEInstances.MessageParam(PARAM_RESULT, IntToStr(Ord(xResult)));
  xParams[1] := TIDEInstances.MessageParam(PARAM_HANDLEBRINGTOFRONT, IntToStr(xSourceWindowHandle)); // do not use Application.MainFormHandle here - it steals focus from active source editor
  xParams[2] := TIDEInstances.MessageParam(PARAM_MODALERRORMESSAGE, dlgRunningInstanceModalError);
  xParams[3] := TIDEInstances.MessageParam(PARAM_FORCEUNIQUEMODALERRORMESSAGE, dlgForceUniqueInstanceModalError);
  xParams[4] := TIDEInstances.MessageParam(PARAM_NOTRESPONDINGERRORMESSAGE, dlgRunningInstanceNotRespondingError);
  SimpleResponse(aMsgID, RESPONSE_OPENFILES, xParams);
end;

procedure TMainServer.SimpleResponse(const aResponseToMsgID: Integer; const
  aResponseType: string; const aParams: array of TMessageParam);
var
  xStream: TMemoryStream;
begin
  xStream := TMemoryStream.Create;
  try
    TIDEInstances.BuildMessage(aResponseType, aParams, xStream);
    xStream.Position := 0;
    PostResponse(aResponseToMsgID, MESSAGETYPE_XML, xStream);
  finally
    xStream.Free;
  end;
end;

procedure TMainServer.StartListening(
  const aStartNewInstanceEvent: TStartNewInstanceEvent;
  const aGetCurrentProjectEvent: TGetCurrentProjectEvent);
begin
  Assert((FTimer = nil) and Assigned(aStartNewInstanceEvent) and Assigned(aGetCurrentProjectEvent));

  FTimer := TTimer.Create(nil);
  FTimer.OnTimer := @CheckMessagesOnTimer;
  FTimer.Interval := 50;
  FTimer.Enabled := True;

  FStartNewInstanceEvent := aStartNewInstanceEvent;
  FGetCurrentProjectEvent := aGetCurrentProjectEvent;
end;

procedure TMainServer.StopListening;
begin
  FreeAndNil(FTimer);

  FStartNewInstanceEvent := nil;
end;

procedure TMainServer.DoCheckMessages;
var
  xMessageType: string;
  xParams: TMessageParams;
  xMsgID, xMsgType: Integer;
begin
  if Active then
  begin
    while
       PeekRequest(FMsgStream, xMsgID{%H-}, xMsgType{%H-}) and
       (xMsgType = MESSAGETYPE_XML) and
       (TIDEInstances.ParseMessage(FMsgStream, xMessageType, xParams))
    do
      case xMessageType of
        MESSAGE_STARTNEWINSTANCE: DoStartNewInstance(xMsgID, xParams);
        MESSAGE_GETOPENEDPROJECT: DoGetCurrentProject(xMsgID, xParams);
      end;
  end;
end;

procedure TMainServer.DoGetCurrentProject(const aMsgID: Integer;
  const aInParams: TMessageParams);
var
  xResult: string;
  xParams: TMessageParams;
begin
  xResult := '';
  if Assigned(FStartNewInstanceEvent) then
    FGetCurrentProjectEvent(xResult);

  SetLength(xParams, 1);
  xParams[0] := TIDEInstances.MessageParam(PARAM_RESULT, xResult);
  SimpleResponse(aMsgID, RESPONSE_GETOPENEDPROJECT, xParams);
end;

initialization
  FLazIDEInstances := TIDEInstances.Create(nil);
  FLazIDEInstances.InitIDEInstances;

finalization
  FreeAndNil(FLazIDEInstances);

end.