File: encloseifdef.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 (449 lines) | stat: -rw-r--r-- 13,413 bytes parent folder | download | duplicates (2)
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
{
 /***************************************************************************
                    encloseifdef.pas  -  Conditional Defines
                    ----------------------------------------

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

 ***************************************************************************
 *                                                                         *
 *   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.   *
 *                                                                         *
 ***************************************************************************
}
unit EncloseIfDef;

{$mode objfpc}{$H+}

interface

(* Utility to assist in inserting conditional defines. For example, to convert
    OnCreate := @CreateHandler
  to:
    OnCreate := {$IFDEF FPC} @ {$ENDIF} CreateHandler
  select @ and then use Edit, Insert $IFDEF (default shortcut Ctrl+Shift+D),
  select "FPC,NONE" and hit return. If you select one or more complete lines
  then the conditional defines are put on sepearate lines as in:
  {$IFDEF DEBUG}
  Writeln('State= ', State)
  {$ENDIF}
  The choices are listed in abbreviated form so:
    MSWINDOWS,UNIX => {$IFDEF MSWINDOWS} ... {$ENDIF} {$IFDEF UNIX} ... {$ENDIF}
    FPC,ELSE       => {$IFDEF FPC} ... {$ELSE} ... {$ENDIF}
    DEBUG,NONE     => {$IFDEF DEBUG} ... {$ENDIF}
  This tool is most useful when you need to put several identical conditionals
  in a file, You can add to the possible conditionals by selecting or typing
  the required symbols in "First test" and /or "Second test" and using the
  Add button. Your additons are saved in the encloseifdef.xml file in the lazarus
  configuration directory.
*)

uses
  Classes, SysUtils, Controls, Forms, StdCtrls, Buttons, ButtonPanel,
  LCLProc, LCLType, LazConf, LazFileUtils, Laz2_XMLCfg, LazFileCache,
  IDEHelpIntf, IDEImagesIntf, LazarusIDEStrConsts;

type

  { TEncloseIfDefForm }

  TEncloseIfDefForm = class(TForm)
    AddBtn: TBitBtn;
    AddInverse: TBitBtn;
    ButtonPanel1: TButtonPanel;
    FirstLabel: TLabel;
    FirstTest: TComboBox;
    ListBox: TListBox;
    NewTestGroupBox: TGroupBox;
    RemoveBtn: TBitBtn;
    SecondLabel: TLabel;
    SecondTest: TComboBox;
    procedure AddBtnClick(Sender: TObject);
    procedure AddInverseCLICK(Sender: TObject);
    procedure btnSaveClick(Sender: TObject);
    procedure OKButtonClick(Sender: TObject);
    procedure TestEditChange(Sender: TObject);
    procedure HelpButtonClick(Sender: TObject);
    procedure CondFormCREATE(Sender: TObject);
    procedure ListBoxClick(Sender: TObject);
    procedure ListBoxDblClick(Sender: TObject);
    procedure RemoveBtnClick(Sender: TObject);
    procedure ListBoxKeyDown(Sender: TObject; var Key: Word; {%H-}Shift: TShiftState);
    procedure FormShow(Sender: TObject);
  private
    StoredChoice, StoredFirst, StoredSecond: string;
    FS: string;
    function SplitActiveRow(out aFirst, aSecond: string): Boolean;
    procedure DeleteSelected;
    procedure UpdateButtons;
    function IsChanged: Boolean;
    procedure SaveIfChanged;
    function CreateXMLConfig: TXMLConfig;
  end;


function EncloseInsideIFDEF(Text: string; IsPascal: Boolean):string;

implementation

{$R *.lfm}

const
  XmlRoot = 'encloseifdef/';

function ShowEncloseIfDefDlg: string;
var
  EncloseIfDefForm: TEncloseIfDefForm;
begin
  Result := '';
  EncloseIfDefForm := TEncloseIfDefForm.Create(nil);
  try
    EncloseIfDefForm.ActiveControl := EncloseIfDefForm.ListBox;
    if EncloseIfDefForm.ShowModal = mrOK then
      Result := EncloseIfDefForm.FS;
  finally
    EncloseIfDefForm.Free;
  end
end;

function EncloseInsideIFDEF(Text: string; IsPascal: Boolean):string;
var
  cond, s, f: string;
  p, p1: Integer;
  IsElse, IsTwo, HasNewline: Boolean;
  Tail, Indent: string;

  function ifdef(s:string):string;
  begin
    Result :='';
    if (s <>'') and (s[1] = '!') then begin
      if IsPascal then
        Result := 'N'
      else
        Result := 'n';
      s := Copy(s,2,Length(s)-1);
    end;
    if IsPascal then
      Result := '{$IF' + Result + 'DEF ' + s + '}'
    else
      Result := '#if' + Result + 'def ' + s;
  end;

begin
  Result := Text;
  cond := ShowEncloseIfDefDlg;
  p := Pos(',',cond);
  if p <= 0 then Exit;
  f := Copy(Cond, 1, p-1);
  s := Copy(Cond, p+1, Length(Cond));
  IsElse := CompareText(s, 'ELSE') = 0;
  IsTwo := CompareText(s, 'NONE') <> 0;
  HasNewline := Pos(#10, Text) > 0;
  if HasNewline then begin
    p := 1;
    { leave leading newlines unchanged (outside $IFDEF) }
    while (p <= Length(Text)) and (Text[p] in [#10,#13]) do Inc(p);
    Result := Copy(Text,1,p-1);
    p1 := p;
    { Work out current indentation, to line up $IFDEFS }
    while (p <= Length(Text)) and (Text[p] in [#9,' ']) do Inc(p);
    Indent := Copy(Text, p1, p-p1);
    Text := Copy(Text,p,Length(Text));
    p := Length(Text);
    { Tailing whitespace is left outside $IFDEF }
    while (p>0) and (Text[p] in [' ',#9,#10,#13]) do Dec(p);
    Tail := Copy(Text, p+1, Length(Text));
    SetLength(Text,p);
  end else begin
    Result := '';
    Tail := '';
    Indent := '';
  end;
  if IsPascal then begin
    f := ifdef(f);
    s := ifdef(s);
    if HasNewline then begin
      Result := Result + Indent + f + LineEnding + Indent + Text + LineEnding;
      if IsElse then
        Result := Result + Indent + '{$ELSE}' + LineEnding
      else begin
        Result := Result + Indent + '{$ENDIF}';
        if IsTwo then
          Result := Result + LineEnding + Indent + s + LineEnding;
      end;
      if IsTwo then
        Result := Result + Indent + Text + LineEnding + Indent + '{$ENDIF}';
      Result := Result + Tail;
    end else begin
      Result := Result + f + ' ' + Text;
      if IsElse then
        Result := Result + ' {$ELSE} '
      else begin
        Result := Result + ' {$ENDIF}';
        if IsTwo then
          Result := Result + ' ' + s + ' ';
      end;
      if IsTwo then
        Result := Result + Text + ' {$ENDIF}';
    end;
  end else begin
    Result := Result + ifdef(f) + LineEnding + indent + Text + LineEnding;
    if IsElse then
      Result := Result + '#else' + LineEnding
    else begin
      Result := Result + '#endif /* ' + f + ' */' + LineEnding;
      if IsTwo then
        Result := Result + ifdef(s) + LineEnding;
    end;
    if IsTwo then begin
      Result := Result + indent + Text + LineEnding + '#endif /* ';
      if IsElse then
        Result := Result + f
      else
        Result := Result + s;
      Result := Result + ' */' + LineEnding;
    end;
    Result := Result + Tail;
  end;
end;

{ TEncloseIfDefForm }

procedure TEncloseIfDefForm.CondFormCREATE(Sender: TObject);
var
  i: Integer;
  XMLConfig: TXMLConfig;
begin
  NewTestGroupBox.Caption := rsCreateNewDefine;
  Caption := rsConditionalDefines;
  FirstLabel.Caption := lisFirstTest;
  SecondLabel.Caption := lisSecondTest;
  AddBtn.Caption := lisBtnAdd;
  IDEImages.AssignImage(AddBtn, 'laz_add');
  AddInverse.Caption := rsAddInverse;
  IDEImages.AssignImage(AddInverse, 'pkg_issues');
  RemoveBtn.Caption := lisBtnRemove;
  IDEImages.AssignImage(RemoveBtn, 'laz_delete');
  ButtonPanel1.CloseButton.Caption := lisSave;
  ButtonPanel1.OKButton.Caption := lisOk;
  //ButtonPanel1.CloseButton.LoadGlyphFromStock(idButtonSave);
  //if btnSave.Glyph.Empty then
  //  btnSave.LoadGlyphFromResourceName(HInstance, 'laz_save');
  try
    XMLConfig:=CreateXMLConfig;
    try
      StoredChoice := XMLConfig.GetValue(XmlRoot + 'Choice',
        '"MSWINDOWS,UNIX","MSWINDOWS,ELSE","FPC,NONE","FPC,ELSE","DEBUG,NONE"');
      StoredFirst := XMLConfig.GetValue(XmlRoot + 'First', 'MSWINDOWS');
      StoredSecond := XMLConfig.GetValue(XmlRoot + 'Second', 'UNIX');
    finally
      XMLConfig.Free;
    end;
  except
    on E: Exception do begin
      debugln('TCondForm.CondFormCREATE ',E.Message);
    end;
  end;
  with ListBox do begin
    Items.CommaText := StoredChoice;
    i := Items.IndexOf(StoredFirst+','+StoredSecond);
    if i < 0 then begin
      Items.Add(StoredFirst+','+StoredSecond);
      ItemIndex := 0;
    end else
      ItemIndex := i;
  end;
end;

procedure TEncloseIfDefForm.FormShow(Sender: TObject);
begin
  if SecondTest.Items.Count < 10 then
    SecondTest.Items.AddStrings(FirstTest.Items);
  ListBoxClick(Nil);
end;

function TEncloseIfDefForm.SplitActiveRow(out aFirst, aSecond: string): Boolean;
var
  i: integer;
  Line: string;
begin
  Result := False;
  aFirst := '';
  aSecond := '';
  with ListBox do
    if ItemIndex >= 0 then begin
      Line := Items[ItemIndex];
      i := Pos(',', Line);
      if i > 0 then begin
        Result := True;
        aFirst := Copy(Line, 1, i-1);
        aSecond := Copy(Line, i+1, Length(Line));
      end
    end;
end;

procedure TEncloseIfDefForm.AddBtnClick(Sender: TObject);
begin
  ListBox.Items.Add(FirstTest.Text+','+SecondTest.Text);
  ListBox.ItemIndex := ListBox.Items.Count-1;
  UpdateButtons;
end;

procedure TEncloseIfDefForm.AddInverseCLICK(Sender: TObject);
begin
  ListBox.Items.Add('!'+FirstTest.Text+','+SecondTest.Text);
  ListBox.ItemIndex := ListBox.Items.Count-1;
  UpdateButtons;
end;

procedure TEncloseIfDefForm.TestEditChange(Sender: TObject);
begin
  UpdateButtons;
end;

procedure TEncloseIfDefForm.btnSaveClick(Sender: TObject);
begin
  SaveIfChanged;
  Close;
end;

procedure TEncloseIfDefForm.OKButtonClick(Sender: TObject);
begin
  SaveIfChanged;
  with ListBox do
    FS := Items[ItemIndex];  // Return selected row to caller.
end;

procedure TEncloseIfDefForm.HelpButtonClick(Sender: TObject);
begin
  LazarusHelp.ShowHelpForIDEControl(Self);
end;

procedure TEncloseIfDefForm.ListBoxClick(Sender: TObject);
var
  ff, ss: string;
begin
  if SplitActiveRow(ff, ss) then begin
    FirstTest.Text := ff;
    SecondTest.Text := ss;
    UpdateButtons;
  end;
end;

procedure TEncloseIfDefForm.ListBoxDblClick(Sender: TObject);
begin
  ModalResult := mrOK;
end;

procedure TEncloseIfDefForm.RemoveBtnClick(Sender: TObject);
begin
  DeleteSelected;
end;

procedure TEncloseIfDefForm.ListBoxKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if Key = VK_DELETE then begin
    DeleteSelected;
    Key := 0;
  end;
end;

procedure TEncloseIfDefForm.DeleteSelected;
var
  i: Integer;
begin
  with ListBox.Items do
    for i := Count-1 downto 0 do
      if ListBox.Selected[i] then begin
        Delete(i);
        UpdateButtons;
      end;
end;

procedure TEncloseIfDefForm.UpdateButtons;
var
  s: string;
begin
  s := FirstTest.Text+','+SecondTest.Text;
  AddBtn.Enabled := (FirstTest.Text <> '') and (ListBox.Items.IndexOf(s) = -1);
  s := '!' + s;
  AddInverse.Enabled := (FirstTest.Text <> '')
                    and (FirstTest.Text[1] <> '!')
                    and (ListBox.Items.IndexOf(s) = -1);
  RemoveBtn.Enabled := ListBox.SelCount > 0;
  ButtonPanel1.CloseButton.Enabled := IsChanged;
  ButtonPanel1.OKButton.Enabled := ListBox.SelCount > 0;
end;

function TEncloseIfDefForm.IsChanged: Boolean;
var
  ff, ss: string;
begin
  if StoredChoice <> ListBox.Items.CommaText then
    Exit(True);
  if SplitActiveRow(ff, ss) then begin
    if StoredFirst <> ff then
      Exit(True);
    if StoredSecond <> ss then
      Exit(True);
  end;
  Result := False;
end;

procedure TEncloseIfDefForm.SaveIfChanged;
var
  ff, ss: string;
  XMLConfig: TXMLConfig;
begin
  if ButtonPanel1.CloseButton.Enabled then // enabled only if there are changes
    try
      SplitActiveRow(ff, ss);
      InvalidateFileStateCache;
      XMLConfig:=CreateXMLConfig;
      try
        XMLConfig.SetValue(XmlRoot + 'Choice', ListBox.Items.CommaText);
        XMLConfig.SetValue(XmlRoot + 'First', ff);
        XMLConfig.SetValue(XmlRoot + 'Second', ss);
        XMLConfig.Flush;
      finally
        XMLConfig.Free;
      end;
    except
      on E: Exception do begin
        debugln('TCondForm.SaveIfChanged ',E.Message);
      end;
    end;
end;

function TEncloseIfDefForm.CreateXMLConfig: TXMLConfig;
var
  ConfFileName: String;
begin
  Result:=nil;
  ConfFileName:=AppendPathDelim(GetPrimaryConfigPath)+'encloseifdef.xml';
  try
    if (not FileExistsUTF8(ConfFileName)) then
      Result:=TXMLConfig.CreateClean(ConfFileName)
    else
      Result:=TXMLConfig.Create(ConfFileName);
  except
    on E: Exception do begin
      debugln('TCondForm.CreateXMLConfig ',E.Message);
    end;
  end;
end;

end.