Menu

[r2000]: / trunk / Src / FmSnippetsEditorDlg.pas  Maximize  Restore  History

Download this file

974 lines (912 with data), 31.8 kB

  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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
{
* FmSnippetsEditorDlg.pas
*
* Implements a dialog box that enables the user to create or edit a user
* defined snippet.
*
* $Rev$
* $Date$
*
* ***** BEGIN LICENSE BLOCK *****
*
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* The Original Code is FmSnippetsEditorDlg, formerly FmUserDBEditDlg.pas
*
* The Initial Developer of the Original Code is Peter Johnson
* (http://www.delphidabbler.com/).
*
* Portions created by the Initial Developer are Copyright (C) 2008-2012 Peter
* Johnson. All Rights Reserved.
*
* Contributors:
* NONE
*
* ***** END LICENSE BLOCK *****
}
unit FmSnippetsEditorDlg;
interface
uses
// Delphi
SysUtils, Classes, ActnList, Buttons, StdCtrls, Forms, Controls, CheckLst,
ComCtrls, ExtCtrls, StdActns, Menus, ImgList,
// Project
ActiveText.UMain, Compilers.UGlobals, DB.USnippet, FmGenericOKDlg,
FrBrowserBase, FrFixedHTMLDlg, FrHTMLDlg, UBaseObjects, UCategoryListAdapter,
UCompileMgr, UCompileResultsLBMgr, UCSSBuilder, ULEDImageList,
UMemoCaretPosDisplayMgr, UMemoHelper, USnipKindListAdapter,
USnippetsChkListMgr, UUnitsChkListMgr, FmSnippetsEditorDlg.FrActiveTextEditor;
type
{
TSnippetsEditorDlg:
Dialog box class that enables the user to create or edit a user defined
snippet.
}
TSnippetsEditorDlg = class(TGenericOKDlg, INoPublicConstruct)
alMain: TActionList;
actAddUnit: TAction;
actCompile: TAction;
actCopy: TEditCopy;
actCut: TEditCut;
actDependencies: TAction;
actPaste: TEditPaste;
actSelectAll: TEditSelectAll;
actSetAllQuery: TAction;
actSetAllSuccess: TAction;
actUndo: TEditUndo;
actViewErrors: TAction;
actViewExtra: TAction;
actViewTestUnit: TAction;
btnAddUnit: TButton;
btnDependencies: TButton;
btnCompile: TButton;
btnSetAllQuery: TBitBtn;
btnSetAllSuccess: TBitBtn;
btnViewExtra: TButton;
btnViewTestUnit: TButton;
cbCategories: TComboBox;
cbKind: TComboBox;
clbDepends: TCheckListBox;
clbUnits: TCheckListBox;
clbXRefs: TCheckListBox;
edName: TEdit;
edSourceCode: TMemo;
edUnit: TEdit;
ilMain: TImageList;
lbCompilers: TListBox;
lblCategories: TLabel;
lblCompilers: TLabel;
lblCompileShortcuts: TLabel;
lblCompResDesc: TLabel;
lblDepends: TLabel;
lblDescription: TLabel;
lblExtra: TLabel;
lblExtraCaretPos: TLabel;
lblName: TLabel;
lblKind: TLabel;
lblSourceCaretPos: TLabel;
lblSourceCode: TLabel;
lblSnippetKindHelp: TLabel;
lblUnits: TLabel;
lblViewCompErrs: TLabel;
lblViewCompErrsKey: TLabel;
lblXRefs: TLabel;
miCopy: TMenuItem;
miCut: TMenuItem;
miPaste: TMenuItem;
miSelectAll: TMenuItem;
miSpacer1: TMenuItem;
miSpacer2: TMenuItem;
miUndo: TMenuItem;
mnuEditCtrls: TPopupMenu;
pcMain: TPageControl;
pnlViewCompErrs: TPanel;
tsCode: TTabSheet;
tsComments: TTabSheet;
tsCompileResults: TTabSheet;
tsReferences: TTabSheet;
frmDescription: TSnippetsActiveTextEdFrame;
btnViewDescription: TButton;
actViewDescription: TAction;
frmExtra: TSnippetsActiveTextEdFrame;
procedure actAddUnitExecute(Sender: TObject);
procedure actAddUnitUpdate(Sender: TObject);
procedure actCompileExecute(Sender: TObject);
procedure actCompileUpdate(Sender: TObject);
procedure actDependenciesExecute(Sender: TObject);
procedure actSetAllQueryExecute(Sender: TObject);
procedure actSetAllSuccessExecute(Sender: TObject);
procedure actViewErrorsExecute(Sender: TObject);
procedure actViewErrorsUpdate(Sender: TObject);
procedure actViewExtraExecute(Sender: TObject);
procedure actViewExtraUpdate(Sender: TObject);
procedure actViewTestUnitExecute(Sender: TObject);
procedure actViewTestUnitUpdate(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure cbKindChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lblSnippetKindHelpClick(Sender: TObject);
procedure lblViewCompErrsClick(Sender: TObject);
procedure pcMainChange(Sender: TObject);
/// <summary>Handles event triggered when user clicks on one of page
/// control tabs. Ensures page control has focus.</summary>
/// <remarks>Without this fix, page control does not always get focus when
/// a tab is clicked.</remarks>
procedure pcMainMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure actViewDescriptionExecute(Sender: TObject);
procedure actViewDescriptionUpdate(Sender: TObject);
strict private
fSnippet: TSnippet; // Snippet being edited: nil for new snippet
fCatList: TCategoryListAdapter; // Accesses sorted list of categories
fSnipKindList:
TSnipKindListAdapter; // Accesses sorted list of snippet kinds
fOrigName: string; // Original name of snippet ('' for new)
fEditData: TSnippetEditData; // Record storing a snippet's editable data
fCompileMgr: TCompileMgr; // Manages compilation and results display
fDependsCLBMgr:
TSnippetsChkListMgr; // Manages dependencies check list box
fXRefsCLBMgr:
TSnippetsChkListMgr; // Manages x-refs check list box
fUnitsCLBMgr: TUnitsChkListMgr; // Manages units check list box
fCompilersLBMgr:
TCompileResultsLBMgr; // Manages compilers list box
fImages: TLEDImageList; // Image list containing LEDs
fSourceMemoHelper: TMemoHelper; // Helper for working with source code memo
fMemoCaretPosDisplayMgr: TMemoCaretPosDisplayMgr;
// Manages display of memo caret positions
procedure PopulateControls;
{Populates controls with dynamic data.
}
procedure InitControls;
{Initialises controls to default values.
}
procedure FocusCtrl(const Ctrl: TWinControl);
{Displays and focusses a control, selecting its parent tab sheet if
necessary.
@param Ctrl [in] Control to be focussed.
}
procedure HandleException(const E: Exception);
{Handles trapped exceptions. EDataEntry exceptions are caught, an error
message is displayed and the control causing the exception is focussed.
Other exceptions are re-raised.
@param E [in] Exception to be handled.
@except Exceptions re-raised if not EDataEntry.
}
procedure SetAllCompilerResults(const CompRes: TCompileResult);
{Sets all compiler results to same value.
@param CompRes [in] Required compiler result.
}
procedure ValidateData;
{Checks all user-entered data in all tabs of the form.
@except EDataEntry raised if data is not valid.
}
function UpdateData: TSnippetEditData;
{Updates snippet's data from user entries. Assumes data has been
validated.
@return Record containing snippet's data.
}
procedure UpdateReferences;
{Updates dependencies and cross-references check lists for snippet being
edited, depending on kind.
}
function CreateTempSnippet: TSnippet;
{Creates a temporary snippet from data entered in dialog box.
@return Required snippet instance.
@except EDataEntry raised if any of entered data is invalid.
}
procedure DisplayCompileResults(const Compilers: ICompilers);
{Displays results of a test compilation. Used as callback method for
compile manager.
@param Compilers [in] Object containing compilation results.
}
strict protected
procedure ArrangeForm; override;
{Arranges controls on form and sizes it.
}
procedure ConfigForm; override;
{Configures form's controls. Sets font and colors of "link" labels. Also
sets item height of owner draw check list boxes.
}
procedure InitForm; override;
{Performs initialisation of form fields and controls.
}
public
class function AddNewSnippet(AOwner: TComponent): Boolean;
{Displays dialog box to enable user to enter a new snippet.
@param AOwner [in] Control that owns the dialog box, over which the
dialog is aligned. May be nil.
@return True if user OKs, False if cancels.
}
class function EditSnippet(AOwner: TComponent;
const Snippet: TSnippet): Boolean;
{Displays dialog box to enable user to edit a snippet.
@param AOwner [in] Control that owns the dialog box, over which the
dialog is aligned. May be nil.
@param Snippet [in] Reference to snippet to be edited.
@return True if user OKs, False if cancels.
}
end;
implementation
uses
// Delphi
Windows {for inlining}, Graphics,
// Project
DB.UMain, DB.USnippetKind, FmDependenciesDlg, FmViewExtraDlg, IntfCommon,
UColours, UConsts, UCSSUtils, UCtrlArranger, UExceptions, UFontHelper,
UIStringList, UReservedCategories, USnippetExtraHelper, USnippetValidator,
UMessageBox, USnippetIDs, UStructs, UStrUtils, UTestUnitDlgMgr, UThemesEx,
UUtils;
{$R *.dfm}
{ TSnippetsEditorDlg }
procedure TSnippetsEditorDlg.actAddUnitExecute(Sender: TObject);
{Adds a unit to the list of required units and selects it.
@param Sender [in] Not used.
}
var
UnitName: string; // name of new unit from edit control
resourcestring
// Error messages
sBadUnitName = 'Unit name is not a valid Pascal identifier';
sUnitNameExists = 'Unit name already in list';
begin
UnitName := StrTrim(edUnit.Text);
Assert(UnitName <> '',
ClassName + '.actAddUnitExecute: UnitName is empty string');
try
if not fUnitsCLBMgr.IsValidUnitName(UnitName) then
raise EDataEntry.Create(
sBadUnitName, edUnit, TSelection.Create(0, Length(UnitName))
);
if fUnitsCLBMgr.ContainsUnit(UnitName) then
raise EDataEntry.Create(
sUnitNameExists, edUnit, TSelection.Create(0, Length(UnitName))
);
fUnitsCLBMgr.IncludeUnit(UnitName, True);
edUnit.Text := '';
except
on E: Exception do
HandleException(E);
end;
end;
procedure TSnippetsEditorDlg.actAddUnitUpdate(Sender: TObject);
{Updates Add Unit action according to whether any unit name is entered in
associated edit control.
@param Sender [in] Action triggering this event.
}
begin
(Sender as TAction).Enabled := (StrTrim(edUnit.Text) <> '')
and clbUnits.Enabled;
end;
procedure TSnippetsEditorDlg.actCompileExecute(Sender: TObject);
{Test compiles edited snippet and updates compilers from test result.
@param Sender [in] Not used.
}
var
TempSnippet: TSnippet; // temp snippet object for compilation
begin
// Hide view compile errors link
pnlViewCompErrs.Hide;
// Disable dialog box and all its controls and actions
Enabled := False;
try
try
TempSnippet := CreateTempSnippet;
except
on E: Exception do
begin
Enabled := True;
HandleException(E);
Exit;
end;
end;
// Test compile snippet
try
fCompileMgr.Compile(tsCompileResults, TempSnippet, DisplayCompileResults);
finally
FreeAndNil(TempSnippet);
end;
finally
// Re-enable dialog and controls
Enabled := True;
end;
end;
procedure TSnippetsEditorDlg.actCompileUpdate(Sender: TObject);
{Updates Test Compile action according to whether any compilers are available
and if a snippet kind is selected that is not freeform.
@param Sender [in] Action triggering this event.
}
begin
(Sender as TAction).Enabled := fCompileMgr.HaveCompilers
and (fSnipKindList.SnippetKind(cbKind.ItemIndex) <> skFreeform);
end;
procedure TSnippetsEditorDlg.actDependenciesExecute(Sender: TObject);
{Displays dependencies for currently edited snippet, per entries in
"Dependencies" check list box.
@param Sender [in] Not used.
}
var
DependsList: TSnippetList; // list of dependencies
begin
DependsList := TSnippetList.Create;
try
fDependsCLBMgr.GetCheckedSnippets(DependsList);
TDependenciesDlg.Execute(
Self,
TSnippetID.Create(StrTrim(edName.Text), True),
DependsList,
[tiDependsUpon]
);
finally
FreeAndNil(DependsList);
end;
end;
procedure TSnippetsEditorDlg.actSetAllQueryExecute(Sender: TObject);
{Sets all compiler results to "query".
@param Sender [in] Not used.
}
begin
SetAllCompilerResults(crQuery);
end;
procedure TSnippetsEditorDlg.actSetAllSuccessExecute(Sender: TObject);
{Sets all compiler results to "success".
@param Sender [in] Not used.
}
begin
SetAllCompilerResults(crSuccess);
end;
procedure TSnippetsEditorDlg.actViewDescriptionExecute(Sender: TObject);
begin
try
frmDescription.Preview;
except
on E: Exception do
HandleException(E);
end;
end;
procedure TSnippetsEditorDlg.actViewDescriptionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := frmDescription.CanPreview;
end;
procedure TSnippetsEditorDlg.actViewErrorsExecute(Sender: TObject);
{Displays compiler errors.
@param Sender [in] Not used.
}
begin
fCompileMgr.ShowErrors;
end;
procedure TSnippetsEditorDlg.actViewErrorsUpdate(Sender: TObject);
{Disables view compiler errors action if panel containing link is not
displayed.
@param Sender [in] Reference to action to be updated.
}
begin
(Sender as TAction).Enabled := pnlViewCompErrs.Visible;
end;
procedure TSnippetsEditorDlg.actViewExtraExecute(Sender: TObject);
{Validates REML entered in the extra information memo control then displays it
as it will appear in the main form.
@param Sender [in] Not used.
}
begin
try
frmExtra.Preview;
except
on E: Exception do
HandleException(E);
end;
end;
procedure TSnippetsEditorDlg.actViewExtraUpdate(Sender: TObject);
{Disables view extra information action if no markup is entered in Extra
Information tab.
@param Sender [in] Reference to action to be updated.
}
begin
(Sender as TAction).Enabled := frmExtra.CanPreview;
end;
procedure TSnippetsEditorDlg.actViewTestUnitExecute(Sender: TObject);
{Displays test unit for current snippet. Error message displayed if snippet
is not valid.
@param Sender [in] Not used.
}
var
TempSnippet: TSnippet; // temp snippet object for compilation
begin
try
TempSnippet := CreateTempSnippet;
except
on E: Exception do
begin
// TempSnippet not created if there is an exception here
HandleException(E);
Exit;
end;
end;
try
TTestUnitDlgMgr.DisplayTestUnit(Self, TempSnippet);
finally
TempSnippet.Free;
end;
end;
procedure TSnippetsEditorDlg.actViewTestUnitUpdate(Sender: TObject);
{Updates View Test Unit action according to whether a compilable snippet is
selected.
@param Sender [in] Action triggering this event.
}
begin
(Sender as TAction).Enabled :=
fSnipKindList.SnippetKind(cbKind.ItemIndex) <> skFreeform;
end;
class function TSnippetsEditorDlg.AddNewSnippet(AOwner: TComponent): Boolean;
{Displays dialog box to enable user to enter a new snippet.
@param AOwner [in] Control that owns the dialog box, over which the dialog
is aligned. May be nil.
@return True if user OKs, False if cancels.
}
resourcestring
sCaption = 'Add a Snippet'; // dialog box caption
begin
with InternalCreate(AOwner) do
try
Caption := sCaption;
fSnippet := nil;
Result := ShowModal = mrOK;
finally
Free;
end;
end;
procedure TSnippetsEditorDlg.ArrangeForm;
{Arranges controls on form and sizes it.
}
begin
// tsCode
TCtrlArranger.AlignRights(
[edSourceCode, lblSourceCaretPos, btnViewDescription]
);
frmDescription.Width := btnViewDescription.Left - frmDescription.Left - 8;
TCtrlArranger.AlignVCentres(3, [lblName, edName]);
TCtrlArranger.AlignVCentres(
TCtrlArranger.BottomOf([lblName, edName], 8),
[lblDescription, frmDescription]
);
TCtrlArranger.AlignTops(
[lblDescription, frmDescription, btnViewDescription],
TCtrlArranger.BottomOf([lblName, edName], 8)
);
TCtrlArranger.AlignVCentres(
TCtrlArranger.BottomOf(
[lblDescription, frmDescription, btnViewDescription], 8
),
[lblKind, cbKind, lblSnippetKindHelp]
);
TCtrlArranger.AlignVCentres(
TCtrlArranger.BottomOf([lblKind, cbKind, lblSnippetKindHelp], 8),
[lblCategories, cbCategories]
);
TCtrlArranger.AlignTops(
[lblSourceCode, lblSourceCaretPos],
TCtrlArranger.BottomOf([lblCategories, cbCategories], 8)
);
TCtrlArranger.MoveBelow([lblSourceCode, lblSourceCaretPos], edSourceCode, 4);
// tsReferences
TCtrlArranger.AlignVCentres(
TCtrlArranger.BottomOf(clbXRefs, 6), [btnDependencies, edUnit, btnAddUnit]
);
TCtrlArranger.MoveToRightOf(cbKind, lblSnippetKindHelp, 12);
// tsComments
TCtrlArranger.AlignVCentres(3, [lblExtra, lblExtraCaretPos]);
TCtrlArranger.AlignRights([frmExtra, lblExtraCaretPos]);
TCtrlArranger.MoveBelow([lblExtra, lblExtraCaretPos], frmExtra, 4);
TCtrlArranger.MoveBelow(frmExtra, btnViewExtra, 12);
// tsCompileResults
lblViewCompErrsKey.Top := TCtrlArranger.BottomOf(lblViewCompErrs);
TCtrlArranger.SetLabelHeight(lblCompResDesc);
lblCompResDesc.Top := TCtrlArranger.BottomOf(lbCompilers, 8);
// set body panel size to accommodate controls
pnlBody.ClientHeight := TCtrlArranger.MaxContainerHeight(
[tsCode, tsComments, tsCompileResults, tsReferences]
) + pnlBody.ClientHeight - tsCode.Height + 8;
inherited;
end;
procedure TSnippetsEditorDlg.btnOKClick(Sender: TObject);
{OnClick event handler for OK button. Validates entries and updates / adds
snippet if all is well.
@param Sender [in] Not used.
}
var
SnippetName: string; // name of snippet being edited / added
begin
inherited;
try
// Validate and record entered data
ValidateData;
fEditData.Assign(UpdateData);
SnippetName := StrTrim(edName.Text);
// Add or update snippet
if Assigned(fSnippet) then
fSnippet := (Database as IDatabaseEdit).UpdateSnippet(
fSnippet, fEditData, SnippetName
)
else
begin
fSnippet := (Database as IDatabaseEdit).AddSnippet(
SnippetName, fEditData
)
end;
except
on E: Exception do
HandleException(E);
end;
end;
procedure TSnippetsEditorDlg.cbKindChange(Sender: TObject);
{Handles change events on snippet kind drop down list. Updates list of
references depending on new kind.
@param Sender [in] Not used.
}
begin
UpdateReferences;
end;
procedure TSnippetsEditorDlg.ConfigForm;
{Configures form's controls. Sets font and colors of "link" labels. Also sets
item height of owner draw check list boxes.
}
begin
inherited;
// Set colour and actions of link labels
lblSnippetKindHelp.Font.Color := clHelpLinkText;
TFontHelper.SetDefaultBaseFont(lblSnippetKindHelp.Font, False);
lblViewCompErrs.Font.Color := clLinkText;
TFontHelper.SetDefaultBaseFont(lblViewCompErrs.Font, False);
lblViewCompErrs.Caption := actViewErrors.Caption;
lblViewCompErrsKey.Caption :=
'(' + ShortcutToText(actViewErrors.ShortCut) + ')';
end;
function TSnippetsEditorDlg.CreateTempSnippet: TSnippet;
{Creates a temporary snippet from data entered in dialog box.
@return Required snippet instance.
@except EDataEntry raised if any of entered data is invalid.
}
var
EditData: TSnippetEditData; // stores snippet's properties and references
begin
ValidateData;
// Create snippet object from entered data
EditData.Assign(UpdateData);
Result := (Database as IDatabaseEdit).CreateTempSnippet(
StrTrim(edName.Text), EditData
);
end;
procedure TSnippetsEditorDlg.DisplayCompileResults(const Compilers: ICompilers);
{Displays results of a test compilation. Used as callback method for compile
manager.
@param Compilers [in] Object containing compilation results.
}
var
Results: TCompileResults; // results of compilation
CompID: TCompilerID; // loops thru each compiler
begin
for CompID := Low(TCompilerID) to High(TCompilerID) do
Results[CompID] := Compilers[CompID].GetLastCompileResult;
fCompilersLBMgr.SetCompileResults(Results);
// Update visibility of show errors link
pnlViewCompErrs.Visible := fCompileMgr.HaveErrors;
end;
class function TSnippetsEditorDlg.EditSnippet(AOwner: TComponent;
const Snippet: TSnippet): Boolean;
{Displays dialog box to enable user to edit a snippet.
@param AOwner [in] Control that owns the dialog box, over which the dialog
is aligned. May be nil.
@param Snippet [in] Reference to snippet to be edited.
@return True if user OKs, False if cancels.
}
resourcestring
sCaption = 'Edit %s'; // dialog box caption
begin
with InternalCreate(AOwner) do
try
Caption := Format(sCaption, [Snippet.Name]);
fSnippet := Snippet;
Result := ShowModal = mrOK;
finally
Free;
end;
end;
procedure TSnippetsEditorDlg.FocusCtrl(const Ctrl: TWinControl);
{Displays and focusses a control, selecting its parent tab sheet if necessary.
@param Ctrl [in] Control to be focussed.
}
var
ParentTab: TTabSheet; // tab sheet on which Ctrl sits
ParentCtrl: TWinControl; // walks up parents of Ctrl
begin
// Find tab sheet that contains edit control
ParentCtrl := Ctrl.Parent;
while Assigned(ParentCtrl) and not (ParentCtrl is TTabSheet) do
ParentCtrl := ParentCtrl.Parent;
if not Assigned(ParentCtrl) then
Exit;
// Display correct tab sheet
ParentTab := ParentCtrl as TTabSheet;
pcMain.ActivePage := ParentTab;
// Focus control
if Ctrl.Enabled then
Ctrl.SetFocus;
end;
procedure TSnippetsEditorDlg.FormCreate(Sender: TObject);
{Form creation event handler. Creates owned objects.
@param Sender [in] Not used.
}
begin
inherited;
fCatList := TCategoryListAdapter.Create(Database.Categories);
fSnipKindList := TSnipKindListAdapter.Create;
fCompileMgr := TCompileMgr.Create(Self); // auto-freed
fMemoCaretPosDisplayMgr := TMemoCaretPosDisplayMgr.Create;
fDependsCLBMgr := TSnippetsChkListMgr.Create(clbDepends);
fXRefsCLBMgr := TSnippetsChkListMgr.Create(clbXRefs);
fUnitsCLBMgr := TUnitsChkListMgr.Create(clbUnits);
fCompilersLBMgr := TCompileResultsLBMgr.Create(
lbCompilers, fCompileMgr.Compilers
);
fImages := TLEDImageList.Create(Self);
fSourceMemoHelper := TMemoHelper.Create(edSourceCode);
alMain.Images := fImages;
end;
procedure TSnippetsEditorDlg.FormDestroy(Sender: TObject);
{Form destruction event handler. Frees owned objects.
@param Sender [in] Not used.
}
begin
inherited;
FreeAndNil(fSourceMemoHelper);
FreeAndNil(fCompilersLBMgr);
FreeAndNil(fUnitsCLBMgr);
FreeAndNil(fXRefsCLBMgr);
FreeAndNil(fDependsCLBMgr);
FreeAndNil(fSnipKindList);
FreeAndNil(fCatList);
fMemoCaretPosDisplayMgr.Free;
end;
procedure TSnippetsEditorDlg.HandleException(const E: Exception);
{Handles trapped exceptions. EDataEntry exceptions are caught, an error
message is displayed and the control causing the exception is focussed. Other
exceptions are re-raised.
@param E [in] Exception to be handled.
@except Exceptions re-raised if not EDataEntry.
}
var
Error: EDataEntry;
begin
if E is EDataEntry then
begin
Error := E as EDataEntry;
TMessageBox.Error(Self, Error.Message);
FocusCtrl(Error.Ctrl);
if Error.HasSelection and (Error.Ctrl is TCustomEdit) then
begin
(Error.Ctrl as TCustomEdit).SelStart := Error.Selection.StartPos;
(Error.Ctrl as TCustomEdit).SelLength := Error.Selection.Length;
end;
ModalResult := mrNone;
end
else
raise E;
end;
procedure TSnippetsEditorDlg.InitControls;
{Initialises controls to default values.
}
begin
if Assigned(fSnippet) then
begin
// We are editing a snippet: initialise controls from snippet's properties
edSourceCode.Text := fSnippet.SourceCode;
frmDescription.DefaultEditMode := emAuto;
frmDescription.ActiveText := fSnippet.Description;
edName.Text := fSnippet.Name;
cbCategories.ItemIndex := fCatList.IndexOf(fSnippet.Category);
frmExtra.DefaultEditMode := emAuto;
frmExtra.ActiveText := fSnippet.Extra;
cbKind.ItemIndex := fSnipKindList.IndexOf(fSnippet.Kind);
// check required items in references check list boxes
UpdateReferences;
fDependsCLBMgr.CheckSnippets(fSnippet.Depends);
fXRefsCLBMgr.CheckSnippets(fSnippet.XRef);
// ensure snippet's units are displayed checked in units check list box
fUnitsCLBMgr.IncludeUnits(fSnippet.Units, True);
end
else
begin
// We are adding a new snippet: clear all controls or set default values
edSourceCode.Clear;
frmDescription.DefaultEditMode := emPlainText;
frmDescription.Clear;
edName.Clear;
cbCategories.ItemIndex := fCatList.IndexOf(TReservedCategories.UserCatID);
if cbCategories.ItemIndex = -1 then
cbCategories.ItemIndex := 0;
cbKind.ItemIndex := fSnipKindList.IndexOf(skFreeform);
frmExtra.DefaultEditMode := emPlainText;
frmExtra.Clear;
UpdateReferences;
end;
// Display all compiler results
fCompilersLBMgr.SetCompileResults(fEditData.Props.CompilerResults);
Assert(cbKind.ItemIndex >= 0,
ClassName + '.InitControls: no selection in cbKind');
Assert(cbCategories.ItemIndex >= 0,
ClassName + '.InitControls: no selection in cbCategories');
// Auto-update caret position display for source and extra info memos
fMemoCaretPosDisplayMgr.Manage(edSourceCode, lblSourceCaretPos);
fMemoCaretPosDisplayMgr.Manage(frmExtra, lblExtraCaretPos);
end;
procedure TSnippetsEditorDlg.InitForm;
{Performs initialisation of form fields and controls.
}
begin
inherited;
// Get data associated with snippet, or blank / default data if adding a new
// snippet
fEditData := (Database as IDatabaseEdit).GetEditableSnippetInfo(fSnippet);
// Record snippet's original name, if any
if Assigned(fSnippet) then
fOrigName := fSnippet.Name
else
fOrigName := '';
// Populate controls with dynamic data
PopulateControls;
// Initialise controls to default values
InitControls;
// Select first tab sheet
pcMain.ActivePageIndex := 0;
end;
procedure TSnippetsEditorDlg.lblSnippetKindHelpClick(Sender: TObject);
{OnClick event handler for Snippet Kind help link label. Displays help topic
that informs what a Snippet Kind is.
@param Sender [in] Not used.
}
begin
DisplayHelp('SnippetKinds');
end;
procedure TSnippetsEditorDlg.lblViewCompErrsClick(Sender: TObject);
{OnClick event handler for compiler errors link label. Displays compiler
warnings and errors in a dialog box.
@param Sender [in] Not used.
}
begin
actViewErrors.Execute;
end;
procedure TSnippetsEditorDlg.pcMainChange(Sender: TObject);
{Handler for OnChange event for page control. Used to load content into
instructions HTML frame for comments tab.
@param Sender [in] Not used.
}
begin
inherited;
// We always hide "view errors" link whenever page changes since snippet
// properties may have changed since page was last accessed
pnlViewCompErrs.Hide;
end;
procedure TSnippetsEditorDlg.pcMainMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if htOnItem in pcMain.GetHitTestInfoAt(X, Y) then
pcMain.SetFocus;
end;
procedure TSnippetsEditorDlg.PopulateControls;
{Populates controls with dynamic data.
}
begin
// Display all kinds in drop down list
fSnipKindList.ToStrings(cbKind.Items);
// Display all available categories in drop down list
fCatList.ToStrings(cbCategories.Items);
end;
procedure TSnippetsEditorDlg.SetAllCompilerResults(
const CompRes: TCompileResult);
{Sets all compiler results to same value.
@param CompRes [in] Required compiler result.
}
begin
fCompilersLBMgr.SetCompileResults(CompRes);
end;
function TSnippetsEditorDlg.UpdateData: TSnippetEditData;
{Updates snippet's data from user entries. Assumes data has been validated.
@return Record containing snippet's data.
}
begin
Result.Init;
with Result do
begin
Props.Cat := fCatList.CatID(cbCategories.ItemIndex);
Props.Kind := fSnipKindList.SnippetKind(cbKind.ItemIndex);
(Props.Desc as IAssignable).Assign(frmDescription.ActiveText);
Props.SourceCode := StrTrimRight(edSourceCode.Text);
(Props.Extra as IAssignable).Assign(frmExtra.ActiveText);
Props.CompilerResults := fCompilersLBMgr.GetCompileResults;
fUnitsCLBMgr.GetCheckedUnits(Refs.Units);
fDependsCLBMgr.GetCheckedSnippets(Refs.Depends);
fXRefsCLBMgr.GetCheckedSnippets(Refs.XRef);
end;
end;
procedure TSnippetsEditorDlg.UpdateReferences;
{Updates dependencies and cross-references check lists for snippet being
edited, depending on kind.
}
var
EditSnippetID: TSnippetID; // id of snippet being edited
Snippet: TSnippet; // each snippet in database
EditSnippetKind: TSnippetKind; // kind of snippet being edited
begin
// Save state of dependencies and x-ref check list boxes and clear them
fDependsCLBMgr.Save;
fDependsCLBMgr.Clear;
fXRefsCLBMgr.Save;
fXRefsCLBMgr.Clear;
EditSnippetID := TSnippetID.Create(fOrigName, True);
EditSnippetKind := fSnipKindList.SnippetKind(cbKind.ItemIndex);
for Snippet in Database.Snippets do
begin
// We ignore snippet being edited and main database snippets if there is
// a user-defined one with same name
if (Snippet.ID <> EditSnippetID) and
(
Snippet.UserDefined or
not Assigned(Database.Snippets.Find(Snippet.Name, True))
) then
begin
// Decide if snippet can be added to depends list: must be correct kind
if Snippet.Kind in
TSnippetValidator.ValidDependsKinds(EditSnippetKind) then
fDependsCLBMgr.AddSnippet(Snippet);
// Anything can be in XRefs list
fXRefsCLBMgr.AddSnippet(Snippet);
end;
end;
// Restore checks to any saved checked item that still exist in new list
fDependsCLBMgr.Restore;
fXRefsCLBMgr.Restore;
clbUnits.Enabled := EditSnippetKind <> skUnit;
edUnit.Enabled := EditSnippetKind <> skUnit;
end;
procedure TSnippetsEditorDlg.ValidateData;
{Checks all user-entered data in all tabs of the form.
@except EDataEntry raised if data is not valid.
}
resourcestring
// Messages
sDependencyPrompt = 'See the dependencies by clicking the View Dependencies '
+ 'button on the References tab.';
var
ErrorMessage: string; // receives validation error messages
ErrorSelection: TSelection; // receives selection containing errors
begin
if not TSnippetValidator.ValidateName(
edName.Text,
not StrSameText(StrTrim(edName.Text), fOrigName),
ErrorMessage,
ErrorSelection
) then
raise EDataEntry.Create(ErrorMessage, edName, ErrorSelection);
frmDescription.Validate;
if not TSnippetValidator.ValidateSourceCode(
edSourceCode.Text, ErrorMessage, ErrorSelection
) then
raise EDataEntry.Create(ErrorMessage, edSourceCode, ErrorSelection);
frmExtra.Validate;
if not TSnippetValidator.ValidateDependsList(
StrTrim(edName.Text), UpdateData, ErrorMessage
) then
raise EDataEntry.Create( // selection not applicable to list boxes
StrMakeSentence(ErrorMessage) + EOL2 + sDependencyPrompt, clbDepends
);
end;
end.
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.