Debian Codegraph @

tools/castle-editor/code/formprogress.pas

raw
1 {
2 Copyright 2023-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Show download progress.
17 Use only through TProgressForm.WaitFor method. }
18 unit FormProgress;
19
20 {$mode ObjFPC}{$H+}
21
22 interface
23
24 uses
25 Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ComCtrls,
26 ExtCtrls, CastleDownload;
27
28 type
29 EDownloadCancelled = class(Exception);
30
31 TProgressForm = class(TForm)
32 ApplicationProperties1: TApplicationProperties;
33 ButtonCancel: TButton;
34 LabelInfo: TLabel;
35 ProgressBar1: TProgressBar;
36 Timer1: TTimer;
37 procedure ButtonCancelClick(Sender: TObject);
38 procedure Timer1Timer(Sender: TObject);
39 private
40 public
41 WaitingFor: TCastleDownload;
42 { Show progress of download, waiting for download to finish.
43 Make exception if download fails or is cancelled. }
44 class procedure WaitFor(const Description: String; const Download: TCastleDownload);
45 end;
46
47 implementation
48
49 uses CastleApplicationProperties;
50
51 {$R *.lfm}
52
53 procedure TProgressForm.ButtonCancelClick(Sender: TObject);
54 begin
55 ModalResult := mrCancel;
56 Close;
57 end;
58
59 procedure TProgressForm.Timer1Timer(Sender: TObject);
60 begin
61 { We don't do this in ApplicationProperties1Idle because
62 it isn't done when TCastleControl installs own idle handler that
63 always sets Done:=false. }
64
65 if WaitingFor.Status = dsDownloading then
66 begin
67 if WaitingFor.TotalBytes <> -1 then
68 ProgressBar1.Position := Round(ProgressBar1.Max *
69 WaitingFor.DownloadedBytes / WaitingFor.TotalBytes);
70
71 // to process downloading
72 ApplicationProperties._Update;
73 end else
74 begin
75 ModalResult := mrOK;
76 Close;
77 end;
78 end;
79
80 class procedure TProgressForm.WaitFor(const Description: String; const Download: TCastleDownload);
81 var
82 Form: TProgressForm;
83 begin
84 Form := TProgressForm.Create(Application);
85 try
86 Form.LabelInfo.Caption := Description;
87 Form.ProgressBar1.Max := 100;
88 Form.ProgressBar1.Position := 0;
89 Form.WaitingFor := Download;
90 Form.ShowModal;
91
92 case Download.Status of
93 dsSuccess: ;
94 dsError: raise Exception.CreateFmt('Download failed: %s', [Download.ErrorMessage]);
95 else raise EDownloadCancelled.Create('Download cancelled');
96 end;
97 finally
98 // TODO: closing before freeing necessary?
99 if Form <> nil then
100 begin
101 Form.OnCloseQuery := nil;
102 Form.Close;
103 end;
104 FreeAndNil(Form);
105 end;
106 end;
107
108 end.
109