Menu

[r375]: / trunk / Src / UCodeImportMgr.pas  Maximize  Restore  History

Download this file

532 lines (498 with data), 19.5 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
{
* UCodeImportMgr.pas
*
* Implements a static class that handles import of a codesnip export file into
* the user-defined database.
*
* $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 UCodeImportMgr.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-2009 Peter
* Johnson. All Rights Reserved.
*
* Contributor(s)
* NONE
*
* ***** END LICENSE BLOCK *****
}
unit UCodeImportMgr;
interface
uses
// Project
UBaseObjects, UCodeImportExport, UExceptions, USnippets;
type
{
TCodeImportMgr:
Sealed static class that handles import of a codesnip export file into the
user-defined database. Gets name of import file, checks for duplicate
entries and updates the user-defined database.
}
TCodeImportMgr = class sealed(TNoConstructObject)
strict private
const
// Ids of buttons used in dialog box shown when an imported snippet exists
mrReplace = 100; // replace button
mrSkip = 101; // skip button
mrRename = 102; // rename button
class procedure CanOpenDialogClose(Sender: TObject;
var CanClose: Boolean);
{Handles open dialog box's OnCanClose event. Prevents dialog from closing
if selected file does not exist.
@param Sender [in] Reference to dialog box that triggered event. Must be
of type TOpenDialogEx.
@param CanClose [in/out] Flag that determines if dialog can close. Set
to False to prevent closure or True to permit it.
}
class function GetImportFileName: string;
{Gets name of import file from user.
@return Name of import file or '' if user cancels.
}
class procedure ReadImportFile(const FileName: string;
out UserInfo: TUserInfo; out Routines: TRoutineInfoList);
{Reads and parses import file.
@param FileName [in] Name of import file.
@param UserInfo [out] Details of user who created file. May be nul if
file doesn't contain user information.
@param Routines [out] List of snippets specified in import file.
@except ECodeImportMgr raised if can't read import file or it is
invalid.
}
class function RenameRoutine(var Routine: TRoutineInfo): Boolean;
{Gets new name for a snippet from user.
@param Routine [in] Info about snippet to be renamed. [out] Name field
updated to receive new name. Unchanged if False returned.
@return True if user changed name, false if renamed was cancelled.
}
class function FilterRoutines(var Routines: TRoutineInfoList): Boolean;
{Checks for duplicate snippets and filters out any that user does not wish
to import. Duplicates may be renamed.
@param Routines [in] List of snippets from import file. [out] List of
filtered snippets (some may be removed or renamed). Undefined if False
is returned.
@return True if import to go ahead, False to abort.
}
class function QueryOverwrite(const RoutineName: string): Integer;
{Displays dialog box that asks user what action to perform if a snippet
already exists in user database.
@return Code representing required action.
}
class procedure UpdateUserDatabase(const UserInfo: TUserInfo;
const Routines: TRoutineInfoList);
{Updates user database with filtered list of imported snippets.
@param UserInfo [in] Record containing user information pertaining to
imported snippets.
@param Routines [in] Details of required snippets.
}
class procedure DisplayUserInfo(const UserInfo: TUserInfo);
{Displays user information from an import file.
@param UserInfo [in] Record containing user information.
}
class procedure ReportImportedRoutines(const Routines: TRoutineInfoList);
{Reports details of imported snippets to user.
@param Routines [in] Details of all imported snippets.
}
public
class procedure Execute;
{Performs import from a user-specified file. Does nothing if user cancels.
@except ECodeImportMgr raised if can't read import file.
}
end;
{
ECodeImportMgr:
Class of exception raised when import manager encounteres an expected error.
}
ECodeImportMgr = class(ECodeSnip);
implementation
uses
// Delphi
SysUtils, Classes, Controls, Dialogs,
// Project
FmEditTextDlg, UActiveText, UConsts, UMessageBox, UOpenDialogEx,
UOpenDialogHelper, USnippetIDs;
{ TCodeImportMgr }
class procedure TCodeImportMgr.CanOpenDialogClose(Sender: TObject;
var CanClose: Boolean);
{Handles open dialog box's OnCanClose event. Prevents dialog from closing if
selected file does not exist.
@param Sender [in] Reference to dialog box that triggered event. Must be of
type TOpenDialogEx.
@param CanClose [in/out] Flag that determines if dialog can close. Set to
False to prevent closure or True to permit it.
}
var
Dlg: TOpenDialogEx; // dialog box instance triggering this event
FileSpec: string; // full path to entered or selected file name
resourcestring
// Error messages
sFileDoesNotExist = '"%s" does not exist.';
begin
Dlg := Sender as TOpenDialogEx;
FileSpec := FileOpenEditedFileName(Dlg);
CanClose := FileExists(FileSpec);
if not CanClose then
TMessageBox.Error(Dlg, Format(sFileDoesNotExist, [FileSpec]));
end;
class procedure TCodeImportMgr.DisplayUserInfo(const UserInfo: TUserInfo);
{Displays user information from an import file.
@param UserInfo [in] Record containing user information.
}
resourcestring
// User name and email message
sUserInfo = 'Importing data supplied by: %0:s <%1:s>';
// User comments message
sUserComments = 'Notes: %s';
var
DisplayStr: string; // text to be displayed in message box
begin
DisplayStr := Format(sUserInfo, [UserInfo.Name, UserInfo.Email]);
if UserInfo.Comments <> '' then
DisplayStr := DisplayStr + EOL2
+ Format(sUserComments, [UserInfo.Comments]);
TMessageBox.Information(nil, DisplayStr);
end;
class procedure TCodeImportMgr.Execute;
{Performs import from a user-specified file. Does nothing if user cancels.
@except ECodeImportMgr raised if can't read import file.
}
var
UserInfo: TUserInfo; // any user info from import file
Routines: TRoutineInfoList; // list of imported snippets
FileName: string; // name of import file
resourcestring
// Message displayed if no snippets imported
sNoRoutines = 'No snippets were imported';
begin
// Import user specified file
FileName := GetImportFileName;
if FileName = '' then
Exit;
ReadImportFile(FileName, UserInfo, Routines);
// Display user info if there is any
if not UserInfo.IsNul then
DisplayUserInfo(UserInfo);
// Perform import: remove any duplicate snippets that are not to be renamed or
// overwritten
if FilterRoutines(Routines) then
begin
UpdateUserDatabase(UserInfo, Routines);
// report import results to user
ReportImportedRoutines(Routines);
end
else
// no snippets imported: inform user
TMessageBox.Information(nil, sNoRoutines);
end;
class function TCodeImportMgr.FilterRoutines(
var Routines: TRoutineInfoList): Boolean;
{Checks for duplicate snippets and filters out any that user does not wish
to import. Duplicates may be renamed.
@param Routines [in] List of snippets from import file. [out] List of
filtered snippets (some may be removed or renamed). Undefined if False is
returned.
@return True if import to go ahead, False to abort.
}
var
Required: TRoutineInfoList; // list of required snippets
RoutineIdx: Integer; // loops through all imported snippets
RequiredCount: Integer; // count of required snippets
// ---------------------------------------------------------------------------
procedure IncludeRoutine(const Routine: TRoutineInfo);
{Includes a snippet in filtered list.
@param Routine [in] Info about snippet to be included.
}
begin
Inc(RequiredCount);
SetLength(Required, RequiredCount);
Required[RequiredCount - 1] := Routine;
end;
// ---------------------------------------------------------------------------
begin
Result := False;
RequiredCount := 0;
// Scan all snippets checking if they already exist in user database
for RoutineIdx := Low(Routines) to High(Routines) do
begin
if Snippets.Routines.Find(Routines[RoutineIdx].Name, True) = nil then
// snippet doesn't exist: include it in import
IncludeRoutine(Routines[RoutineIdx])
else
begin
// snippet exists, get required action from user
case QueryOverwrite(Routines[RoutineIdx].Name) of
mrReplace:
// overwrite snippet: include in filtered list
IncludeRoutine(Routines[RoutineIdx]);
mrSkip:
// skip snippet: do nothing (i.e. don't place in filtered list)
;
mrRename:
begin
// rename snippet: get user to rename and include in filtered list
// unless user cancels rename
if RenameRoutine(Routines[RoutineIdx]) then
IncludeRoutine(Routines[RoutineIdx]);
end;
mrCancel:
// cancel whole import
Exit;
end;
end;
end;
if RequiredCount = 0 then
// No snippets required
Exit;
// Copy required snippets into Routines param
SetLength(Routines, Length(Required));
for RoutineIdx := Low(Required) to High(Required) do
Routines[RoutineIdx] := Required[RoutineIdx];
Result := True;
end;
class function TCodeImportMgr.GetImportFileName: string;
{Gets name of import file from user.
@return Name of import file or '' if user cancels.
}
var
OpenDlg: TOpenDialogEx; // self-aligning enhanced open dialog box
resourcestring
sFilter = 'CodeSnip export files (*.csexp)|*.csexp|' // file filter
+ 'All files (*.*)|*.*';
sTitle = 'Import Snippets'; // dialog box title
begin
// Create and initialise
OpenDlg := TOpenDialogEx.Create(nil);
try
OpenDlg.OnCanClose := CanOpenDialogClose;
OpenDlg.Filter := sFilter;
OpenDlg.FilterIndex := 1;
OpenDlg.InitialDir := '';
// we don't include ofFileMustExist in Options below since we handle
// non-existant files ourselves
OpenDlg.Options := [ofHideReadOnly, ofEnableSizing];
OpenDlg.OptionsEx := [];
OpenDlg.Title := sTitle;
OpenDlg.HelpKeyword := 'ImportFileDlg'; // ** do not localise
if OpenDlg.Execute then
// User OKd: return entered file name
Result := OpenDlg.FileName
else
Result := '';
finally
FreeAndNil(OpenDlg);
end;
end;
class function TCodeImportMgr.QueryOverwrite(
const RoutineName: string): Integer;
{Displays dialog box that asks user what action to perform if a snippet
already exists in user database.
@return Code representing required action.
}
resourcestring
// Prompt displayed in dialog box
sPrompt = 'Importing %0:s' + EOL2
+ 'The user database already contains a snippet named %0:s.' + EOL2
+ 'You can replace the existing snippet, skip importing the snippet or '
+ 'rename the imported snippet.' + EOL
+ 'Click cancel to abort the import.';
// Dialog box button captions
sBtnReplace = '&Replace';
sBtnSkip = '&Skip';
sBtnRename = 'Re&name';
begin
Result := TMessageBox.Custom(
nil,
Format(sPrompt, [RoutineName]),
[
TMessageBoxButton.Create(sBtnReplace, mrReplace),
TMessageBoxButton.Create(sBtnSkip, mrSkip, True),
TMessageBoxButton.Create(sBtnRename, mrRename),
TMessageBoxButton.Create(sBtnCancel, mrCancel, False, True)
]
);
end;
class procedure TCodeImportMgr.ReadImportFile(const FileName: string;
out UserInfo: TUserInfo; out Routines: TRoutineInfoList);
{Reads and parses import file.
@param FileName [in] Name of import file.
@param UserInfo [out] Details of user who created file. May be nul if file
doesn't contain user information.
@param Routines [out] List of snippets specified in import file.
@except ECodeImportMgr raised if can't read import file or it is invalid.
}
var
InStream: TStream; // stream onto import file
begin
Assert(FileName <> '',
ClassName + '.ReadImportFile: No file name provided');
try
InStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
TCodeImporter.ImportData(UserInfo, Routines, InStream);
finally
FreeAndNil(InStream);
end;
except
on E: EStreamError do
raise ECodeImportMgr.Create(E);
on E: ECodeImporter do
raise ECodeImportMgr.Create(E);
else
raise;
end;
end;
class function TCodeImportMgr.RenameRoutine(var Routine: TRoutineInfo): Boolean;
{Gets new name for a snippet from user.
@param Routine [in] Info about snippet to be renamed. [out] Name field
updated to receive new name. Unchanged if False returned.
@return True if user changed name, false if renamed was cancelled.
}
resourcestring
// Dialog box title and prompt
sDlgTitle = 'Rename Snippet';
sDlgPrompt = 'Enter a new snippet &name (cancel skips the snippet):';
// Error message
sRoutineExists = 'A user defined snippet name "%s" already exists';
// Information message
sSkippingRoutine = 'Skipping "%s"';
var
Done: Boolean; // flag true if snippet renamed successfully
NewName: string; // new snippet name
NameCounter: Integer; // counter used to append to snippet name
begin
// Create new suggested name
NameCounter := 2;
while Snippets.Routines.Find(
Routine.Name + IntToStr(NameCounter), True
) <> nil do
Inc(NameCounter);
NewName := Routine.Name + IntToStr(NameCounter);
// Get name from user
Done := False;
repeat
Result := TEditTextDlg.Execute(nil, sDlgTitle, sDlgPrompt, NewName);
if Result then
begin
Done := Snippets.Routines.Find(NewName, True) = nil;
if not Done then
TMessageBox.Error(nil, Format(sRoutineExists, [NewName]));
end
else
TMessageBox.Information(nil, Format(sSkippingRoutine, [NewName]));
until Done or not Result;
if Result then
// Everything OK: record new name
Routine.Name := NewName;
end;
class procedure TCodeImportMgr.ReportImportedRoutines(
const Routines: TRoutineInfoList);
{Reports details of imported snippets to user.
@param Routines [in] Details of all imported snippets.
}
resourcestring
// Messages displayed depending on if one or more than one snippets imported
sSingle = 'A snippet named "%s" was imported';
sMultiple = 'The following snippets were imported:' + EOL2 + '%s';
var
Idx: Integer; // loops through list of snippets
RoutineList: string; // display list of snippet names
begin
Assert(Length(Routines) > 0, // ** do not localise
ClassName + '.ReportImportedRoutines: No snippets to report.');
if Length(Routines) = 1 then
// Only one snippet: just report the name
TMessageBox.Information(nil, Format(sSingle, [Routines[0].Name]))
else
begin
// More that one snippet: display bullet list of names
RoutineList := '';
for Idx := Low(Routines) to High(Routines) do
RoutineList := RoutineList + ' '#$bb' ' + Routines[Idx].Name + EOL;
TMessageBox.Information(nil, Format(sMultiple, [TrimRight(RoutineList)]));
end;
end;
class procedure TCodeImportMgr.UpdateUserDatabase(const UserInfo: TUserInfo;
const Routines: TRoutineInfoList);
{Updates user database with filtered list of imported snippets.
@param UserInfo [in] Record containing user information pertaining to
imported snippets.
@param Routines [in] Details of required snippet.
}
// ---------------------------------------------------------------------------
procedure AdjustDependsList(const Depends: ISnippetIDList);
{Adjusts a snippet's dependency list so that main database is searched for
a required snippet if it is not in the user database.
@param Depends [in] Dependency list to be adjusted.
}
var
Idx: Integer; // loops through dependencies
RoutineID: TSnippetID; // each snippet ID in dependency list
begin
// NOTE: The data file format does not record which database a required
// snippet belongs to, so we first look in the user database and if it's
// not there, we assume the main database
for Idx := 0 to Pred(Depends.Count) do
begin
RoutineID := Depends[Idx];
RoutineID.UserDefined :=
Snippets.Routines.Find(RoutineID.Name, True) <> nil;
Depends[Idx] := RoutineID;
end;
end;
function UserInfoActiveText: IActiveText;
{Builds an active text representation of the contributing user's name and
email address.
@return Required active text representation.
}
resourcestring
// user information text template
sContributorText = 'Contributed by: %0:s <%1:s>';
begin
Assert(not UserInfo.IsNul, ClassName +
'.UpdateUserDatabase:CreateUserInfoActiveText: UserInfo is nul');
Result := TActiveTextFactory.CreateActiveText;
Result.AddElem(TActiveTextFactory.CreateActionElem(ekPara, fsOpen));
Result.AddElem(
TActiveTextFactory.CreateTextElem(
Format(sContributorText, [UserInfo.Name, UserInfo.Email])
)
);
Result.AddElem(TActiveTextFactory.CreateActionElem(ekPara, fsClose));
end;
// ---------------------------------------------------------------------------
var
Idx: Integer; // loops through all snippets
Editor: ISnippetsEdit; // object used to update user database
Routine: TRoutine; // reference to existing snippets
begin
Editor := Snippets as ISnippetsEdit;
for Idx := Low(Routines) to High(Routines) do
begin
AdjustDependsList(Routines[Idx].Data.Refs.Depends);
if not UserInfo.IsNul then
Routines[Idx].Data.Props.Extra.Append(UserInfoActiveText);
Routine := Snippets.Routines.Find(Routines[Idx].Name, True);
if Assigned(Routine) then
// snippet already exists: overwrite it
Editor.UpdateRoutine(Routine, Routines[Idx].Data)
else
// snippet is new: add to database
Editor.AddRoutine(Routines[Idx].Name, Routines[Idx].Data);
end;
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.